source
stringlengths
3
92
c
stringlengths
26
2.25M
Layer_Conv2D.h
/* * Layers.h * rl * * Created by Guido Novati on 11.02.16. * Copyright 2016 ETH Zurich. All rights reserved. * */ #pragma once #include "Layers.h" template < int InX, int InY, int InC, //input image: x:width, y:height, c:color channels int KnX, int KnY, int KnC, //filter: x:width, y:height, c:color channels int OpX, int OpY //output img: x:width, y:height, same color channels as KnC > struct Conv2DLayer: public Layer { Params* allocate_params() const override { //number of kernel parameters: // 2d kernel size * number of inp channels * number of out channels const int nParams = KnY * KnX * InC * KnC; const int nBiases = KnC; return new Params(nParams, nBiases); } Conv2DLayer(const int _ID) : Layer(OpX * OpY * KnC, _ID) { static_assert(InX>0 && InY>0 && InC>0, "Invalid input"); static_assert(KnX>0 && KnY>0 && KnC>0, "Invalid kernel"); static_assert(OpX>0 && OpY>0, "Invalid outpus"); print(); } void print() { printf("(%d) Conv: In:[%d %d %d %d %d] F:[%d %d %d %d] Out:[%d %d %d]\n", ID, OpY,OpX,KnY,KnX,InC, KnY,KnX,InC,KnC, OpX,OpY,KnC); } void forward(const std::vector<Activation*>& act, const std::vector<Params*>& param) const override { assert(act[ID]->layersSize == OpY * OpX * KnC); assert(act[ID-1]->layersSize == OpY * OpX * KnY * KnX * InC ); assert(param[ID]->nWeights == KnY * KnX * InC * KnC); assert(param[ID]->nBiases == KnC); const int batchSize = act[ID]->batchSize; { Real* const __restrict__ OUT = act[ID]->output; const Real* const __restrict__ B = param[ID]->biases; #pragma omp parallel for schedule(static) for (int i=0; i<batchSize * OpY * OpX * KnC; i++) OUT[i] = B[i % KnC]; } { const int mm_outRow = batchSize * OpY * OpX; const int mm_nInner = KnY * KnX * InC; const int mm_outCol = KnC; gemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, mm_outRow, mm_outCol, mm_nInner, (Real) 1.0, act[ID-1]->output, mm_nInner, param[ID]->weights, mm_outCol, (Real) 1.0, act[ID]->output, mm_outCol); } } void bckward(const std::vector<Activation*>& act, const std::vector<Params*>& param, const std::vector<Params*>& grad) const override { const int batchSize = act[ID]->batchSize; { const Real* const __restrict__ dEdO = act[ID]->dError_dOutput; Real* const __restrict__ B = grad[ID]->biases; std::fill(B, B+KnC, 0); #pragma omp parallel for schedule(static) reduction(+ : B[:KnC]) for (int i=0; i<batchSize * OpY * OpX * KnC; i++) B[i % KnC] += dEdO[i]; } { // Compute gradient of error wrt to kernel parameters: // [KnY*KnX*InC, KnC] = [BS*OpY*OpX, KnY*KnX*InC]^T [BS*OpX*OpY, KnC] const int mm_outRow = KnY * KnX * InC; const int mm_nInner = batchSize * OpY * OpX; const int mm_outCol = KnC; gemm(CblasRowMajor, CblasTrans, CblasNoTrans, mm_outRow, mm_outCol, mm_nInner, (Real) 1.0, act[ID-1]->output, mm_outRow, act[ID]->dError_dOutput, mm_outCol, (Real) 0.0, grad[ID]->weights, mm_outCol); } { // Compute gradient of error wrt to output of previous layer: //[BS*OpY*OpX, KnY*KnX*InC] = [BS*OpY*OpX, KnC] [KnY*KnX*InC, KnC]^T const int mm_outRow = batchSize * OpY * OpX; const int mm_nInner = KnC; const int mm_outCol = KnY * KnX * InC; gemm(CblasRowMajor, CblasNoTrans, CblasTrans, mm_outRow, mm_outCol, mm_nInner, (Real) 1.0, act[ID]->dError_dOutput, mm_nInner, param[ID]->weights, mm_nInner, (Real) 0.0, act[ID-1]->dError_dOutput, mm_outCol); } } void init(std::mt19937& gen, const std::vector<Params*>& param) const override { // get pointers to layer's weights and bias Real *const W = param[ID]->weights, *const B = param[ID]->biases; // initialize weights with Xavier initialization const int nAdded = KnX * KnY * InC, nW = param[ID]->nWeights; const Real scale = std::sqrt(6.0 / (nAdded + KnC)); std::uniform_real_distribution < Real > dis(-scale, scale); std::generate(W, W + nW, [&]() {return dis( gen );}); std::fill(B, B + KnC, 0); } };
big_wkld.c
/* * Code to simulate a "big"-core workload for lab assignment in [A2] Task Mapping on Soft Heterogeneous Systems. * Workload consists of a parallel implementation of quicksort. * Implementation not optimized! Only meant to be used in conjunction with lab assignment. * The performance of the workload increases proportianlly with clock frequency. In a task mapping scenario, * this workload should be mapped to the "big" cores for optimal performance. * * @author: Apan Qasem <apan@txstate.edu> * @date: 04/02/20 * * @update: 03/12/21 */ #include<stdlib.h> #include<stdio.h> #include<sys/time.h> #include<omp.h> const int VAL_RANGE = 1024; const unsigned ELEMENTS_TO_VERIFY = 1; /* timer function */ double get_time_in_seconds() { struct timeval tp; struct timezone tzp; int i; i = gettimeofday(&tp,&tzp); return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 ); } void swap(double *x, double *y) { double tmp; tmp = (*x); (*x) = (*y); (*y) = tmp; return; } /* * partition array for quicksort * - move pivot to far right * - accumulate values smaller than pivot to the left */ int partition(double values[], int left, int right, int pivotIndex) { int pivotValue = values[pivotIndex]; swap(&values[pivotIndex],&values[right]); // Move pivot to end int storeIndex = left; for(int i = left; i < right; i++) { if (values[i] < pivotValue) { swap(&values[i],&values[storeIndex]); storeIndex++; } } swap(&values[storeIndex],&values[right]); // Move pivot to its final place return storeIndex; } /* * recursive quicksort */ void quickSort(double values[], int left, int right) { if (left < right) { int pivotIndex = (left + right)/2; int pivotNewIndex = partition(values, left, right, pivotIndex); #pragma omp task shared(values) firstprivate(left, pivotNewIndex) quickSort(values, left, pivotNewIndex - 1); #pragma omp task shared(values) firstprivate(right, pivotNewIndex) quickSort(values, pivotNewIndex + 1, right); #pragma omp taskwait } return; } /* * display array contents */ void display(double values[], long long N) { for (int i = 0; i < N; i++) fprintf(stdout, "%3.4f ", values[i]); fprintf(stdout, "\n"); } int main(int argc, char *argv[]) { if (argc < 2) { printf("usage: \n"); printf(" ./big_wkld N t\n"); printf(" N = input size\n"); printf(" t = number of OpenMP threads\n"); exit(0); } long long N = atoi(argv[1]); unsigned threads = atoi(argv[2]); omp_set_num_threads(threads); double start_time, end_time; double *values = (double *) malloc(sizeof(double) * N); for (int i = 0; i < N; i++) values[i] = rand() / (double) (RAND_MAX/VAL_RANGE); /* computation */ start_time = get_time_in_seconds(); quickSort(values, 0, N - 1); end_time = get_time_in_seconds(); fprintf(stdout, "\033[1;36m[wk0] compute time = %.3f s\n\033[0m", end_time - start_time); #ifdef VERIFY fprintf(stdout, "Verification: "); display(values, ELEMENTS_TO_VERIFY); #endif return 0; }
GB_unop__identity_uint32_uint8.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_uint32_uint8 // op(A') function: GB_unop_tran__identity_uint32_uint8 // C type: uint32_t // A type: uint8_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint32_t z = (uint32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t 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_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint32_uint8 ( uint32_t *Cx, // Cx and Ax may be aliased const uint8_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++) { uint8_t 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_uint8 ( 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
sse.h
/* SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright: * 2017-2020 Evan Nemerson <evan@nemerson.com> * 2015-2017 John W. Ratcliff <jratcliffscarab@gmail.com> * 2015 Brandon Rowlett <browlett@nvidia.com> * 2015 Ken Fast <kfast@gdeb.com> */ #if !defined(SIMDE_X86_SSE_H) #define SIMDE_X86_SSE_H #include "mmx.h" #if defined(_WIN32) #include <windows.h> #endif HEDLEY_DIAGNOSTIC_PUSH SIMDE_DISABLE_UNWANTED_DIAGNOSTICS SIMDE_BEGIN_DECLS_ typedef union { #if defined(SIMDE_VECTOR_SUBSCRIPT) SIMDE_ALIGN_TO_16 int8_t i8 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int16_t i16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int32_t i32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int64_t i64 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint8_t u8 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint16_t u16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint32_t u32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint64_t u64 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #if defined(SIMDE_HAVE_INT128_) SIMDE_ALIGN_TO_16 simde_int128 i128 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 simde_uint128 u128 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #endif SIMDE_ALIGN_TO_16 simde_float32 f32 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 int_fast32_t i32f SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; SIMDE_ALIGN_TO_16 uint_fast32_t u32f SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #else SIMDE_ALIGN_TO_16 int8_t i8[16]; SIMDE_ALIGN_TO_16 int16_t i16[8]; SIMDE_ALIGN_TO_16 int32_t i32[4]; SIMDE_ALIGN_TO_16 int64_t i64[2]; SIMDE_ALIGN_TO_16 uint8_t u8[16]; SIMDE_ALIGN_TO_16 uint16_t u16[8]; SIMDE_ALIGN_TO_16 uint32_t u32[4]; SIMDE_ALIGN_TO_16 uint64_t u64[2]; #if defined(SIMDE_HAVE_INT128_) SIMDE_ALIGN_TO_16 simde_int128 i128[1]; SIMDE_ALIGN_TO_16 simde_uint128 u128[1]; #endif SIMDE_ALIGN_TO_16 simde_float32 f32[4]; SIMDE_ALIGN_TO_16 int_fast32_t i32f[16 / sizeof(int_fast32_t)]; SIMDE_ALIGN_TO_16 uint_fast32_t u32f[16 / sizeof(uint_fast32_t)]; #endif SIMDE_ALIGN_TO_16 simde__m64_private m64_private[2]; SIMDE_ALIGN_TO_16 simde__m64 m64[2]; #if defined(SIMDE_X86_SSE_NATIVE) SIMDE_ALIGN_TO_16 __m128 n; #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_ALIGN_TO_16 int8x16_t neon_i8; SIMDE_ALIGN_TO_16 int16x8_t neon_i16; SIMDE_ALIGN_TO_16 int32x4_t neon_i32; SIMDE_ALIGN_TO_16 int64x2_t neon_i64; SIMDE_ALIGN_TO_16 uint8x16_t neon_u8; SIMDE_ALIGN_TO_16 uint16x8_t neon_u16; SIMDE_ALIGN_TO_16 uint32x4_t neon_u32; SIMDE_ALIGN_TO_16 uint64x2_t neon_u64; SIMDE_ALIGN_TO_16 float32x4_t neon_f32; #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) SIMDE_ALIGN_TO_16 float64x2_t neon_f64; #endif #elif defined(SIMDE_WASM_SIMD128_NATIVE) SIMDE_ALIGN_TO_16 v128_t wasm_v128; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned char) altivec_u8; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned short) altivec_u16; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned int) altivec_u32; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed char) altivec_i8; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed short) altivec_i16; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed int) altivec_i32; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(float) altivec_f32; #if defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(unsigned long long) altivec_u64; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(signed long long) altivec_i64; SIMDE_ALIGN_TO_16 SIMDE_POWER_ALTIVEC_VECTOR(double) altivec_f64; #endif #endif } simde__m128_private; #if defined(SIMDE_X86_SSE_NATIVE) typedef __m128 simde__m128; #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) typedef float32x4_t simde__m128; #elif defined(SIMDE_WASM_SIMD128_NATIVE) typedef v128_t simde__m128; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) typedef SIMDE_POWER_ALTIVEC_VECTOR(float) simde__m128; #elif defined(SIMDE_VECTOR_SUBSCRIPT) typedef simde_float32 simde__m128 SIMDE_ALIGN_TO_16 SIMDE_VECTOR(16) SIMDE_MAY_ALIAS; #else typedef simde__m128_private simde__m128; #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) typedef simde__m128 __m128; #endif HEDLEY_STATIC_ASSERT(16 == sizeof(simde__m128), "simde__m128 size incorrect"); HEDLEY_STATIC_ASSERT(16 == sizeof(simde__m128_private), "simde__m128_private size incorrect"); #if defined(SIMDE_CHECK_ALIGNMENT) && defined(SIMDE_ALIGN_OF) HEDLEY_STATIC_ASSERT(SIMDE_ALIGN_OF(simde__m128) == 16, "simde__m128 is not 16-byte aligned"); HEDLEY_STATIC_ASSERT(SIMDE_ALIGN_OF(simde__m128_private) == 16, "simde__m128_private is not 16-byte aligned"); #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde__m128_from_private(simde__m128_private v) { simde__m128 r; simde_memcpy(&r, &v, sizeof(r)); return r; } SIMDE_FUNCTION_ATTRIBUTES simde__m128_private simde__m128_to_private(simde__m128 v) { simde__m128_private r; simde_memcpy(&r, &v, sizeof(r)); return r; } #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int8x16_t, neon, i8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int16x8_t, neon, i16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int32x4_t, neon, i32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, int64x2_t, neon, i64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint8x16_t, neon, u8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint16x8_t, neon, u16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint32x4_t, neon, u32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, uint64x2_t, neon, u64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, float32x4_t, neon, f32) #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, float64x2_t, neon, f64) #endif #endif /* defined(SIMDE_ARM_NEON_A32V7_NATIVE) */ #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed char), altivec, i8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed short), altivec, i16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed int), altivec, i32) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned char), altivec, u8) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned short), altivec, u16) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned int), altivec, u32) #if defined(SIMDE_BUG_GCC_95782) SIMDE_FUNCTION_ATTRIBUTES SIMDE_POWER_ALTIVEC_VECTOR(float) simde__m128_to_altivec_f32(simde__m128 value) { simde__m128_private r_ = simde__m128_to_private(value); return r_.altivec_f32; } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde__m128_from_altivec_f32(SIMDE_POWER_ALTIVEC_VECTOR(float) value) { simde__m128_private r_; r_.altivec_f32 = value; return simde__m128_from_private(r_); } #else SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(float), altivec, f32) #endif #if defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(signed long long), altivec, i64) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, SIMDE_POWER_ALTIVEC_VECTOR(unsigned long long), altivec, u64) #endif #elif defined(SIMDE_WASM_SIMD128_NATIVE) SIMDE_X86_GENERATE_CONVERSION_FUNCTION(m128, v128_t, wasm, v128); #endif /* defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) */ enum { #if defined(SIMDE_X86_SSE_NATIVE) SIMDE_MM_ROUND_NEAREST = _MM_ROUND_NEAREST, SIMDE_MM_ROUND_DOWN = _MM_ROUND_DOWN, SIMDE_MM_ROUND_UP = _MM_ROUND_UP, SIMDE_MM_ROUND_TOWARD_ZERO = _MM_ROUND_TOWARD_ZERO #else SIMDE_MM_ROUND_NEAREST = 0x0000, SIMDE_MM_ROUND_DOWN = 0x2000, SIMDE_MM_ROUND_UP = 0x4000, SIMDE_MM_ROUND_TOWARD_ZERO = 0x6000 #endif }; #if defined(_MM_FROUND_TO_NEAREST_INT) # define SIMDE_MM_FROUND_TO_NEAREST_INT _MM_FROUND_TO_NEAREST_INT # define SIMDE_MM_FROUND_TO_NEG_INF _MM_FROUND_TO_NEG_INF # define SIMDE_MM_FROUND_TO_POS_INF _MM_FROUND_TO_POS_INF # define SIMDE_MM_FROUND_TO_ZERO _MM_FROUND_TO_ZERO # define SIMDE_MM_FROUND_CUR_DIRECTION _MM_FROUND_CUR_DIRECTION # define SIMDE_MM_FROUND_RAISE_EXC _MM_FROUND_RAISE_EXC # define SIMDE_MM_FROUND_NO_EXC _MM_FROUND_NO_EXC #else # define SIMDE_MM_FROUND_TO_NEAREST_INT 0x00 # define SIMDE_MM_FROUND_TO_NEG_INF 0x01 # define SIMDE_MM_FROUND_TO_POS_INF 0x02 # define SIMDE_MM_FROUND_TO_ZERO 0x03 # define SIMDE_MM_FROUND_CUR_DIRECTION 0x04 # define SIMDE_MM_FROUND_RAISE_EXC 0x00 # define SIMDE_MM_FROUND_NO_EXC 0x08 #endif #define SIMDE_MM_FROUND_NINT \ (SIMDE_MM_FROUND_TO_NEAREST_INT | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_FLOOR \ (SIMDE_MM_FROUND_TO_NEG_INF | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_CEIL \ (SIMDE_MM_FROUND_TO_POS_INF | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_TRUNC \ (SIMDE_MM_FROUND_TO_ZERO | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_RINT \ (SIMDE_MM_FROUND_CUR_DIRECTION | SIMDE_MM_FROUND_RAISE_EXC) #define SIMDE_MM_FROUND_NEARBYINT \ (SIMDE_MM_FROUND_CUR_DIRECTION | SIMDE_MM_FROUND_NO_EXC) #if defined(SIMDE_X86_SSE4_1_ENABLE_NATIVE_ALIASES) && !defined(_MM_FROUND_TO_NEAREST_INT) # define _MM_FROUND_TO_NEAREST_INT SIMDE_MM_FROUND_TO_NEAREST_INT # define _MM_FROUND_TO_NEG_INF SIMDE_MM_FROUND_TO_NEG_INF # define _MM_FROUND_TO_POS_INF SIMDE_MM_FROUND_TO_POS_INF # define _MM_FROUND_TO_ZERO SIMDE_MM_FROUND_TO_ZERO # define _MM_FROUND_CUR_DIRECTION SIMDE_MM_FROUND_CUR_DIRECTION # define _MM_FROUND_RAISE_EXC SIMDE_MM_FROUND_RAISE_EXC # define _MM_FROUND_NINT SIMDE_MM_FROUND_NINT # define _MM_FROUND_FLOOR SIMDE_MM_FROUND_FLOOR # define _MM_FROUND_CEIL SIMDE_MM_FROUND_CEIL # define _MM_FROUND_TRUNC SIMDE_MM_FROUND_TRUNC # define _MM_FROUND_RINT SIMDE_MM_FROUND_RINT # define _MM_FROUND_NEARBYINT SIMDE_MM_FROUND_NEARBYINT #endif #if defined(_MM_EXCEPT_INVALID) # define SIMDE_MM_EXCEPT_INVALID _MM_EXCEPT_INVALID #else # define SIMDE_MM_EXCEPT_INVALID (0x0001) #endif #if defined(_MM_EXCEPT_DENORM) # define SIMDE_MM_EXCEPT_DENORM _MM_EXCEPT_DENORM #else # define SIMDE_MM_EXCEPT_DENORM (0x0002) #endif #if defined(_MM_EXCEPT_DIV_ZERO) # define SIMDE_MM_EXCEPT_DIV_ZERO _MM_EXCEPT_DIV_ZERO #else # define SIMDE_MM_EXCEPT_DIV_ZERO (0x0004) #endif #if defined(_MM_EXCEPT_OVERFLOW) # define SIMDE_MM_EXCEPT_OVERFLOW _MM_EXCEPT_OVERFLOW #else # define SIMDE_MM_EXCEPT_OVERFLOW (0x0008) #endif #if defined(_MM_EXCEPT_UNDERFLOW) # define SIMDE_MM_EXCEPT_UNDERFLOW _MM_EXCEPT_UNDERFLOW #else # define SIMDE_MM_EXCEPT_UNDERFLOW (0x0010) #endif #if defined(_MM_EXCEPT_INEXACT) # define SIMDE_MM_EXCEPT_INEXACT _MM_EXCEPT_INEXACT #else # define SIMDE_MM_EXCEPT_INEXACT (0x0020) #endif #if defined(_MM_EXCEPT_MASK) # define SIMDE_MM_EXCEPT_MASK _MM_EXCEPT_MASK #else # define SIMDE_MM_EXCEPT_MASK \ (SIMDE_MM_EXCEPT_INVALID | SIMDE_MM_EXCEPT_DENORM | \ SIMDE_MM_EXCEPT_DIV_ZERO | SIMDE_MM_EXCEPT_OVERFLOW | \ SIMDE_MM_EXCEPT_UNDERFLOW | SIMDE_MM_EXCEPT_INEXACT) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_EXCEPT_INVALID SIMDE_MM_EXCEPT_INVALID #define _MM_EXCEPT_DENORM SIMDE_MM_EXCEPT_DENORM #define _MM_EXCEPT_DIV_ZERO SIMDE_MM_EXCEPT_DIV_ZERO #define _MM_EXCEPT_OVERFLOW SIMDE_MM_EXCEPT_OVERFLOW #define _MM_EXCEPT_UNDERFLOW SIMDE_MM_EXCEPT_UNDERFLOW #define _MM_EXCEPT_INEXACT SIMDE_MM_EXCEPT_INEXACT #define _MM_EXCEPT_MASK SIMDE_MM_EXCEPT_MASK #endif #if defined(_MM_MASK_INVALID) # define SIMDE_MM_MASK_INVALID _MM_MASK_INVALID #else # define SIMDE_MM_MASK_INVALID (0x0080) #endif #if defined(_MM_MASK_DENORM) # define SIMDE_MM_MASK_DENORM _MM_MASK_DENORM #else # define SIMDE_MM_MASK_DENORM (0x0100) #endif #if defined(_MM_MASK_DIV_ZERO) # define SIMDE_MM_MASK_DIV_ZERO _MM_MASK_DIV_ZERO #else # define SIMDE_MM_MASK_DIV_ZERO (0x0200) #endif #if defined(_MM_MASK_OVERFLOW) # define SIMDE_MM_MASK_OVERFLOW _MM_MASK_OVERFLOW #else # define SIMDE_MM_MASK_OVERFLOW (0x0400) #endif #if defined(_MM_MASK_UNDERFLOW) # define SIMDE_MM_MASK_UNDERFLOW _MM_MASK_UNDERFLOW #else # define SIMDE_MM_MASK_UNDERFLOW (0x0800) #endif #if defined(_MM_MASK_INEXACT) # define SIMDE_MM_MASK_INEXACT _MM_MASK_INEXACT #else # define SIMDE_MM_MASK_INEXACT (0x1000) #endif #if defined(_MM_MASK_MASK) # define SIMDE_MM_MASK_MASK _MM_MASK_MASK #else # define SIMDE_MM_MASK_MASK \ (SIMDE_MM_MASK_INVALID | SIMDE_MM_MASK_DENORM | \ SIMDE_MM_MASK_DIV_ZERO | SIMDE_MM_MASK_OVERFLOW | \ SIMDE_MM_MASK_UNDERFLOW | SIMDE_MM_MASK_INEXACT) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_MASK_INVALID SIMDE_MM_MASK_INVALID #define _MM_MASK_DENORM SIMDE_MM_MASK_DENORM #define _MM_MASK_DIV_ZERO SIMDE_MM_MASK_DIV_ZERO #define _MM_MASK_OVERFLOW SIMDE_MM_MASK_OVERFLOW #define _MM_MASK_UNDERFLOW SIMDE_MM_MASK_UNDERFLOW #define _MM_MASK_INEXACT SIMDE_MM_MASK_INEXACT #define _MM_MASK_MASK SIMDE_MM_MASK_MASK #endif #if defined(_MM_FLUSH_ZERO_MASK) # define SIMDE_MM_FLUSH_ZERO_MASK _MM_FLUSH_ZERO_MASK #else # define SIMDE_MM_FLUSH_ZERO_MASK (0x8000) #endif #if defined(_MM_FLUSH_ZERO_ON) # define SIMDE_MM_FLUSH_ZERO_ON _MM_FLUSH_ZERO_ON #else # define SIMDE_MM_FLUSH_ZERO_ON (0x8000) #endif #if defined(_MM_FLUSH_ZERO_OFF) # define SIMDE_MM_FLUSH_ZERO_OFF _MM_FLUSH_ZERO_OFF #else # define SIMDE_MM_FLUSH_ZERO_OFF (0x0000) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_FLUSH_ZERO_MASK SIMDE_MM_FLUSH_ZERO_MASK #define _MM_FLUSH_ZERO_ON SIMDE_MM_FLUSH_ZERO_ON #define _MM_FLUSH_ZERO_OFF SIMDE_MM_FLUSH_ZERO_OFF #endif SIMDE_FUNCTION_ATTRIBUTES unsigned int SIMDE_MM_GET_ROUNDING_MODE(void) { #if defined(SIMDE_X86_SSE_NATIVE) return _MM_GET_ROUNDING_MODE(); #elif defined(SIMDE_HAVE_FENV_H) unsigned int vfe_mode; switch (fegetround()) { #if defined(FE_TONEAREST) case FE_TONEAREST: vfe_mode = SIMDE_MM_ROUND_NEAREST; break; #endif #if defined(FE_TOWARDZERO) case FE_TOWARDZERO: vfe_mode = SIMDE_MM_ROUND_DOWN; break; #endif #if defined(FE_UPWARD) case FE_UPWARD: vfe_mode = SIMDE_MM_ROUND_UP; break; #endif #if defined(FE_DOWNWARD) case FE_DOWNWARD: vfe_mode = SIMDE_MM_ROUND_TOWARD_ZERO; break; #endif default: vfe_mode = SIMDE_MM_ROUND_NEAREST; break; } return vfe_mode; #else return SIMDE_MM_ROUND_NEAREST; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_GET_ROUNDING_MODE() SIMDE_MM_GET_ROUNDING_MODE() #endif SIMDE_FUNCTION_ATTRIBUTES void SIMDE_MM_SET_ROUNDING_MODE(unsigned int a) { #if defined(SIMDE_X86_SSE_NATIVE) _MM_SET_ROUNDING_MODE(a); #elif defined(SIMDE_HAVE_FENV_H) int fe_mode = FE_TONEAREST; switch (a) { #if defined(FE_TONEAREST) case SIMDE_MM_ROUND_NEAREST: fe_mode = FE_TONEAREST; break; #endif #if defined(FE_TOWARDZERO) case SIMDE_MM_ROUND_TOWARD_ZERO: fe_mode = FE_TOWARDZERO; break; #endif #if defined(FE_DOWNWARD) case SIMDE_MM_ROUND_DOWN: fe_mode = FE_DOWNWARD; break; #endif #if defined(FE_UPWARD) case SIMDE_MM_ROUND_UP: fe_mode = FE_UPWARD; break; #endif default: return; } fesetround(fe_mode); #else (void) a; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_SET_ROUNDING_MODE(a) SIMDE_MM_SET_ROUNDING_MODE(a) #endif SIMDE_FUNCTION_ATTRIBUTES uint32_t SIMDE_MM_GET_FLUSH_ZERO_MODE (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_getcsr() & _MM_FLUSH_ZERO_MASK; #else return SIMDE_MM_FLUSH_ZERO_OFF; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_SET_FLUSH_ZERO_MODE(a) SIMDE_MM_SET_FLUSH_ZERO_MODE(a) #endif SIMDE_FUNCTION_ATTRIBUTES void SIMDE_MM_SET_FLUSH_ZERO_MODE (uint32_t a) { #if defined(SIMDE_X86_SSE_NATIVE) _MM_SET_FLUSH_ZERO_MODE(a); #else (void) a; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _MM_SET_FLUSH_ZERO_MODE(a) SIMDE_MM_SET_FLUSH_ZERO_MODE(a) #endif SIMDE_FUNCTION_ATTRIBUTES uint32_t simde_mm_getcsr (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_getcsr(); #else return SIMDE_MM_GET_ROUNDING_MODE(); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_getcsr() simde_mm_getcsr() #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_setcsr (uint32_t a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_setcsr(a); #else SIMDE_MM_SET_ROUNDING_MODE(HEDLEY_STATIC_CAST(unsigned int, a)); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_setcsr(a) simde_mm_setcsr(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_round_ps (simde__m128 a, int rounding, int lax_rounding) SIMDE_REQUIRE_CONSTANT_RANGE(rounding, 0, 15) SIMDE_REQUIRE_CONSTANT_RANGE(lax_rounding, 0, 1) { simde__m128_private r_, a_ = simde__m128_to_private(a); (void) lax_rounding; /* For architectures which lack a current direction SIMD instruction. * * Note that NEON actually has a current rounding mode instruction, * but in ARMv8+ the rounding mode is ignored and nearest is always * used, so we treat ARMv7 as having a rounding mode but ARMv8 as * not. */ #if \ defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || \ defined(SIMDE_ARM_NEON_A32V8) if ((rounding & 7) == SIMDE_MM_FROUND_CUR_DIRECTION) rounding = HEDLEY_STATIC_CAST(int, SIMDE_MM_GET_ROUNDING_MODE()) << 13; #endif switch (rounding & ~SIMDE_MM_FROUND_NO_EXC) { case SIMDE_MM_FROUND_CUR_DIRECTION: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_round(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_f32 = vrndiq_f32(a_.neon_f32); #elif defined(simde_math_nearbyintf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_nearbyintf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_NEAREST_INT: #if defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_rint(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndnq_f32(a_.neon_f32); #elif defined(simde_math_roundevenf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_roundevenf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_NEG_INF: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_floor(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndmq_f32(a_.neon_f32); #elif defined(simde_math_floorf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_floorf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_POS_INF: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_ceil(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndpq_f32(a_.neon_f32); #elif defined(simde_math_ceilf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_ceilf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; case SIMDE_MM_FROUND_TO_ZERO: #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_trunc(a_.altivec_f32)); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) r_.neon_f32 = vrndq_f32(a_.neon_f32); #elif defined(simde_math_truncf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_truncf(a_.f32[i]); } #else HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); #endif break; default: HEDLEY_UNREACHABLE_RETURN(simde_mm_undefined_pd()); } return simde__m128_from_private(r_); } #if defined(SIMDE_X86_SSE4_1_NATIVE) #define simde_mm_round_ps(a, rounding) _mm_round_ps((a), (rounding)) #else #define simde_mm_round_ps(a, rounding) simde_x_mm_round_ps((a), (rounding), 0) #endif #if defined(SIMDE_X86_SSE4_1_ENABLE_NATIVE_ALIASES) #define _mm_round_ps(a, rounding) simde_mm_round_ps((a), (rounding)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ps (simde_float32 e3, simde_float32 e2, simde_float32 e1, simde_float32 e0) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ps(e3, e2, e1, e0); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) SIMDE_ALIGN_TO_16 simde_float32 data[4] = { e0, e1, e2, e3 }; r_.neon_f32 = vld1q_f32(data); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_make(e0, e1, e2, e3); #else r_.f32[0] = e0; r_.f32[1] = e1; r_.f32[2] = e2; r_.f32[3] = e3; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ps(e3, e2, e1, e0) simde_mm_set_ps(e3, e2, e1, e0) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ps1 (simde_float32 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ps1(a); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vdupq_n_f32(a); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) (void) a; return vec_splats(a); #else return simde_mm_set_ps(a, a, a, a); #endif } #define simde_mm_set1_ps(a) simde_mm_set_ps1(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ps1(a) simde_mm_set_ps1(a) # define _mm_set1_ps(a) simde_mm_set1_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_move_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_move_ss(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(vgetq_lane_f32(b_.neon_f32, 0), a_.neon_f32, 0); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) SIMDE_POWER_ALTIVEC_VECTOR(unsigned char) m = { 16, 17, 18, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; r_.altivec_f32 = vec_perm(a_.altivec_f32, b_.altivec_f32, m); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_i8x16_shuffle(b_.wasm_v128, a_.wasm_v128, 0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 4, 1, 2, 3); #else r_.f32[0] = b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_move_ss(a, b) simde_mm_move_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_add_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_add_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vaddq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_add(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_add(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 + b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] + b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_add_ps(a, b) simde_mm_add_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_add_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_add_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_add_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t b0 = vgetq_lane_f32(b_.neon_f32, 0); float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); // the upper values in the result must be the remnants of <a>. r_.neon_f32 = vaddq_f32(a_.neon_f32, value); #else r_.f32[0] = a_.f32[0] + b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_add_ss(a, b) simde_mm_add_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_and_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_and_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vandq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_and(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = a_.i32 & b_.i32; #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_and(a_.altivec_f32, b_.altivec_f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = a_.i32[i] & b_.i32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_and_ps(a, b) simde_mm_and_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_andnot_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_andnot_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vbicq_s32(b_.neon_i32, a_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_andnot(b_.wasm_v128, a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = vec_andc(b_.altivec_f32, a_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = ~a_.i32 & b_.i32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = ~(a_.i32[i]) & b_.i32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_andnot_ps(a, b) simde_mm_andnot_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_xor_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_xor_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = veorq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_xor(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_xor(a_.altivec_i32, b_.altivec_i32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32f = a_.i32f ^ b_.i32f; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i] ^ b_.u32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_xor_ps(a, b) simde_mm_xor_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_or_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_or_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vorrq_s32(a_.neon_i32, b_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_or(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_or(a_.altivec_i32, b_.altivec_i32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32f = a_.i32f | b_.i32f; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i] | b_.u32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_or_ps(a, b) simde_mm_or_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_not_ps(simde__m128 a) { #if defined(SIMDE_X86_AVX512VL_NATIVE) __m128i ai = _mm_castps_si128(a); return _mm_castsi128_ps(_mm_ternarylogic_epi32(ai, ai, ai, 0x55)); #elif defined(SIMDE_X86_SSE2_NATIVE) /* Note: we use ints instead of floats because we don't want cmpeq * to return false for (NaN, NaN) */ __m128i ai = _mm_castps_si128(a); return _mm_castsi128_ps(_mm_andnot_si128(ai, _mm_cmpeq_epi32(ai, ai))); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vmvnq_s32(a_.neon_i32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_i32 = vec_nor(a_.altivec_i32, a_.altivec_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_not(a_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = ~a_.i32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = ~(a_.i32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_select_ps(simde__m128 a, simde__m128 b, simde__m128 mask) { /* This function is for when you want to blend two elements together * according to a mask. It is similar to _mm_blendv_ps, except that * it is undefined whether the blend is based on the highest bit in * each lane (like blendv) or just bitwise operations. This allows * us to implement the function efficiently everywhere. * * Basically, you promise that all the lanes in mask are either 0 or * ~0. */ #if defined(SIMDE_X86_SSE4_1_NATIVE) return _mm_blendv_ps(a, b, mask); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b), mask_ = simde__m128_to_private(mask); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i32 = vbslq_s32(mask_.neon_u32, b_.neon_i32, a_.neon_i32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_bitselect(b_.wasm_v128, a_.wasm_v128, mask_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) r_.altivec_i32 = vec_sel(a_.altivec_i32, b_.altivec_i32, mask_.altivec_u32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = a_.i32 ^ ((a_.i32 ^ b_.i32) & mask_.i32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = a_.i32[i] ^ ((a_.i32[i] ^ b_.i32[i]) & mask_.i32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_avg_pu16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_avg_pu16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u16 = vrhadd_u16(b_.neon_u16, a_.neon_u16); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) && defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) && defined(SIMDE_CONVERT_VECTOR_) uint32_t wa SIMDE_VECTOR(16); uint32_t wb SIMDE_VECTOR(16); uint32_t wr SIMDE_VECTOR(16); SIMDE_CONVERT_VECTOR_(wa, a_.u16); SIMDE_CONVERT_VECTOR_(wb, b_.u16); wr = (wa + wb + 1) >> 1; SIMDE_CONVERT_VECTOR_(r_.u16, wr); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u16) / sizeof(r_.u16[0])) ; i++) { r_.u16[i] = (a_.u16[i] + b_.u16[i] + 1) >> 1; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pavgw(a, b) simde_mm_avg_pu16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_avg_pu16(a, b) simde_mm_avg_pu16(a, b) # define _m_pavgw(a, b) simde_mm_avg_pu16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_avg_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_avg_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vrhadd_u8(b_.neon_u8, a_.neon_u8); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) && defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) && defined(SIMDE_CONVERT_VECTOR_) uint16_t wa SIMDE_VECTOR(16); uint16_t wb SIMDE_VECTOR(16); uint16_t wr SIMDE_VECTOR(16); SIMDE_CONVERT_VECTOR_(wa, a_.u8); SIMDE_CONVERT_VECTOR_(wb, b_.u8); wr = (wa + wb + 1) >> 1; SIMDE_CONVERT_VECTOR_(r_.u8, wr); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] + b_.u8[i] + 1) >> 1; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pavgb(a, b) simde_mm_avg_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_avg_pu8(a, b) simde_mm_avg_pu8(a, b) # define _m_pavgb(a, b) simde_mm_avg_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_abs_ps(simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) simde_float32 mask_; uint32_t u32_ = UINT32_C(0x7FFFFFFF); simde_memcpy(&mask_, &u32_, sizeof(u32_)); return _mm_and_ps(_mm_set1_ps(mask_), a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vabsq_f32(a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = vec_abs(a_.altivec_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_abs(a_.wasm_v128); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_fabsf(a_.f32[i]); } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpeq_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpeq_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vceqq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_eq(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpeq(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), a_.f32 == b_.f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] == b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpeq_ps(a, b) simde_mm_cmpeq_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpeq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpeq_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpeq_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] == b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpeq_ss(a, b) simde_mm_cmpeq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpge_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpge_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcgeq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_ge(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpge(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 >= b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] >= b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpge_ps(a, b) simde_mm_cmpge_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpge_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpge_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpge_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] >= b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpge_ss(a, b) simde_mm_cmpge_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpgt_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpgt_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcgtq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_gt(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpgt(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 > b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] > b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpgt_ps(a, b) simde_mm_cmpgt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpgt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpgt_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpgt_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] > b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpgt_ss(a, b) simde_mm_cmpgt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmple_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmple_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcleq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_le(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmple(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 <= b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] <= b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmple_ps(a, b) simde_mm_cmple_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmple_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmple_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmple_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] <= b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmple_ss(a, b) simde_mm_cmple_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmplt_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmplt_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vcltq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_lt(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmplt(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 < b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] < b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmplt_ps(a, b) simde_mm_cmplt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmplt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmplt_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmplt_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] < b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmplt_ss(a, b) simde_mm_cmplt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpneq_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpneq_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u32 = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_ne(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P9_NATIVE) && SIMDE_ARCH_POWER_CHECK(900) && !defined(HEDLEY_IBM_VERSION) /* vec_cmpne(SIMDE_POWER_ALTIVEC_VECTOR(float), SIMDE_POWER_ALTIVEC_VECTOR(float)) is missing from XL C/C++ v16.1.1, though the documentation (table 89 on page 432 of the IBM XL C/C++ for Linux Compiler Reference, Version 16.1.1) shows that it should be present. Both GCC and clang support it. */ r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpne(a_.altivec_f32, b_.altivec_f32)); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_cmpeq(a_.altivec_f32, b_.altivec_f32)); r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_nor(r_.altivec_f32, r_.altivec_f32)); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.i32 = HEDLEY_STATIC_CAST(__typeof__(r_.i32), (a_.f32 != b_.f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (a_.f32[i] != b_.f32[i]) ? ~UINT32_C(0) : UINT32_C(0); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpneq_ps(a, b) simde_mm_cmpneq_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpneq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpneq_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpneq_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.u32[0] = (a_.f32[0] != b_.f32[0]) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpneq_ss(a, b) simde_mm_cmpneq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnge_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmplt_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnge_ps(a, b) simde_mm_cmpnge_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnge_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmplt_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnge_ss(a, b) simde_mm_cmpnge_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpngt_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmple_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpngt_ps(a, b) simde_mm_cmpngt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpngt_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmple_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpngt_ss(a, b) simde_mm_cmpngt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnle_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmpgt_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnle_ps(a, b) simde_mm_cmpnle_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnle_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmpgt_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnle_ss(a, b) simde_mm_cmpnle_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnlt_ps (simde__m128 a, simde__m128 b) { return simde_mm_cmpge_ps(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnlt_ps(a, b) simde_mm_cmpnlt_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpnlt_ss (simde__m128 a, simde__m128 b) { return simde_mm_cmpge_ss(a, b); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpnlt_ss(a, b) simde_mm_cmpnlt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpord_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpord_ps(a, b); #elif defined(SIMDE_WASM_SIMD128_NATIVE) return wasm_v128_and(wasm_f32x4_eq(a, a), wasm_f32x4_eq(b, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) /* Note: NEON does not have ordered compare builtin Need to compare a eq a and b eq b to check for NaN Do AND of results to get final */ uint32x4_t ceqaa = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t ceqbb = vceqq_f32(b_.neon_f32, b_.neon_f32); r_.neon_u32 = vandq_u32(ceqaa, ceqbb); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_and(wasm_f32x4_eq(a_.wasm_v128, a_.wasm_v128), wasm_f32x4_eq(b_.wasm_v128, b_.wasm_v128)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_and(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); #elif defined(simde_math_isnanf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (simde_math_isnanf(a_.f32[i]) || simde_math_isnanf(b_.f32[i])) ? UINT32_C(0) : ~UINT32_C(0); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpord_ps(a, b) simde_mm_cmpord_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpunord_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpunord_ps(a, b); #elif defined(SIMDE_WASM_SIMD128_NATIVE) return wasm_v128_or(wasm_f32x4_ne(a, a), wasm_f32x4_ne(b, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t ceqaa = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t ceqbb = vceqq_f32(b_.neon_f32, b_.neon_f32); r_.neon_u32 = vmvnq_u32(vandq_u32(ceqaa, ceqbb)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_or(wasm_f32x4_ne(a_.wasm_v128, a_.wasm_v128), wasm_f32x4_ne(b_.wasm_v128, b_.wasm_v128)); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_nand(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_and(vec_cmpeq(a_.altivec_f32, a_.altivec_f32), vec_cmpeq(b_.altivec_f32, b_.altivec_f32))); r_.altivec_f32 = vec_nor(r_.altivec_f32, r_.altivec_f32); #elif defined(simde_math_isnanf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = (simde_math_isnanf(a_.f32[i]) || simde_math_isnanf(b_.f32[i])) ? ~UINT32_C(0) : UINT32_C(0); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpunord_ps(a, b) simde_mm_cmpunord_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpunord_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) return _mm_cmpunord_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpunord_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(simde_math_isnanf) r_.u32[0] = (simde_math_isnanf(a_.f32[0]) || simde_math_isnanf(b_.f32[0])) ? ~UINT32_C(0) : UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.u32) / sizeof(r_.u32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpunord_ss(a, b) simde_mm_cmpunord_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comieq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comieq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_eq_b = vceqq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0); #else return a_.f32[0] == b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comieq_ss(a, b) simde_mm_comieq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comige_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comige_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_ge_b = vcgeq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0); #else return a_.f32[0] >= b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comige_ss(a, b) simde_mm_comige_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comigt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comigt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_gt_b = vcgtq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0); #else return a_.f32[0] > b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comigt_ss(a, b) simde_mm_comigt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comile_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comile_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_le_b = vcleq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0); #else return a_.f32[0] <= b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comile_ss(a, b) simde_mm_comile_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comilt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comilt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_lt_b = vcltq_f32(a_.neon_f32, b_.neon_f32); return !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0); #else return a_.f32[0] < b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comilt_ss(a, b) simde_mm_comilt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_comineq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_comineq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); return !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0); #else return a_.f32[0] != b_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_comineq_ss(a, b) simde_mm_comineq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_copysign_ps(simde__m128 dest, simde__m128 src) { simde__m128_private r_, dest_ = simde__m128_to_private(dest), src_ = simde__m128_to_private(src); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) const uint32x4_t sign_pos = vreinterpretq_u32_f32(vdupq_n_f32(-SIMDE_FLOAT32_C(0.0))); r_.neon_u32 = vbslq_u32(sign_pos, src_.neon_u32, dest_.neon_u32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) const v128_t sign_pos = wasm_f32x4_splat(-0.0f); r_.wasm_v128 = wasm_v128_bitselect(src_.wasm_v128, dest_.wasm_v128, sign_pos); #elif defined(SIMDE_POWER_ALTIVEC_P9_NATIVE) #if !defined(HEDLEY_IBM_VERSION) r_.altivec_f32 = vec_cpsgn(dest_.altivec_f32, src_.altivec_f32); #else r_.altivec_f32 = vec_cpsgn(src_.altivec_f32, dest_.altivec_f32); #endif #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) const SIMDE_POWER_ALTIVEC_VECTOR(unsigned int) sign_pos = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(unsigned int), vec_splats(-0.0f)); r_.altivec_f32 = vec_sel(dest_.altivec_f32, src_.altivec_f32, sign_pos); #elif defined(SIMDE_IEEE754_STORAGE) (void) src_; (void) dest_; simde__m128 sign_pos = simde_mm_set1_ps(-0.0f); r_ = simde__m128_to_private(simde_mm_xor_ps(dest, simde_mm_and_ps(simde_mm_xor_ps(dest, src), sign_pos))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = simde_math_copysignf(dest_.f32[i], src_.f32[i]); } #endif return simde__m128_from_private(r_); } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_xorsign_ps(simde__m128 dest, simde__m128 src) { return simde_mm_xor_ps(simde_mm_and_ps(simde_mm_set1_ps(-0.0f), src), dest); } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvt_pi2ps (simde__m128 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvt_pi2ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); simde__m64_private b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vcvt_f32_s32(b_.neon_i32), vget_high_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, b_.i32); r_.m64_private[1] = a_.m64_private[1]; #else r_.f32[0] = (simde_float32) b_.i32[0]; r_.f32[1] = (simde_float32) b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_pi2ps(a, b) simde_mm_cvt_pi2ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvt_ps2pi (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvt_ps2pi(a); #else simde__m64_private r_; simde__m128_private a_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); r_.neon_i32 = vcvt_s32_f32(vget_low_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) && SIMDE_NATURAL_VECTOR_SIZE_GE(128) a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); SIMDE_CONVERT_VECTOR_(r_.i32, a_.m64_private[0].f32); #else a_ = simde__m128_to_private(a); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { r_.i32[i] = HEDLEY_STATIC_CAST(int32_t, simde_math_nearbyintf(a_.f32[i])); } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_ps2pi(a) simde_mm_cvt_ps2pi((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvt_si2ss (simde__m128 a, int32_t b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvt_si2ss(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float, b), a_.neon_f32, 0); #else r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); r_.i32[1] = a_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_si2ss(a, b) simde_mm_cvt_si2ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvt_ss2si (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvt_ss2si(a); #elif defined(SIMDE_ARM_NEON_A32V8_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) && !defined(SIMDE_BUG_GCC_95399) return vgetq_lane_s32(vcvtnq_s32_f32(simde__m128_to_neon_f32(a)), 0); #else simde__m128_private a_ = simde__m128_to_private(simde_mm_round_ps(a, SIMDE_MM_FROUND_CUR_DIRECTION)); #if !defined(SIMDE_FAST_CONVERSION_RANGE) return ((a_.f32[0] > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (a_.f32[0] < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, a_.f32[0]) : INT32_MIN; #else return SIMDE_CONVERT_FTOI(int32_t, a_.f32[0]); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvt_ss2si(a) simde_mm_cvt_ss2si((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi16_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi16_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vmovl_s16(a_.neon_i16)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.f32, a_.i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { simde_float32 v = a_.i16[i]; r_.f32[i] = v; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi16_ps(a) simde_mm_cvtpi16_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi32_ps (simde__m128 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi32_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a); simde__m64_private b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vcvt_f32_s32(b_.neon_i32), vget_high_f32(a_.neon_f32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, b_.i32); r_.m64_private[1] = a_.m64_private[1]; #else r_.f32[0] = (simde_float32) b_.i32[0]; r_.f32[1] = (simde_float32) b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi32_ps(a, b) simde_mm_cvtpi32_ps((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi32x2_ps (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi32x2_ps(a, b); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vcombine_s32(a_.neon_i32, b_.neon_i32)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.m64_private[0].f32, a_.i32); SIMDE_CONVERT_VECTOR_(r_.m64_private[1].f32, b_.i32); #else r_.f32[0] = (simde_float32) a_.i32[0]; r_.f32[1] = (simde_float32) a_.i32[1]; r_.f32[2] = (simde_float32) b_.i32[0]; r_.f32[3] = (simde_float32) b_.i32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi32x2_ps(a, b) simde_mm_cvtpi32x2_ps(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpi8_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpi8_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_s32(vmovl_s16(vget_low_s16(vmovl_s8(a_.neon_i8)))); #else r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[0]); r_.f32[1] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[1]); r_.f32[2] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[2]); r_.f32[3] = HEDLEY_STATIC_CAST(simde_float32, a_.i8[3]); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpi8_ps(a) simde_mm_cvtpi8_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi16 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi16(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_i16 = vmovn_s32(vcvtq_s32_f32(vrndiq_f32(a_.neon_f32))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = SIMDE_CONVERT_FTOI(int16_t, simde_math_roundf(a_.f32[i])); } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi16(a) simde_mm_cvtps_pi16((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi32 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi32(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) && !defined(SIMDE_BUG_GCC_95399) r_.neon_i32 = vcvt_s32_f32(vget_low_f32(vrndiq_f32(a_.neon_f32))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i32) / sizeof(r_.i32[0])) ; i++) { simde_float32 v = simde_math_roundf(a_.f32[i]); #if !defined(SIMDE_FAST_CONVERSION_RANGE) r_.i32[i] = ((v > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (v < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, v) : INT32_MIN; #else r_.i32[i] = SIMDE_CONVERT_FTOI(int32_t, v); #endif } #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi32(a) simde_mm_cvtps_pi32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtps_pi8 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtps_pi8(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V8_NATIVE) && !defined(SIMDE_BUG_GCC_95471) /* Clamp the input to [INT8_MIN, INT8_MAX], round, convert to i32, narrow to * i16, combine with an all-zero vector of i16 (which will become the upper * half), narrow to i8. */ float32x4_t max = vdupq_n_f32(HEDLEY_STATIC_CAST(simde_float32, INT8_MAX)); float32x4_t min = vdupq_n_f32(HEDLEY_STATIC_CAST(simde_float32, INT8_MIN)); float32x4_t values = vrndnq_f32(vmaxq_f32(vminq_f32(max, a_.neon_f32), min)); r_.neon_i8 = vmovn_s16(vcombine_s16(vmovn_s32(vcvtq_s32_f32(values)), vdup_n_s16(0))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(a_.f32) / sizeof(a_.f32[0])) ; i++) { if (a_.f32[i] > HEDLEY_STATIC_CAST(simde_float32, INT8_MAX)) r_.i8[i] = INT8_MAX; else if (a_.f32[i] < HEDLEY_STATIC_CAST(simde_float32, INT8_MIN)) r_.i8[i] = INT8_MIN; else r_.i8[i] = SIMDE_CONVERT_FTOI(int8_t, simde_math_roundf(a_.f32[i])); } /* Note: the upper half is undefined */ #endif return simde__m64_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtps_pi8(a) simde_mm_cvtps_pi8((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpu16_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpu16_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_u32(vmovl_u16(a_.neon_u16)); #elif defined(SIMDE_CONVERT_VECTOR_) SIMDE_CONVERT_VECTOR_(r_.f32, a_.u16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (simde_float32) a_.u16[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpu16_ps(a) simde_mm_cvtpu16_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtpu8_ps (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtpu8_ps(a); #else simde__m128_private r_; simde__m64_private a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcvtq_f32_u32(vmovl_u16(vget_low_u16(vmovl_u8(a_.neon_u8)))); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = HEDLEY_STATIC_CAST(simde_float32, a_.u8[i]); } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtpu8_ps(a) simde_mm_cvtpu8_ps(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtsi32_ss (simde__m128 a, int32_t b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtsi32_ss(a, b); #else simde__m128_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float32_t, b), a_.neon_f32, 0); #else r_ = a_; r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtsi32_ss(a, b) simde_mm_cvtsi32_ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cvtsi64_ss (simde__m128 a, int64_t b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) #if !defined(__PGI) return _mm_cvtsi64_ss(a, b); #else return _mm_cvtsi64x_ss(a, b); #endif #else simde__m128_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(HEDLEY_STATIC_CAST(float32_t, b), a_.neon_f32, 0); #else r_ = a_; r_.f32[0] = HEDLEY_STATIC_CAST(simde_float32, b); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) || (defined(SIMDE_ENABLE_NATIVE_ALIASES) && !defined(SIMDE_ARCH_AMD64)) # define _mm_cvtsi64_ss(a, b) simde_mm_cvtsi64_ss((a), b) #endif SIMDE_FUNCTION_ATTRIBUTES simde_float32 simde_mm_cvtss_f32 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtss_f32(a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vgetq_lane_f32(a_.neon_f32, 0); #else return a_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_f32(a) simde_mm_cvtss_f32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvtss_si32 (simde__m128 a) { return simde_mm_cvt_ss2si(a); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtss_si32(a) simde_mm_cvtss_si32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int64_t simde_mm_cvtss_si64 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) #if !defined(__PGI) return _mm_cvtss_si64(a); #else return _mm_cvtss_si64x(a); #endif #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return SIMDE_CONVERT_FTOI(int64_t, simde_math_roundf(vgetq_lane_f32(a_.neon_f32, 0))); #else return SIMDE_CONVERT_FTOI(int64_t, simde_math_roundf(a_.f32[0])); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) || (defined(SIMDE_ENABLE_NATIVE_ALIASES) && !defined(SIMDE_ARCH_AMD64)) # define _mm_cvtss_si64(a) simde_mm_cvtss_si64((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_cvtt_ps2pi (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_cvtt_ps2pi(a); #else simde__m64_private r_; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) r_.neon_i32 = vcvt_s32_f32(vget_low_f32(a_.neon_f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { simde_float32 v = a_.f32[i]; #if !defined(SIMDE_FAST_CONVERSION_RANGE) r_.i32[i] = ((v > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (v < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, v) : INT32_MIN; #else r_.i32[i] = SIMDE_CONVERT_FTOI(int32_t, v); #endif } #endif return simde__m64_from_private(r_); #endif } #define simde_mm_cvttps_pi32(a) simde_mm_cvtt_ps2pi(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtt_ps2pi(a) simde_mm_cvtt_ps2pi((a)) # define _mm_cvttps_pi32(a) simde_mm_cvttps_pi32((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int32_t simde_mm_cvtt_ss2si (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cvtt_ss2si(a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) && defined(SIMDE_FAST_CONVERSION_RANGE) return SIMDE_CONVERT_FTOI(int32_t, vgetq_lane_f32(a_.neon_f32, 0)); #else simde_float32 v = a_.f32[0]; #if !defined(SIMDE_FAST_CONVERSION_RANGE) return ((v > HEDLEY_STATIC_CAST(simde_float32, INT32_MIN)) && (v < HEDLEY_STATIC_CAST(simde_float32, INT32_MAX))) ? SIMDE_CONVERT_FTOI(int32_t, v) : INT32_MIN; #else return SIMDE_CONVERT_FTOI(int32_t, v); #endif #endif #endif } #define simde_mm_cvttss_si32(a) simde_mm_cvtt_ss2si((a)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cvtt_ss2si(a) simde_mm_cvtt_ss2si((a)) # define _mm_cvttss_si32(a) simde_mm_cvtt_ss2si((a)) #endif SIMDE_FUNCTION_ATTRIBUTES int64_t simde_mm_cvttss_si64 (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_ARCH_AMD64) && !defined(_MSC_VER) #if defined(__PGI) return _mm_cvttss_si64x(a); #else return _mm_cvttss_si64(a); #endif #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) return SIMDE_CONVERT_FTOI(int64_t, vgetq_lane_f32(a_.neon_f32, 0)); #else return SIMDE_CONVERT_FTOI(int64_t, a_.f32[0]); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) || (defined(SIMDE_ENABLE_NATIVE_ALIASES) && !defined(SIMDE_ARCH_AMD64)) # define _mm_cvttss_si64(a) simde_mm_cvttss_si64((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_cmpord_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_cmpord_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_cmpord_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(simde_math_isnanf) r_.u32[0] = (simde_math_isnanf(simde_mm_cvtss_f32(a)) || simde_math_isnanf(simde_mm_cvtss_f32(b))) ? UINT32_C(0) : ~UINT32_C(0); SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.u32[i] = a_.u32[i]; } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_cmpord_ss(a, b) simde_mm_cmpord_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_div_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_div_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vdivq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t recip0 = vrecpeq_f32(b_.neon_f32); float32x4_t recip1 = vmulq_f32(recip0, vrecpsq_f32(recip0, b_.neon_f32)); r_.neon_f32 = vmulq_f32(a_.neon_f32, recip1); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_div(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_div(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 / b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] / b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_div_ps(a, b) simde_mm_div_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_div_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_div_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_div_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(simde__m128_to_private(simde_mm_div_ps(a, b)).neon_f32, 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = a_.f32[0] / b_.f32[0]; SIMDE_VECTORIZE for (size_t i = 1 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_div_ss(a, b) simde_mm_div_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int16_t simde_mm_extract_pi16 (simde__m64 a, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 3) { simde__m64_private a_ = simde__m64_to_private(a); return a_.i16[imm8]; } #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(HEDLEY_PGI_VERSION) # if defined(SIMDE_BUG_CLANG_44589) # define simde_mm_extract_pi16(a, imm8) ( \ HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wvector-conversion\"") \ HEDLEY_STATIC_CAST(int16_t, _mm_extract_pi16((a), (imm8))) \ HEDLEY_DIAGNOSTIC_POP \ ) # else # define simde_mm_extract_pi16(a, imm8) HEDLEY_STATIC_CAST(int16_t, _mm_extract_pi16(a, imm8)) # endif #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) # define simde_mm_extract_pi16(a, imm8) vget_lane_s16(simde__m64_to_private(a).neon_i16, imm8) #endif #define simde_m_pextrw(a, imm8) simde_mm_extract_pi16(a, imm8) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_extract_pi16(a, imm8) simde_mm_extract_pi16((a), (imm8)) # define _m_pextrw(a, imm8) simde_mm_extract_pi16((a), (imm8)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_insert_pi16 (simde__m64 a, int16_t i, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 3) { simde__m64_private r_, a_ = simde__m64_to_private(a); r_.i64[0] = a_.i64[0]; r_.i16[imm8] = i; return simde__m64_from_private(r_); } #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # if defined(SIMDE_BUG_CLANG_44589) # define ssimde_mm_insert_pi16(a, i, imm8) ( \ HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wvector-conversion\"") \ (_mm_insert_pi16((a), (i), (imm8))) \ HEDLEY_DIAGNOSTIC_POP \ ) # else # define simde_mm_insert_pi16(a, i, imm8) _mm_insert_pi16(a, i, imm8) # endif #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) # define simde_mm_insert_pi16(a, i, imm8) simde__m64_from_neon_i16(vset_lane_s16((i), simde__m64_to_neon_i16(a), (imm8))) #endif #define simde_m_pinsrw(a, i, imm8) (simde_mm_insert_pi16(a, i, imm8)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_insert_pi16(a, i, imm8) simde_mm_insert_pi16(a, i, imm8) # define _m_pinsrw(a, i, imm8) simde_mm_insert_pi16(a, i, imm8) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ps(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_f32(mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_vsx_ld(0, mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_ld(0, mem_addr); #else simde_memcpy(&r_, SIMDE_ALIGN_ASSUME_LIKE(mem_addr, simde__m128), sizeof(r_)); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ps(mem_addr) simde_mm_load_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load1_ps (simde_float32 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ps1(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_dup_f32(mem_addr); #else r_ = simde__m128_to_private(simde_mm_set1_ps(*mem_addr)); #endif return simde__m128_from_private(r_); #endif } #define simde_mm_load_ps1(mem_addr) simde_mm_load1_ps(mem_addr) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ps1(mem_addr) simde_mm_load1_ps(mem_addr) # define _mm_load1_ps(mem_addr) simde_mm_load1_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_load_ss (simde_float32 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_load_ss(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(*mem_addr, vdupq_n_f32(0), 0); #else r_.f32[0] = *mem_addr; r_.i32[1] = 0; r_.i32[2] = 0; r_.i32[3] = 0; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_load_ss(mem_addr) simde_mm_load_ss(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadh_pi (simde__m128 a, simde__m64 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_loadh_pi(a, HEDLEY_REINTERPRET_CAST(__m64 const*, mem_addr)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vget_low_f32(a_.neon_f32), vld1_f32(HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr))); #else simde__m64_private b_ = *HEDLEY_REINTERPRET_CAST(simde__m64_private const*, mem_addr); r_.f32[0] = a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = b_.f32[0]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #if HEDLEY_HAS_WARNING("-Wold-style-cast") #define _mm_loadh_pi(a, mem_addr) simde_mm_loadh_pi((a), HEDLEY_REINTERPRET_CAST(simde__m64 const*, (mem_addr))) #else #define _mm_loadh_pi(a, mem_addr) simde_mm_loadh_pi((a), (simde__m64 const*) (mem_addr)) #endif #endif /* The SSE documentation says that there are no alignment requirements for mem_addr. Unfortunately they used the __m64 type for the argument which is supposed to be 8-byte aligned, so some compilers (like clang with -Wcast-align) will generate a warning if you try to cast, say, a simde_float32* to a simde__m64* for this function. I think the choice of argument type is unfortunate, but I do think we need to stick to it here. If there is demand I can always add something like simde_x_mm_loadl_f32(simde__m128, simde_float32 mem_addr[2]) */ SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadl_pi (simde__m128 a, simde__m64 const* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadl_pi(a, HEDLEY_REINTERPRET_CAST(__m64 const*, mem_addr)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vcombine_f32(vld1_f32( HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr)), vget_high_f32(a_.neon_f32)); #else simde__m64_private b_; simde_memcpy(&b_, mem_addr, sizeof(b_)); r_.i32[0] = b_.i32[0]; r_.i32[1] = b_.i32[1]; r_.i32[2] = a_.i32[2]; r_.i32[3] = a_.i32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #if HEDLEY_HAS_WARNING("-Wold-style-cast") #define _mm_loadl_pi(a, mem_addr) simde_mm_loadl_pi((a), HEDLEY_REINTERPRET_CAST(simde__m64 const*, (mem_addr))) #else #define _mm_loadl_pi(a, mem_addr) simde_mm_loadl_pi((a), (simde__m64 const*) (mem_addr)) #endif #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadr_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadr_ps(mem_addr); #else simde__m128_private r_, v_ = simde__m128_to_private(simde_mm_load_ps(mem_addr)); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vrev64q_f32(v_.neon_f32); r_.neon_f32 = vextq_f32(r_.neon_f32, r_.neon_f32, 2); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) && defined(__PPC64__) r_.altivec_f32 = vec_reve(v_.altivec_f32); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, v_.f32, v_.f32, 3, 2, 1, 0); #else r_.f32[0] = v_.f32[3]; r_.f32[1] = v_.f32[2]; r_.f32[2] = v_.f32[1]; r_.f32[3] = v_.f32[0]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadr_ps(mem_addr) simde_mm_loadr_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_loadu_ps (simde_float32 const mem_addr[HEDLEY_ARRAY_PARAM(4)]) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_loadu_ps(mem_addr); #else simde__m128_private r_; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vld1q_f32(HEDLEY_REINTERPRET_CAST(const float32_t*, mem_addr)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_load(mem_addr); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) && defined(__PPC64__) r_.altivec_f32 = vec_vsx_ld(0, mem_addr); #else simde_memcpy(&r_, mem_addr, sizeof(r_)); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_loadu_ps(mem_addr) simde_mm_loadu_ps(mem_addr) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_maskmove_si64 (simde__m64 a, simde__m64 mask, int8_t* mem_addr) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) _mm_maskmove_si64(a, mask, HEDLEY_REINTERPRET_CAST(char*, mem_addr)); #else simde__m64_private a_ = simde__m64_to_private(a), mask_ = simde__m64_to_private(mask); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(a_.i8) / sizeof(a_.i8[0])) ; i++) if (mask_.i8[i] < 0) mem_addr[i] = a_.i8[i]; #endif } #define simde_m_maskmovq(a, mask, mem_addr) simde_mm_maskmove_si64(a, mask, mem_addr) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_maskmove_si64(a, mask, mem_addr) simde_mm_maskmove_si64((a), (mask), SIMDE_CHECKED_REINTERPRET_CAST(int8_t*, char*, (mem_addr))) # define _m_maskmovq(a, mask, mem_addr) simde_mm_maskmove_si64((a), (mask), SIMDE_CHECKED_REINTERPRET_CAST(int8_t*, char*, (mem_addr))) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_max_pi16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_max_pi16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i16 = vmax_s16(a_.neon_i16, b_.neon_i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = (a_.i16[i] > b_.i16[i]) ? a_.i16[i] : b_.i16[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmaxsw(a, b) simde_mm_max_pi16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_pi16(a, b) simde_mm_max_pi16(a, b) # define _m_pmaxsw(a, b) simde_mm_max_pi16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_max_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_max_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) && defined(SIMDE_FAST_NANS) r_.neon_f32 = vmaxq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vbslq_f32(vcgtq_f32(a_.neon_f32, b_.neon_f32), a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) && defined(SIMDE_FAST_NANS) r_.wasm_v128 = wasm_f32x4_max(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_v128_bitselect(a_.wasm_v128, b_.wasm_v128, wasm_f32x4_gt(a_.wasm_v128, b_.wasm_v128)); #elif (defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE)) && defined(SIMDE_FAST_NANS) r_.altivec_f32 = vec_max(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = vec_sel(b_.altivec_f32, a_.altivec_f32, vec_cmpgt(a_.altivec_f32, b_.altivec_f32)); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (a_.f32[i] > b_.f32[i]) ? a_.f32[i] : b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_ps(a, b) simde_mm_max_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_max_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_max_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vmax_u8(a_.neon_u8, b_.neon_u8); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] > b_.u8[i]) ? a_.u8[i] : b_.u8[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmaxub(a, b) simde_mm_max_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_pu8(a, b) simde_mm_max_pu8(a, b) # define _m_pmaxub(a, b) simde_mm_max_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_max_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_max_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_max_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(maxq_f32(a_.neon_f32, b_.neon_f32), 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = (a_.f32[0] > b_.f32[0]) ? a_.f32[0] : b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_max_ss(a, b) simde_mm_max_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_min_pi16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_min_pi16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_i16 = vmin_s16(a_.neon_i16, b_.neon_i16); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.i16) / sizeof(r_.i16[0])) ; i++) { r_.i16[i] = (a_.i16[i] < b_.i16[i]) ? a_.i16[i] : b_.i16[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pminsw(a, b) simde_mm_min_pi16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_pi16(a, b) simde_mm_min_pi16(a, b) # define _m_pminsw(a, b) simde_mm_min_pi16(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_min_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_min_ps(a, b); #elif defined(SIMDE_FAST_NANS) && defined(SIMDE_ARM_NEON_A32V7_NATIVE) return simde__m128_from_neon_f32(vminq_f32(simde__m128_to_neon_f32(a), simde__m128_to_neon_f32(b))); #elif defined(SIMDE_WASM_SIMD128_NATIVE) simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_FAST_NANS) r_.wasm_v128 = wasm_f32x4_min(a_.wasm_v128, b_.wasm_v128); #else r_.wasm_v128 = wasm_v128_bitselect(a_.wasm_v128, b_.wasm_v128, wasm_f32x4_lt(a_.wasm_v128, b_.wasm_v128)); #endif return simde__m128_from_private(r_); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_FAST_NANS) r_.altivec_f32 = vec_min(a_.altivec_f32, b_.altivec_f32); #else r_.altivec_f32 = vec_sel(b_.altivec_f32, a_.altivec_f32, vec_cmpgt(b_.altivec_f32, a_.altivec_f32)); #endif return simde__m128_from_private(r_); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) simde__m128 mask = simde_mm_cmplt_ps(a, b); return simde_mm_or_ps(simde_mm_and_ps(mask, a), simde_mm_andnot_ps(mask, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = (a_.f32[i] < b_.f32[i]) ? a_.f32[i] : b_.f32[i]; } return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_ps(a, b) simde_mm_min_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_min_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_min_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_u8 = vmin_u8(a_.neon_u8, b_.neon_u8); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { r_.u8[i] = (a_.u8[i] < b_.u8[i]) ? a_.u8[i] : b_.u8[i]; } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pminub(a, b) simde_mm_min_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_pu8(a, b) simde_mm_min_pu8(a, b) # define _m_pminub(a, b) simde_mm_min_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_min_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_min_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_min_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(vminq_f32(a_.neon_f32, b_.neon_f32), 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #else r_.f32[0] = (a_.f32[0] < b_.f32[0]) ? a_.f32[0] : b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_min_ss(a, b) simde_mm_min_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_movehl_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_movehl_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a32 = vget_high_f32(a_.neon_f32); float32x2_t b32 = vget_high_f32(b_.neon_f32); r_.neon_f32 = vcombine_f32(b32, a32); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_mergel(b_.altivec_i64, a_.altivec_i64)); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 6, 7, 2, 3); #else r_.f32[0] = b_.f32[2]; r_.f32[1] = b_.f32[3]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movehl_ps(a, b) simde_mm_movehl_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_movelh_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_movelh_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a10 = vget_low_f32(a_.neon_f32); float32x2_t b10 = vget_low_f32(b_.neon_f32); r_.neon_f32 = vcombine_f32(a10, b10); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 0, 1, 4, 5); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_13_NATIVE) r_.altivec_f32 = HEDLEY_REINTERPRET_CAST(SIMDE_POWER_ALTIVEC_VECTOR(float), vec_mergeh(a_.altivec_i64, b_.altivec_i64)); #else r_.f32[0] = a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = b_.f32[0]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movelh_ps(a, b) simde_mm_movelh_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_movemask_pi8 (simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_movemask_pi8(a); #else simde__m64_private a_ = simde__m64_to_private(a); int r = 0; #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) uint8x8_t input = a_.neon_u8; const int8_t xr[8] = {-7, -6, -5, -4, -3, -2, -1, 0}; const uint8x8_t mask_and = vdup_n_u8(0x80); const int8x8_t mask_shift = vld1_s8(xr); const uint8x8_t mask_result = vshl_u8(vand_u8(input, mask_and), mask_shift); uint8x8_t lo = mask_result; r = vaddv_u8(lo); #else const size_t nmemb = sizeof(a_.i8) / sizeof(a_.i8[0]); SIMDE_VECTORIZE_REDUCTION(|:r) for (size_t i = 0 ; i < nmemb ; i++) { r |= (a_.u8[nmemb - 1 - i] >> 7) << (nmemb - 1 - i); } #endif return r; #endif } #define simde_m_pmovmskb(a) simde_mm_movemask_pi8(a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movemask_pi8(a) simde_mm_movemask_pi8(a) # define _m_pmovmskb(a) simde_mm_movemask_pi8(a) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_movemask_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_movemask_ps(a); #else int r = 0; simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) static const int32_t shift_amount[] = { 0, 1, 2, 3 }; const int32x4_t shift = vld1q_s32(shift_amount); uint32x4_t tmp = vshrq_n_u32(a_.neon_u32, 31); return HEDLEY_STATIC_CAST(int, vaddvq_u32(vshlq_u32(tmp, shift))); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) // Shift out everything but the sign bits with a 32-bit unsigned shift right. uint64x2_t high_bits = vreinterpretq_u64_u32(vshrq_n_u32(a_.neon_u32, 31)); // Merge the two pairs together with a 64-bit unsigned shift right + add. uint8x16_t paired = vreinterpretq_u8_u64(vsraq_n_u64(high_bits, high_bits, 31)); // Extract the result. return vgetq_lane_u8(paired, 0) | (vgetq_lane_u8(paired, 8) << 2); #else SIMDE_VECTORIZE_REDUCTION(|:r) for (size_t i = 0 ; i < sizeof(a_.u32) / sizeof(a_.u32[0]) ; i++) { r |= (a_.u32[i] >> ((sizeof(a_.u32[i]) * CHAR_BIT) - 1)) << i; } #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_movemask_ps(a) simde_mm_movemask_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_mul_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_mul_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vmulq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_mul(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 * b_.f32; #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) r_.altivec_f32 = vec_mul(a_.altivec_f32, b_.altivec_f32); #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] * b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mul_ps(a, b) simde_mm_mul_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_mul_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_mul_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_mul_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[0] * b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mul_ss(a, b) simde_mm_mul_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_mulhi_pu16 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_mulhi_pu16(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) const uint32x4_t t1 = vmull_u16(a_.neon_u16, b_.neon_u16); const uint32x4_t t2 = vshrq_n_u32(t1, 16); const uint16x4_t t3 = vmovn_u32(t2); r_.neon_u16 = t3; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.u16) / sizeof(r_.u16[0])) ; i++) { r_.u16[i] = HEDLEY_STATIC_CAST(uint16_t, ((HEDLEY_STATIC_CAST(uint32_t, a_.u16[i]) * HEDLEY_STATIC_CAST(uint32_t, b_.u16[i])) >> UINT32_C(16))); } #endif return simde__m64_from_private(r_); #endif } #define simde_m_pmulhuw(a, b) simde_mm_mulhi_pu16(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_mulhi_pu16(a, b) simde_mm_mulhi_pu16(a, b) # define _m_pmulhuw(a, b) simde_mm_mulhi_pu16(a, b) #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(HEDLEY_GCC_VERSION) #define SIMDE_MM_HINT_NTA HEDLEY_STATIC_CAST(enum _mm_hint, 0) #define SIMDE_MM_HINT_T0 HEDLEY_STATIC_CAST(enum _mm_hint, 1) #define SIMDE_MM_HINT_T1 HEDLEY_STATIC_CAST(enum _mm_hint, 2) #define SIMDE_MM_HINT_T2 HEDLEY_STATIC_CAST(enum _mm_hint, 3) #define SIMDE_MM_HINT_ENTA HEDLEY_STATIC_CAST(enum _mm_hint, 4) #define SIMDE_MM_HINT_ET0 HEDLEY_STATIC_CAST(enum _mm_hint, 5) #define SIMDE_MM_HINT_ET1 HEDLEY_STATIC_CAST(enum _mm_hint, 6) #define SIMDE_MM_HINT_ET2 HEDLEY_STATIC_CAST(enum _mm_hint, 7) #else #define SIMDE_MM_HINT_NTA 0 #define SIMDE_MM_HINT_T0 1 #define SIMDE_MM_HINT_T1 2 #define SIMDE_MM_HINT_T2 3 #define SIMDE_MM_HINT_ENTA 4 #define SIMDE_MM_HINT_ET0 5 #define SIMDE_MM_HINT_ET1 6 #define SIMDE_MM_HINT_ET2 7 #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) HEDLEY_DIAGNOSTIC_PUSH #if HEDLEY_HAS_WARNING("-Wreserved-id-macro") _Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"") #endif #undef _MM_HINT_NTA #define _MM_HINT_NTA SIMDE_MM_HINT_NTA #undef _MM_HINT_T0 #define _MM_HINT_T0 SIMDE_MM_HINT_T0 #undef _MM_HINT_T1 #define _MM_HINT_T1 SIMDE_MM_HINT_T1 #undef _MM_HINT_T2 #define _MM_HINT_T2 SIMDE_MM_HINT_T2 #undef _MM_HINT_ETNA #define _MM_HINT_ETNA SIMDE_MM_HINT_ETNA #undef _MM_HINT_ET0 #define _MM_HINT_ET0 SIMDE_MM_HINT_ET0 #undef _MM_HINT_ET1 #define _MM_HINT_ET1 SIMDE_MM_HINT_ET1 #undef _MM_HINT_ET1 #define _MM_HINT_ET2 SIMDE_MM_HINT_ET2 HEDLEY_DIAGNOSTIC_POP #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_prefetch (char const* p, int i) { #if defined(HEDLEY_GCC_VERSION) __builtin_prefetch(p); #else (void) p; #endif (void) i; } #if defined(SIMDE_X86_SSE_NATIVE) #if defined(__clang__) && !SIMDE_DETECT_CLANG_VERSION_CHECK(10,0,0) /* https://reviews.llvm.org/D71718 */ #define simde_mm_prefetch(p, i) \ (__extension__({ \ HEDLEY_DIAGNOSTIC_PUSH \ HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ _mm_prefetch((p), (i)); \ HEDLEY_DIAGNOSTIC_POP \ })) #else #define simde_mm_prefetch(p, i) _mm_prefetch(p, i) #endif #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) #define _mm_prefetch(p, i) simde_mm_prefetch(p, i) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_negate_ps(simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return simde_mm_xor_ps(a, _mm_set1_ps(SIMDE_FLOAT32_C(-0.0))); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) && \ (!defined(HEDLEY_GCC_VERSION) || HEDLEY_GCC_VERSION_CHECK(8,1,0)) r_.altivec_f32 = vec_neg(a_.altivec_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vnegq_f32(a_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_neg(a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P8_NATIVE) r_.altivec_f32 = vec_neg(a_.altivec_f32); #elif defined(SIMDE_VECTOR_NEGATE) r_.f32 = -a_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = -a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rcp_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rcp_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t recip = vrecpeq_f32(a_.neon_f32); #if SIMDE_ACCURACY_PREFERENCE > 0 for (int i = 0; i < SIMDE_ACCURACY_PREFERENCE ; ++i) { recip = vmulq_f32(recip, vrecpsq_f32(recip, a_.neon_f32)); } #endif r_.neon_f32 = recip; #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_div(simde_mm_set1_ps(1.0f), a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_re(a_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_SCALAR) r_.f32 = 1.0f / a_.f32; #elif defined(SIMDE_IEEE754_STORAGE) /* https://stackoverflow.com/questions/12227126/division-as-multiply-and-lut-fast-float-division-reciprocal/12228234#12228234 */ SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { int32_t ix; simde_float32 fx = a_.f32[i]; simde_memcpy(&ix, &fx, sizeof(ix)); int32_t x = INT32_C(0x7EF311C3) - ix; simde_float32 temp; simde_memcpy(&temp, &x, sizeof(temp)); r_.f32[i] = temp * (SIMDE_FLOAT32_C(2.0) - temp * fx); } #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = 1.0f / a_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rcp_ps(a) simde_mm_rcp_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rcp_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rcp_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_rcp_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); r_.f32[0] = 1.0f / a_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rcp_ss(a) simde_mm_rcp_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rsqrt_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rsqrt_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vrsqrteq_f32(a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_rsqrte(a_.altivec_f32); #elif defined(SIMDE_IEEE754_STORAGE) /* https://basesandframes.files.wordpress.com/2020/04/even_faster_math_functions_green_2020.pdf Pages 100 - 103 */ SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { #if SIMDE_ACCURACY_PREFERENCE <= 0 r_.i32[i] = INT32_C(0x5F37624F) - (a_.i32[i] >> 1); #else simde_float32 x = a_.f32[i]; simde_float32 xhalf = SIMDE_FLOAT32_C(0.5) * x; int32_t ix; simde_memcpy(&ix, &x, sizeof(ix)); #if SIMDE_ACCURACY_PREFERENCE == 1 ix = INT32_C(0x5F375A82) - (ix >> 1); #else ix = INT32_C(0x5F37599E) - (ix >> 1); #endif simde_memcpy(&x, &ix, sizeof(x)); #if SIMDE_ACCURACY_PREFERENCE >= 2 x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); #endif x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); r_.f32[i] = x; #endif } #elif defined(simde_math_sqrtf) SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = 1.0f / simde_math_sqrtf(a_.f32[i]); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rsqrt_ps(a) simde_mm_rsqrt_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_rsqrt_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_rsqrt_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_rsqrt_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsetq_lane_f32(vgetq_lane_f32(simde_mm_rsqrt_ps(a).neon_f32, 0), a_.neon_f32, 0); #elif defined(SIMDE_IEEE754_STORAGE) { #if SIMDE_ACCURACY_PREFERENCE <= 0 r_.i32[0] = INT32_C(0x5F37624F) - (a_.i32[0] >> 1); #else simde_float32 x = a_.f32[0]; simde_float32 xhalf = SIMDE_FLOAT32_C(0.5) * x; int32_t ix; simde_memcpy(&ix, &x, sizeof(ix)); #if SIMDE_ACCURACY_PREFERENCE == 1 ix = INT32_C(0x5F375A82) - (ix >> 1); #else ix = INT32_C(0x5F37599E) - (ix >> 1); #endif simde_memcpy(&x, &ix, sizeof(x)); #if SIMDE_ACCURACY_PREFERENCE >= 2 x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); #endif x = x * (SIMDE_FLOAT32_C(1.5008909) - xhalf * x * x); r_.f32[0] = x; #endif } r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #elif defined(simde_math_sqrtf) r_.f32[0] = 1.0f / simde_math_sqrtf(a_.f32[0]); r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_rsqrt_ss(a) simde_mm_rsqrt_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_sad_pu8 (simde__m64 a, simde__m64 b) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) return _mm_sad_pu8(a, b); #else simde__m64_private r_, a_ = simde__m64_to_private(a), b_ = simde__m64_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint16x4_t t = vpaddl_u8(vabd_u8(a_.neon_u8, b_.neon_u8)); uint16_t r0 = t[0] + t[1] + t[2] + t[3]; r_.neon_u16 = vset_lane_u16(r0, vdup_n_u16(0), 0); #else uint16_t sum = 0; #if defined(SIMDE_HAVE_STDLIB_H) SIMDE_VECTORIZE_REDUCTION(+:sum) for (size_t i = 0 ; i < (sizeof(r_.u8) / sizeof(r_.u8[0])) ; i++) { sum += HEDLEY_STATIC_CAST(uint8_t, abs(a_.u8[i] - b_.u8[i])); } r_.i16[0] = HEDLEY_STATIC_CAST(int16_t, sum); r_.i16[1] = 0; r_.i16[2] = 0; r_.i16[3] = 0; #else HEDLEY_UNREACHABLE(); #endif #endif return simde__m64_from_private(r_); #endif } #define simde_m_psadbw(a, b) simde_mm_sad_pu8(a, b) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sad_pu8(a, b) simde_mm_sad_pu8(a, b) # define _m_psadbw(a, b) simde_mm_sad_pu8(a, b) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_set_ss (simde_float32 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_set_ss(a); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vsetq_lane_f32(a, vdupq_n_f32(SIMDE_FLOAT32_C(0.0)), 0); #else return simde_mm_set_ps(SIMDE_FLOAT32_C(0.0), SIMDE_FLOAT32_C(0.0), SIMDE_FLOAT32_C(0.0), a); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_set_ss(a) simde_mm_set_ss(a) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_setr_ps (simde_float32 e3, simde_float32 e2, simde_float32 e1, simde_float32 e0) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_setr_ps(e3, e2, e1, e0); #else return simde_mm_set_ps(e0, e1, e2, e3); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_setr_ps(e3, e2, e1, e0) simde_mm_setr_ps(e3, e2, e1, e0) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_setzero_ps (void) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_setzero_ps(); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) return vdupq_n_f32(SIMDE_FLOAT32_C(0.0)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) return vec_splats(SIMDE_FLOAT32_C(0.0)); #else simde__m128 r; simde_memset(&r, 0, sizeof(r)); return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_setzero_ps() simde_mm_setzero_ps() #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_PUSH SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_undefined_ps (void) { simde__m128_private r_; #if defined(SIMDE_HAVE_UNDEFINED128) r_.n = _mm_undefined_ps(); #elif !defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) r_ = simde__m128_to_private(simde_mm_setzero_ps()); #endif return simde__m128_from_private(r_); } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_undefined_ps() simde_mm_undefined_ps() #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_POP #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_x_mm_setone_ps (void) { simde__m128 t = simde_mm_setzero_ps(); return simde_mm_cmpeq_ps(t, t); } SIMDE_FUNCTION_ATTRIBUTES void simde_mm_sfence (void) { /* TODO: Use Hedley. */ #if defined(SIMDE_X86_SSE_NATIVE) _mm_sfence(); #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) __atomic_thread_fence(__ATOMIC_SEQ_CST); #elif !defined(__INTEL_COMPILER) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 9) __atomic_thread_fence(__ATOMIC_SEQ_CST); #else atomic_thread_fence(memory_order_seq_cst); #endif #elif defined(_MSC_VER) MemoryBarrier(); #elif HEDLEY_HAS_EXTENSION(c_atomic) __c11_atomic_thread_fence(__ATOMIC_SEQ_CST); #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) __sync_synchronize(); #elif defined(_OPENMP) #pragma omp critical(simde_mm_sfence_) { } #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sfence() simde_mm_sfence() #endif #define SIMDE_MM_SHUFFLE(z, y, x, w) (((z) << 6) | ((y) << 4) | ((x) << 2) | (w)) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _MM_SHUFFLE(z, y, x, w) SIMDE_MM_SHUFFLE(z, y, x, w) #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # define simde_mm_shuffle_pi16(a, imm8) _mm_shuffle_pi16(a, imm8) #elif defined(SIMDE_SHUFFLE_VECTOR_) # define simde_mm_shuffle_pi16(a, imm8) (__extension__ ({ \ const simde__m64_private simde__tmp_a_ = simde__m64_to_private(a); \ simde__m64_from_private((simde__m64_private) { .i16 = \ SIMDE_SHUFFLE_VECTOR_(16, 8, \ (simde__tmp_a_).i16, \ (simde__tmp_a_).i16, \ (((imm8) ) & 3), \ (((imm8) >> 2) & 3), \ (((imm8) >> 4) & 3), \ (((imm8) >> 6) & 3)) }); })) #else SIMDE_FUNCTION_ATTRIBUTES simde__m64 simde_mm_shuffle_pi16 (simde__m64 a, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 255) { simde__m64_private r_; simde__m64_private a_ = simde__m64_to_private(a); for (size_t i = 0 ; i < sizeof(r_.i16) / sizeof(r_.i16[0]) ; i++) { r_.i16[i] = a_.i16[(imm8 >> (i * 2)) & 3]; } HEDLEY_DIAGNOSTIC_PUSH #if HEDLEY_HAS_WARNING("-Wconditional-uninitialized") # pragma clang diagnostic ignored "-Wconditional-uninitialized" #endif return simde__m64_from_private(r_); HEDLEY_DIAGNOSTIC_POP } #endif #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) && !defined(__PGI) # define simde_m_pshufw(a, imm8) _m_pshufw(a, imm8) #else # define simde_m_pshufw(a, imm8) simde_mm_shuffle_pi16(a, imm8) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_shuffle_pi16(a, imm8) simde_mm_shuffle_pi16(a, imm8) # define _m_pshufw(a, imm8) simde_mm_shuffle_pi16(a, imm8) #endif #if defined(SIMDE_X86_SSE_NATIVE) && !defined(__PGI) # define simde_mm_shuffle_ps(a, b, imm8) _mm_shuffle_ps(a, b, imm8) #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) #define simde_mm_shuffle_ps(a, b, imm8) \ __extension__({ \ float32x4_t ret; \ ret = vmovq_n_f32( \ vgetq_lane_f32(a, (imm8) & (0x3))); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(a, ((imm8) >> 2) & 0x3), \ ret, 1); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(b, ((imm8) >> 4) & 0x3), \ ret, 2); \ ret = vsetq_lane_f32( \ vgetq_lane_f32(b, ((imm8) >> 6) & 0x3), \ ret, 3); \ }) #elif defined(SIMDE_SHUFFLE_VECTOR_) # define simde_mm_shuffle_ps(a, b, imm8) (__extension__ ({ \ simde__m128_from_private((simde__m128_private) { .f32 = \ SIMDE_SHUFFLE_VECTOR_(32, 16, \ simde__m128_to_private(a).f32, \ simde__m128_to_private(b).f32, \ (((imm8) ) & 3), \ (((imm8) >> 2) & 3), \ (((imm8) >> 4) & 3) + 4, \ (((imm8) >> 6) & 3) + 4) }); })) #else SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_shuffle_ps (simde__m128 a, simde__m128 b, const int imm8) SIMDE_REQUIRE_CONSTANT_RANGE(imm8, 0, 255) { simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[(imm8 >> 0) & 3]; r_.f32[1] = a_.f32[(imm8 >> 2) & 3]; r_.f32[2] = b_.f32[(imm8 >> 4) & 3]; r_.f32[3] = b_.f32[(imm8 >> 6) & 3]; return simde__m128_from_private(r_); } #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_shuffle_ps(a, b, imm8) simde_mm_shuffle_ps((a), (b), imm8) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sqrt_ps (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sqrt_ps(a); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vsqrtq_f32(a_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t est = vrsqrteq_f32(a_.neon_f32); for (int i = 0 ; i <= SIMDE_ACCURACY_PREFERENCE ; i++) { est = vmulq_f32(vrsqrtsq_f32(vmulq_f32(a_.neon_f32, est), est), est); } r_.neon_f32 = vmulq_f32(a_.neon_f32, est); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_sqrt(a_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) || defined(SIMDE_ZARCH_ZVECTOR_14_NATIVE) r_.altivec_f32 = vec_sqrt(a_.altivec_f32); #elif defined(simde_math_sqrt) SIMDE_VECTORIZE for (size_t i = 0 ; i < sizeof(r_.f32) / sizeof(r_.f32[0]) ; i++) { r_.f32[i] = simde_math_sqrtf(a_.f32[i]); } #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sqrt_ps(a) simde_mm_sqrt_ps((a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sqrt_ss (simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sqrt_ss(a); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_sqrt_ps(a)); #else simde__m128_private r_, a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32_t value = vgetq_lane_f32(simde__m128_to_private(simde_mm_sqrt_ps(a)).neon_f32, 0); r_.neon_f32 = vsetq_lane_f32(value, a_.neon_f32, 0); #elif defined(simde_math_sqrtf) r_.f32[0] = simde_math_sqrtf(a_.f32[0]); r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; #else HEDLEY_UNREACHABLE(); #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sqrt_ss(a) simde_mm_sqrt_ss((a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr, a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(a_.altivec_f32, 0, mem_addr); #elif defined(SIMDE_WASM_SIMD128_NATIVE) wasm_v128_store(mem_addr, a_.wasm_v128); #else simde_memcpy(mem_addr, &a_, sizeof(a)); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ps(mem_addr, a) simde_mm_store_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store1_ps (simde_float32 mem_addr[4], simde__m128 a) { simde_float32* mem_addr_ = SIMDE_ALIGN_ASSUME_LIKE(mem_addr, simde__m128); #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ps1(mem_addr_, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr_, vdupq_lane_f32(vget_low_f32(a_.neon_f32), 0)); #elif defined(SIMDE_WASM_SIMD128_NATIVE) wasm_v128_store(mem_addr_, wasm_i32x4_shuffle(a_.wasm_v128, a_.wasm_v128, 0, 0, 0, 0)); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(vec_splat(a_.altivec_f32, 0), 0, mem_addr_); #elif defined(SIMDE_SHUFFLE_VECTOR_) simde__m128_private tmp_; tmp_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, a_.f32, 0, 0, 0, 0); simde_mm_store_ps(mem_addr_, tmp_.f32); #else SIMDE_VECTORIZE_ALIGNED(mem_addr_:16) for (size_t i = 0 ; i < sizeof(a_.f32) / sizeof(a_.f32[0]) ; i++) { mem_addr_[i] = a_.f32[0]; } #endif #endif } #define simde_mm_store_ps1(mem_addr, a) simde_mm_store1_ps(mem_addr, a) #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ps1(mem_addr, a) simde_mm_store1_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) # define _mm_store1_ps(mem_addr, a) simde_mm_store1_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_store_ss (simde_float32* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_store_ss(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_lane_f32(mem_addr, a_.neon_f32, 0); #else *mem_addr = a_.f32[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_store_ss(mem_addr, a) simde_mm_store_ss(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storeh_pi (simde__m64* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storeh_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1_f32(HEDLEY_REINTERPRET_CAST(float32_t*, mem_addr), vget_high_f32(a_.neon_f32)); #else simde_memcpy(mem_addr, &(a_.m64[1]), sizeof(a_.m64[1])); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storeh_pi(mem_addr, a) simde_mm_storeh_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storel_pi (simde__m64* mem_addr, simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storel_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m64_private* dest_ = HEDLEY_REINTERPRET_CAST(simde__m64_private*, mem_addr); simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) dest_->neon_f32 = vget_low_f32(a_.neon_f32); #else dest_->f32[0] = a_.f32[0]; dest_->f32[1] = a_.f32[1]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storel_pi(mem_addr, a) simde_mm_storel_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storer_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storer_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) vec_st(vec_reve(a_.altivec_f32), 0, mem_addr); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x4_t tmp = vrev64q_f32(a_.neon_f32); vst1q_f32(mem_addr, vextq_f32(tmp, tmp, 2)); #elif defined(SIMDE_SHUFFLE_VECTOR_) a_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, a_.f32, 3, 2, 1, 0); simde_mm_store_ps(mem_addr, simde__m128_from_private(a_)); #else SIMDE_VECTORIZE_ALIGNED(mem_addr:16) for (size_t i = 0 ; i < sizeof(a_.f32) / sizeof(a_.f32[0]) ; i++) { mem_addr[i] = a_.f32[((sizeof(a_.f32) / sizeof(a_.f32[0])) - 1) - i]; } #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storer_ps(mem_addr, a) simde_mm_storer_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_storeu_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_storeu_ps(mem_addr, a); #else simde__m128_private a_ = simde__m128_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) vst1q_f32(mem_addr, a_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P7_NATIVE) vec_vsx_st(a_.altivec_f32, 0, mem_addr); #else simde_memcpy(mem_addr, &a_, sizeof(a_)); #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_storeu_ps(mem_addr, a) simde_mm_storeu_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sub_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sub_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) r_.neon_f32 = vsubq_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_WASM_SIMD128_NATIVE) r_.wasm_v128 = wasm_f32x4_sub(a_.wasm_v128, b_.wasm_v128); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_sub(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_VECTOR_SUBSCRIPT_OPS) r_.f32 = a_.f32 - b_.f32; #else SIMDE_VECTORIZE for (size_t i = 0 ; i < (sizeof(r_.f32) / sizeof(r_.f32[0])) ; i++) { r_.f32[i] = a_.f32[i] - b_.f32[i]; } #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sub_ps(a, b) simde_mm_sub_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_sub_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_sub_ss(a, b); #elif (SIMDE_NATURAL_VECTOR_SIZE > 0) return simde_mm_move_ss(a, simde_mm_sub_ps(a, b)); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); r_.f32[0] = a_.f32[0] - b_.f32[0]; r_.f32[1] = a_.f32[1]; r_.f32[2] = a_.f32[2]; r_.f32[3] = a_.f32[3]; return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_sub_ss(a, b) simde_mm_sub_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomieq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomieq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_eq_b = vceqq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] == b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] == b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomieq_ss(a, b) simde_mm_ucomieq_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomige_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomige_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_ge_b = vcgeq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] >= b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] >= b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomige_ss(a, b) simde_mm_ucomige_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomigt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomigt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_gt_b = vcgtq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] > b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] > b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomigt_ss(a, b) simde_mm_ucomigt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomile_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomile_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_le_b = vcleq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] <= b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] <= b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomile_ss(a, b) simde_mm_ucomile_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomilt_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomilt_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); uint32x4_t a_lt_b = vcltq_f32(a_.neon_f32, b_.neon_f32); r = !!(vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] < b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] < b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomilt_ss(a, b) simde_mm_ucomilt_ss((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES int simde_mm_ucomineq_ss (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_ucomineq_ss(a, b); #else simde__m128_private a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); int r; #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) uint32x4_t a_not_nan = vceqq_f32(a_.neon_f32, a_.neon_f32); uint32x4_t b_not_nan = vceqq_f32(b_.neon_f32, b_.neon_f32); uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(a_.neon_f32, b_.neon_f32)); r = !!(vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0); #elif defined(SIMDE_HAVE_FENV_H) fenv_t envp; int x = feholdexcept(&envp); r = a_.f32[0] != b_.f32[0]; if (HEDLEY_LIKELY(x == 0)) fesetenv(&envp); #else r = a_.f32[0] != b_.f32[0]; #endif return r; #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_ucomineq_ss(a, b) simde_mm_ucomineq_ss((a), (b)) #endif #if defined(SIMDE_X86_SSE_NATIVE) # if defined(__has_builtin) # if __has_builtin(__builtin_ia32_undef128) # define SIMDE_HAVE_UNDEFINED128 # endif # elif !defined(__PGI) && !defined(SIMDE_BUG_GCC_REV_208793) && !defined(_MSC_VER) # define SIMDE_HAVE_UNDEFINED128 # endif #endif #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) HEDLEY_DIAGNOSTIC_PUSH SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_unpackhi_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_unpackhi_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vzip2q_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a1 = vget_high_f32(a_.neon_f32); float32x2_t b1 = vget_high_f32(b_.neon_f32); float32x2x2_t result = vzip_f32(a1, b1); r_.neon_f32 = vcombine_f32(result.val[0], result.val[1]); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 2, 6, 3, 7); #else r_.f32[0] = a_.f32[2]; r_.f32[1] = b_.f32[2]; r_.f32[2] = a_.f32[3]; r_.f32[3] = b_.f32[3]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_unpackhi_ps(a, b) simde_mm_unpackhi_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES simde__m128 simde_mm_unpacklo_ps (simde__m128 a, simde__m128 b) { #if defined(SIMDE_X86_SSE_NATIVE) return _mm_unpacklo_ps(a, b); #else simde__m128_private r_, a_ = simde__m128_to_private(a), b_ = simde__m128_to_private(b); #if defined(SIMDE_ARM_NEON_A64V8_NATIVE) r_.neon_f32 = vzip1q_f32(a_.neon_f32, b_.neon_f32); #elif defined(SIMDE_POWER_ALTIVEC_P6_NATIVE) r_.altivec_f32 = vec_mergeh(a_.altivec_f32, b_.altivec_f32); #elif defined(SIMDE_SHUFFLE_VECTOR_) r_.f32 = SIMDE_SHUFFLE_VECTOR_(32, 16, a_.f32, b_.f32, 0, 4, 1, 5); #elif defined(SIMDE_ARM_NEON_A32V7_NATIVE) float32x2_t a1 = vget_low_f32(a_.neon_f32); float32x2_t b1 = vget_low_f32(b_.neon_f32); float32x2x2_t result = vzip_f32(a1, b1); r_.neon_f32 = vcombine_f32(result.val[0], result.val[1]); #else r_.f32[0] = a_.f32[0]; r_.f32[1] = b_.f32[0]; r_.f32[2] = a_.f32[1]; r_.f32[3] = b_.f32[1]; #endif return simde__m128_from_private(r_); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_unpacklo_ps(a, b) simde_mm_unpacklo_ps((a), (b)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_stream_pi (simde__m64* mem_addr, simde__m64 a) { #if defined(SIMDE_X86_SSE_NATIVE) && defined(SIMDE_X86_MMX_NATIVE) _mm_stream_pi(HEDLEY_REINTERPRET_CAST(__m64*, mem_addr), a); #else simde__m64_private* dest = HEDLEY_REINTERPRET_CAST(simde__m64_private*, mem_addr), a_ = simde__m64_to_private(a); #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) dest->i64[0] = vget_lane_s64(a_.neon_i64, 0); #else dest->i64[0] = a_.i64[0]; #endif #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_stream_pi(mem_addr, a) simde_mm_stream_pi(mem_addr, (a)) #endif SIMDE_FUNCTION_ATTRIBUTES void simde_mm_stream_ps (simde_float32 mem_addr[4], simde__m128 a) { #if defined(SIMDE_X86_SSE_NATIVE) _mm_stream_ps(mem_addr, a); #elif HEDLEY_HAS_BUILTIN(__builtin_nontemporal_store) && defined(SIMDE_VECTOR_SUBSCRIPT_OPS) simde__m128_private a_ = simde__m128_to_private(a); __builtin_nontemporal_store(a_.f32, SIMDE_ALIGN_CAST(__typeof__(a_.f32)*, mem_addr)); #else simde_mm_store_ps(mem_addr, a); #endif } #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _mm_stream_ps(mem_addr, a) simde_mm_stream_ps(SIMDE_CHECKED_REINTERPRET_CAST(float*, simde_float32*, mem_addr), (a)) #endif #if defined(SIMDE_ARM_NEON_A32V7_NATIVE) #define SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ do { \ float32x4x2_t ROW01 = vtrnq_f32(row0, row1); \ float32x4x2_t ROW23 = vtrnq_f32(row2, row3); \ row0 = vcombine_f32(vget_low_f32(ROW01.val[0]), \ vget_low_f32(ROW23.val[0])); \ row1 = vcombine_f32(vget_low_f32(ROW01.val[1]), \ vget_low_f32(ROW23.val[1])); \ row2 = vcombine_f32(vget_high_f32(ROW01.val[0]), \ vget_high_f32(ROW23.val[0])); \ row3 = vcombine_f32(vget_high_f32(ROW01.val[1]), \ vget_high_f32(ROW23.val[1])); \ } while (0) #else #define SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) \ do { \ simde__m128 tmp3, tmp2, tmp1, tmp0; \ tmp0 = simde_mm_unpacklo_ps((row0), (row1)); \ tmp2 = simde_mm_unpacklo_ps((row2), (row3)); \ tmp1 = simde_mm_unpackhi_ps((row0), (row1)); \ tmp3 = simde_mm_unpackhi_ps((row2), (row3)); \ row0 = simde_mm_movelh_ps(tmp0, tmp2); \ row1 = simde_mm_movehl_ps(tmp2, tmp0); \ row2 = simde_mm_movelh_ps(tmp1, tmp3); \ row3 = simde_mm_movehl_ps(tmp3, tmp1); \ } while (0) #endif #if defined(SIMDE_X86_SSE_ENABLE_NATIVE_ALIASES) # define _MM_TRANSPOSE4_PS(row0, row1, row2, row3) SIMDE_MM_TRANSPOSE4_PS(row0, row1, row2, row3) #endif SIMDE_END_DECLS_ HEDLEY_DIAGNOSTIC_POP #endif /* !defined(SIMDE_X86_SSE_H) */
XSHA512_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 2008,2011 by Solar Designer */ #if FMT_EXTERNS_H extern struct fmt_main fmt_XSHA512; #elif FMT_REGISTERS_H john_register_one(&fmt_XSHA512); #else #include "sha2.h" #include "arch.h" #include "params.h" #include "common.h" #include "formats.h" #include "johnswap.h" #include "simd-intrinsics.h" #include "rawSHA512_common.h" //#undef SIMD_COEF_64 #ifdef _OPENMP #include <omp.h> #ifdef SIMD_COEF_64 #ifndef OMP_SCALE #define OMP_SCALE 4096 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 8192 #endif #endif #endif #include "memdbg.h" #define FORMAT_LABEL "xsha512" #define FORMAT_NAME "Mac OS X 10.7" #define ALGORITHM_NAME "SHA512 " SHA512_ALGORITHM_NAME #define PLAINTEXT_LENGTH 107 #define SALT_SIZE 4 #define SALT_ALIGN sizeof(ARCH_WORD_32) #ifdef SIMD_COEF_64 #define MIN_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #if ARCH_BITS >= 64 || defined(__SSE2__) /* 64-bitness happens to correlate with faster memcpy() */ #define PRECOMPUTE_CTX_FOR_SALT #else #undef PRECOMPUTE_CTX_FOR_SALT #endif #define BINARY_SIZE DIGEST_SIZE #ifdef SIMD_COEF_64 #define GETPOS(i, index) ( (index&(SIMD_COEF_64-1))*8 + ((i)&(0xffffffff-7))*SIMD_COEF_64 + (7-((i)&7)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64*8 ) static ARCH_WORD_64 (*saved_key)[SHA_BUF_SIZ*MAX_KEYS_PER_CRYPT]; static ARCH_WORD_64 (*crypt_out); static int max_keys; #else static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int (*saved_len); static ARCH_WORD_32 (*crypt_out)[16]; #ifdef PRECOMPUTE_CTX_FOR_SALT static SHA512_CTX ctx_salt; #else static ARCH_WORD_32 saved_salt; #endif #endif static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif #ifdef SIMD_COEF_64 #ifndef _OPENMP int omp_t = 1; #endif saved_key = mem_calloc_align(omp_t, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_out = mem_calloc_align(self->params.max_keys_per_crypt, 8 * sizeof(ARCH_WORD_64), MEM_ALIGN_SIMD); max_keys = self->params.max_keys_per_crypt; #else saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); #endif } static void done(void) { MEM_FREE(crypt_out); #ifndef SIMD_COEF_64 MEM_FREE(saved_len); #endif MEM_FREE(saved_key); } static void *get_salt(char *ciphertext) { static union { unsigned char c[SALT_SIZE]; ARCH_WORD_32 dummy; } buf; unsigned char *out = buf.c; char *p; int i; ciphertext += XSHA512_TAG_LENGTH; p = ciphertext; for (i = 0; i < sizeof(buf.c); i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } #ifdef SIMD_COEF_64 #define HASH_IDX (((unsigned int)index&(SIMD_COEF_64-1))+(unsigned int)index/SIMD_COEF_64*8*SIMD_COEF_64) static int get_hash_0 (int index) { return crypt_out[HASH_IDX] & PH_MASK_0; } static int get_hash_1 (int index) { return crypt_out[HASH_IDX] & PH_MASK_1; } static int get_hash_2 (int index) { return crypt_out[HASH_IDX] & PH_MASK_2; } static int get_hash_3 (int index) { return crypt_out[HASH_IDX] & PH_MASK_3; } static int get_hash_4 (int index) { return crypt_out[HASH_IDX] & PH_MASK_4; } static int get_hash_5 (int index) { return crypt_out[HASH_IDX] & PH_MASK_5; } static int get_hash_6 (int index) { return crypt_out[HASH_IDX] & PH_MASK_6; } #else static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } #endif static int salt_hash(void *salt) { return *(ARCH_WORD_32 *)salt & (SALT_HASH_SIZE - 1); } static void set_salt(void *salt) { #ifndef SIMD_COEF_64 #ifdef PRECOMPUTE_CTX_FOR_SALT SHA512_Init(&ctx_salt); SHA512_Update(&ctx_salt, salt, SALT_SIZE); #else saved_salt = *(ARCH_WORD_32 *)salt; #endif #else int i; unsigned char *wucp = (unsigned char*)saved_key; for (i = 0; i < max_keys; ++i) { wucp[GETPOS(0, i)] = ((char*)salt)[0]; wucp[GETPOS(1, i)] = ((char*)salt)[1]; wucp[GETPOS(2, i)] = ((char*)salt)[2]; wucp[GETPOS(3, i)] = ((char*)salt)[3]; } #endif } static void set_key(char *key, int index) { #ifndef SIMD_COEF_64 int length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; saved_len[index] = length; memcpy(saved_key[index], key, length); #else ARCH_WORD_64 *keybuffer = &((ARCH_WORD_64 *)saved_key)[(index&(SIMD_COEF_64-1)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64]; ARCH_WORD_64 *keybuf_word = keybuffer; unsigned int len; ARCH_WORD_64 temp; unsigned char *wucp = (unsigned char*)saved_key; // ok, first 4 bytes (if there are that many or more), we handle one offs. // this is because we already have 4 byte salt loaded into our saved_key. // IF there are more bytes of password, we drop into the multi loader. #if ARCH_ALLOWS_UNALIGNED const ARCH_WORD_64 *wkey = (ARCH_WORD_64*)&(key[4]); #else char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint64_t)); const ARCH_WORD_64 *wkey = is_aligned(key + 4, sizeof(uint64_t)) ? (ARCH_WORD_64*)(key + 4) : (ARCH_WORD_64*)buf_aligned; if ((char *)wkey == buf_aligned && strlen(key) >= 4) strcpy(buf_aligned, key + 4); #endif len = 4; if (key[0] == 0) {wucp[GETPOS(4, index)] = 0x80; wucp[GETPOS(5, index)] = wucp[GETPOS(6, index)] = wucp[GETPOS(7, index)] = 0; goto key_cleaning; } wucp[GETPOS(4, index)] = key[0]; ++len; if (key[1] == 0) {wucp[GETPOS(5, index)] = 0x80; wucp[GETPOS(6, index)] = wucp[GETPOS(7, index)] = 0; goto key_cleaning; } wucp[GETPOS(5, index)] = key[1]; ++len; if (key[2] == 0) {wucp[GETPOS(6, index)] = 0x80; wucp[GETPOS(7, index)] = 0; goto key_cleaning; } wucp[GETPOS(6, index)] = key[2]; ++len; if (key[3] == 0) {wucp[GETPOS(7, index)] = 0x80; goto key_cleaning; } wucp[GETPOS(7, index)] = key[3]; ++len; keybuf_word += SIMD_COEF_64; while((unsigned char)(temp = *wkey++)) { if (!(temp & 0xff00)) { *keybuf_word = JOHNSWAP64((temp & 0xff) | (0x80 << 8)); len++; goto key_cleaning; } if (!(temp & 0xff0000)) { *keybuf_word = JOHNSWAP64((temp & 0xffff) | (0x80 << 16)); len+=2; goto key_cleaning; } if (!(temp & 0xff000000)) { *keybuf_word = JOHNSWAP64((temp & 0xffffff) | (0x80ULL << 24)); len+=3; goto key_cleaning; } if (!(temp & 0xff00000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffff) | (0x80ULL << 32)); len+=4; goto key_cleaning; } if (!(temp & 0xff0000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffULL) | (0x80ULL << 40)); len+=5; goto key_cleaning; } if (!(temp & 0xff000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffULL) | (0x80ULL << 48)); len+=6; goto key_cleaning; } if (!(temp & 0xff00000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffffULL) | (0x80ULL << 56)); len+=7; goto key_cleaning; } *keybuf_word = JOHNSWAP64(temp); len += 8; keybuf_word += SIMD_COEF_64; } *keybuf_word = 0x8000000000000000ULL; key_cleaning: keybuf_word += SIMD_COEF_64; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_64; } keybuffer[15*SIMD_COEF_64] = len << 3; #endif } static char *get_key(int index) { #ifndef SIMD_COEF_64 saved_key[index][saved_len[index]] = 0; return saved_key[index]; #else static unsigned char key[PLAINTEXT_LENGTH+1]; int i; unsigned char *wucp = (unsigned char*)saved_key; ARCH_WORD_64 *keybuffer = &((ARCH_WORD_64*)saved_key)[(index&(SIMD_COEF_64-1)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64]; int len = (keybuffer[15*SIMD_COEF_64] >> 3) - SALT_SIZE; for (i = 0; i < len; ++i) key[i] = wucp[GETPOS(SALT_SIZE + i, index)]; key[i] = 0; return (char*)key; #endif } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; #ifdef _OPENMP #ifndef SIMD_COEF_64 #ifdef PRECOMPUTE_CTX_FOR_SALT #pragma omp parallel for default(none) private(index) shared(ctx_salt, saved_key, saved_len, crypt_out) #else #pragma omp parallel for default(none) private(index) shared(saved_salt, saved_key, saved_len, crypt_out) #endif #else #pragma omp parallel for #endif #endif for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) { #ifdef SIMD_COEF_64 SIMDSHA512body(&saved_key[index/MAX_KEYS_PER_CRYPT], &crypt_out[HASH_IDX], NULL, SSEi_MIXED_IN); #else SHA512_CTX ctx; #ifdef PRECOMPUTE_CTX_FOR_SALT memcpy(&ctx, &ctx_salt, sizeof(ctx)); #else SHA512_Init(&ctx); SHA512_Update(&ctx, &saved_salt, SALT_SIZE); #endif SHA512_Update(&ctx, saved_key[index], saved_len[index]); SHA512_Final((unsigned char *)(crypt_out[index]), &ctx); #endif } return count; } static int cmp_all(void *binary, int count) { unsigned int index; for (index = 0; index < count; index++) #ifdef SIMD_COEF_64 if (((ARCH_WORD_64 *) binary)[0] == crypt_out[HASH_IDX]) #else if ( ((ARCH_WORD_32*)binary)[0] == crypt_out[index][0] ) #endif return 1; return 0; } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_64 int i; for (i = 0; i < BINARY_SIZE/sizeof(ARCH_WORD_64); i++) if (((ARCH_WORD_64*) binary)[i] != crypt_out[HASH_IDX + i*SIMD_COEF_64]) return 0; return 1; #else return !memcmp(binary, crypt_out[index], BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_XSHA512 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, XSHA512_BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { NULL }, sha512_common_tests_xsha512 }, { init, done, fmt_default_reset, sha512_common_prepare_xsha512, sha512_common_valid_xsha512, sha512_common_split_xsha512, sha512_common_binary_xsha512, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
common.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_UTILS_COMMON_H_ #define LIGHTGBM_UTILS_COMMON_H_ #if ((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__))) #include <LightGBM/utils/common_legacy_solaris.h> #endif #include <LightGBM/utils/log.h> #include <LightGBM/utils/openmp_wrapper.h> #include <limits> #include <string> #include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <cstdio> #include <cstring> #include <functional> #include <iomanip> #include <iterator> #include <map> #include <memory> #include <sstream> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> #if (!((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)))) #define FMT_HEADER_ONLY #include "LightGBM/fmt/format.h" #endif #include "LightGBM/fast_double_parser.h" #ifdef _MSC_VER #include <intrin.h> #pragma intrinsic(_BitScanReverse) #endif #if defined(_MSC_VER) #include <malloc.h> #elif MM_MALLOC #include <mm_malloc.h> // https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html // https://www.oreilly.com/library/view/mac-os-x/0596003560/ch05s01s02.html #elif defined(__GNUC__) && defined(HAVE_MALLOC_H) #include <malloc.h> #define _mm_malloc(a, b) memalign(b, a) #define _mm_free(a) free(a) #else #include <stdlib.h> #define _mm_malloc(a, b) malloc(a) #define _mm_free(a) free(a) #endif namespace LightGBM { namespace Common { /*! * Imbues the stream with the C locale. */ static void C_stringstream(std::stringstream &ss) { ss.imbue(std::locale::classic()); } inline static char tolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } inline static std::string Trim(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of(" \f\n\r\t\v") + 1); str.erase(0, str.find_first_not_of(" \f\n\r\t\v")); return str; } inline static std::string RemoveQuotationSymbol(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of("'\"") + 1); str.erase(0, str.find_first_not_of("'\"")); return str; } inline static bool StartsWith(const std::string& str, const std::string prefix) { if (str.substr(0, prefix.size()) == prefix) { return true; } else { return false; } } inline static std::vector<std::string> Split(const char* c_str, char delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == delimiter) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> SplitBrackets(const char* c_str, char left_delimiter, char right_delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; bool open = false; while (pos < str.length()) { if (str[pos] == left_delimiter) { open = true; ++pos; i = pos; } else if (str[pos] == right_delimiter && open) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } open = false; ++pos; } else { ++pos; } } return ret; } inline static std::vector<std::string> SplitLines(const char* c_str) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == '\n' || str[pos] == '\r') { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } // skip the line endings while (str[pos] == '\n' || str[pos] == '\r') ++pos; // new begin i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> Split(const char* c_str, const char* delimiters) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { bool met_delimiters = false; for (int j = 0; delimiters[j] != '\0'; ++j) { if (str[pos] == delimiters[j]) { met_delimiters = true; break; } } if (met_delimiters) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } template<typename T> inline static const char* Atoi(const char* p, T* out) { int sign; T value; while (*p == ' ') { ++p; } sign = 1; if (*p == '-') { sign = -1; ++p; } else if (*p == '+') { ++p; } for (value = 0; *p >= '0' && *p <= '9'; ++p) { value = value * 10 + (*p - '0'); } *out = static_cast<T>(sign * value); while (*p == ' ') { ++p; } return p; } template<typename T> inline static double Pow(T base, int power) { if (power < 0) { return 1.0 / Pow(base, -power); } else if (power == 0) { return 1; } else if (power % 2 == 0) { return Pow(base*base, power / 2); } else if (power % 3 == 0) { return Pow(base*base*base, power / 3); } else { return base * Pow(base, power - 1); } } inline static const char* Atof(const char* p, double* out) { int frac; double sign, value, scale; *out = NAN; // Skip leading white space, if any. while (*p == ' ') { ++p; } // Get sign, if any. sign = 1.0; if (*p == '-') { sign = -1.0; ++p; } else if (*p == '+') { ++p; } // is a number if ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E') { // Get digits before decimal point or exponent, if any. for (value = 0.0; *p >= '0' && *p <= '9'; ++p) { value = value * 10.0 + (*p - '0'); } // Get digits after decimal point, if any. if (*p == '.') { double right = 0.0; int nn = 0; ++p; while (*p >= '0' && *p <= '9') { right = (*p - '0') + right * 10.0; ++nn; ++p; } value += right / Pow(10.0, nn); } // Handle exponent, if any. frac = 0; scale = 1.0; if ((*p == 'e') || (*p == 'E')) { uint32_t expon; // Get sign of exponent, if any. ++p; if (*p == '-') { frac = 1; ++p; } else if (*p == '+') { ++p; } // Get digits of exponent, if any. for (expon = 0; *p >= '0' && *p <= '9'; ++p) { expon = expon * 10 + (*p - '0'); } if (expon > 308) expon = 308; // Calculate scaling factor. while (expon >= 50) { scale *= 1E50; expon -= 50; } while (expon >= 8) { scale *= 1E8; expon -= 8; } while (expon > 0) { scale *= 10.0; expon -= 1; } } // Return signed and scaled floating point result. *out = sign * (frac ? (value / scale) : (value * scale)); } else { size_t cnt = 0; while (*(p + cnt) != '\0' && *(p + cnt) != ' ' && *(p + cnt) != '\t' && *(p + cnt) != ',' && *(p + cnt) != '\n' && *(p + cnt) != '\r' && *(p + cnt) != ':') { ++cnt; } if (cnt > 0) { std::string tmp_str(p, cnt); std::transform(tmp_str.begin(), tmp_str.end(), tmp_str.begin(), Common::tolower); if (tmp_str == std::string("na") || tmp_str == std::string("nan") || tmp_str == std::string("null")) { *out = NAN; } else if (tmp_str == std::string("inf") || tmp_str == std::string("infinity")) { *out = sign * 1e308; } else { Log::Fatal("Unknown token %s in data file", tmp_str.c_str()); } p += cnt; } } while (*p == ' ') { ++p; } return p; } inline static bool AtoiAndCheck(const char* p, int* out) { const char* after = Atoi(p, out); if (*after != '\0') { return false; } return true; } inline static bool AtofAndCheck(const char* p, double* out) { const char* after = Atof(p, out); if (*after != '\0') { return false; } return true; } inline static const char* SkipSpaceAndTab(const char* p) { while (*p == ' ' || *p == '\t') { ++p; } return p; } inline static const char* SkipReturn(const char* p) { while (*p == '\n' || *p == '\r' || *p == ' ') { ++p; } return p; } template<typename T, typename T2> inline static std::vector<T2> ArrayCast(const std::vector<T>& arr) { std::vector<T2> ret(arr.size()); for (size_t i = 0; i < arr.size(); ++i) { ret[i] = static_cast<T2>(arr[i]); } return ret; } template<typename T, bool is_float> struct __StringToTHelper { T operator()(const std::string& str) const { T ret = 0; Atoi(str.c_str(), &ret); return ret; } }; template<typename T> struct __StringToTHelper<T, true> { T operator()(const std::string& str) const { return static_cast<T>(std::stod(str)); } }; template<typename T> inline static std::vector<T> StringToArray(const std::string& str, char delimiter) { std::vector<std::string> strs = Split(str.c_str(), delimiter); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T> inline static std::vector<std::vector<T>> StringToArrayofArrays( const std::string& str, char left_bracket, char right_bracket, char delimiter) { std::vector<std::string> strs = SplitBrackets(str.c_str(), left_bracket, right_bracket); std::vector<std::vector<T>> ret; for (const auto& s : strs) { ret.push_back(StringToArray<T>(s, delimiter)); } return ret; } template<typename T> inline static std::vector<T> StringToArray(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } std::vector<std::string> strs = Split(str.c_str(), ' '); CHECK_EQ(strs.size(), static_cast<size_t>(n)); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T, bool is_float> struct __StringToTHelperFast { const char* operator()(const char*p, T* out) const { return Atoi(p, out); } }; template<typename T> struct __StringToTHelperFast<T, true> { const char* operator()(const char*p, T* out) const { double tmp = 0.0f; auto ret = Atof(p, &tmp); *out = static_cast<T>(tmp); return ret; } }; template<typename T> inline static std::vector<T> StringToArrayFast(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } auto p_str = str.c_str(); __StringToTHelperFast<T, std::is_floating_point<T>::value> helper; std::vector<T> ret(n); for (int i = 0; i < n; ++i) { p_str = helper(p_str, &ret[i]); } return ret; } template<typename T> inline static std::string Join(const std::vector<T>& strs, const char* delimiter, const bool force_C_locale = false) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; if (force_C_locale) { C_stringstream(str_buf); } str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[0]; for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } template<> inline std::string Join<int8_t>(const std::vector<int8_t>& strs, const char* delimiter, const bool force_C_locale) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; if (force_C_locale) { C_stringstream(str_buf); } str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << static_cast<int16_t>(strs[0]); for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << static_cast<int16_t>(strs[i]); } return str_buf.str(); } template<typename T> inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter, const bool force_C_locale = false) { if (end - start <= 0) { return std::string(""); } start = std::min(start, static_cast<size_t>(strs.size()) - 1); end = std::min(end, static_cast<size_t>(strs.size())); std::stringstream str_buf; if (force_C_locale) { C_stringstream(str_buf); } str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[start]; for (size_t i = start + 1; i < end; ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } inline static int64_t Pow2RoundUp(int64_t x) { int64_t t = 1; for (int i = 0; i < 64; ++i) { if (t >= x) { return t; } t <<= 1; } return 0; } /*! * \brief Do inplace softmax transformation on p_rec * \param p_rec The input/output vector of the values. */ inline static void Softmax(std::vector<double>* p_rec) { std::vector<double> &rec = *p_rec; double wmax = rec[0]; for (size_t i = 1; i < rec.size(); ++i) { wmax = std::max(rec[i], wmax); } double wsum = 0.0f; for (size_t i = 0; i < rec.size(); ++i) { rec[i] = std::exp(rec[i] - wmax); wsum += rec[i]; } for (size_t i = 0; i < rec.size(); ++i) { rec[i] /= static_cast<double>(wsum); } } inline static void Softmax(const double* input, double* output, int len) { double wmax = input[0]; for (int i = 1; i < len; ++i) { wmax = std::max(input[i], wmax); } double wsum = 0.0f; for (int i = 0; i < len; ++i) { output[i] = std::exp(input[i] - wmax); wsum += output[i]; } for (int i = 0; i < len; ++i) { output[i] /= static_cast<double>(wsum); } } template<typename T> std::vector<const T*> ConstPtrInVectorWrapper(const std::vector<std::unique_ptr<T>>& input) { std::vector<const T*> ret; for (auto t = input.begin(); t !=input.end(); ++t) { ret.push_back(t->get()); } return ret; } template<typename T1, typename T2> inline static void SortForPair(std::vector<T1>* keys, std::vector<T2>* values, size_t start, bool is_reverse = false) { std::vector<std::pair<T1, T2>> arr; auto& ref_key = *keys; auto& ref_value = *values; for (size_t i = start; i < keys->size(); ++i) { arr.emplace_back(ref_key[i], ref_value[i]); } if (!is_reverse) { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first < b.first; }); } else { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first > b.first; }); } for (size_t i = start; i < arr.size(); ++i) { ref_key[i] = arr[i].first; ref_value[i] = arr[i].second; } } template <typename T> inline static std::vector<T*> Vector2Ptr(std::vector<std::vector<T>>* data) { std::vector<T*> ptr(data->size()); auto& ref_data = *data; for (size_t i = 0; i < data->size(); ++i) { ptr[i] = ref_data[i].data(); } return ptr; } template <typename T> inline static std::vector<int> VectorSize(const std::vector<std::vector<T>>& data) { std::vector<int> ret(data.size()); for (size_t i = 0; i < data.size(); ++i) { ret[i] = static_cast<int>(data[i].size()); } return ret; } inline static double AvoidInf(double x) { if (std::isnan(x)) { return 0.0; } else if (x >= 1e300) { return 1e300; } else if (x <= -1e300) { return -1e300; } else { return x; } } inline static float AvoidInf(float x) { if (std::isnan(x)) { return 0.0f; } else if (x >= 1e38) { return 1e38f; } else if (x <= -1e38) { return -1e38f; } else { return x; } } template<typename _Iter> inline static typename std::iterator_traits<_Iter>::value_type* IteratorValType(_Iter) { return (0); } template<typename _RanIt, typename _Pr, typename _VTRanIt> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred, _VTRanIt*) { size_t len = _Last - _First; const size_t kMinInnerLen = 1024; int num_threads = OMP_NUM_THREADS(); if (len <= kMinInnerLen || num_threads <= 1) { std::sort(_First, _Last, _Pred); return; } size_t inner_size = (len + num_threads - 1) / num_threads; inner_size = std::max(inner_size, kMinInnerLen); num_threads = static_cast<int>((len + inner_size - 1) / inner_size); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < num_threads; ++i) { size_t left = inner_size*i; size_t right = left + inner_size; right = std::min(right, len); if (right > left) { std::sort(_First + left, _First + right, _Pred); } } // Buffer for merge. std::vector<_VTRanIt> temp_buf(len); _RanIt buf = temp_buf.begin(); size_t s = inner_size; // Recursive merge while (s < len) { int loop_size = static_cast<int>((len + s * 2 - 1) / (s * 2)); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < loop_size; ++i) { size_t left = i * 2 * s; size_t mid = left + s; size_t right = mid + s; right = std::min(len, right); if (mid >= right) { continue; } std::copy(_First + left, _First + mid, buf + left); std::merge(buf + left, buf + mid, _First + mid, _First + right, _First + left, _Pred); } s *= 2; } } template<typename _RanIt, typename _Pr> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred) { return ParallelSort(_First, _Last, _Pred, IteratorValType(_First)); } // Check that all y[] are in interval [ymin, ymax] (end points included); throws error if not template <typename T> inline static void CheckElementsIntervalClosed(const T *y, T ymin, T ymax, int ny, const char *callername) { auto fatal_msg = [&y, &ymin, &ymax, &callername](int i) { std::ostringstream os; os << "[%s]: does not tolerate element [#%i = " << y[i] << "] outside [" << ymin << ", " << ymax << "]"; Log::Fatal(os.str().c_str(), callername, i); }; for (int i = 1; i < ny; i += 2) { if (y[i - 1] < y[i]) { if (y[i - 1] < ymin) { fatal_msg(i - 1); } else if (y[i] > ymax) { fatal_msg(i); } } else { if (y[i - 1] > ymax) { fatal_msg(i - 1); } else if (y[i] < ymin) { fatal_msg(i); } } } if (ny & 1) { // odd if (y[ny - 1] < ymin || y[ny - 1] > ymax) { fatal_msg(ny - 1); } } } // One-pass scan over array w with nw elements: find min, max and sum of elements; // this is useful for checking weight requirements. template <typename T1, typename T2> inline static void ObtainMinMaxSum(const T1 *w, int nw, T1 *mi, T1 *ma, T2 *su) { T1 minw; T1 maxw; T1 sumw; int i; if (nw & 1) { // odd minw = w[0]; maxw = w[0]; sumw = w[0]; i = 2; } else { // even if (w[0] < w[1]) { minw = w[0]; maxw = w[1]; } else { minw = w[1]; maxw = w[0]; } sumw = w[0] + w[1]; i = 3; } for (; i < nw; i += 2) { if (w[i - 1] < w[i]) { minw = std::min(minw, w[i - 1]); maxw = std::max(maxw, w[i]); } else { minw = std::min(minw, w[i]); maxw = std::max(maxw, w[i - 1]); } sumw += w[i - 1] + w[i]; } if (mi != nullptr) { *mi = minw; } if (ma != nullptr) { *ma = maxw; } if (su != nullptr) { *su = static_cast<T2>(sumw); } } inline static std::vector<uint32_t> EmptyBitset(int n) { int size = n / 32; if (n % 32 != 0) ++size; return std::vector<uint32_t>(size); } template<typename T> inline static void InsertBitset(std::vector<uint32_t>* vec, const T val) { auto& ref_v = *vec; int i1 = val / 32; int i2 = val % 32; if (static_cast<int>(vec->size()) < i1 + 1) { vec->resize(i1 + 1, 0); } ref_v[i1] |= (1 << i2); } template<typename T> inline static std::vector<uint32_t> ConstructBitset(const T* vals, int n) { std::vector<uint32_t> ret; for (int i = 0; i < n; ++i) { int i1 = vals[i] / 32; int i2 = vals[i] % 32; if (static_cast<int>(ret.size()) < i1 + 1) { ret.resize(i1 + 1, 0); } ret[i1] |= (1 << i2); } return ret; } template<typename T> inline static bool FindInBitset(const uint32_t* bits, int n, T pos) { int i1 = pos / 32; if (i1 >= n) { return false; } int i2 = pos % 32; return (bits[i1] >> i2) & 1; } inline static bool CheckDoubleEqualOrdered(double a, double b) { double upper = std::nextafter(a, INFINITY); return b <= upper; } inline static double GetDoubleUpperBound(double a) { return std::nextafter(a, INFINITY); } inline static size_t GetLine(const char* str) { auto start = str; while (*str != '\0' && *str != '\n' && *str != '\r') { ++str; } return str - start; } inline static const char* SkipNewLine(const char* str) { if (*str == '\r') { ++str; } if (*str == '\n') { ++str; } return str; } template <typename T> static int Sign(T x) { return (x > T(0)) - (x < T(0)); } template <typename T> static T SafeLog(T x) { if (x > 0) { return std::log(x); } else { return -INFINITY; } } inline bool CheckAllowedJSON(const std::string& s) { unsigned char char_code; for (auto c : s) { char_code = static_cast<unsigned char>(c); if (char_code == 34 // " || char_code == 44 // , || char_code == 58 // : || char_code == 91 // [ || char_code == 93 // ] || char_code == 123 // { || char_code == 125 // } ) { return false; } } return true; } inline int RoundInt(double x) { return static_cast<int>(x + 0.5f); } template <typename T, std::size_t N = 32> class AlignmentAllocator { public: typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; inline AlignmentAllocator() throw() {} template <typename T2> inline AlignmentAllocator(const AlignmentAllocator<T2, N>&) throw() {} inline ~AlignmentAllocator() throw() {} inline pointer adress(reference r) { return &r; } inline const_pointer adress(const_reference r) const { return &r; } inline pointer allocate(size_type n) { return (pointer)_mm_malloc(n * sizeof(value_type), N); } inline void deallocate(pointer p, size_type) { _mm_free(p); } inline void construct(pointer p, const value_type& wert) { new (p) value_type(wert); } inline void destroy(pointer p) { p->~value_type(); } inline size_type max_size() const throw() { return size_type(-1) / sizeof(value_type); } template <typename T2> struct rebind { typedef AlignmentAllocator<T2, N> other; }; bool operator!=(const AlignmentAllocator<T, N>& other) const { return !(*this == other); } // Returns true if and only if storage allocated from *this // can be deallocated from other, and vice versa. // Always returns true for stateless allocators. bool operator==(const AlignmentAllocator<T, N>&) const { return true; } }; class Timer { public: Timer() { #ifdef TIMETAG int num_threads = OMP_NUM_THREADS(); start_time_.resize(num_threads); stats_.resize(num_threads); #endif // TIMETAG } ~Timer() { Print(); } #ifdef TIMETAG void Start(const std::string& name) { auto tid = omp_get_thread_num(); start_time_[tid][name] = std::chrono::steady_clock::now(); } void Stop(const std::string& name) { auto cur_time = std::chrono::steady_clock::now(); auto tid = omp_get_thread_num(); if (stats_[tid].find(name) == stats_[tid].end()) { stats_[tid][name] = std::chrono::duration<double, std::milli>(0); } stats_[tid][name] += cur_time - start_time_[tid][name]; } #else void Start(const std::string&) {} void Stop(const std::string&) {} #endif // TIMETAG void Print() const { #ifdef TIMETAG std::unordered_map<std::string, std::chrono::duration<double, std::milli>> stats(stats_[0].begin(), stats_[0].end()); for (size_t i = 1; i < stats_.size(); ++i) { for (auto it = stats_[i].begin(); it != stats_[i].end(); ++it) { if (stats.find(it->first) == stats.end()) { stats[it->first] = it->second; } else { stats[it->first] += it->second; } } } std::map<std::string, std::chrono::duration<double, std::milli>> ordered( stats.begin(), stats.end()); for (auto it = ordered.begin(); it != ordered.end(); ++it) { Log::Info("%s costs:\t %f", it->first.c_str(), it->second * 1e-3); } #endif // TIMETAG } #ifdef TIMETAG std::vector< std::unordered_map<std::string, std::chrono::steady_clock::time_point>> start_time_; std::vector<std::unordered_map<std::string, std::chrono::duration<double, std::milli>>> stats_; #endif // TIMETAG }; // Note: this class is not thread-safe, don't use it inside omp blocks class FunctionTimer { public: #ifdef TIMETAG FunctionTimer(const std::string& name, Timer& timer) : timer_(timer) { timer.Start(name); name_ = name; } ~FunctionTimer() { timer_.Stop(name_); } private: std::string name_; Timer& timer_; #else FunctionTimer(const std::string&, Timer&) {} #endif // TIMETAG }; } // namespace Common extern Common::Timer global_timer; /*! * Provides locale-independent alternatives to Common's methods. * Essential to make models robust to locale settings. */ namespace CommonC { template<typename T> inline static std::string Join(const std::vector<T>& strs, const char* delimiter) { return LightGBM::Common::Join(strs, delimiter, true); } template<typename T> inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter) { return LightGBM::Common::Join(strs, start, end, delimiter, true); } inline static const char* Atof(const char* p, double* out) { return LightGBM::Common::Atof(p, out); } template<typename T, bool is_float> struct __StringToTHelperFast { const char* operator()(const char*p, T* out) const { return LightGBM::Common::Atoi(p, out); } }; /*! * \warning Beware that ``Common::Atof`` in ``__StringToTHelperFast``, * has **less** floating point precision than ``__StringToTHelper``. * Both versions are kept to maintain bit-for-bit the "legacy" LightGBM behaviour in terms of precision. * Check ``StringToArrayFast`` and ``StringToArray`` for more details on this. */ template<typename T> struct __StringToTHelperFast<T, true> { const char* operator()(const char*p, T* out) const { double tmp = 0.0f; auto ret = Atof(p, &tmp); *out = static_cast<T>(tmp); return ret; } }; template<typename T, bool is_float> struct __StringToTHelper { T operator()(const std::string& str) const { T ret = 0; LightGBM::Common::Atoi(str.c_str(), &ret); return ret; } }; /*! * \warning Beware that ``Common::Atof`` in ``__StringToTHelperFast``, * has **less** floating point precision than ``__StringToTHelper``. * Both versions are kept to maintain bit-for-bit the "legacy" LightGBM behaviour in terms of precision. * Check ``StringToArrayFast`` and ``StringToArray`` for more details on this. * \note It is possible that ``fast_double_parser::parse_number`` is faster than ``Common::Atof``. */ template<typename T> struct __StringToTHelper<T, true> { T operator()(const std::string& str) const { double tmp; // Fast (common) path: For numeric inputs in RFC 7159 format: const bool fast_parse_succeeded = fast_double_parser::parse_number(str.c_str(), &tmp); // Rare path: Not in RFC 7159 format. Possible "inf", "nan", etc. Fallback to standard library: if (!fast_parse_succeeded) { std::stringstream ss; Common::C_stringstream(ss); ss << str; ss >> tmp; } return static_cast<T>(tmp); } }; /*! * \warning Beware that due to internal use of ``Common::Atof`` in ``__StringToTHelperFast``, * this method has less precision for floating point numbers than ``StringToArray``, * which calls ``__StringToTHelper``. * As such, ``StringToArrayFast`` and ``StringToArray`` are not equivalent! * Both versions were kept to maintain bit-for-bit the "legacy" LightGBM behaviour in terms of precision. */ template<typename T> inline static std::vector<T> StringToArrayFast(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } auto p_str = str.c_str(); __StringToTHelperFast<T, std::is_floating_point<T>::value> helper; std::vector<T> ret(n); for (int i = 0; i < n; ++i) { p_str = helper(p_str, &ret[i]); } return ret; } /*! * \warning Do not replace calls to this method by ``StringToArrayFast``. * This method is more precise for floating point numbers. * Check ``StringToArrayFast`` for more details. */ template<typename T> inline static std::vector<T> StringToArray(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } std::vector<std::string> strs = LightGBM::Common::Split(str.c_str(), ' '); CHECK_EQ(strs.size(), static_cast<size_t>(n)); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } /*! * \warning Do not replace calls to this method by ``StringToArrayFast``. * This method is more precise for floating point numbers. * Check ``StringToArrayFast`` for more details. */ template<typename T> inline static std::vector<T> StringToArray(const std::string& str, char delimiter) { std::vector<std::string> strs = LightGBM::Common::Split(str.c_str(), delimiter); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } #if (!((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)))) /*! * Safely formats a value onto a buffer according to a format string and null-terminates it. * * \note It checks that the full value was written or forcefully aborts. * This safety check serves to prevent incorrect internal API usage. * Correct usage will never incur in this problem: * - The received buffer size shall be sufficient at all times for the input format string and value. */ template <typename T> inline static void format_to_buf(char* buffer, const size_t buf_len, const char* format, const T value) { auto result = fmt::format_to_n(buffer, buf_len, format, value); if (result.size >= buf_len) { Log::Fatal("Numerical conversion failed. Buffer is too small."); } buffer[result.size] = '\0'; } template<typename T, bool is_float, bool high_precision> struct __TToStringHelper { void operator()(T value, char* buffer, size_t buf_len) const { format_to_buf(buffer, buf_len, "{}", value); } }; template<typename T> struct __TToStringHelper<T, true, false> { void operator()(T value, char* buffer, size_t buf_len) const { format_to_buf(buffer, buf_len, "{:g}", value); } }; template<typename T> struct __TToStringHelper<T, true, true> { void operator()(T value, char* buffer, size_t buf_len) const { format_to_buf(buffer, buf_len, "{:.17g}", value); } }; /*! * Converts an array to a string with with values separated by the space character. * This method replaces Common's ``ArrayToString`` and ``ArrayToStringFast`` functionality * and is locale-independent. * * \note If ``high_precision_output`` is set to true, * floating point values are output with more digits of precision. */ template<bool high_precision_output = false, typename T> inline static std::string ArrayToString(const std::vector<T>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } __TToStringHelper<T, std::is_floating_point<T>::value, high_precision_output> helper; const size_t buf_len = high_precision_output ? 32 : 16; std::vector<char> buffer(buf_len); std::stringstream str_buf; Common::C_stringstream(str_buf); helper(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { helper(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } #endif // (!((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)))) } // namespace CommonC } // namespace LightGBM #endif // LIGHTGBM_UTILS_COMMON_H_
parallel-simple.c
/* * parallel-simple.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run-race | FileCheck %s // RUN: %libarcher-compile-and-run-race-noserial | FileCheck %s // REQUIRES: tsan #include <omp.h> #include <stdio.h> int main(int argc, char *argv[]) { int var = 0; #pragma omp parallel num_threads(8) shared(var) { var++; } int error = (var != 2); fprintf(stderr, "DONE\n"); return error; } // CHECK: WARNING: ThreadSanitizer: data race // CHECK-NEXT: {{(Write|Read)}} of size 4 // CHECK-NEXT: #0 {{.*}}parallel-simple.c:23 // CHECK: Previous write of size 4 // CHECK-NEXT: #0 {{.*}}parallel-simple.c:23 // CHECK: DONE // CHECK: ThreadSanitizer: reported 1 warnings
stats_tools.c
/*Daala video codec Copyright (c) 2013 Daala project contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <string.h> #include "stats_tools.h" #include "od_defs.h" #include "od_filter.h" #include "od_intra.h" #include "../src/dct.h" #include "../src/intra.h" #define PRINT_SCALE (0) void mode_data_init(mode_data *_md,int _b_sz){ int i; _md->n=0; _md->mean=0; _md->var=0; for(i=0;i<B_SZ_MAX*B_SZ_MAX;i++){ _md->satd_avg[i]=0; } od_covmat_init(&_md->ref,_b_sz*_b_sz); od_covmat_init(&_md->res,_b_sz*_b_sz); } void mode_data_clear(mode_data *_md){ od_covmat_clear(&_md->ref); od_covmat_clear(&_md->res); } void mode_data_reset(mode_data *_md){ int i; _md->n=0; _md->mean=0; _md->var=0; for(i=0;i<B_SZ_MAX*B_SZ_MAX;i++){ _md->satd_avg[i]=0; } od_covmat_reset(&_md->ref); od_covmat_reset(&_md->res); } /* update the input mean and variance */ void mode_data_add_input(mode_data *_md,const unsigned char *_data,int _stride, int _b_sz){ int n; int i; int j; n=_md->n*_b_sz*_b_sz; for(j=0;j<_b_sz;j++){ for(i=0;i<_b_sz;i++){ double delta; double s; n++; s=1.0/n; delta=_data[_stride*j+i]*INPUT_SCALE-_md->mean; _md->mean+=delta*s; _md->var+=delta*delta*(n-1)*s; } } _md->n++; } void mode_data_add_block(mode_data *_md,const od_coeff *_block,int _stride, int _ref){ int j; int i; double buf[B_SZ*B_SZ]; for(j=0;j<B_SZ;j++){ for(i=0;i<B_SZ;i++){ buf[B_SZ*j+i]=_block[_stride*j+i]; } } if(_ref){ od_covmat_add(&_md->ref,buf,1); } else{ od_covmat_add(&_md->res,buf,1); } } void mode_data_combine(mode_data *_a,const mode_data *_b){ double s; double delta; int i; if(_b->n==0){ return; } s=((double)_b->n)/(_a->n+_b->n); delta=_b->mean-_a->mean; _a->mean+=delta*s; for(i=0;i<B_SZ_MAX*B_SZ_MAX;i++){ _a->satd_avg[i]+=(_b->satd_avg[i]-_a->satd_avg[i])*s; } s*=_a->n; _a->var+=_b->var+delta*s; od_covmat_combine(&_a->ref,&_b->ref); od_covmat_combine(&_a->res,&_b->res); _a->n+=_b->n; } void mode_data_correct(mode_data *_md,int _b_sz){ _md->var/=_md->n*_b_sz*_b_sz; od_covmat_correct(&_md->ref); od_covmat_correct(&_md->res); } void mode_data_print(mode_data *_md,const char *_label,double *_scale, int _b_sz){ double cg_ref; double cg_res; int v; int u; double satd_avg; double bits_avg; cg_ref=10*log10(_md->var); cg_res=10*log10(_md->var); satd_avg=0; bits_avg=0; for(v=0;v<_b_sz;v++){ for(u=0;u<_b_sz;u++){ int i; int ii; double b; i=_b_sz*v+u; ii=_b_sz*_b_sz*i+i; cg_ref-=10*log10(_md->ref.cov[ii]*_scale[v]*_scale[u])/(_b_sz*_b_sz); cg_res-=10*log10(_md->res.cov[ii]*_scale[v]*_scale[u])/(_b_sz*_b_sz); satd_avg+=sqrt(_scale[v]*_scale[u])*_md->satd_avg[i]; b=sqrt(_scale[v]*_scale[u]*_md->res.cov[ii]/2); bits_avg+=1+OD_LOG2(b)+M_LOG2E/b*_md->satd_avg[i]; } } printf("%s Blocks %5i SATD %G Bits %G Mean %G Var %G CgRef %G CgRes %G Pg %G\n", _label,_md->n,satd_avg,bits_avg,_md->mean,_md->var,cg_ref,cg_res,cg_res-cg_ref); } void mode_data_params(mode_data *_this,double _b[B_SZ*B_SZ],double *_scale){ int v; int u; int i; int ii; for(v=0;v<B_SZ;v++){ for(u=0;u<B_SZ;u++){ i=(v*B_SZ+u); ii=B_SZ*B_SZ*i+i; _b[i]=sqrt(_scale[v]*_scale[u]*_this->res.cov[ii]/2); } } } void intra_stats_init(intra_stats *_this,int _b_sz_log){ int mode; _this->b_sz_log=_b_sz_log; mode_data_init(&_this->fr,1<<_b_sz_log); for(mode=0;mode<OD_INTRA_NMODES;mode++){ mode_data_init(&_this->md[mode],1<<_b_sz_log); } } void intra_stats_clear(intra_stats *_this){ int i; mode_data_clear(&_this->fr); for(i=0;i<OD_INTRA_NMODES;i++){ mode_data_clear(&_this->md[i]); } } void intra_stats_reset(intra_stats *_this){ int i; mode_data_reset(&_this->fr); for(i=0;i<OD_INTRA_NMODES;i++){ mode_data_reset(&_this->md[i]); } } void intra_stats_update(intra_stats *_this,const unsigned char *_data, int _stride,int _mode,const od_coeff *_ref,int _ref_stride, const double *_res,int _res_stride){ int b_sz; mode_data *fr; mode_data *md; int j; int i; double buf[B_SZ_MAX*B_SZ_MAX]; b_sz=1<<_this->b_sz_log; fr=&_this->fr; md=&_this->md[_mode]; /* Update the input mean and variance. */ mode_data_add_input(fr,_data,_stride,b_sz); mode_data_add_input(md,_data,_stride,b_sz); /* Update the reference mean and covariance. */ for(j=0;j<b_sz;j++){ for(i=0;i<b_sz;i++){ buf[b_sz*j+i]=_ref[_ref_stride*j+i]; } } od_covmat_add(&fr->ref,buf,1); od_covmat_add(&md->ref,buf,1); /* Update the residual mean and covariance. */ for(j=0;j<b_sz;j++){ for(i=0;i<b_sz;i++){ buf[b_sz*j+i]=_res[_res_stride*j+i]; } } od_covmat_add(&fr->res,buf,1); od_covmat_add(&md->res,buf,1); /* Update the average SATD. */ for(j=0;j<b_sz;j++){ for(i=0;i<b_sz;i++){ double satd; satd=abs(buf[b_sz*j+i]); fr->satd_avg[b_sz*j+i]+=(satd-fr->satd_avg[b_sz*j+i])/fr->n; md->satd_avg[b_sz*j+i]+=(satd-md->satd_avg[b_sz*j+i])/md->n; } } } void intra_stats_correct(intra_stats *_this){ int mode; mode_data_correct(&_this->fr,1<<_this->b_sz_log); for(mode=0;mode<OD_INTRA_NMODES;mode++){ mode_data_correct(&_this->md[mode],1<<_this->b_sz_log); } } void intra_stats_print(intra_stats *_this,const char *_label, double *_scale){ int mode; printf("%s\n",_label); for(mode=0;mode<OD_INTRA_NMODES;mode++){ char label[16]; sprintf(label,"Mode %i",mode); mode_data_print(&_this->md[mode],label,_scale,1<<_this->b_sz_log); } mode_data_print(&_this->fr,"Pooled",_scale,1<<_this->b_sz_log); } void intra_stats_combine(intra_stats *_this,const intra_stats *_that){ int mode; mode_data_combine(&_this->fr,&_that->fr); for(mode=0;mode<OD_INTRA_NMODES;mode++){ mode_data_combine(&_this->md[mode],&_that->md[mode]); } } /* compute the scale factors for the DCT and TDLT transforms */ double VP8_SCALE[OD_NBSIZES][B_SZ_MAX]; double OD_SCALE[OD_NBSIZES][B_SZ_MAX]; #define SCALE_BITS (14) void vp8_scale_init(double *_vp8_scale,int _b_sz_log){ int b_sz; int j; int i; od_coeff buf[B_SZ_MAX]; b_sz=1<<_b_sz_log; for(i=0;i<b_sz;i++){ for(j=0;j<b_sz;j++){ buf[j]=i!=j?0:(1<<SCALE_BITS); } (*OD_IDCT_1D[_b_sz_log-OD_LOG_BSIZE0])(buf,1,buf); _vp8_scale[i]=0; for(j=0;j<b_sz;j++){ double c=((double)buf[j])/(1<<SCALE_BITS); _vp8_scale[i]+=c*c; } #if PRINT_SCALE printf("%s%- 24.18G",i==0?"":" ",_vp8_scale[i]); #endif } #if PRINT_SCALE printf("\n"); #endif } #define APPLY_PREFILTER (1) #define APPLY_POSTFILTER (1) void od_scale_init(double *_od_scale,int _b_sz_log){ int b_sz; int i; int j; od_coeff buf[2*B_SZ_MAX]; b_sz=1<<_b_sz_log; for(i=0;i<b_sz;i++){ for(j=0;j<2*b_sz;j++){ buf[j]=(b_sz>>1)+i!=j?0:(1<<SCALE_BITS); } (*OD_IDCT_1D[_b_sz_log-OD_LOG_BSIZE0])(&buf[b_sz>>1],1,&buf[b_sz>>1]); #if APPLY_POSTFILTER (*NE_POST_FILTER[_b_sz_log-OD_LOG_BSIZE0])(buf,buf); (*NE_POST_FILTER[_b_sz_log-OD_LOG_BSIZE0])(&buf[b_sz],&buf[b_sz]); #endif _od_scale[i]=0; for(j=0;j<2*b_sz;j++){ double c=((double)buf[j])/(1<<SCALE_BITS); _od_scale[i]+=c*c; } #if PRINT_SCALE printf("%s%- 24.18G",i==0?"":" ",_od_scale[i]); #endif } #if PRINT_SCALE printf("\n"); #endif } #define SCALE_SATD (1) /* find the best vp8 mode */ int vp8_select_mode(const unsigned char *_data,int _stride,double *_weight){ int best_mode; double best_satd; double next_best_satd; double *vp8_scale; int mode; best_mode=0; best_satd=UINT_MAX; next_best_satd=best_satd; vp8_scale=VP8_SCALE[B_SZ_LOG-OD_LOG_BSIZE0]; for(mode=0;mode<OD_INTRA_NMODES;mode++){ unsigned char block[B_SZ*B_SZ]; od_coeff buf[B_SZ*B_SZ]; int j; int i; double satd; memset(block,0,B_SZ*B_SZ); vp8_intra_predict(block,B_SZ,_data,_stride,mode); for(j=0;j<B_SZ;j++){ for(i=0;i<B_SZ;i++){ buf[B_SZ*j+i]=block[B_SZ*j+i]-_data[_stride*j+i]; } } #if B_SZ_LOG>=OD_LOG_BSIZE0&&B_SZ_LOG<OD_LOG_BSIZE0+OD_NBSIZES (*OD_FDCT_2D[B_SZ_LOG-OD_LOG_BSIZE0])(buf,B_SZ,buf,B_SZ); #else # error "Need an fDCT implementation for this block size." #endif satd=0; for(j=0;j<B_SZ;j++){ for(i=0;i<B_SZ;i++){ #if SCALE_SATD satd+=sqrt(vp8_scale[j]*vp8_scale[i])*abs(buf[B_SZ*j+i]); #else satd+=abs(buf[B_SZ*j+i]); #endif } } if(satd<best_satd){ next_best_satd=best_satd; best_satd=satd; best_mode=mode; } else{ if(satd<next_best_satd){ next_best_satd=satd; } } } if(_weight!=NULL){ *_weight=best_mode!=0?next_best_satd-best_satd:1; } return best_mode; } int od_select_mode_bits(const od_coeff *_block,double *_weight, double _b[OD_INTRA_NMODES][B_SZ*B_SZ]){ const od_coeff *c; int best_mode; double best_bits; double next_best_bits; double *od_scale; int mode; c=_block+4*B_SZ*B_SZ; best_mode=0; best_bits=UINT_MAX; next_best_bits=best_bits; od_scale=OD_SCALE[B_SZ_LOG-OD_LOG_BSIZE0]; for(mode=0;mode<OD_INTRA_NMODES;mode++){ double p[B_SZ*B_SZ]; double bits; int j; int i; #if B_SZ_LOG>=OD_LOG_BSIZE0&&B_SZ_LOG<OD_LOG_BSIZE0+OD_NBSIZES #if 0 (*OD_INTRA_MULT[B_SZ_LOG-OD_LOG_BSIZE0])(p,_block,_stride,mode); #else (*NE_INTRA_MULT[B_SZ_LOG-OD_LOG_BSIZE0])(p,B_SZ,_block,mode); #endif #else # error "Need a predictor implementation for this block size." #endif bits=0; for(j=0;j<B_SZ;j++){ for(i=0;i<B_SZ;i++){ double res; res=sqrt(od_scale[j]*od_scale[i])* abs(c[B_SZ*j+i]-(od_coeff)floor(p[B_SZ*j+i]+0.5)); bits+=1+OD_LOG2(_b[mode][j*B_SZ+i])+M_LOG2E/_b[mode][j*B_SZ+i]*res; } } if(bits<best_bits){ next_best_bits=best_bits; best_bits=bits; best_mode=mode; } else{ if(bits<next_best_bits){ next_best_bits=bits; } } } if(_weight!=NULL){ *_weight=best_mode!=0?next_best_bits-best_bits:1; } return best_mode; } int od_select_mode_satd(const od_coeff *_block,double *_weight,int _b_sz_log){ int b_sz; const od_coeff *c; int best_mode; double best_satd; double next_best_satd; double *od_scale; int mode; b_sz=1<<_b_sz_log; c=_block+4*b_sz*b_sz; best_mode=0; best_satd=UINT_MAX; next_best_satd=best_satd; od_scale=OD_SCALE[_b_sz_log-OD_LOG_BSIZE0]; for(mode=0;mode<OD_INTRA_NMODES;mode++){ double p[B_SZ_MAX*B_SZ_MAX]; double satd; int j; int i; (*NE_INTRA_MULT[_b_sz_log-OD_LOG_BSIZE0])(p,b_sz,_block,mode); satd=0; for(j=0;j<b_sz;j++){ for(i=0;i<b_sz;i++){ #if SCALE_SATD satd+=sqrt(od_scale[j]*od_scale[i])* abs(c[b_sz*j+i]-(od_coeff)floor(p[b_sz*j+i]+0.5)); #else satd+=abs(c[b_sz*j+i]-(od_coeff)floor(p[b_sz*j+i]+0.5)); #endif } } if(satd<best_satd){ next_best_satd=best_satd; best_mode=mode; best_satd=satd; } else{ if(satd<next_best_satd){ next_best_satd=satd; } } } if(_weight!=NULL){ *_weight=best_mode!=0?next_best_satd-best_satd:1; } return best_mode; } int ne_apply_to_blocks(void *_ctx,int _ctx_sz,int _plmask,int _padding, plane_start_func _start,int _nfuncs,const block_func *_funcs, plane_finish_func _finish,int _argc,const char *_argv[]){ int ai; #pragma omp parallel for schedule(dynamic) for(ai=1;ai<_argc;ai++){ FILE *fin; video_input vid; video_input_info info; video_input_ycbcr ycbcr; int pli; int tid; unsigned char *ctx; fin=fopen(_argv[ai],"rb"); if(fin==NULL){ fprintf(stderr,"Could not open '%s' for reading.\n",_argv[ai]); continue; } if(video_input_open(&vid,fin)<0){ fprintf(stderr,"Error reading video info from '%s'.\n",_argv[ai]); continue; } video_input_get_info(&vid,&info); if(video_input_fetch_frame(&vid,ycbcr,NULL)<0){ fprintf(stderr,"Error reading first frame from '%s'.\n",_argv[ai]); continue; } tid=OD_OMP_GET_THREAD; ctx=((unsigned char *)_ctx)+tid*_ctx_sz; for(pli=0;pli<3;pli++){ if(_plmask&1<<pli){ int x0; int y0; int nxblocks; int nyblocks; get_intra_dims(&info,pli,_padding,&x0,&y0,&nxblocks,&nyblocks); if(_start!=NULL){ (*_start)(ctx,_argv[ai],&info,pli,nxblocks,nyblocks); } if(_funcs!=NULL){ int f; for(f=0;f<_nfuncs;f++){ if(_funcs[f]!=NULL){ const unsigned char *data; int stride; int bj; int bi; data=ycbcr[pli].data; stride=ycbcr[pli].stride; for(bj=0;bj<nyblocks;bj++){ int y; y=y0+B_SZ*bj; for(bi=0;bi<nxblocks;bi++){ int x; x=x0+B_SZ*bi; (*_funcs[f])(ctx,&data[stride*y+x],stride,bi,bj); } } } } } if(_finish!=NULL){ (*_finish)(ctx); } } } video_input_close(&vid); } return EXIT_SUCCESS; }
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/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/APINotes/APINotesManager.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <functional> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; /// A key method to reduce duplicate debug info from Sema. virtual void anchor(); ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions FPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; api_notes::APINotesManager APINotes; /// 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; void Act(SourceLocation PragmaLocation, PragmaClangSectionAction Action, StringLiteral* Name); }; 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) }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value); // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; // #pragma pack. // Sentinel to represent when the stack is set to mac68k alignment. static const unsigned kMac68kAlignmentSentinel = ~0U; PragmaStack<unsigned> PackStack; // The current #pragma pack values and locations at each #include. struct PackIncludeState { unsigned CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<PackIncludeState, 8> PackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. 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::SmallPtrSet<Expr *, 2>; 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; 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; } /// \brief Callback to the parser to parse a type expressed as a string. std::function<TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback; class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// A flag to indicate that we're in a context that permits abstract /// references to fields. This is really a bool AllowAbstractFieldReference; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// Whether we are in a decltype expression. bool IsDecltype; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; 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; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the FP_CONTRACT state on entry/exit of compound /// statements. class FPContractStateRAII { public: FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } private: Sema& S; FPOptions OldFPFeaturesState; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getFPOptions() { return FPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// 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. SemaDiagnosticBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class SemaDiagnosticBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op // in that case anwyay. SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; ~SemaDiagnosticBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First flush the underlying // DiagnosticBuilder data, and clear the diagnostic builder itself so it // won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. FlushCounts(); Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template<typename T> friend const SemaDiagnosticBuilder &operator<<( const SemaDiagnosticBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } }; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; void emitAndClearUnusedLocalTypedefWarnings(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool 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); 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); 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 { 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 swift_name /// attribute for the decl \p D. Raise a diagnostic if the name is invalid /// for the given declaration. /// /// For a function, this will validate a compound Swift name, /// e.g. <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, /// and the function will output the number of parameter names, and whether /// this is a single-arg initializer. /// /// For a type, enum constant, property, or variable declaration, this will /// validate either a simple identifier, or a qualified /// <code>context.identifier</code> name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation ArgLoc, const IdentifierInfo *AttrName); private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return !D->isHidden() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T) { return !RequireCompleteTypeImpl(Loc, T, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// 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 a non-type, and an expression representing /// that name has been formed. NC_ContextIndependentExpr, /// 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, }; 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 ContextIndependentExpr(ExprResult E) { NameClassification Result(NC_ContextIndependentExpr); 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 UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_ContextIndependentExpr); 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_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_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); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range); bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); QualType adjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // 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 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); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); DeclContext *getContainingDC(DeclContext *DC); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Uuid); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name, bool Override); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true); ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// 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, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfOnlyViableOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfOnlyViableOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); 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); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplate }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, 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); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing); bool isKnownName(StringRef name); /// 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); // 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 Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr(Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(E, nullptr, Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(ER, nullptr, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Map any API notes provided for this declaration to attributes on the /// declaration. /// /// Triggered by declaration-attribute processing. void ProcessAPINotes(Decl *D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Check whether a nullability type specifier can be added to the given /// type through some means not written in source (e.g. API notes). /// /// \param type The type to which the nullability specifier will be /// added. On success, this type will be updated appropriately. /// /// \param nullability The nullability specifier to add. /// /// \param diagLoc The location to use for diagnostics. /// /// \param allowArrayTypes Whether to accept nullability specifiers on an /// array type (e.g., because it will decay to a pointer). /// /// \param overrideExisting Whether to override an existing, locally-specified /// nullability specifier rather than complaining about the conflict. /// /// \returns true if nullability cannot be applied, false otherwise. bool checkImplicitNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, SourceLocation diagLoc, bool allowArrayTypes, bool overrideExisting); /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// 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); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// 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 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); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); 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); 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 DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); // "({..})" // 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); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// default constructor of a class will have, and whether the parameter /// will be const. ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD); /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult 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(SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc); /// 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); /// 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, and false is returned. bool CheckConstraintExpression(Expr *CE); private: /// \brief 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; public: /// \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); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \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(TemplateDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); bool CheckConstraintSatisfaction(ClassTemplatePartialSpecializationDecl *TD, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); bool CheckConstraintSatisfaction(VarTemplatePartialSpecializationDecl *TD, 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 that the associated constraints of a template declaration match the /// associated constraints of an older declaration of which it is a /// redeclaration. bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old, TemplateParameterList *New); /// \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. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction& Satisfaction); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied because it was ill-formed. void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation, StringRef Diagnostic); void DiagnoseRedeclarationConstraintMismatch(const TemplateParameterList *Old, const TemplateParameterList *New); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, 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(Scope *S, Decl *Template); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void 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 AmbigiousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool 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. NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); 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, SourceLocation TemplateKWLoc = SourceLocation(), AssumedTemplateKind *ATK = nullptr); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization); /// 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); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// 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(Decl *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); DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc, 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 ActOnDependentTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); // Concepts Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression, UPPC_Block }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const 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 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, /// 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); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); 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); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); VarDecl *getVarTemplateSpecialization( VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs, const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc); 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 ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; /// Check whether the declared result type of the given Objective-C /// method declaration is compatible with the method's class. ResultTypeCompatibilityKind checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method, const ObjCInterfaceDecl *CurrentClass); 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 PragmaPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, DeclaratorDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// FreePackedContext - Deallocate and null out PackContext. void FreePackedContext(); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(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); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = Ext; } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. unsigned DeclareTargetNestingLevel = 0; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// 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); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckForDelayedContext = true); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckCaller = true); /// Check if the expression is allowed to be used in expressions for the /// OpenMP devices. void checkOpenMPDeviceExpr(const Expr *E); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); /// Marks all the functions that might be required for the currently active /// OpenMP context. void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse); public: /// Struct to store the context selectors info for declare variant directive. using OMPCtxStringType = SmallString<8>; using OMPCtxSelectorData = OpenMPCtxSelectorData<SmallVector<OMPCtxStringType, 4>, ExprResult>; /// 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. bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, 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 requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); /// Called at the end of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, ArrayRef<OMPClause *> ClauseList); /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return DeclareTargetNestingLevel > 0; } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type); /// 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. /// \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, 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 Data Set of context-specific data for the specified context /// selector. void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, SourceRange SR, ArrayRef<OMPCtxSelectorData> Data); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation DepLinMapLastLoc); /// 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, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause *ActOnOpenMPFromClause( ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 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 '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); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This is DefaultFunctionArrayLvalueConversion, // except that it assumes the operand isn't of function or array // type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// 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, /// 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, AssignmentAction Action, bool AllowExplicit, ImplicitConversionSequence& ICS); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); 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 FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // 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, Function = 0x2, DerivedToBase = 0x4, ObjC = 0x8, ObjCLifetime = 0x10, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); virtual ~VerifyICEDiagnoser() { } }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr); /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// A partial call graph maintained during CUDA/OpenMP device code compilation /// to support deferred diagnostics. /// /// Functions are only added here if, at the time they're considered, they are /// not known-emitted. As soon as we discover that a function is /// known-emitted, we remove it and everything it transitively calls from this /// set and add those functions to DeviceKnownEmittedFns. llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, SourceLocation>> DeviceCallGraph; /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be /// deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class DeviceDiagBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); DeviceDiagBuilder(DeviceDiagBuilder &&D); DeviceDiagBuilder(const DeviceDiagBuilder &) = default; ~DeviceDiagBuilder(); /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (DeviceDiagBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a DeviceDiagBuilder yourself. operator bool() const { return ImmediateDiag.hasValue(); } template <typename T> friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Indicate that this function (and thus everything it transtively calls) /// will be codegen'ed, and emit any deferred diagnostics on this function and /// its (transitive) callees. void markKnownEmitted( Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, SourceLocation OrigLoc, const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder 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. DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas declared inside __device__ or __global__ functions inherit /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ /// functions become __host__ __device__ themselves. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); void CodeCompleteAfterIf(Scope *S); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, 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 CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(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 CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(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 AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; 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; } /// 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 }; }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getRawEncoding()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
geometryIO.h
// This code is part of the Problem Based Benchmark Suite (PBBS) // Copyright (c) 2011 Guy Blelloch and the PBBS team // // 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 _BENCH_GEOMETRY_IO #define _BENCH_GEOMETRY_IO #include "IO.h" #include "parallel.h" #include "geometry.h" using namespace benchIO; inline int xToStringLen(point2d a) { return xToStringLen(a.x) + xToStringLen(a.y) + 1; } inline void xToString(char* s, point2d a) { int l = xToStringLen(a.x); xToString(s, a.x); s[l] = ' '; xToString(s+l+1, a.y); } inline int xToStringLen(point3d a) { return xToStringLen(a.x) + xToStringLen(a.y) + xToStringLen(a.z) + 2; } inline void xToString(char* s, point3d a) { int lx = xToStringLen(a.x); int ly = xToStringLen(a.y); xToString(s, a.x); s[lx] = ' '; xToString(s+lx+1, a.y); s[lx+ly+1] = ' '; xToString(s+lx+ly+2, a.z); } inline int xToStringLen(triangle a) { return xToStringLen(a.C[0]) + xToStringLen(a.C[1]) + xToStringLen(a.C[2]) + 2; } inline void xToString(char* s, triangle a) { int lx = xToStringLen(a.C[0]); int ly = xToStringLen(a.C[1]); xToString(s, a.C[0]); s[lx] = ' '; xToString(s+lx+1, a.C[1]); s[lx+ly+1] = ' '; xToString(s+lx+ly+2, a.C[2]); } namespace benchIO { using namespace std; string HeaderPoint2d = "pbbs_sequencePoint2d"; string HeaderPoint3d = "pbbs_sequencePoint3d"; string HeaderTriangles = "pbbs_triangles"; template <class pointT> int writePointsToFile(pointT* P, intT n, char* fname) { string Header = (pointT::dim == 2) ? HeaderPoint2d : HeaderPoint3d; int r = writeArrayToFile(Header, P, n, fname); return r; } template <class pointT> void parsePoints(char** Str, pointT* P, intT n) { int d = pointT::dim; double* a = newA(double,n*d); #pragma omp parallel for schedule(dynamic,1) for (long i=0; i < d*n; i++) a[i] = atof(Str[i]); #pragma omp parallel for schedule(dynamic,1) for (long i=0; i < n; i++) P[i] = pointT(a+(d*i)); free(a); } template <class pointT> _seq<pointT> readPointsFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); int d = pointT::dim; if (W.m == 0 || W.Strings[0] != (d == 2 ? HeaderPoint2d : HeaderPoint3d)) { cout << "readPointsFromFile wrong file type" << endl; abort(); } long n = (W.m-1)/d; pointT *P = newA(pointT, n); parsePoints(W.Strings + 1, P, n); return _seq<pointT>(P, n); } triangles<point2d> readTrianglesFromFileNodeEle(char* fname) { string nfilename(fname); _seq<char> S = readStringFromFile((char*)nfilename.append(".node").c_str()); words W = stringToWords(S.A, S.n); triangles<point2d> Tr; Tr.numPoints = atol(W.Strings[0]); if (W.m < 4*Tr.numPoints + 4) { cout << "readStringFromFileNodeEle inconsistent length" << endl; abort(); } Tr.P = newA(point2d, Tr.numPoints); for(intT i=0; i < Tr.numPoints; i++) Tr.P[i] = point2d(atof(W.Strings[4*i+5]), atof(W.Strings[4*i+6])); string efilename(fname); _seq<char> SN = readStringFromFile((char*)efilename.append(".ele").c_str()); words WE = stringToWords(SN.A, SN.n); Tr.numTriangles = atol(WE.Strings[0]); if (WE.m < 4*Tr.numTriangles + 3) { cout << "readStringFromFileNodeEle inconsistent length" << endl; abort(); } Tr.T = newA(triangle, Tr.numTriangles); for (long i=0; i < Tr.numTriangles; i++) for (int j=0; j < 3; j++) Tr.T[i].C[j] = atol(WE.Strings[4*i + 4 + j]); return Tr; } template <class pointT> triangles<pointT> readTrianglesFromFile(char* fname, intT offset) { int d = pointT::dim; _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); if (W.Strings[0] != HeaderTriangles) { cout << "readTrianglesFromFile wrong file type" << endl; abort(); } int headerSize = 3; triangles<pointT> Tr; Tr.numPoints = atol(W.Strings[1]); Tr.numTriangles = atol(W.Strings[2]); if (W.m != headerSize + 3 * Tr.numTriangles + d * Tr.numPoints) { cout << "readTrianglesFromFile inconsistent length" << endl; abort(); } Tr.P = newA(pointT, Tr.numPoints); parsePoints(W.Strings + headerSize, Tr.P, Tr.numPoints); Tr.T = newA(triangle, Tr.numTriangles); char** Triangles = W.Strings + headerSize + d * Tr.numPoints; for (long i=0; i < Tr.numTriangles; i++) for (int j=0; j < 3; j++) Tr.T[i].C[j] = atol(Triangles[3*i + j])-offset; return Tr; } template <class pointT> int writeTrianglesToFile(triangles<pointT> Tr, char* fileName) { ofstream file (fileName, ios::binary); if (!file.is_open()) { std::cout << "Unable to open file: " << fileName << std::endl; return 1; } file << HeaderTriangles << endl; file << Tr.numPoints << endl; file << Tr.numTriangles << endl; writeArrayToStream(file, Tr.P, Tr.numPoints); writeArrayToStream(file, Tr.T, Tr.numTriangles); file.close(); return 0; } }; #endif // _BENCH_GEOMETRY_IO
Vertex.h
#pragma once template<typename real_t> struct Pos2D { real_t x, y, h; Pos2D() {} Pos2D(const real_t _x, const real_t _y, const real_t _h) : x(_x), y(_y), h(_h) {} bool isVisible() const { return h > 0.0f; } }; template<typename real_t> struct Pos3D { real_t x,y,z,h; Pos3D() {} Pos3D(const real_t _x, const real_t _y, const real_t _z, const real_t _h) : x(_x), y(_y), z(_z), h(_h) {} }; template<typename real_t> struct Attribute { real_t rho, vel, I, type; Attribute() {} Attribute(const real_t _rho, const real_t _vel, const real_t _I = 1.0f, const real_t _type = 1.0f ) : rho(_rho), vel(_vel), I(_I), type(_type) {} }; template<typename Tpos, typename Tattr, typename Tcolor> class VertexArrayT { private: Tpos *_pos; Tcolor *_color; Tattr *_attr; int _size; public: struct Vertex { Tpos pos; Tattr attr; Tcolor color; Vertex(const Tpos &_pos, const Tcolor &_color, const Tattr &_attr) : pos(_pos), color(_color), attr(_attr) {} bool isVisible() const { return pos.isVisible(); } Vertex operator=(const Vertex &v) { pos = v.pos; color = v.color; attr = v.attr; } }; struct VertexRef { Tpos &pos; Tcolor &color; Tattr &attr; VertexRef(Tpos &_pos, Tcolor &_color, Tattr &_attr) : pos(_pos), color(_color), attr(_attr) {} VertexRef& operator=(const Vertex &v) { pos = v.pos; color = v.color; attr = v.attr; return *this; } VertexRef& operator=(const VertexRef &v) { pos = v.pos; color = v.color; attr = v.attr; return *this; } operator Vertex() const { return Vertex(pos,color,attr); } bool isVisible() const {return pos.isVisible(); } }; private: void free() { if (_size > 0) { ::free(_pos ); ::free(_color); ::free(_attr ); _size = 0; } _pos = NULL; _color = NULL; _attr = NULL; } public: void realloc(const int size) { free(); _size = size; if (_size > 0) { _pos = (Tpos *)::malloc(sizeof(Tpos )*_size); _color = (Tcolor*)::malloc(sizeof(Tcolor)*_size); _attr = (Tattr *)::malloc(sizeof(Tattr )*_size); } } VertexArrayT(const int size = 0) : _pos(NULL), _color(NULL), _attr(NULL), _size(size) { realloc(size); } VertexArrayT(const Tpos *pos, const Tcolor *color, const Tattr *attr, const int size) { realloc(size); #pragma omp parallel for schedule(static) for (int i = 0; i < _size; i++) { _pos [i] = pos [i]; _color[i] = color[i]; _attr [i] = attr [i]; } } ~VertexArrayT() { free(); } friend void swap(VertexArrayT &a, VertexArrayT &b) { std::swap(a._pos, b._pos); std::swap(a._color, b._color); std::swap(a._attr, b._attr); std::swap(a._size, b._size); } VertexRef operator[](const int i) {return VertexRef(_pos[i], _color[i], _attr[i]);} const VertexRef operator[](const int i) const {return VertexRef(_pos[i], _color[i], _attr[i]);} int size() const {return _size;} };
task-dependency.c
/* * task-dependency.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run | FileCheck %s #include <omp.h> #include <stdio.h> #include <unistd.h> #include "ompt/ompt-signal.h" int main(int argc, char *argv[]) { int var = 0, a = 0; #pragma omp parallel num_threads(2) shared(var, a) #pragma omp master { #pragma omp task shared(var, a) depend(out : var) { var++; OMPT_SIGNAL(a); } #pragma omp task shared(var, a) depend(in : var) { OMPT_WAIT(a, 2); } #pragma omp task shared(var, a) depend(in : var) { OMPT_SIGNAL(a); var++; } // Give other thread time to steal the task. OMPT_WAIT(a, 1); } fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK-NOT: ThreadSanitizer: data race // CHECK-NOT: ThreadSanitizer: reported // CHECK: DONE
zkbdf_verify.c
/* Name: zkbdf_verify.c Author: Tan Teik Guan Description: Verify function for VDF realization using ZKBoo with PCP optimization. Modified from MPC_SHA256_VERIFIER.c */ /* ============================================================================ Name : MPC_SHA256_VERIFIER.c Author : Sobuno Version : 0.1 Description : Verifies a proof for SHA-256 generated by MPC_SHA256.c ============================================================================ */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/time.h> #include "shared.h" int NUM_ROUNDS = 100; int NUM_LOOPS = 1; void printbits(uint32_t n) { if (n) { printbits(n >> 1); printf("%d", n & 1); } } #define CH(e,f,g) ((e & f) ^ ((~e) & g)) int sha256(unsigned char* result, unsigned char* input, int numBits) { uint32_t hA[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; int remainingBits = numBits; int chars; int i; while (remainingBits >= 0) { if (remainingBits > 447) { chars = 64; remainingBits -= 512; } else { chars = remainingBits >> 3; remainingBits = -1; } unsigned char* chunk = calloc(64, 1); //512 bits memcpy(chunk, input, chars); input += chars; if (chars < 64) { chunk[chars] = 0x80; chunk[60] = numBits >> 24; chunk[61] = numBits >> 16; chunk[62] = numBits >> 8; chunk[63] = numBits; } uint32_t w[64]; for (i = 0; i < 16; i++) { w[i] = (chunk[i * 4] << 24) | (chunk[i * 4 + 1] << 16) | (chunk[i * 4 + 2] << 8) | chunk[i * 4 + 3]; } uint32_t s0, s1; for (i = 16; i < 64; i++) { s0 = RIGHTROTATE(w[i - 15], 7) ^ RIGHTROTATE(w[i - 15], 18) ^ (w[i - 15] >> 3); s1 = RIGHTROTATE(w[i - 2], 17) ^ RIGHTROTATE(w[i - 2], 19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] + s0 + w[i - 7] + s1; } uint32_t a, b, c, d, e, f, g, h, temp1, temp2, maj; a = hA[0]; b = hA[1]; c = hA[2]; d = hA[3]; e = hA[4]; f = hA[5]; g = hA[6]; h = hA[7]; for (i = 0; i < 64; i++) { s1 = RIGHTROTATE(e,6) ^ RIGHTROTATE(e, 11) ^ RIGHTROTATE(e, 25); temp1 = h + s1 + CH(e, f, g) + k[i] + w[i]; s0 = RIGHTROTATE(a,2) ^ RIGHTROTATE(a, 13) ^ RIGHTROTATE(a, 22); maj = (a & (b ^ c)) ^ (b & c); temp2 = s0 + maj; h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2; } hA[0] += a; hA[1] += b; hA[2] += c; hA[3] += d; hA[4] += e; hA[5] += f; hA[6] += g; hA[7] += h; } for (i = 0; i < 8; i++) { result[i * 4] = (hA[i] >> 24); result[i * 4 + 1] = (hA[i] >> 16); result[i * 4 + 2] = (hA[i] >> 8); result[i * 4 + 3] = hA[i]; } return 0; } int GetNextSelected(int size,unsigned char * data, int *dataPtr) { int value=0; int modulo = size; while (size > 0) { value <<=8; value += (int) data[*dataPtr]; size >>=8; (*dataPtr)++; } if (!(value & 0x01)) value++; return (int) value % modulo; } int main(int argc, char * argv[]) { setbuf(stdout, NULL); init_EVP(); openmp_thread_setup(); char CHALLENGE[BLOCK_SIZE]; char ek[BLOCK_SIZE]; if (argc != 4) { printf("Usage: %s <number of rounds (e.g. 20, 40, 60, 80, 100)> <challenge (Max %d char> <eval key (Max %d char)>\n",argv[0],MSG_SIZE,MSG_SIZE); return -1; } NUM_ROUNDS = atoi(argv[1]); memset(CHALLENGE,0,sizeof(CHALLENGE)); strncpy(CHALLENGE,argv[2],MSG_SIZE); memset(ek,0,sizeof(ek)); strncpy(ek,argv[3],MSG_SIZE); int PCProunds = (int) ceil(log(NUM_ROUNDS)/log(2)); int Totalselected = 0; unsigned char PCPselected[NUM_ROUNDS]; unsigned char tempBuf[64]; unsigned char hashBuf[NUM_ROUNDS*32]; unsigned char rootHash[32]; int tempBufPtr; int Nextselected; int failed = 0; printf("Iterations of PCP: %d\n", PCProunds); int i; i = strlen(ek); printf("length of ek: %d\n",i); unsigned char input[BLOCK_SIZE]; memset(input,0,sizeof(input)); for (int j=0;j<i;j++) input[j] = ek[j]; a as[2][PCProunds]; z zs[2][PCProunds]; unsigned char MerkleBranch[PCProunds][(32*2*PCProunds)]; FILE *file; char outputFile[3*sizeof(int) + 8]; sprintf(outputFile, "pcp%i-%i.bin", NUM_ROUNDS,PCProunds); file = fopen(outputFile, "rb"); if (!file) { printf("Unable to open file!"); return -1; } memset(rootHash,0,sizeof(rootHash)); memset(hashBuf,0,sizeof(hashBuf)); memset(MerkleBranch,0,PCProunds*32*2*PCProunds); fread(rootHash,32,1,file); fread(hashBuf,32,NUM_ROUNDS,file); memset(tempBuf,0,sizeof(tempBuf)); memcpy(&(tempBuf[32]),rootHash,32); sha256(tempBuf,tempBuf,64*8); tempBufPtr = 0; memset(PCPselected,0,sizeof(PCPselected)); while (Totalselected < PCProunds) { Nextselected = GetNextSelected(NUM_ROUNDS,tempBuf,&tempBufPtr); if (!PCPselected[Nextselected]) { PCPselected[Nextselected] = 1; Totalselected++; } if (tempBufPtr >= 32) { sha256(tempBuf,tempBuf,64*8); tempBufPtr = 0; } } for (int j = 0; j < PCProunds;j++) { fread(MerkleBranch[j],64,PCProunds,file); fread(&(as[0][j]), sizeof(a), 1, file); fread(&(zs[0][j]), sizeof(z), 1, file); fread(&(as[1][j]), sizeof(a), 1, file); fread(&(zs[1][j]), sizeof(z), 1, file); } fclose(file); struct timeval begin, delta; gettimeofday(&begin,NULL); for(int loops=0;loops<NUM_LOOPS;loops++) { uint32_t y1[8]; uint32_t y2[8]; reconstruct(as[0][0].yp1[0],as[0][0].yp1[1],as[0][0].yp1[2],y1); reconstruct(as[0][0].yp2[0],as[0][0].yp2[1],as[0][0].yp2[2],y2); printf("Received output for H(ek): "); for(int i=0;i<8;i++) { printf("%02X", y1[i]); } printf("\n"); printf("Received output for Hmac(ek,challenge): "); for(int i=0;i<8;i++) { printf("%02X", y2[i]); } printf("\n"); { SHA256_CTX ctx; unsigned char expectedhash[SHA256_DIGEST_LENGTH]; int l; SHA256_Init(&ctx); SHA256_Update(&ctx, input, strlen(input)); SHA256_Final(expectedhash, &ctx); for (l=0;l<8;l++) { uint32_t temp; // to take care of big endian unsigned char tempc[4]; tempc[0] = expectedhash[l*4+3]; tempc[1] = expectedhash[l*4+2]; tempc[2] = expectedhash[l*4+1]; tempc[3] = expectedhash[l*4]; memcpy(&temp,tempc,4); if (temp != y1[l]) { printf("hash does not match !!\n"); return -1; } } } int es[2][PCProunds*2]; unsigned char plaintext[2][PCProunds][16]; int branchdone; int Nextselected = 0;; for (int i=0; i<(PCProunds); i++) { SHA256_CTX ctx; unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_Init(&ctx); SHA256_Update(&ctx, &(zs[0][i]), sizeof(z)); SHA256_Final(hash, &ctx); while ((PCPselected[Nextselected] != 1) && (Nextselected<NUM_ROUNDS)) Nextselected++; if (memcmp(hash,&(hashBuf[Nextselected*32]),32)) { printf("Hash Not Verified %d\n", i); failed = 1; continue; } memcpy(&(plaintext[0][i]),&(hashBuf[(Nextselected-1)*32]),16); if (Nextselected>1) memcpy(&(plaintext[1][i]),&(hashBuf[(Nextselected-2)*32]),16); else memset(&(plaintext[1][i]),0x30,16); Nextselected++; if (memcmp(hash,&(MerkleBranch[i][32]),32)) { printf("Hash branch Not Verified %d\n", i); failed = 1; continue; } // #pragma omp parallel for for (int k = 0; k < (PCProunds-1); k++) { unsigned char branchhash[32]; if (!failed) { sha256(branchhash,&(MerkleBranch[i][k*64]),64*8); if (memcmp(branchhash,&(MerkleBranch[i][(k+1)*64]),32)) { if (memcmp(branchhash,&(MerkleBranch[i][(k+1)*64+32]),32)) { printf("Hash branch not verified %d %d\n",k,i); failed = 1; } } } } if (failed) continue; sha256(hash,&(MerkleBranch[i][(PCProunds-1)*64]),64*8); if (memcmp(hash,rootHash,32)) { printf("root hash not verified %d \n",i); failed = 1; } if (failed) continue; H3(y1,y2,&(as[0][i]), 1, &(es[0][i])); H3(y1,y2,&(as[1][i]), 1, &(es[1][i])); } if (!failed) { #pragma omp parallel for for(int i = 0; i<(PCProunds); i++) { int verifyResult = verify(as[0][i], CHALLENGE, es[0][i], plaintext[0][i], zs[0][i]); if (verifyResult != 0) { printf("Not Verified %d\n", i); failed = 1; } else { int verifyResult = verify(as[1][i], CHALLENGE, es[1][i], plaintext[1][i], zs[1][i]); if (verifyResult != 0) { printf("Not previous Verified %d \n", i); failed = 1; } } } } } if (!failed) printf("verified ok\n"); gettimeofday(&delta,NULL); unsigned long inMilli = (delta.tv_sec - begin.tv_sec)*1000000 + (delta.tv_usec - begin.tv_usec); inMilli /= 1000; printf("Total time for %d loops: %ju miliseconds\n", NUM_LOOPS,(uintmax_t)inMilli); printf("Time for 1 loop: %ju miliseconds\n", (uintmax_t)inMilli/NUM_LOOPS); openmp_thread_cleanup(); cleanup_EVP(); return EXIT_SUCCESS; }
GB_binop__pair_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__pair_int8 // A.*B function (eWiseMult): GB_AemultB__pair_int8 // A*D function (colscale): GB_AxD__pair_int8 // D*A function (rowscale): GB_DxB__pair_int8 // C+=B function (dense accum): GB_Cdense_accumB__pair_int8 // C+=b function (dense accum): GB_Cdense_accumb__pair_int8 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__pair_int8 // C=scalar+B (none) // C=scalar+B' (none) // C=A+scalar (none) // C=A'+scalar (none) // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = 1 #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int8_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) \ ; // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = 1 ; // 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_PAIR || GxB_NO_INT8 || GxB_NO_PAIR_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__pair_int8 ( 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__pair_int8 ( 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__pair_int8 ( 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 int8_t int8_t bwork = (*((int8_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__pair_int8 ( 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 int8_t *GB_RESTRICT Cx = (int8_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__pair_int8 ( 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 int8_t *GB_RESTRICT Cx = (int8_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__pair_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__pair_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info (none) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
atomic.c
/* Copyright (C) 2005-2018 Free Software Foundation, Inc. Contributed by Richard Henderson <rth@redhat.com>. This file is part of the GNU Offloading and Multi Processing Library (libgomp). Libgomp is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ /* This file contains helpers for the ATOMIC construct. */ #include "libgomp.h" /* This mutex is used when atomic operations don't exist for the target in the mode requested. The result is not globally atomic, but works so long as all parallel references are within #pragma omp atomic directives. According to responses received from omp@openmp.org, appears to be within spec. Which makes sense, since that's how several other compilers handle this situation as well. */ static gomp_mutex_t atomic_lock; void GOMP_atomic_start (void) { gomp_mutex_lock (&atomic_lock); } void GOMP_atomic_end (void) { gomp_mutex_unlock (&atomic_lock); } #if !GOMP_MUTEX_INIT_0 static void __attribute__((constructor)) initialize_atomic (void) { gomp_mutex_init (&atomic_lock); } #endif
fmt.c
/** * @file fmt.c * 各種分子積分計算で用いる誤差関数の計算に関する関数群 * * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "ofmo-def.h" #ifdef USE_CUDA //#include "cuda/cudalib.h" #include "cuda/cuda-fmt.h" #endif //#define Free(a) if ( a != NULL ) free( a ); a = NULL static double FMT_inv2 = 1.0 / 2.0; static double FMT_inv6 = 1.0 / 6.0; static int FMT_fmt_m; static int FMT_fmt_inv_d = 512; // 2^9 static int FMT_fmt_max_m; static double FMT_fmt_t; static int FMT_fmt_n_step; static double *FMT_fmt_table; // 変更 double FMT_fmt_step_size; double FMT_fmt_inv_step_size; double FMT_pi_div2; static int FMT_fmt_max_m1; static int FMT_MAXLQN = -1; // 各m専用のテーブル // double *FMT_fmt_table0; double *FMT_fmt_table1; double *FMT_fmt_table2; double *FMT_fmt_table3; double *FMT_fmt_table4; double *FMT_fmt_table5; double *FMT_fmt_table6; double *FMT_fmt_table7; double *FMT_fmt_table8; /* --------------------------------------------------------------- 不完全Γ関数(誤差関数)計算の後処理ルーチン ------------------------------------------------------------------ */ static void fmt_finalize() { int ret; if (FMT_MAXLQN < 0) return; if (FMT_fmt_table != NULL) Free( FMT_fmt_table ); if (FMT_fmt_table0 != NULL) { Free( FMT_fmt_table0 ); Free( FMT_fmt_table1 ); Free( FMT_fmt_table2 ); Free( FMT_fmt_table3 ); Free( FMT_fmt_table4 ); Free( FMT_fmt_table5 ); Free( FMT_fmt_table6 ); Free( FMT_fmt_table7 ); Free( FMT_fmt_table8 ); } FMT_fmt_table = NULL; FMT_fmt_table0 = NULL; FMT_fmt_table1 = NULL; FMT_fmt_table2 = NULL; FMT_fmt_table3 = NULL; FMT_fmt_table4 = NULL; FMT_fmt_table5 = NULL; FMT_fmt_table6 = NULL; FMT_fmt_table7 = NULL; FMT_fmt_table8 = NULL; FMT_MAXLQN = -1; } /** 誤差関数計算関数の初期化ルーチン * * 誤差関数\f$ F_m(T)=\int_0^1 t^{2m}\exp[-Tt^2]\f$の計算で用いる * 誤差関数テーブルを作成する * * @param[in] max_lqn 最大軌道量子数 * * @return なし * * @ingroup integ-fmt * */ void fmt_initialize(int max_lqn) { double thr_zero = 1.0e-17; int i,j,m,nu; double eps,t,expt,t2,term,func; int it0; #ifdef USE_CUDA if (max_lqn<2) max_lqn = 2; #endif if (max_lqn <= FMT_MAXLQN) return; if (FMT_MAXLQN < 0) atexit(fmt_finalize); // 最初に呼び出されたとき if ( FMT_fmt_table != NULL ) free( FMT_fmt_table ); //fmt_finalize(); // 基本的な変数の定義 FMT_fmt_m = 4 * max_lqn + 2; FMT_fmt_max_m = FMT_fmt_m + 3; FMT_fmt_t = 2 * FMT_fmt_m + 36; FMT_fmt_n_step = FMT_fmt_t * FMT_fmt_inv_d; FMT_fmt_step_size = FMT_fmt_t / FMT_fmt_n_step; FMT_fmt_inv_step_size= 1.0 / FMT_fmt_step_size; FMT_fmt_max_m1 = FMT_fmt_max_m + 1; FMT_pi_div2 = 2.0 * atan(1.0); // 誤差関数計算のテーブルのためのメモリ確保 FMT_fmt_table = (double*)malloc(sizeof(double)*(FMT_fmt_max_m+1)*(FMT_fmt_n_step+1)); // added if (FMT_fmt_table0==NULL) { FMT_fmt_table0 = (double*)malloc(sizeof(double)*(0+4)*(36*FMT_fmt_inv_d+1) ); FMT_fmt_table1 = (double*)malloc(sizeof(double)*(1+4)*(38*FMT_fmt_inv_d+1) ); FMT_fmt_table2 = (double*)malloc(sizeof(double)*(2+4)*(40*FMT_fmt_inv_d+1) ); FMT_fmt_table3 = (double*)malloc(sizeof(double)*(3+4)*(42*FMT_fmt_inv_d+1) ); FMT_fmt_table4 = (double*)malloc(sizeof(double)*(4+4)*(44*FMT_fmt_inv_d+1) ); FMT_fmt_table5 = (double*)malloc(sizeof(double)*(5+4)*(46*FMT_fmt_inv_d+1) ); FMT_fmt_table6 = (double*)malloc(sizeof(double)*(6+4)*(48*FMT_fmt_inv_d+1) ); FMT_fmt_table7 = (double*)malloc(sizeof(double)*(7+4)*(50*FMT_fmt_inv_d+1) ); FMT_fmt_table8 = (double*)malloc(sizeof(double)*(8+4)*(52*FMT_fmt_inv_d+1) ); } // 計算開始 // T=0の場合の計算 Fm(0) = 1/(2m+1) for (m=0; m<=FMT_fmt_max_m; m++) FMT_fmt_table[m] = 1.0 / (2*m+1); // T>0の場合の計算 Fm(T) (T>0) m=FMT_fmt_max_m; for (j=1, it0=FMT_fmt_max_m1; j<=FMT_fmt_n_step; j++, it0 += FMT_fmt_max_m1){ t = FMT_fmt_step_size * j; expt = exp(-t); nu = 2*m+1; t2 = 2.0 * t; eps = (expt/t2) * thr_zero; term = 1.0 / nu; func = term; i = nu; while (1) { i += 2; term *= t2 / i; func += term; if (term <= eps) break; } FMT_fmt_table[it0 + m] = expt * func; for (i=m-1; i>=0; i--){ nu -= 2; FMT_fmt_table[it0 + i] = (expt + t2*FMT_fmt_table[it0 + (i+1)]) / nu; } } // added double *dtmp[8+1+1]; dtmp[0] = FMT_fmt_table0; dtmp[1] = FMT_fmt_table1; dtmp[2] = FMT_fmt_table2; dtmp[3] = FMT_fmt_table3; dtmp[4] = FMT_fmt_table4; dtmp[5] = FMT_fmt_table5; dtmp[6] = FMT_fmt_table6; dtmp[7] = FMT_fmt_table7; dtmp[8] = FMT_fmt_table8; for ( m=0; m<=max_lqn*4; m++ ) { for ( j=0; j<=(36+2*m)*FMT_fmt_inv_d; j++ ) { for ( i=0; i<(m+4); i++ ) { dtmp[m][j*(m+4)+i] = FMT_fmt_table[j*FMT_fmt_max_m1 + i]; } } } // special procedure at m=0 double c[4]; c[0] = 1.e0; c[1] = 1.e0; c[2] = 1.e0 / 2.e0; c[3] = 1.e0 / (2.e0*3.e0); for ( j=0; j<=36*FMT_fmt_inv_d; j++ ) { for ( i=0; i<4; i++ ) FMT_fmt_table0[j*4+i] *= c[i]; } FMT_MAXLQN = max_lqn; } #ifdef USE_CUDA int cuda_fmt_initialize(void) { int ret = 0; int max_lqn = FMT_MAXLQN; #pragma omp master { double *dtmp[8+1+1]; size_t mtmp[8+1+1]; dtmp[0] = FMT_fmt_table0; dtmp[1] = FMT_fmt_table1; dtmp[2] = FMT_fmt_table2; dtmp[3] = FMT_fmt_table3; dtmp[4] = FMT_fmt_table4; dtmp[5] = FMT_fmt_table5; dtmp[6] = FMT_fmt_table6; dtmp[7] = FMT_fmt_table7; dtmp[8] = FMT_fmt_table8; dtmp[9] = FMT_fmt_table; for (int m=0; m<=max_lqn*4; m++) mtmp[m] = (m+4)*((36+2*m)*FMT_fmt_inv_d+1); mtmp[9] = (FMT_fmt_max_m+1)*(FMT_fmt_n_step+1); ret = cuda_FMT_Init(dtmp, mtmp, FMT_fmt_step_size, FMT_fmt_max_m1); } return ret; } #endif /** 誤差関数を計算する関数 * * \c fmt_initialize 関数で作成された誤差関数テーブルを用いるなどして * 誤差関数を計算する * * @attention * @li 事前に初期化ルーチンを \c fmt_initialize を呼び出しておく必要がある * * @param[out] f[] 計算した誤差関数を代入する配列 * (\f$ \tt{f[0]}\sim \tt{f[m]} \f$ * @param[in] m 誤差関数の次数 * @param[in] t 誤差関数の引数 * @param[in] coef 誤差関数に掛ける定数 * * @return なし * * @ingroup integ-fmt * */ void fmt(double f[], const int m, const double t, const double coef){ int i,ts; double d,t_inv,nu; int ts0; // main if (t <= (2*m+36)) { ts = 0.5 + t * FMT_fmt_inv_step_size; d = ts * FMT_fmt_step_size - t; ts0 = ts * FMT_fmt_max_m1; for (i=0; i<=m; i++){ f[i] = coef * (((FMT_fmt_table[ts0 + i + 3] * FMT_inv6 * d + FMT_fmt_table[ts0 + i + 2] * FMT_inv2 ) * d + FMT_fmt_table[ts0 + i + 1] ) * d + FMT_fmt_table[ts0 + i + 0] ); } } else { t_inv = FMT_inv2 / t; f[0] = coef * sqrt(FMT_pi_div2*t_inv); nu = 1.0; for (i=1; i<=m; i++){ f[i] = t_inv * nu * f[i-1]; nu += 2.0; } } } void fmt_(double f[], int *pm, double *pt, double *pcoef) { int i,ts, m=*pm; double d,t_inv,nu, t=*pt, coef=*pcoef; int ts0; // main if (t <= (2*m+36)) { ts = 0.5 + t * FMT_fmt_inv_step_size; d = ts * FMT_fmt_step_size - t; ts0 = ts * FMT_fmt_max_m1; for (i=0; i<=m; i++){ f[i] = coef * (((FMT_fmt_table[ts0 + i + 3] * FMT_inv6 * d + FMT_fmt_table[ts0 + i + 2] * FMT_inv2 ) * d + FMT_fmt_table[ts0 + i + 1] ) * d + FMT_fmt_table[ts0 + i + 0] ); } } else { t_inv = FMT_inv2 / t; f[0] = coef * sqrt(FMT_pi_div2*t_inv); nu = 1.0; for (i=1; i<=m; i++){ f[i] = t_inv * nu * f[i-1]; nu += 2.0; } } }
omp_parallel_for_reduction.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <math.h> #include "omp_testsuite.h" #define DOUBLE_DIGITS 20 /* dt^DOUBLE_DIGITS */ #define MAX_FACTOR 10 #define KNOWN_PRODUCT 3628800 /* 10! */ int test_omp_parallel_for_reduction() { int sum; int known_sum; double dsum; double dknown_sum; double dt=0.5; /* base of geometric row for + and - test*/ double rounding_error= 1.E-9; int diff; double ddiff; int product; int known_product; int logic_and; int logic_or; int bit_and; int bit_or; int exclusiv_bit_or; int logics[LOOPCOUNT]; int i; double dpt; int result; sum =0; dsum=0; dt = 1./3.; result = 0; product = 1; logic_and=1; logic_or=0; bit_and=1; bit_or=0; exclusiv_bit_or=0; /* Tests for integers */ known_sum = (LOOPCOUNT*(LOOPCOUNT+1))/2; #pragma omp parallel for schedule(dynamic,1) private(i) reduction(+:sum) for (i=1;i<=LOOPCOUNT;i++) { sum=sum+i; } if(known_sum!=sum) { result++; fprintf(stderr,"Error in sum with integers: Result was %d" " instead of %d\n",sum,known_sum); } diff = (LOOPCOUNT*(LOOPCOUNT+1))/2; #pragma omp parallel for schedule(dynamic,1) private(i) reduction(-:diff) for (i=1;i<=LOOPCOUNT;++i) { diff=diff-i; } if(diff != 0) { result++; fprintf(stderr,"Error in difference with integers: Result was %d" " instead of 0.\n",diff); } /* Tests for doubles */ dsum=0; dpt=1; for (i=0;i<DOUBLE_DIGITS;++i) { dpt*=dt; } dknown_sum = (1-dpt)/(1-dt); #pragma omp parallel for schedule(dynamic,1) private(i) reduction(+:dsum) for (i=0;i<DOUBLE_DIGITS;++i) { dsum += pow(dt,i); } if( fabs(dsum-dknown_sum) > rounding_error ) { result++; fprintf(stderr,"Error in sum with doubles: Result was %f" " instead of %f (Difference: %E)\n", dsum, dknown_sum, dsum-dknown_sum); } dpt=1; for (i=0;i<DOUBLE_DIGITS;++i) { dpt*=dt; } fprintf(stderr,"\n"); ddiff = (1-dpt)/(1-dt); #pragma omp parallel for schedule(dynamic,1) private(i) reduction(-:ddiff) for (i=0;i<DOUBLE_DIGITS;++i) { ddiff -= pow(dt,i); } if( fabs(ddiff) > rounding_error) { result++; fprintf(stderr,"Error in Difference with doubles: Result was %E" " instead of 0.0\n",ddiff); } /* Tests for integers */ #pragma omp parallel for schedule(dynamic,1) private(i) reduction(*:product) for(i=1;i<=MAX_FACTOR;i++) { product *= i; } known_product = KNOWN_PRODUCT; if(known_product != product) { result++; fprintf(stderr,"Error in Product with integers: Result was %d" " instead of %d\n\n",product,known_product); } /* Tests for logic AND */ for(i=0;i<LOOPCOUNT;i++) { logics[i]=1; } #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(&&:logic_and) for(i=0;i<LOOPCOUNT;++i) { logic_and = (logic_and && logics[i]); } if(!logic_and) { result++; fprintf(stderr,"Error in logic AND part 1.\n"); } logic_and = 1; logics[LOOPCOUNT/2]=0; #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(&&:logic_and) for(i=0;i<LOOPCOUNT;++i) { logic_and = logic_and && logics[i]; } if(logic_and) { result++; fprintf(stderr,"Error in logic AND part 2.\n"); } /* Tests for logic OR */ for(i=0;i<LOOPCOUNT;i++) { logics[i]=0; } #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(||:logic_or) for(i=0;i<LOOPCOUNT;++i) { logic_or = logic_or || logics[i]; } if(logic_or) { result++; fprintf(stderr,"Error in logic OR part 1.\n"); } logic_or = 0; logics[LOOPCOUNT/2]=1; #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(||:logic_or) for(i=0;i<LOOPCOUNT;++i) { logic_or = logic_or || logics[i]; } if(!logic_or) { result++; fprintf(stderr,"Error in logic OR part 2.\n"); } /* Tests for bitwise AND */ for(i=0;i<LOOPCOUNT;++i) { logics[i]=1; } #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(&:bit_and) for(i=0;i<LOOPCOUNT;++i) { bit_and = (bit_and & logics[i]); } if(!bit_and) { result++; fprintf(stderr,"Error in BIT AND part 1.\n"); } bit_and = 1; logics[LOOPCOUNT/2]=0; #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(&:bit_and) for(i=0;i<LOOPCOUNT;++i) { bit_and = bit_and & logics[i]; } if(bit_and) { result++; fprintf(stderr,"Error in BIT AND part 2.\n"); } /* Tests for bitwise OR */ for(i=0;i<LOOPCOUNT;i++) { logics[i]=0; } #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(|:bit_or) for(i=0;i<LOOPCOUNT;++i) { bit_or = bit_or | logics[i]; } if(bit_or) { result++; fprintf(stderr,"Error in BIT OR part 1\n"); } bit_or = 0; logics[LOOPCOUNT/2]=1; #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(|:bit_or) for(i=0;i<LOOPCOUNT;++i) { bit_or = bit_or | logics[i]; } if(!bit_or) { result++; fprintf(stderr,"Error in BIT OR part 2\n"); } /* Tests for bitwise XOR */ for(i=0;i<LOOPCOUNT;i++) { logics[i]=0; } #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(^:exclusiv_bit_or) for(i=0;i<LOOPCOUNT;++i) { exclusiv_bit_or = exclusiv_bit_or ^ logics[i]; } if(exclusiv_bit_or) { result++; fprintf(stderr,"Error in EXCLUSIV BIT OR part 1\n"); } exclusiv_bit_or = 0; logics[LOOPCOUNT/2]=1; #pragma omp parallel for schedule(dynamic,1) private(i) \ reduction(^:exclusiv_bit_or) for(i=0;i<LOOPCOUNT;++i) { exclusiv_bit_or = exclusiv_bit_or ^ logics[i]; } if(!exclusiv_bit_or) { result++; fprintf(stderr,"Error in EXCLUSIV BIT OR part 2\n"); } /*printf("\nResult:%d\n",result);*/ return (result==0); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_parallel_for_reduction()) { num_failed++; } } return num_failed; }
pngquant.c
/* pngquant.c - quantize the colors in an alphamap down to a specified number ** ** Copyright (C) 1989, 1991 by Jef Poskanzer. ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. ** ** - - - - ** ** © 1997-2002 by Greg Roelofs; based on an idea by Stefan Schneider. ** © 2009-2015 by Kornel Lesiński. ** ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and/or other materials provided with the distribution. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** */ #define PNGQUANT_VERSION LIQ_VERSION_STRING " (July 2017)" #define PNGQUANT_USAGE "\ usage: pngquant [options] [ncolors] -- pngfile [pngfile ...]\n\ pngquant [options] [ncolors] - >stdout <stdin\n\n\ options:\n\ --force overwrite existing output files (synonym: -f)\n\ --skip-if-larger only save converted files if they're smaller than original\n\ --output file destination file path to use instead of --ext (synonym: -o)\n\ --ext new.png set custom suffix/extension for output filenames\n\ --quality min-max don't save below min, use fewer colors below max (0-100)\n\ --speed N speed/quality trade-off. 1=slow, 3=default, 11=fast & rough\n\ --nofs disable Floyd-Steinberg dithering\n\ --posterize N output lower-precision color (e.g. for ARGB4444 output)\n\ --strip remove optional metadata (default on Mac)\n\ --verbose print status messages (synonym: -v)\n\ \n\ Quantizes one or more 32-bit RGBA PNGs to 8-bit (or smaller) RGBA-palette.\n\ The output filename is the same as the input name except that\n\ it ends in \"-fs8.png\", \"-or8.png\" or your custom extension (unless the\n\ input is stdin, in which case the quantized image will go to stdout).\n\ If you pass the special output path \"-\" and a single input file, that file\n\ will be processed and the quantized image will go to stdout.\n\ The default behavior if the output file exists is to skip the conversion;\n\ use --force to overwrite. See man page for full list of options.\n" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <stdbool.h> #include <math.h> #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) # include <fcntl.h> /* O_BINARY */ # include <io.h> /* setmode() */ #else # include <unistd.h> #endif #ifdef _OPENMP #include <omp.h> #else #define omp_get_max_threads() 1 #define omp_get_thread_num() 0 #endif #include "rwpng.h" /* typedefs, common macros, public prototypes */ #include "libimagequant.h" /* if it fails here, run: git submodule update; ./configure; or add -Ilib to compiler flags */ #include "pngquant_opts.h" static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform tag, png8_image *output_image); static void set_palette(liq_result *result, png8_image *output_image); static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose); static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options); static char *add_filename_extension(const char *filename, const char *newext); static bool file_exists(const char *outname); static void verbose_printf(struct pngquant_options *context, const char *fmt, ...) { if (context->log_callback) { va_list va; va_start(va, fmt); int required_space = vsnprintf(NULL, 0, fmt, va)+1; // +\0 va_end(va); #if defined(_MSC_VER) char *buf = malloc(required_space); #else char buf[required_space]; #endif va_start(va, fmt); vsnprintf(buf, required_space, fmt, va); va_end(va); context->log_callback(context->liq, buf, context->log_callback_user_info); #if defined(_MSC_VER) free(buf); #endif } } static void log_callback(const liq_attr *attr, const char *msg, void* user_info) { fprintf(stderr, "%s\n", msg); } #ifdef _OPENMP #define LOG_BUFFER_SIZE 1300 struct buffered_log { int buf_used; char buf[LOG_BUFFER_SIZE]; }; static void log_callback_buferred_flush(const liq_attr *attr, void *context) { struct buffered_log *log = context; if (log->buf_used) { fwrite(log->buf, 1, log->buf_used, stderr); fflush(stderr); log->buf_used = 0; } } static void log_callback_buferred(const liq_attr *attr, const char *msg, void* context) { struct buffered_log *log = context; int len = strlen(msg); if (len > LOG_BUFFER_SIZE-2) len = LOG_BUFFER_SIZE-2; if (len > LOG_BUFFER_SIZE - log->buf_used - 2) log_callback_buferred_flush(attr, log); memcpy(&log->buf[log->buf_used], msg, len); log->buf_used += len+1; log->buf[log->buf_used-1] = '\n'; log->buf[log->buf_used] = '\0'; } #endif static void print_full_version(FILE *fd) { fprintf(fd, "pngquant, %s, by Kornel Lesinski, Greg Roelofs.\n" #ifndef NDEBUG " WARNING: this is a DEBUG (slow) version.\n" /* NDEBUG disables assert() */ #endif #if !USE_SSE && (defined(__SSE__) || defined(__amd64__) || defined(__X86_64__) || defined(__i386__)) " SSE acceleration disabled.\n" #endif #if _OPENMP " Compiled with OpenMP (multicore support).\n" #endif , PNGQUANT_VERSION); rwpng_version_info(fd); fputs("\n", fd); } static void print_usage(FILE *fd) { fputs(PNGQUANT_USAGE, fd); } /** * N = automatic quality, uses limit unless force is set (N-N or 0-N) * -N = no better than N (same as 0-N) * N-M = no worse than N, no better than M * N- = no worse than N, perfect if possible (same as N-100) * * where N,M are numbers between 0 (lousy) and 100 (perfect) */ static bool parse_quality(const char *quality, liq_attr *options, bool *min_quality_limit) { long limit, target; const char *str = quality; char *end; long t1 = strtol(str, &end, 10); if (str == end) return false; str = end; if ('\0' == end[0] && t1 < 0) { // quality="-%d" target = -t1; limit = 0; } else if ('\0' == end[0]) { // quality="%d" target = t1; limit = t1*9/10; } else if ('-' == end[0] && '\0' == end[1]) { // quality="%d-" target = 100; limit = t1; } else { // quality="%d-%d" long t2 = strtol(str, &end, 10); if (str == end || t2 > 0) return false; target = -t2; limit = t1; } *min_quality_limit = (limit > 0); return LIQ_OK == liq_set_quality(options, limit, target); } pngquant_error pngquant_main(struct pngquant_options *options); pngquant_error pngquant_file(const char *filename, const char *outname, struct pngquant_options *options); #ifndef PNGQUANT_NO_MAIN int main(int argc, char *argv[]) { struct pngquant_options options = { .floyd = 1.f, // floyd-steinberg dithering .strip = false, }; pngquant_error retval = pngquant_parse_options(argc, argv, &options); if (retval != SUCCESS) { return retval; } return pngquant_main(&options); } #endif pngquant_error pngquant_main(struct pngquant_options *options) { if (options->print_version) { puts(PNGQUANT_VERSION); return SUCCESS; } if (options->missing_arguments) { print_full_version(stderr); print_usage(stderr); return MISSING_ARGUMENT; } if (options->print_help) { print_full_version(stdout); print_usage(stdout); return SUCCESS; } options->liq = liq_attr_create(); if (!options->liq) { fputs("SSE-capable CPU is required for this build.\n", stderr); return WRONG_ARCHITECTURE; } if (options->verbose) { liq_set_log_callback(options->liq, log_callback, NULL); options->log_callback = log_callback; } if (options->quality && !parse_quality(options->quality, options->liq, &options->min_quality_limit)) { fputs("Quality should be in format min-max where min and max are numbers in range 0-100.\n", stderr); return INVALID_ARGUMENT; } if (options->iebug) { // opacities above 238 will be rounded up to 255, because IE6 truncates <255 to 0. liq_set_min_opacity(options->liq, 238); fputs(" warning: the workaround for IE6 is deprecated\n", stderr); } if (options->last_index_transparent) { liq_set_last_index_transparent(options->liq, true); } if (options->speed >= 10) { options->fast_compression = true; if (options->speed == 11) { options->floyd = 0; options->speed = 10; } } if (options->speed && LIQ_OK != liq_set_speed(options->liq, options->speed)) { fputs("Speed should be between 1 (slow) and 11 (fast).\n", stderr); return INVALID_ARGUMENT; } if (options->colors && LIQ_OK != liq_set_max_colors(options->liq, options->colors)) { fputs("Number of colors must be between 2 and 256.\n", stderr); return INVALID_ARGUMENT; } if (options->posterize && LIQ_OK != liq_set_min_posterization(options->liq, options->posterize)) { fputs("Posterization should be number of bits in range 0-4.\n", stderr); return INVALID_ARGUMENT; } if (options->extension && options->output_file_path) { fputs("--ext and --output options can't be used at the same time\n", stderr); return INVALID_ARGUMENT; } // new filename extension depends on options used. Typically basename-fs8.png if (options->extension == NULL) { options->extension = options->floyd > 0 ? "-fs8.png" : "-or8.png"; } if (options->output_file_path && options->num_files != 1) { fputs("Only one input file is allowed when --output is used\n", stderr); return INVALID_ARGUMENT; } if (options->using_stdout && !options->using_stdin && options->num_files != 1) { fputs("Only one input file is allowed when using the special output path \"-\" to write to stdout\n", stderr); return INVALID_ARGUMENT; } if (options->map_file) { png24_image tmp = {.width=0}; if (SUCCESS != read_image(options->liq, options->map_file, false, &tmp, &options->fixed_palette_image, true, true, false)) { fprintf(stderr, " error: unable to load %s", options->map_file); return INVALID_ARGUMENT; } liq_result *tmp_quantize = liq_quantize_image(options->liq, options->fixed_palette_image); const liq_palette *pal = liq_get_palette(tmp_quantize); if (!pal) { fprintf(stderr, " error: unable to read colors from %s", options->map_file); return INVALID_ARGUMENT; } for(unsigned int i=0; i < pal->count; i++) { liq_image_add_fixed_color(options->fixed_palette_image, pal->entries[i]); } liq_result_destroy(tmp_quantize); } if (!options->num_files && !options->using_stdin) { fputs("No input files specified.\n", stderr); if (options->verbose) { print_full_version(stderr); } print_usage(stderr); return MISSING_ARGUMENT; } #ifdef _OPENMP // if there's a lot of files, coarse parallelism can be used if (options->num_files > 2*omp_get_max_threads()) { omp_set_nested(0); omp_set_dynamic(1); } else { omp_set_nested(1); } #endif unsigned int error_count=0, skipped_count=0, file_count=0; pngquant_error latest_error=SUCCESS; #pragma omp parallel for \ schedule(static, 1) reduction(+:skipped_count) reduction(+:error_count) reduction(+:file_count) shared(latest_error) for(int i=0; i < options->num_files; i++) { const char *filename = options->using_stdin ? "stdin" : options->files[i]; struct pngquant_options opts = *options; opts.liq = liq_attr_copy(options->liq); #ifdef _OPENMP struct buffered_log buf = {0}; if (opts.log_callback && omp_get_num_threads() > 1 && opts.num_files > 1) { liq_set_log_callback(opts.liq, log_callback_buferred, &buf); liq_set_log_flush_callback(opts.liq, log_callback_buferred_flush, &buf); opts.log_callback = log_callback_buferred; opts.log_callback_user_info = &buf; } #endif pngquant_error retval = SUCCESS; const char *outname = opts.output_file_path; char *outname_free = NULL; if (!opts.using_stdout) { if (!outname) { outname = outname_free = add_filename_extension(filename, opts.extension); } if (!opts.force && file_exists(outname)) { fprintf(stderr, " error: '%s' exists; not overwriting\n", outname); retval = NOT_OVERWRITING_ERROR; } } if (SUCCESS == retval) { retval = pngquant_file(filename, outname, &opts); } free(outname_free); liq_attr_destroy(opts.liq); if (retval) { #pragma omp critical { latest_error = retval; } if (retval == TOO_LOW_QUALITY || retval == TOO_LARGE_FILE) { skipped_count++; } else { error_count++; } } ++file_count; } if (error_count) { verbose_printf(options, "There were errors quantizing %d file%s out of a total of %d file%s.", error_count, (error_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); } if (skipped_count) { verbose_printf(options, "Skipped %d file%s out of a total of %d file%s.", skipped_count, (skipped_count == 1)? "" : "s", file_count, (file_count == 1)? "" : "s"); } if (!skipped_count && !error_count) { verbose_printf(options, "Quantized %d image%s.", file_count, (file_count == 1)? "" : "s"); } if (options->fixed_palette_image) liq_image_destroy(options->fixed_palette_image); liq_attr_destroy(options->liq); return latest_error; } pngquant_error pngquant_file(const char *filename, const char *outname, struct pngquant_options *options) { pngquant_error retval = SUCCESS; verbose_printf(options, "%s:", filename); liq_image *input_image = NULL; png24_image input_image_rwpng = {.width=0}; bool keep_input_pixels = options->skip_if_larger || (options->using_stdout && options->min_quality_limit); // original may need to be output to stdout if (SUCCESS == retval) { retval = read_image(options->liq, filename, options->using_stdin, &input_image_rwpng, &input_image, keep_input_pixels, options->strip, options->verbose); } int quality_percent = 90; // quality on 0-100 scale, updated upon successful remap png8_image output_image = {.width=0}; if (SUCCESS == retval) { verbose_printf(options, " read %luKB file", (input_image_rwpng.file_size+1023UL)/1024UL); if (RWPNG_ICCP == input_image_rwpng.input_color) { verbose_printf(options, " used embedded ICC profile to transform image to sRGB colorspace"); } else if (RWPNG_GAMA_CHRM == input_image_rwpng.input_color) { verbose_printf(options, " used gAMA and cHRM chunks to transform image to sRGB colorspace"); } else if (RWPNG_ICCP_WARN_GRAY == input_image_rwpng.input_color) { verbose_printf(options, " warning: ignored ICC profile in GRAY colorspace"); } else if (RWPNG_COCOA == input_image_rwpng.input_color) { // No comment } else if (RWPNG_SRGB == input_image_rwpng.input_color) { verbose_printf(options, " passing sRGB tag from the input"); } else if (input_image_rwpng.gamma != 0.45455) { verbose_printf(options, " converted image from gamma %2.1f to gamma 2.2", 1.0/input_image_rwpng.gamma); } // when using image as source of a fixed palette the palette is extracted using regular quantization liq_result *remap; liq_error remap_error = liq_image_quantize(options->fixed_palette_image ? options->fixed_palette_image : input_image, options->liq, &remap); if (LIQ_OK == remap_error) { // fixed gamma ~2.2 for the web. PNG can't store exact 1/2.2 // NB: can't change gamma here, because output_color is allowed to be an sRGB tag liq_set_output_gamma(remap, 0.45455); liq_set_dithering_level(remap, options->floyd); retval = prepare_output_image(remap, input_image, input_image_rwpng.output_color, &output_image); if (SUCCESS == retval) { if (LIQ_OK != liq_write_remapped_image_rows(remap, input_image, output_image.row_pointers)) { retval = OUT_OF_MEMORY_ERROR; } set_palette(remap, &output_image); double palette_error = liq_get_quantization_error(remap); if (palette_error >= 0) { quality_percent = liq_get_quantization_quality(remap); verbose_printf(options, " mapped image to new colors...MSE=%.3f (Q=%d)", palette_error, quality_percent); } } liq_result_destroy(remap); } else if (LIQ_QUALITY_TOO_LOW == remap_error) { retval = TOO_LOW_QUALITY; } else { retval = INVALID_ARGUMENT; // dunno } } if (SUCCESS == retval) { if (options->skip_if_larger) { // this is very rough approximation, but generally avoid losing more quality than is gained in file size. // Quality is raised to 1.5, because even greater savings are needed to justify big quality loss. // but >50% savings are considered always worthwile in order to allow low quality conversions to work at all const double quality = quality_percent/100.0; const double expected_reduced_size = pow(quality, 1.5); output_image.maximum_file_size = (input_image_rwpng.file_size-1) * (expected_reduced_size < 0.5 ? 0.5 : expected_reduced_size); } output_image.fast_compression = options->fast_compression; output_image.chunks = input_image_rwpng.chunks; input_image_rwpng.chunks = NULL; retval = write_image(&output_image, NULL, outname, options); if (TOO_LARGE_FILE == retval) { verbose_printf(options, " file exceeded expected size of %luKB", (unsigned long)output_image.maximum_file_size/1024UL); } if (SUCCESS == retval && output_image.metadata_size > 0) { verbose_printf(options, " copied %dKB of additional PNG metadata", (int)(output_image.metadata_size+999)/1000); } } if (options->using_stdout && keep_input_pixels && (TOO_LARGE_FILE == retval || TOO_LOW_QUALITY == retval)) { // when outputting to stdout it'd be nasty to create 0-byte file // so if quality is too low, output 24-bit original pngquant_error write_retval = write_image(NULL, &input_image_rwpng, outname, options); if (write_retval) { retval = write_retval; } } if (input_image) liq_image_destroy(input_image); rwpng_free_image24(&input_image_rwpng); rwpng_free_image8(&output_image); return retval; } static void set_palette(liq_result *result, png8_image *output_image) { const liq_palette *palette = liq_get_palette(result); output_image->num_palette = palette->count; for(unsigned int i=0; i < palette->count; i++) { const liq_color px = palette->entries[i]; output_image->palette[i] = (rwpng_rgba){.r=px.r, .g=px.g, .b=px.b, .a=px.a}; } } static bool file_exists(const char *outname) { FILE *outfile = fopen(outname, "rb"); if ((outfile ) != NULL) { fclose(outfile); return true; } return false; } /* build the output filename from the input name by inserting "-fs8" or * "-or8" before the ".png" extension (or by appending that plus ".png" if * there isn't any extension), then make sure it doesn't exist already */ static char *add_filename_extension(const char *filename, const char *newext) { size_t x = strlen(filename); char* outname = malloc(x+4+strlen(newext)+1); if (!outname) return NULL; strncpy(outname, filename, x); if (strncmp(outname+x-4, ".png", 4) == 0 || strncmp(outname+x-4, ".PNG", 4) == 0) { strcpy(outname+x-4, newext); } else { strcpy(outname+x, newext); } return outname; } static char *temp_filename(const char *basename) { size_t x = strlen(basename); char *outname = malloc(x+1+4); if (!outname) return NULL; strcpy(outname, basename); strcpy(outname+x, ".tmp"); return outname; } static void set_binary_mode(FILE *fp) { #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) setmode(fp == stdout ? 1 : 0, O_BINARY); #endif } static const char *filename_part(const char *path) { const char *outfilename = strrchr(path, '/'); if (outfilename) { return outfilename+1; } else { return path; } } static bool replace_file(const char *from, const char *to, const bool force) { #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) if (force) { // On Windows rename doesn't replace unlink(to); } #endif return (0 == rename(from, to)); } static pngquant_error write_image(png8_image *output_image, png24_image *output_image24, const char *outname, struct pngquant_options *options) { FILE *outfile; char *tempname = NULL; if (options->using_stdout) { set_binary_mode(stdout); outfile = stdout; if (output_image) { verbose_printf(options, " writing %d-color image to stdout", output_image->num_palette); } else { verbose_printf(options, " writing truecolor image to stdout"); } } else { tempname = temp_filename(outname); if (!tempname) return OUT_OF_MEMORY_ERROR; if ((outfile = fopen(tempname, "wb")) == NULL) { fprintf(stderr, " error: cannot open '%s' for writing\n", tempname); free(tempname); return CANT_WRITE_ERROR; } if (output_image) { verbose_printf(options, " writing %d-color image as %s", output_image->num_palette, filename_part(outname)); } else { verbose_printf(options, " writing truecolor image as %s", filename_part(outname)); } } pngquant_error retval; #pragma omp critical (libpng) { if (output_image) { retval = rwpng_write_image8(outfile, output_image); } else { retval = rwpng_write_image24(outfile, output_image24); } } if (!options->using_stdout) { fclose(outfile); if (SUCCESS == retval) { // Image has been written to a temporary file and then moved over destination. // This makes replacement atomic and avoids damaging destination file on write error. if (!replace_file(tempname, outname, options->force)) { retval = CANT_WRITE_ERROR; } } if (retval) { unlink(tempname); } } free(tempname); if (retval && retval != TOO_LARGE_FILE) { fprintf(stderr, " error: failed writing image to %s (%d)\n", options->using_stdout ? "stdout" : outname, retval); } return retval; } static pngquant_error read_image(liq_attr *options, const char *filename, int using_stdin, png24_image *input_image_p, liq_image **liq_image_p, bool keep_input_pixels, bool strip, bool verbose) { FILE *infile; if (using_stdin) { set_binary_mode(stdin); infile = stdin; } else if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, " error: cannot open %s for reading\n", filename); return READ_ERROR; } pngquant_error retval; #pragma omp critical (libpng) { retval = rwpng_read_image24(infile, input_image_p, strip, verbose); } if (!using_stdin) { fclose(infile); } if (retval) { fprintf(stderr, " error: cannot decode image %s\n", using_stdin ? "from stdin" : filename_part(filename)); return retval; } *liq_image_p = liq_image_create_rgba_rows(options, (void**)input_image_p->row_pointers, input_image_p->width, input_image_p->height, input_image_p->gamma); if (!*liq_image_p) { return OUT_OF_MEMORY_ERROR; } if (!keep_input_pixels) { if (LIQ_OK != liq_image_set_memory_ownership(*liq_image_p, LIQ_OWN_ROWS | LIQ_OWN_PIXELS)) { return OUT_OF_MEMORY_ERROR; } input_image_p->row_pointers = NULL; input_image_p->rgba_data = NULL; } return SUCCESS; } static pngquant_error prepare_output_image(liq_result *result, liq_image *input_image, rwpng_color_transform output_color, png8_image *output_image) { output_image->width = liq_image_get_width(input_image); output_image->height = liq_image_get_height(input_image); output_image->gamma = liq_get_output_gamma(result); output_image->output_color = output_color; /* ** Step 3.7 [GRR]: allocate memory for the entire indexed image */ output_image->indexed_data = malloc(output_image->height * output_image->width); output_image->row_pointers = malloc(output_image->height * sizeof(output_image->row_pointers[0])); if (!output_image->indexed_data || !output_image->row_pointers) { return OUT_OF_MEMORY_ERROR; } for(size_t row = 0; row < output_image->height; row++) { output_image->row_pointers[row] = output_image->indexed_data + row * output_image->width; } const liq_palette *palette = liq_get_palette(result); // tRNS, etc. output_image->num_palette = palette->count; return SUCCESS; }
GB_binop__pair_fc32.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__pair_fc32 // A.*B function (eWiseMult): GB_AemultB__pair_fc32 // A*D function (colscale): GB_AxD__pair_fc32 // D*A function (rowscale): GB_DxB__pair_fc32 // C+=B function (dense accum): GB_Cdense_accumB__pair_fc32 // C+=b function (dense accum): GB_Cdense_accumb__pair_fc32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__pair_fc32 // C=scalar+B (none) // C=scalar+B' (none) // C=A+scalar (none) // C=A'+scalar (none) // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GxB_CMPLXF(1,0) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GxB_CMPLXF(1,0) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_PAIR || GxB_NO_FC32 || GxB_NO_PAIR_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__pair_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__pair_fc32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__pair_fc32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__pair_fc32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__pair_fc32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // 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__pair_fc32 ( 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__pair_fc32 ( 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 //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( 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 GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; ; ; Cx [p] = GxB_CMPLXF(1,0) ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( 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 ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = GxB_CMPLXF(1,0) ; } 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) \ { \ ; ; \ Cx [pC] = GxB_CMPLXF(1,0) ; \ } GrB_Info (none) ( 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 \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_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] = GxB_CMPLXF(1,0) ; \ } GrB_Info (none) ( 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 GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/distribute-cache-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/timer-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const Quantum *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static const void *GetVirtualMetacontentFromCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *, ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,Quantum *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCacheMetacontent(CacheInfo *magick_restrict, NexusInfo *magick_restrict,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static Quantum *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *magick_restrict,const MapMode, const ssize_t,const ssize_t,const size_t,const size_t, const MagickBooleanType,NexusInfo *magick_restrict,ExceptionInfo *) magick_hot_spot; #if defined(MAGICKCORE_OPENCL_SUPPORT) static void CopyOpenCLBuffer(CacheInfo *magick_restrict); #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static ssize_t cache_anonymous_memory = (-1); static time_t cache_epoch = 0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *value; cache_info=(CacheInfo *) AcquireAlignedMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->disk_mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); value=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } value=GetPolicyValue("cache:synchronize"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } cache_info->width_limit=GetMagickResourceLimit(WidthResource); cache_info->height_limit=GetMagickResourceLimit(HeightResource); cache_info->semaphore=AcquireSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AcquireSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory(2* number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *nexus_info=(NexusInfo *) AcquireQuantumMemory(2*number_threads, sizeof(**nexus_info)); if (*nexus_info == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(*nexus_info,0,2*number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) (2*number_threads); i++) { nexus_info[i]=(*nexus_info+i); if (i < (ssize_t) number_threads) nexus_info[i]->virtual_nexus=(*nexus_info+number_threads+i); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % void *AcquirePixelCachePixels(const Image *image,size_t *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *AcquirePixelCachePixels(const Image *image,size_t *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); (void) exception; cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=(size_t) cache_info->length; return(cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickPrivate MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickPrivate void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); /* no op-- nothing to destroy */ RelinquishSemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict p, *magick_restrict q; ssize_t y; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & WriteMaskChannel) == 0) return(MagickTrue); if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height, nexus_info->virtual_nexus,exception); q=nexus_info->pixels; if ((p == (Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickFalse); for (y=0; y < (ssize_t) nexus_info->region.height; y++) { register ssize_t x; for (x=0; x < (ssize_t) nexus_info->region.width; x++) { double mask_alpha; register ssize_t i; mask_alpha=QuantumScale*GetPixelWriteMask(image,p); if (fabs(mask_alpha) >= MagickEpsilon) { for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(MagickOver_((double) p[i],mask_alpha* GetPixelAlpha(image,p),(double) q[i],(double) GetPixelAlpha(image,q))); } SetPixelAlpha(image,GetPixelAlpha(image,p),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); if ((lseek(cache_info->file,0,SEEK_SET) < 0) || (lseek(clone_info->file,0,SEEK_SET) < 0)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) { #if defined(MAGICKCORE_HAVE_LINUX_SENDFILE) if (cache_info->length < 0x7ffff000) { count=sendfile(clone_info->file,cache_info->file,(off_t *) NULL, (ssize_t) cache_info->length); if (count == (ssize_t) cache_info->length) return(MagickTrue); if ((lseek(cache_info->file,0,SEEK_SET) < 0) || (lseek(clone_info->file,0,SEEK_SET) < 0)) return(MagickFalse); } #endif quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); } buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads ((size_t) GetMagickResourceLimit(ThreadResource)) #define cache_number_threads(source,destination,chunk,multithreaded) \ num_threads((multithreaded) == 0 ? 1 : \ (((source)->type != MemoryCache) && ((source)->type != MapCache)) || \ (((destination)->type != MemoryCache) && ((destination)->type != MapCache)) ? \ MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1) : \ MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),(ssize_t) (chunk)/256),1)) MagickBooleanType optimize, status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); length=cache_info->number_channels*sizeof(*cache_info->channel_map); if ((cache_info->storage_class == clone_info->storage_class) && (cache_info->colorspace == clone_info->colorspace) && (cache_info->alpha_trait == clone_info->alpha_trait) && (cache_info->channels == clone_info->channels) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) && (cache_info->metacontent_extent == clone_info->metacontent_extent)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->number_channels*cache_info->columns*cache_info->rows* sizeof(*cache_info->pixels)); if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) (void) memcpy(clone_info->metacontent,cache_info->metacontent, cache_info->columns*cache_info->rows* clone_info->metacontent_extent*sizeof(unsigned char)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(cache_info->number_threads); clone_nexus=AcquirePixelCacheNexus(clone_info->number_threads); length=cache_info->number_channels*sizeof(*cache_info->channel_map); optimize=(cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ? MagickTrue : MagickFalse; length=(size_t) MagickMin(cache_info->number_channels*cache_info->columns, clone_info->number_channels*clone_info->columns); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; register ssize_t x; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y, cache_info->columns,1,MagickFalse,cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y, clone_info->columns,1,MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; (void) memset(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); if (optimize != MagickFalse) (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length* sizeof(Quantum)); else { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; /* Mismatched pixel channel map. */ p=cache_nexus[id]->pixels; q=clone_nexus[id]->pixels; for (x=0; x < (ssize_t) cache_info->columns; x++) { register ssize_t i; if (x == (ssize_t) clone_info->columns) break; for (i=0; i < (ssize_t) clone_info->number_channels; i++) { PixelChannel channel; PixelTrait traits; channel=clone_info->channel_map[i].channel; traits=cache_info->channel_map[channel].traits; if (traits != UndefinedPixelTrait) *q=*(p+cache_info->channel_map[channel].offset); q++; } p+=cache_info->number_channels; } } status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) { /* Clone metacontent. */ length=(size_t) MagickMin(cache_info->metacontent_extent, clone_info->metacontent_extent); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y, cache_info->columns,1,MagickFalse,cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y, clone_info->columns,1,MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; if ((clone_nexus[id]->metacontent != (void *) NULL) && (cache_nexus[id]->metacontent != (void *) NULL)) (void) memcpy(clone_nexus[id]->metacontent, cache_nexus[id]->metacontent,length*sizeof(unsigned char)); status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception); } } clone_nexus=DestroyPixelCacheNexus(clone_nexus,clone_info->number_threads); cache_nexus=DestroyPixelCacheNexus(cache_nexus,cache_info->number_threads); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache != (void *) NULL) image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { #if defined(MAGICKCORE_OPENCL_SUPPORT) if (cache_info->opencl != (MagickCLCacheInfo) NULL) { cache_info->opencl=RelinquishMagickCLCacheInfo(cache_info->opencl, MagickTrue); cache_info->pixels=(Quantum *) NULL; break; } #endif if (cache_info->mapped == MagickFalse) cache_info->pixels=(Quantum *) RelinquishAlignedMemory( cache_info->pixels); else (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->metacontent=(void *) NULL; } MagickPrivate Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishAlignedMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(Quantum *) NULL; nexus_info->pixels=(Quantum *) NULL; nexus_info->metacontent=(void *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) (2*number_threads); i++) { if (nexus_info[i]->cache != (Quantum *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } *nexus_info=(NexusInfo *) RelinquishMagickMemory(*nexus_info); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontent() returns the authentic metacontent corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the associated pixels are not available. % % The format of the GetAuthenticMetacontent() method is: % % void *GetAuthenticMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void *GetAuthenticMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) { void *metacontent; metacontent=cache_info->methods. get_authentic_metacontent_from_handler(image); return(metacontent); } assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontentFromCache() returns the meta-content corresponding % with the last call to QueueAuthenticPixelsCache() or % GetAuthenticPixelsCache(). % % The format of the GetAuthenticMetacontentFromCache() method is: % % void *GetAuthenticMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *GetAuthenticMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL % operations. % % The format of the GetAuthenticOpenCLBuffer() method is: % % cl_mem GetAuthenticOpenCLBuffer(const Image *image, % MagickCLDevice device,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o device: the device to use. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image, MagickCLDevice device,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(device != (const MagickCLDevice) NULL); cache_info=(CacheInfo *) image->cache; if ((cache_info->type == UndefinedCache) || (cache_info->reference_count > 1)) { SyncImagePixelCache((Image *) image,exception); cache_info=(CacheInfo *) image->cache; } if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse)) return((cl_mem) NULL); LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->opencl != (MagickCLCacheInfo) NULL) && (cache_info->opencl->device->context != device->context)) cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); if (cache_info->opencl == (MagickCLCacheInfo) NULL) { assert(cache_info->pixels != (Quantum *) NULL); cache_info->opencl=AcquireMagickCLCacheInfo(device,cache_info->pixels, cache_info->length); } if (cache_info->opencl != (MagickCLCacheInfo) NULL) RetainOpenCLMemObject(cache_info->opencl->buffer); UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->opencl == (MagickCLCacheInfo) NULL) return((cl_mem) NULL); assert(cache_info->opencl->pixels == cache_info->pixels); return(cache_info->opencl->buffer); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (Quantum *) NULL) return((Quantum *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); if (cache_info->metacontent_extent != 0) if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % Quantum *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static Quantum *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated % corresponding with the last call to QueueAuthenticPixels() or % GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % Quantum *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Quantum *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a Quantum array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image has corresponding metacontent,call % GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the % meta-content corresponding to the region. Once the Quantum array has % been updated, the changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % Quantum *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { const CacheInfo *magick_restrict cache_info; const PixelChannelMap *magick_restrict p, *magick_restrict q; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; p=image->channel_map; q=cache_info->channel_map; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->alpha_trait != cache_info->alpha_trait) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (image->number_channels != cache_info->number_channels) || (memcmp(p,q,image->number_channels*sizeof(*p)) != 0) || (image->metacontent_extent != cache_info->metacontent_extent) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = MagickResourceInfinity, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_timelimit=GetMagickResourceLimit(TimeResource); cache_epoch=GetMagickTime(); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (GetMagickTime()-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AcquireSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { destroy=MagickTrue; image->cache=clone_info; } } RelinquishSemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ if (image->type != UndefinedType) image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MemoryCache, MapCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType CopyPixel(const Image *image, const Quantum *source,Quantum *destination) { register ssize_t i; if (source == (const Quantum *) NULL) { destination[RedPixelChannel]=ClampToQuantum(image->background_color.red); destination[GreenPixelChannel]=ClampToQuantum( image->background_color.green); destination[BluePixelChannel]=ClampToQuantum( image->background_color.blue); destination[BlackPixelChannel]=ClampToQuantum( image->background_color.black); destination[AlphaPixelChannel]=ClampToQuantum( image->background_color.alpha); return(MagickFalse); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); destination[channel]=source[i]; } return(MagickTrue); } MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,Quantum *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id], exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixelInfo() method is: % % MagickBooleanType GetOneVirtualPixelInfo(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelInfo *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelInfo *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); GetPixelInfo(image,pixel); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (p == (const Quantum *) NULL) return(MagickFalse); GetPixelInfoPixel(image,p,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the colorspace of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheFilename() returns the filename associated with the pixel % cache. % % The format of the GetPixelCacheFilename() method is: % % const char *GetPixelCacheFilename(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetPixelCacheFilename(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->cache_filename); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) memset(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_metacontent_from_handler= GetVirtualMetacontentFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated % corresponding with the last call to SetPixelCacheNexusPixels() or % GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=cache_info->length; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimized cache tile width in pixels. % % o height: the optimized cache tile height in pixels. % */ MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *width=2048UL/(MagickMax(cache_info->number_channels,1)*sizeof(Quantum)); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/(MagickMax(cache_info->number_channels,1)*sizeof(Quantum)); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromCache() returns the meta-content corresponding with % the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualMetacontentFromCache() method is: % % void *GetVirtualMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const void *GetVirtualMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromNexus() returns the meta-content for the specified % cache nexus. % % The format of the GetVirtualMetacontentFromNexus() method is: % % const void *GetVirtualMetacontentFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the meta-content. % */ MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((void *) NULL); return(nexus_info->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontent() returns the virtual metacontent corresponding with % the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the meta-content are not available. % % The format of the GetVirtualMetacontent() method is: % % const void *GetVirtualMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const void *GetVirtualMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image); if (metacontent != (void *) NULL) return(metacontent); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCacheNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCacheNexus() method is: % % Quantum *GetVirtualPixelCacheNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; modulo.quotient=offset/((ssize_t) extent); modulo.remainder=offset % ((ssize_t) extent); if ((modulo.remainder != 0) && ((offset ^ ((ssize_t) extent)) < 0)) { modulo.quotient-=1; modulo.remainder+=((ssize_t) extent); } return(modulo); } MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo *magick_restrict virtual_nexus; Quantum *magick_restrict pixels, virtual_pixel[MaxPixelChannels]; register const Quantum *magick_restrict p; register const void *magick_restrict r; register Quantum *magick_restrict q; register ssize_t i, u; register unsigned char *magick_restrict s; ssize_t v; void *magick_restrict virtual_metacontent; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const Quantum *) NULL); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,x,y,columns,rows, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); if (pixels == (Quantum *) NULL) return((const Quantum *) NULL); q=pixels; offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns-1) < (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows-1) < (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(q); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); if (cache_info->metacontent_extent != 0) { status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); } return(q); } /* Pixel request is outside cache extents. */ virtual_nexus=nexus_info->virtual_nexus; s=(unsigned char *) nexus_info->metacontent; (void) memset(virtual_pixel,0,cache_info->number_channels* sizeof(*virtual_pixel)); virtual_metacontent=(void *) NULL; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: case EdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: { if (cache_info->metacontent_extent != 0) { /* Acquire a metacontent buffer. */ virtual_metacontent=(void *) AcquireQuantumMemory(1, cache_info->metacontent_extent); if (virtual_metacontent == (void *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), CacheError,"UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) memset(virtual_metacontent,0,cache_info->metacontent_extent); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case GrayVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange/2, virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case TransparentVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,TransparentAlpha,virtual_pixel); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } default: { SetPixelRed(image,ClampToQuantum(image->background_color.red), virtual_pixel); SetPixelGreen(image,ClampToQuantum(image->background_color.green), virtual_pixel); SetPixelBlue(image,ClampToQuantum(image->background_color.blue), virtual_pixel); SetPixelBlack(image,ClampToQuantum(image->background_color.black), virtual_pixel); SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha), virtual_pixel); break; } } break; } default: break; } for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info, nexus_info->virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=virtual_pixel; r=virtual_metacontent; break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=virtual_pixel; r=virtual_metacontent; break; } p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } } if (p == (const Quantum *) NULL) break; (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels; if ((s != (void *) NULL) && (r != (const void *) NULL)) { (void) memcpy(s,r,(size_t) cache_info->metacontent_extent); s+=cache_info->metacontent_extent; } continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,virtual_nexus,exception); if (p == (const Quantum *) NULL) break; r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels*length; if ((r != (void *) NULL) && (s != (const void *) NULL)) { (void) memcpy(s,r,(size_t) length); s+=length*cache_info->metacontent_extent; } } if (u < (ssize_t) columns) break; } /* Free resources. */ if (virtual_metacontent != (void *) NULL) virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent); if (v < (ssize_t) rows) return((const Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const Quantum *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const Quantum *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const Quantum *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const Quantum *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % access the meta-content (of type void) corresponding to the % region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const Quantum *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const Quantum *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated corresponding with the % last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % Quantum *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const Quantum *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const Quantum *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((Quantum *) NULL); return((const Quantum *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the composite mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum ApplyPixelCompositeMask(const Quantum p, const MagickRealType alpha,const Quantum q,const MagickRealType beta) { double mask_alpha; Quantum pixel; if (fabs(alpha-OpaqueAlpha) < MagickEpsilon) return(p); mask_alpha=1.0-QuantumScale*QuantumScale*alpha*beta; mask_alpha=PerceptibleReciprocal(mask_alpha); pixel=ClampToQuantum(mask_alpha*MagickOver_((double) p,alpha,(double) q, beta)); return(pixel); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict p, *magick_restrict q; ssize_t y; /* Apply composite mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & CompositeMaskChannel) == 0) return(MagickTrue); if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height, nexus_info->virtual_nexus,exception); q=nexus_info->pixels; if ((p == (Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickFalse); for (y=0; y < (ssize_t) nexus_info->region.height; y++) { register ssize_t x; for (x=0; x < (ssize_t) nexus_info->region.width; x++) { double mask_alpha; register ssize_t i; mask_alpha=(double) GetPixelCompositeMask(image,p); for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyPixelCompositeMask(p[i],mask_alpha,q[i],(MagickRealType) GetPixelAlpha(image,q)); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % metacontent, and memory mapping the cache if it is disk based. The cache % nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->disk_mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->disk_mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MagickPathExtent], message[MagickPathExtent]; (void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format); (void) FormatLocaleString(message,MagickPathExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); if (count != 1) return(MagickFalse); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) if (posix_fallocate(cache_info->file,offset+1,extent-offset) != 0) return(MagickFalse); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *hosts, *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (cache_anonymous_memory < 0) { char *value; /* Does the security policy require anonymous mapping for pixel cache? */ cache_anonymous_memory=0; value=GetPolicyValue("pixel-cache-memory"); if (value == (char *) NULL) value=GetPolicyValue("cache:memory-map"); if (LocaleCompare(value,"anonymous") == 0) { #if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS) cache_anonymous_memory=1; #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn", "'%s' (policy requires anonymous memory mapping)",image->filename); #endif } value=DestroyString(value); } if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (((MagickSizeType) image->columns > cache_info->width_limit) || ((MagickSizeType) image->rows > cache_info->height_limit)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); if (GetMagickResourceLimit(ListLengthResource) != MagickResourceInfinity) { length=GetImageListLength(image); if (AcquireMagickResource(ListLengthResource,length) == MagickFalse) ThrowBinaryException(ResourceLimitError,"ListLengthExceedsLimit", image->filename); } source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) image->scene); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->channels=image->channels; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,(MagickSizeType) cache_info->columns*cache_info->rows); if (cache_info->mode == PersistMode) status=MagickFalse; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)) && ((cache_info->type == UndefinedCache) || (cache_info->type == MemoryCache))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (status != MagickFalse) { status=MagickTrue; if (cache_anonymous_memory <= 0) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); } else { cache_info->mapped=MagickTrue; cache_info->pixels=(Quantum *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } if (cache_info->pixels == (Quantum *) NULL) { cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; } else { /* Create memory pixel cache. */ cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } cache_info->storage_class=image->storage_class; if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } } status=AcquireMagickResource(DiskResource,cache_info->length); hosts=(const char *) GetImageRegistry(StringRegistryType,"cache:hosts", exception); if ((status == MagickFalse) && (hosts != (const char *) NULL)) { DistributeCacheInfo *server_info; /* Distribute the pixel cache to a remote server. */ server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ status=MagickTrue; cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } /* Create pixel cache on disk. */ if (status == MagickFalse) { cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) && (cache_info->mode != PersistMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } cache_info->type=DiskCache; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length == (MagickSizeType) ((size_t) length)) { status=AcquireMagickResource(MapResource,cache_info->length); if (status != MagickFalse) { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; RelinquishMagickResource(MapResource,cache_info->length); } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); cache_info->type=MapCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(MagickTrue); } /* Clone persistent pixel cache. */ status=AcquireMagickResource(DiskResource,cache_info->length); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } clone_info=(CacheInfo *) ClonePixelCache(cache_info); clone_info->type=DiskCache; (void) CopyMagickString(clone_info->cache_filename,filename,MagickPathExtent); clone_info->file=(-1); clone_info->storage_class=cache_info->storage_class; clone_info->colorspace=cache_info->colorspace; clone_info->alpha_trait=cache_info->alpha_trait; clone_info->channels=cache_info->channels; clone_info->columns=cache_info->columns; clone_info->rows=cache_info->rows; clone_info->number_channels=cache_info->number_channels; clone_info->metacontent_extent=cache_info->metacontent_extent; clone_info->mode=PersistMode; clone_info->length=cache_info->length; (void) memcpy(clone_info->channel_map,cache_info->channel_map, MaxPixelChannels*sizeof(*cache_info->channel_map)); clone_info->offset=(*offset); status=ClonePixelCacheRepository(clone_info,cache_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; Quantum *magick_restrict pixels; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((Quantum *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((Quantum *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((Quantum *) NULL); /* Return pixel cache. */ pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,x,y,columns,rows, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a Quantum array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % obtain the meta-content (of type void) corresponding to the region. % Once the Quantum (and/or Quantum) array has been updated, the % changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y, columns,rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheMetacontent() reads metacontent from the specified region of % the pixel cache. % % The format of the ReadPixelCacheMetacontent() method is: % % MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the metacontent. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheMetacontent( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register ssize_t y; register unsigned char *magick_restrict q; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; q=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict p; /* Read meta-content from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->metacontent_extent*cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } break; } case DiskCache: { /* Read meta content from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read metacontent from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register Quantum *magick_restrict q; register ssize_t y; size_t number_channels, rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; number_channels=cache_info->number_channels; length=(MagickSizeType) number_channels*nexus_info->region.width* sizeof(Quantum); if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); y=0; q=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*q),length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheChannels() resets the pixel cache channels. % % The format of the ResetPixelCacheChannels method is: % % void ResetPixelCacheChannels(Image *) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate void ResetPixelCacheChannels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); cache_info->number_channels=GetPixelChannels(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t C a c h e A n o n y m o u s M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetCacheAnonymousMemory() resets the anonymous_memory value. % % The format of the ResetCacheAnonymousMemory method is: % % void ResetCacheAnonymousMemory(void) % */ MagickPrivate void ResetCacheAnonymousMemory(void) { cache_anonymous_memory=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_metacontent_from_handler != (GetVirtualMetacontentFromHandler) NULL) cache_info->methods.get_virtual_metacontent_from_handler= cache_methods->get_virtual_metacontent_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) cache_info->methods.get_authentic_metacontent_from_handler= cache_methods->get_authentic_metacontent_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % Quantum SetPixelCacheNexusPixels( % const CacheInfo *magick_restrict cache_info,const MapMode mode, % const ssize_t x,const ssize_t y,const size_t width,const size_t height, % const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o x,y,width,height: define the region of this particular cache nexus. % % o buffered: if true, nexus pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,const MagickSizeType length, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { if (length != (MagickSizeType) ((size_t) length)) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=0; nexus_info->mapped=MagickFalse; if (cache_anonymous_memory <= 0) { nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) length)); if (nexus_info->cache != (Quantum *) NULL) (void) memset(nexus_info->cache,0,(size_t) length); } else { nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t) length); if (nexus_info->cache != (Quantum *) NULL) nexus_info->mapped=MagickTrue; } if (nexus_info->cache == (Quantum *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=length; return(MagickTrue); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { if (nexus_info->length < CACHE_LINE_SIZE) return; if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE, 0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE,1,1); } static Quantum *SetPixelCacheNexusPixels( const CacheInfo *magick_restrict cache_info,const MapMode mode, const ssize_t x,const ssize_t y,const size_t width,const size_t height, const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((Quantum *) NULL); assert(nexus_info->signature == MagickCoreSignature); (void) memset(&nexus_info->region,0,sizeof(nexus_info->region)); if ((width == 0) || (height == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "NoPixelsDefinedInCache","`%s'",cache_info->filename); return((Quantum *) NULL); } if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { if (((x >= 0) && (y >= 0) && (((ssize_t) height+y-1) < (ssize_t) cache_info->rows)) && (((x == 0) && (width == cache_info->columns)) || ((height == 1) && (((ssize_t) width+x-1) < (ssize_t) cache_info->columns)))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) y*cache_info->columns+x; nexus_info->pixels=cache_info->pixels+cache_info->number_channels* offset; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(unsigned char *) cache_info->metacontent+ offset*cache_info->metacontent_extent; nexus_info->region.width=width; nexus_info->region.height=height; nexus_info->region.x=x; nexus_info->region.y=y; nexus_info->authentic_pixel_cache=MagickTrue; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ if (((MagickSizeType) width > cache_info->width_limit) || ((MagickSizeType) height > cache_info->height_limit)) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "WidthOrHeightExceedsLimit","`%s'",cache_info->filename); return((Quantum *) NULL); } number_pixels=(MagickSizeType) width*height; length=MagickMax(number_pixels,MagickMax(cache_info->columns, cache_info->rows))*cache_info->number_channels*sizeof(*nexus_info->pixels); if (cache_info->metacontent_extent != 0) length+=number_pixels*cache_info->metacontent_extent; status=MagickTrue; if (nexus_info->cache == (Quantum *) NULL) status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); } if (status == MagickFalse) return((Quantum *) NULL); nexus_info->pixels=nexus_info->cache; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(void *) (nexus_info->pixels+ cache_info->number_channels*number_pixels); nexus_info->region.width=width; nexus_info->region.height=height; nexus_info->region.x=x; nexus_info->region.y=y; nexus_info->authentic_pixel_cache=cache_info->type == PingCache ? MagickTrue : MagickFalse; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); break; } case TransparentVirtualPixelMethod: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); break; } default: break; } return(method); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticOpenCLBuffer() makes sure that all the OpenCL operations have % been completed and updates the host memory. % % The format of the SyncAuthenticOpenCLBuffer() method is: % % void SyncAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info) { assert(cache_info != (CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->type != MemoryCache) || (cache_info->opencl == (MagickCLCacheInfo) NULL)) return; /* Ensure single threaded access to OpenCL environment. */ LockSemaphoreInfo(cache_info->semaphore); cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); UnlockSemaphoreInfo(cache_info->semaphore); } MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); cache_info=(CacheInfo *) image->cache; CopyOpenCLBuffer(cache_info); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if (image->mask_trait != UpdatePixelTrait) { if (((image->channels & WriteMaskChannel) != 0) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (((image->channels & CompositeMaskChannel) != 0) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); } if (nexus_info->authentic_pixel_cache != MagickFalse) { if (image->taint == MagickFalse) image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->metacontent_extent != 0) && (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if ((status != MagickFalse) && (image->taint == MagickFalse)) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) { status=cache_info->methods.sync_authentic_pixels_handler(image, exception); return(status); } assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheMetacontent() writes the meta-content to the specified region % of the pixel cache. % % The format of the WritePixelCacheMetacontent() method is: % % MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the meta-content. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const unsigned char *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=(MagickSizeType) length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict q; /* Write associated pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width*cache_info->metacontent_extent; q+=cache_info->columns*cache_info->metacontent_extent; } break; } case DiskCache: { /* Write associated pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write metacontent to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const Quantum *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width* sizeof(Quantum); extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*nexus_info->region.width; q+=cache_info->number_channels*cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*p),length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
image.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII M M AAA GGGG EEEEE % % I MM MM A A G E % % I M M M AAAAA G GG EEE % % I M M A A G G E % % IIIII M M A A GGGG EEEEE % % % % % % MagickCore Image Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/magick-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/timer.h" #include "MagickCore/timer-private.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xwindow-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImage() returns a pointer to an image structure initialized to % default values. % % The format of the AcquireImage method is: % % Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AcquireImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; Image *image; MagickStatusType flags; /* Allocate image structure. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); image=(Image *) AcquireCriticalMemory(sizeof(*image)); (void) memset(image,0,sizeof(*image)); /* Initialize Image structure. */ (void) CopyMagickString(image->magick,"MIFF",MagickPathExtent); image->storage_class=DirectClass; image->depth=MAGICKCORE_QUANTUM_DEPTH; image->colorspace=sRGBColorspace; image->rendering_intent=PerceptualIntent; image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.red_primary.z=0.0300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.green_primary.z=0.1000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.blue_primary.z=0.7900f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->chromaticity.white_point.z=0.3583f; image->interlace=NoInterlace; image->ticks_per_second=UndefinedTicksPerSecond; image->compose=OverCompositeOp; (void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color, exception); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image->transparent_color,exception); GetTimerInfo(&image->timer); image->cache=AcquirePixelCache(0); image->channel_mask=DefaultChannels; image->channel_map=AcquirePixelChannelMap(); image->blob=CloneBlobInfo((BlobInfo *) NULL); image->timestamp=GetMagickTime(); image->debug=IsEventLogging(); image->reference_count=1; image->semaphore=AcquireSemaphoreInfo(); image->signature=MagickCoreSignature; if (image_info == (ImageInfo *) NULL) return(image); /* Transfer image info. */ SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue : MagickFalse); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent); if (image_info->size != (char *) NULL) { (void) ParseAbsoluteGeometry(image_info->size,&image->extract_info); image->columns=image->extract_info.width; image->rows=image->extract_info.height; image->offset=image->extract_info.x; image->extract_info.x=0; image->extract_info.y=0; } if (image_info->extract != (char *) NULL) { RectangleInfo geometry; (void) memset(&geometry,0,sizeof(geometry)); flags=ParseAbsoluteGeometry(image_info->extract,&geometry); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) { image->extract_info=geometry; Swap(image->columns,image->extract_info.width); Swap(image->rows,image->extract_info.height); } } image->compression=image_info->compression; image->quality=image_info->quality; image->endian=image_info->endian; image->interlace=image_info->interlace; image->units=image_info->units; if (image_info->density != (char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(image_info->density,&geometry_info); if ((flags & RhoValue) != 0) image->resolution.x=geometry_info.rho; image->resolution.y=image->resolution.x; if ((flags & SigmaValue) != 0) image->resolution.y=geometry_info.sigma; } if (image_info->page != (char *) NULL) { char *geometry; image->page=image->extract_info; geometry=GetPageGeometry(image_info->page); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } if (image_info->depth != 0) image->depth=image_info->depth; image->dither=image_info->dither; image->matte_color=image_info->matte_color; image->background_color=image_info->background_color; image->border_color=image_info->border_color; image->transparent_color=image_info->transparent_color; image->ping=image_info->ping; image->progress_monitor=image_info->progress_monitor; image->client_data=image_info->client_data; if (image_info->cache != (void *) NULL) ClonePixelCacheMethods(image->cache,image_info->cache); /* Set all global options that map to per-image settings. */ (void) SyncImageSettings(image_info,image,exception); /* Global options that are only set for new images. */ option=GetImageOption(image_info,"delay"); if (option != (const char *) NULL) { GeometryInfo geometry_info; flags=ParseGeometry(option,&geometry_info); if ((flags & GreaterValue) != 0) { if ((double) image->delay > floor(geometry_info.rho+0.5)) image->delay=(size_t) CastDoubleToLong(floor( geometry_info.rho+0.5)); } else if ((flags & LessValue) != 0) { if ((double) image->delay < floor(geometry_info.rho+0.5)) image->ticks_per_second=CastDoubleToLong(floor( geometry_info.sigma+0.5)); } else image->delay=(size_t) CastDoubleToLong(floor( geometry_info.rho+0.5)); if ((flags & SigmaValue) != 0) image->ticks_per_second=CastDoubleToLong(floor( geometry_info.sigma+0.5)); } option=GetImageOption(image_info,"dispose"); if (option != (const char *) NULL) image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions, MagickFalse,option); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImageInfo() allocates the ImageInfo structure. % % The format of the AcquireImageInfo method is: % % ImageInfo *AcquireImageInfo(void) % */ MagickExport ImageInfo *AcquireImageInfo(void) { ImageInfo *image_info; image_info=(ImageInfo *) AcquireCriticalMemory(sizeof(*image_info)); GetImageInfo(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % The format of the AcquireNextImage method is: % % void AcquireNextImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { /* Allocate image structure. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->next=AcquireImage(image_info,exception); if (GetNextImageInList(image) == (Image *) NULL) return; (void) CopyMagickString(GetNextImageInList(image)->filename,image->filename, MagickPathExtent); if (image_info != (ImageInfo *) NULL) (void) CopyMagickString(GetNextImageInList(image)->filename, image_info->filename,MagickPathExtent); DestroyBlob(GetNextImageInList(image)); image->next->blob=ReferenceBlob(image->blob); image->next->endian=image->endian; image->next->scene=image->scene+1; image->next->previous=image; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A p p e n d I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AppendImages() takes all images from the current image pointer to the end % of the image list and appends them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting effects how the image is justified in the % final image. % % The format of the AppendImages method is: % % Image *AppendImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AppendImages(const Image *images, const MagickBooleanType stack,ExceptionInfo *exception) { #define AppendImageTag "Append/Image" CacheView *append_view; Image *append_image; MagickBooleanType homogeneous_colorspace, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; const Image *next; size_t depth, height, number_images, width; ssize_t x_offset, y, y_offset; /* Compute maximum area of appended area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); alpha_trait=images->alpha_trait; number_images=1; width=images->columns; height=images->rows; depth=images->depth; homogeneous_colorspace=MagickTrue; next=GetNextImageInList(images); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->depth > depth) depth=next->depth; if (next->colorspace != images->colorspace) homogeneous_colorspace=MagickFalse; if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; continue; } width+=next->columns; if (next->rows > height) height=next->rows; } /* Append images. */ append_image=CloneImage(images,width,height,MagickTrue,exception); if (append_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse) { append_image=DestroyImage(append_image); return((Image *) NULL); } if (homogeneous_colorspace == MagickFalse) (void) SetImageColorspace(append_image,sRGBColorspace,exception); append_image->depth=depth; append_image->alpha_trait=alpha_trait; append_image->page=images->page; (void) SetImageBackgroundColor(append_image,exception); status=MagickTrue; x_offset=0; y_offset=0; next=images; append_view=AcquireAuthenticCacheView(append_image,exception); for (n=0; n < (MagickOffsetType) number_images; n++) { CacheView *image_view; MagickBooleanType proceed; SetGeometry(append_image,&geometry); GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry); if (stack != MagickFalse) x_offset-=geometry.x; else y_offset-=geometry.y; image_view=AcquireVirtualCacheView(next,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(next,next,next->rows,1) #endif for (y=0; y < (ssize_t) next->rows; y++) { MagickBooleanType sync; PixelInfo pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception); q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset, next->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(next,&pixel); for (x=0; x < (ssize_t) next->columns; x++) { GetPixelInfoPixel(next,p,&pixel); SetPixelViaPixelInfo(append_image,&pixel,q); p+=GetPixelChannels(next); q+=GetPixelChannels(append_image); } sync=SyncCacheViewAuthenticPixels(append_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (stack == MagickFalse) { x_offset+=(ssize_t) next->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) next->rows; } proceed=SetImageProgress(append_image,AppendImageTag,n,number_images); if (proceed == MagickFalse) break; next=GetNextImageInList(next); } append_view=DestroyCacheView(append_view); if (status == MagickFalse) append_image=DestroyImage(append_image); return(append_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a t c h I m a g e E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CatchImageException() returns if no exceptions are found in the image % sequence, otherwise it determines the most severe exception and reports % it as a warning or error depending on the severity. % % The format of the CatchImageException method is: % % ExceptionType CatchImageException(Image *image) % % A description of each parameter follows: % % o image: An image sequence. % */ MagickExport ExceptionType CatchImageException(Image *image) { ExceptionInfo *exception; ExceptionType severity; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=AcquireExceptionInfo(); CatchException(exception); severity=exception->severity; exception=DestroyExceptionInfo(exception); return(severity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipImagePath() sets the image clip mask based any clipping path information % if it exists. % % The format of the ClipImagePath method is: % % MagickBooleanType ClipImagePath(Image *image,const char *pathname, % const MagickBooleanType inside,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception) { return(ClipImagePath(image,"#1",MagickTrue,exception)); } MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname, const MagickBooleanType inside,ExceptionInfo *exception) { #define ClipImagePathTag "ClipPath/Image" char *property; const char *value; Image *clip_mask; ImageInfo *image_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pathname != NULL); property=AcquireString(pathname); (void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s", pathname); value=GetImageProperty(image,property,exception); property=DestroyString(property); if (value == (const char *) NULL) { ThrowFileException(exception,OptionError,"NoClipPathDefined", image->filename); return(MagickFalse); } image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,image->filename, MagickPathExtent); (void) ConcatenateMagickString(image_info->filename,pathname, MagickPathExtent); clip_mask=BlobToImage(image_info,value,strlen(value),exception); image_info=DestroyImageInfo(image_info); if (clip_mask == (Image *) NULL) return(MagickFalse); if (clip_mask->storage_class == PseudoClass) { (void) SyncImage(clip_mask,exception); if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse) return(MagickFalse); } if (inside == MagickFalse) (void) NegateImage(clip_mask,MagickFalse,exception); (void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent, "8BIM:1999,2998:%s\nPS",pathname); (void) SetImageMask(image,WritePixelMask,clip_mask,exception); image->mask_trait=UpdatePixelTrait; clip_mask=DestroyImage(clip_mask); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImage() copies an image and returns the copy as a new image object. % % If the specified columns and rows is 0, an exact copy of the image is % returned, otherwise the pixel data is undefined and must be initialized % with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On % failure, a NULL image is returned and exception describes the reason for the % failure. % % The format of the CloneImage method is: % % Image *CloneImage(const Image *image,const size_t columns, % const size_t rows,const MagickBooleanType orphan, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the cloned image. % % o rows: the number of rows in the cloned image. % % o detach: With a value other than 0, the cloned image is detached from % its parent I/O stream. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { Image *clone_image; double scale; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "NegativeOrZeroImageSize","`%s'",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireCriticalMemory(sizeof(*clone_image)); (void) memset(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickCoreSignature; clone_image->storage_class=image->storage_class; clone_image->number_channels=image->number_channels; clone_image->number_meta_channels=image->number_meta_channels; clone_image->metacontent_extent=image->metacontent_extent; clone_image->colorspace=image->colorspace; clone_image->alpha_trait=image->alpha_trait; clone_image->channels=image->channels; clone_image->mask_trait=image->mask_trait; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; clone_image->image_info=CloneImageInfo(image->image_info); (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->extent=image->extent; clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; clone_image->channel_mask=image->channel_mask; clone_image->channel_map=ClonePixelChannelMap(image->channel_map); (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MagickPathExtent); (void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent); (void) CopyMagickString(clone_image->filename,image->filename, MagickPathExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AcquireSemaphoreInfo(); if (image->colormap != (PixelInfo *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length+1, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelInfo *) NULL) { clone_image=DestroyImage(clone_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memcpy(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) CastDoubleToLong(floor(scale* image->page.width+0.5)); clone_image->page.x=CastDoubleToLong(ceil(scale*image->page.x-0.5)); clone_image->tile_offset.x=CastDoubleToLong(ceil(scale* image->tile_offset.x-0.5)); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) CastDoubleToLong(floor(scale* image->page.height+0.5)); clone_image->page.y=CastDoubleToLong(ceil(scale*image->page.y-0.5)); clone_image->tile_offset.y=CastDoubleToLong(ceil(scale* image->tile_offset.y-0.5)); clone_image->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse) clone_image=DestroyImage(clone_image); return(clone_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageInfo() makes a copy of the given image info structure. If % NULL is specified, a new image info structure is created initialized to % default values. % % The format of the CloneImageInfo method is: % % ImageInfo *CloneImageInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info) { ImageInfo *clone_info; clone_info=AcquireImageInfo(); if (image_info == (ImageInfo *) NULL) return(clone_info); clone_info->compression=image_info->compression; clone_info->temporary=image_info->temporary; clone_info->adjoin=image_info->adjoin; clone_info->antialias=image_info->antialias; clone_info->scene=image_info->scene; clone_info->number_scenes=image_info->number_scenes; clone_info->depth=image_info->depth; if (image_info->size != (char *) NULL) (void) CloneString(&clone_info->size,image_info->size); if (image_info->extract != (char *) NULL) (void) CloneString(&clone_info->extract,image_info->extract); if (image_info->scenes != (char *) NULL) (void) CloneString(&clone_info->scenes,image_info->scenes); if (image_info->page != (char *) NULL) (void) CloneString(&clone_info->page,image_info->page); clone_info->interlace=image_info->interlace; clone_info->endian=image_info->endian; clone_info->units=image_info->units; clone_info->quality=image_info->quality; if (image_info->sampling_factor != (char *) NULL) (void) CloneString(&clone_info->sampling_factor, image_info->sampling_factor); if (image_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,image_info->server_name); if (image_info->font != (char *) NULL) (void) CloneString(&clone_info->font,image_info->font); if (image_info->texture != (char *) NULL) (void) CloneString(&clone_info->texture,image_info->texture); if (image_info->density != (char *) NULL) (void) CloneString(&clone_info->density,image_info->density); clone_info->pointsize=image_info->pointsize; clone_info->fuzz=image_info->fuzz; clone_info->matte_color=image_info->matte_color; clone_info->background_color=image_info->background_color; clone_info->border_color=image_info->border_color; clone_info->transparent_color=image_info->transparent_color; clone_info->dither=image_info->dither; clone_info->monochrome=image_info->monochrome; clone_info->colorspace=image_info->colorspace; clone_info->type=image_info->type; clone_info->orientation=image_info->orientation; clone_info->ping=image_info->ping; clone_info->verbose=image_info->verbose; clone_info->progress_monitor=image_info->progress_monitor; clone_info->client_data=image_info->client_data; clone_info->cache=image_info->cache; if (image_info->cache != (void *) NULL) clone_info->cache=ReferencePixelCache(image_info->cache); if (image_info->profile != (void *) NULL) clone_info->profile=(void *) CloneStringInfo((StringInfo *) image_info->profile); SetImageInfoFile(clone_info,image_info->file); SetImageInfoBlob(clone_info,image_info->blob,image_info->length); clone_info->stream=image_info->stream; clone_info->custom_stream=image_info->custom_stream; (void) CopyMagickString(clone_info->magick,image_info->magick, MagickPathExtent); (void) CopyMagickString(clone_info->unique,image_info->unique, MagickPathExtent); (void) CopyMagickString(clone_info->filename,image_info->filename, MagickPathExtent); clone_info->channel=image_info->channel; (void) CloneImageOptions(clone_info,image_info); clone_info->debug=IsEventLogging(); clone_info->signature=image_info->signature; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyImagePixels() copies pixels from the source image as defined by the % geometry the destination image at the specified offset. % % The format of the CopyImagePixels method is: % % MagickBooleanType CopyImagePixels(Image *image,const Image *source_image, % const RectangleInfo *geometry,const OffsetInfo *offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o image: the destination image. % % o source_image: the source image. % % o geometry: define the dimensions of the source pixel rectangle. % % o offset: define the offset in the destination image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType CopyImagePixels(Image *image, const Image *source_image,const RectangleInfo *geometry, const OffsetInfo *offset,ExceptionInfo *exception) { #define CopyImageTag "Copy/Image" CacheView *image_view, *source_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(source_image != (Image *) NULL); assert(geometry != (RectangleInfo *) NULL); assert(offset != (OffsetInfo *) NULL); if ((offset->x < 0) || (offset->y < 0) || ((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) || ((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows)) ThrowBinaryException(OptionError,"GeometryDoesNotContainImage", image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Copy image pixels. */ status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,source_image,geometry->height,1) #endif for (y=0; y < (ssize_t) geometry->height; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y, geometry->width,1,exception); q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y, geometry->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) geometry->width; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if ((traits == UndefinedPixelTrait) || ((traits & UpdatePixelTrait) == 0) || (source_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CopyImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImage() dereferences an image, deallocating memory associated with % the image if the reference count becomes zero. % % The format of the DestroyImage method is: % % Image *DestroyImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *DestroyImage(Image *image) { MagickBooleanType destroy; /* Dereference image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); destroy=MagickFalse; LockSemaphoreInfo(image->semaphore); image->reference_count--; if (image->reference_count == 0) destroy=MagickTrue; UnlockSemaphoreInfo(image->semaphore); if (destroy == MagickFalse) return((Image *) NULL); /* Destroy image. */ DestroyImagePixels(image); image->channel_map=DestroyPixelChannelMap(image->channel_map); if (image->montage != (char *) NULL) image->montage=DestroyString(image->montage); if (image->directory != (char *) NULL) image->directory=DestroyString(image->directory); if (image->colormap != (PixelInfo *) NULL) image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); if (image->geometry != (char *) NULL) image->geometry=DestroyString(image->geometry); DestroyImageProfiles(image); DestroyImageProperties(image); DestroyImageArtifacts(image); if (image->ascii85 != (Ascii85Info *) NULL) image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85); if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); DestroyBlob(image); if (image->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&image->semaphore); image->signature=(~MagickCoreSignature); image=(Image *) RelinquishMagickMemory(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageInfo() deallocates memory associated with an ImageInfo % structure. % % The format of the DestroyImageInfo method is: % % ImageInfo *DestroyImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); if (image_info->size != (char *) NULL) image_info->size=DestroyString(image_info->size); if (image_info->extract != (char *) NULL) image_info->extract=DestroyString(image_info->extract); if (image_info->scenes != (char *) NULL) image_info->scenes=DestroyString(image_info->scenes); if (image_info->page != (char *) NULL) image_info->page=DestroyString(image_info->page); if (image_info->sampling_factor != (char *) NULL) image_info->sampling_factor=DestroyString( image_info->sampling_factor); if (image_info->server_name != (char *) NULL) image_info->server_name=DestroyString( image_info->server_name); if (image_info->font != (char *) NULL) image_info->font=DestroyString(image_info->font); if (image_info->texture != (char *) NULL) image_info->texture=DestroyString(image_info->texture); if (image_info->density != (char *) NULL) image_info->density=DestroyString(image_info->density); if (image_info->cache != (void *) NULL) image_info->cache=DestroyPixelCache(image_info->cache); if (image_info->profile != (StringInfo *) NULL) image_info->profile=(void *) DestroyStringInfo((StringInfo *) image_info->profile); DestroyImageOptions(image_info); image_info->signature=(~MagickCoreSignature); image_info=(ImageInfo *) RelinquishMagickMemory(image_info); return(image_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i s a s s o c i a t e I m a g e S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisassociateImageStream() disassociates the image stream. It checks if the % blob of the specified image is referenced by other images. If the reference % count is higher then 1 a new blob is assigned to the specified image. % % The format of the DisassociateImageStream method is: % % void DisassociateImageStream(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DisassociateImageStream(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); DisassociateBlob(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfo() initializes image_info to default values. % % The format of the GetImageInfo method is: % % void GetImageInfo(ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport void GetImageInfo(ImageInfo *image_info) { char *synchronize; ExceptionInfo *exception; /* File and image dimension members. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info != (ImageInfo *) NULL); (void) memset(image_info,0,sizeof(*image_info)); image_info->adjoin=MagickTrue; image_info->interlace=NoInterlace; image_info->channel=DefaultChannels; image_info->quality=UndefinedCompressionQuality; image_info->antialias=MagickTrue; image_info->dither=MagickTrue; synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { image_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } exception=AcquireExceptionInfo(); (void) QueryColorCompliance(BackgroundColor,AllCompliance, &image_info->background_color,exception); (void) QueryColorCompliance(BorderColor,AllCompliance, &image_info->border_color,exception); (void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color, exception); (void) QueryColorCompliance(TransparentColor,AllCompliance, &image_info->transparent_color,exception); exception=DestroyExceptionInfo(exception); image_info->debug=IsEventLogging(); image_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageInfoFile() returns the image info file member. % % The format of the GetImageInfoFile method is: % % FILE *GetImageInfoFile(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info) { return(image_info->file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMask() returns the mask associated with the image. % % The format of the GetImageMask method is: % % Image *GetImageMask(const Image *image,const PixelMask type, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % */ MagickExport Image *GetImageMask(const Image *image,const PixelMask type, ExceptionInfo *exception) { CacheView *mask_view, *image_view; Image *mask_image; MagickBooleanType status; ssize_t y; /* Get image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); switch (type) { case ReadPixelMask: { if ((image->channels & ReadMaskChannel) == 0) return((Image *) NULL); break; } case WritePixelMask: { if ((image->channels & WriteMaskChannel) == 0) return((Image *) NULL); break; } default: { if ((image->channels & CompositeMaskChannel) == 0) return((Image *) NULL); break; } } mask_image=AcquireImage((ImageInfo *) NULL,exception); status=SetImageExtent(mask_image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImage(mask_image)); status=MagickTrue; mask_image->alpha_trait=UndefinedPixelTrait; (void) SetImageColorspace(mask_image,GRAYColorspace,exception); image_view=AcquireVirtualCacheView(image,exception); mask_view=AcquireAuthenticCacheView(mask_image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { switch (type) { case ReadPixelMask: { SetPixelGray(mask_image,GetPixelReadMask(image,p),q); break; } case WritePixelMask: { SetPixelGray(mask_image,GetPixelWriteMask(image,p),q); break; } default: { SetPixelGray(mask_image,GetPixelCompositeMask(image,p),q); break; } } p+=GetPixelChannels(image); q+=GetPixelChannels(mask_image); } if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) mask_image=DestroyImage(mask_image); return(mask_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e R e f e r e n c e C o u n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageReferenceCount() returns the image reference count. % % The format of the GetReferenceCount method is: % % ssize_t GetImageReferenceCount(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport ssize_t GetImageReferenceCount(Image *image) { ssize_t reference_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); LockSemaphoreInfo(image->semaphore); reference_count=image->reference_count; UnlockSemaphoreInfo(image->semaphore); return(reference_count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageVirtualPixelMethod() gets the "virtual pixels" method for the % image. A virtual pixel is any pixel access that is outside the boundaries % of the image cache. % % The format of the GetImageVirtualPixelMethod() method is: % % VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(GetPixelCacheVirtualMethod(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageFilename() interprets embedded characters in an image filename. % The filename length is returned. % % The format of the InterpretImageFilename method is: % % size_t InterpretImageFilename(const ImageInfo *image_info,Image *image, % const char *format,int value,char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info.. % % o image: the image. % % o format: A filename describing the format to use to write the numeric % argument. Only the first numeric format identifier is replaced. % % o value: Numeric value to substitute into format filename. % % o filename: return the formatted filename in this character buffer. % % o exception: return any errors or warnings in this structure. % */ MagickExport size_t InterpretImageFilename(const ImageInfo *image_info, Image *image,const char *format,int value,char *filename, ExceptionInfo *exception) { char *q; int c; MagickBooleanType canonical; const char *p; ssize_t field_width, offset; canonical=MagickFalse; offset=0; (void) CopyMagickString(filename,format,MagickPathExtent); for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%')) { q=(char *) p+1; if (*q == '%') { p=q+1; continue; } field_width=0; if (*q == '0') field_width=(ssize_t) strtol(q,&q,10); switch (*q) { case 'd': case 'o': case 'x': { q++; c=(*q); *q='\0'; (void) FormatLocaleString(filename+(p-format-offset),(size_t) (MagickPathExtent-(p-format-offset)),p,value); offset+=(4-field_width); *q=c; (void) ConcatenateMagickString(filename,q,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } case '[': { char pattern[MagickPathExtent]; const char *option; char *r; ssize_t i; ssize_t depth; /* Image option. */ if (strchr(p,']') == (char *) NULL) break; depth=1; r=q+1; for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++) { if (*r == '[') depth++; if (*r == ']') depth--; if (depth <= 0) break; pattern[i]=(*r++); } pattern[i]='\0'; if (LocaleNCompare(pattern,"filename:",9) != 0) break; option=(const char *) NULL; if (image != (Image *) NULL) option=GetImageProperty(image,pattern,exception); if ((option == (const char *) NULL) && (image != (Image *) NULL)) option=GetImageArtifact(image,pattern); if ((option == (const char *) NULL) && (image_info != (ImageInfo *) NULL)) option=GetImageOption(image_info,pattern); if (option == (const char *) NULL) break; q--; c=(*q); *q='\0'; (void) CopyMagickString(filename+(p-format-offset),option,(size_t) (MagickPathExtent-(p-format-offset))); offset+=strlen(pattern)-strlen(option)+3; *q=c; (void) ConcatenateMagickString(filename,r+1,MagickPathExtent); canonical=MagickTrue; if (*(q-1) != '%') break; p++; break; } default: break; } } if (canonical == MagickFalse) (void) CopyMagickString(filename,format,MagickPathExtent); else for (q=filename; *q != '\0'; q++) if ((*q == '%') && (*(q+1) == '%')) (void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename))); return(strlen(filename)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s H i g h D y n a m i c R a n g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsHighDynamicRangeImage() returns MagickTrue if any pixel component is % non-integer or exceeds the bounds of the quantum depth (e.g. for Q16 % 0..65535. % % The format of the IsHighDynamicRangeImage method is: % % MagickBooleanType IsHighDynamicRangeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image, ExceptionInfo *exception) { #if !defined(MAGICKCORE_HDRI_SUPPORT) (void) image; (void) exception; return(MagickFalse); #else CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); 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++) { const Quantum *p; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double pixel; PixelTrait traits; traits=GetPixelChannelTraits(image,(PixelChannel) i); if (traits == UndefinedPixelTrait) continue; pixel=(double) p[i]; if ((pixel < 0.0) || (pixel > QuantumRange) || (pixel != (double) ((QuantumAny) pixel))) break; } p+=GetPixelChannels(image); if (i < (ssize_t) GetPixelChannels(image)) status=MagickFalse; } if (x < (ssize_t) image->columns) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status != MagickFalse ? MagickFalse : MagickTrue); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s I m a g e O b j e c t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsImageObject() returns MagickTrue if the image sequence contains a valid % set of image objects. % % The format of the IsImageObject method is: % % MagickBooleanType IsImageObject(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsImageObject(const Image *image) { const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) if (p->signature != MagickCoreSignature) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s T a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsTaintImage() returns MagickTrue any pixel in the image has been altered % since it was first constituted. % % The format of the IsTaintImage method is: % % MagickBooleanType IsTaintImage(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType IsTaintImage(const Image *image) { char magick[MagickPathExtent], filename[MagickPathExtent]; const Image *p; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); (void) CopyMagickString(magick,image->magick,MagickPathExtent); (void) CopyMagickString(filename,image->filename,MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { if (p->taint != MagickFalse) return(MagickTrue); if (LocaleCompare(p->magick,magick) != 0) return(MagickTrue); if (LocaleCompare(p->filename,filename) != 0) return(MagickTrue); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModifyImage() ensures that there is only a single reference to the image % to be modified, updating the provided image pointer to point to a clone of % the original image if necessary. % % The format of the ModifyImage method is: % % MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ModifyImage(Image **image, ExceptionInfo *exception) { Image *clone_image; assert(image != (Image **) NULL); assert(*image != (Image *) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); if (GetImageReferenceCount(*image) <= 1) return(MagickTrue); clone_image=CloneImage(*image,0,0,MagickTrue,exception); LockSemaphoreInfo((*image)->semaphore); (*image)->reference_count--; UnlockSemaphoreInfo((*image)->semaphore); *image=clone_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w M a g i c k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewMagickImage() creates a blank image canvas of the specified size and % background color. % % The format of the NewMagickImage method is: % % Image *NewMagickImage(const ImageInfo *image_info,const size_t width, % const size_t height,const PixelInfo *background, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the image width. % % o height: the image height. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *NewMagickImage(const ImageInfo *image_info, const size_t width,const size_t height,const PixelInfo *background, ExceptionInfo *exception) { CacheView *image_view; Image *image; MagickBooleanType status; ssize_t y; assert(image_info != (const ImageInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image_info->signature == MagickCoreSignature); assert(background != (const PixelInfo *) NULL); image=AcquireImage(image_info,exception); image->columns=width; image->rows=height; image->colorspace=background->colorspace; image->alpha_trait=background->alpha_trait; image->fuzz=background->fuzz; image->depth=background->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e f e r e n c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferenceImage() increments the reference count associated with an image % returning a pointer to the image. % % The format of the ReferenceImage method is: % % Image *ReferenceImage(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Image *ReferenceImage(Image *image) { assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); LockSemaphoreInfo(image->semaphore); image->reference_count++; UnlockSemaphoreInfo(image->semaphore); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePage() resets the image page canvas and position. % % The format of the ResetImagePage method is: % % MagickBooleanType ResetImagePage(Image *image,const char *page) % % A description of each parameter follows: % % o image: the image. % % o page: the relative page specification. % */ MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page) { MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); flags=ParseAbsoluteGeometry(page,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; image->page.width=geometry.width; image->page.height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) image->page.x+=geometry.x; if ((flags & YValue) != 0) image->page.y+=geometry.y; } else { if ((flags & XValue) != 0) { image->page.x=geometry.x; if ((image->page.width == 0) && (geometry.x > 0)) image->page.width=image->columns+geometry.x; } if ((flags & YValue) != 0) { image->page.y=geometry.y; if ((image->page.height == 0) && (geometry.y > 0)) image->page.height=image->rows+geometry.y; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePixels() reset the image pixels, that is, all the pixel components % are zereod. % % The format of the SetImage method is: % % MagickBooleanType ResetImagePixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ResetImagePixels(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; size_t length; ssize_t y; void *pixels; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); pixels=AcquirePixelCachePixels(image,&length,exception); if (pixels != (void *) NULL) { /* Reset in-core image pixels. */ (void) memset(pixels,0,length); return(MagickTrue); } /* Reset image pixels. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { (void) memset(q,0,GetPixelChannels(image)*sizeof(Quantum)); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageAlpha() sets the alpha levels of the image. % % The format of the SetImageAlpha method is: % % MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: the level of transparency: 0 is fully transparent and QuantumRange % is fully opaque. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireAuthenticCacheView(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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) > (QuantumRange/2)) SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e B a c k g r o u n d C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageBackgroundColor() initializes the image pixels to the image % background color. The background color is defined by the background_color % member of the image structure. % % The format of the SetImage method is: % % MagickBooleanType SetImageBackgroundColor(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageBackgroundColor(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo background; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlphaChannel(image,OnAlphaChannel,exception); ConformPixelInfo(image,&image->background_color,&background,exception); /* Set image background color. */ status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannelMask() sets the image channel mask from the specified channel % mask. % % The format of the SetImageChannelMask method is: % % ChannelType SetImageChannelMask(Image *image, % const ChannelType channel_mask) % % A description of each parameter follows: % % o image: the image. % % o channel_mask: the channel mask. % */ MagickExport ChannelType SetImageChannelMask(Image *image, const ChannelType channel_mask) { return(SetPixelChannelMask(image,channel_mask)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColor() set the entire image canvas to the specified color. % % The format of the SetImageColor method is: % % MagickBooleanType SetImageColor(Image *image,const PixelInfo *color, % ExeptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o background: the image color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageColor(Image *image, const PixelInfo *color,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); assert(color != (const PixelInfo *) NULL); image->colorspace=color->colorspace; image->alpha_trait=color->alpha_trait; image->fuzz=color->fuzz; image->depth=color->depth; status=MagickTrue; image_view=AcquireAuthenticCacheView(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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelViaPixelInfo(image,color,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageStorageClass() sets the image class: DirectClass for true color % images or PseudoClass for colormapped images. % % The format of the SetImageStorageClass method is: % % MagickBooleanType SetImageStorageClass(Image *image, % const ClassType storage_class,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o storage_class: The image class. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageStorageClass(Image *image, const ClassType storage_class,ExceptionInfo *exception) { 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); image->storage_class=storage_class; return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageExtent() sets the image size (i.e. columns & rows). % % The format of the SetImageExtent method is: % % MagickBooleanType SetImageExtent(Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: The image width in pixels. % % o rows: The image height in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { if ((columns == 0) || (rows == 0)) ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename); image->columns=columns; image->rows=rows; if (image->depth == 0) { image->depth=8; (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageDepthNotSupported","`%s'",image->filename); } if (image->depth > (8*sizeof(MagickSizeType))) { image->depth=8*sizeof(MagickSizeType); (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageDepthNotSupported","`%s'",image->filename); } return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t I m a g e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfo() initializes the 'magick' field of the ImageInfo structure. % It is set to a type of image format based on the prefix or suffix of the % filename. For example, 'ps:image' returns PS indicating a Postscript image. % JPEG is returned for this filename: 'image.jpg'. The filename prefix has % precendence over the suffix. Use an optional index enclosed in brackets % after a file name to specify a desired scene of a multi-resolution image % format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value % indicates success. % % The format of the SetImageInfo method is: % % MagickBooleanType SetImageInfo(ImageInfo *image_info, % const unsigned int frames,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o frames: the number of images you intend to write. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info, const unsigned int frames,ExceptionInfo *exception) { char component[MagickPathExtent], magic[MagickPathExtent], path[MagickPathExtent], *q; const MagicInfo *magic_info; const MagickInfo *magick_info; ExceptionInfo *sans_exception; Image *image; MagickBooleanType status; const char *p; ssize_t count; /* Look for 'image.format' in filename. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); *component='\0'; GetPathComponent(image_info->filename,SubimagePath,component); if (*component != '\0') { /* Look for scene specification (e.g. img0001.pcd[4]). */ if (IsSceneGeometry(component,MagickFalse) == MagickFalse) { if (IsGeometry(component) != MagickFalse) (void) CloneString(&image_info->extract,component); } else { size_t first, last; (void) CloneString(&image_info->scenes,component); image_info->scene=StringToUnsignedLong(image_info->scenes); image_info->number_scenes=image_info->scene; p=image_info->scenes; for (q=(char *) image_info->scenes; *q != '\0'; p++) { while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; first=(size_t) strtol(p,&q,10); last=first; while (isspace((int) ((unsigned char) *q)) != 0) q++; if (*q == '-') last=(size_t) strtol(q+1,&q,10); if (first > last) Swap(first,last); if (first < image_info->scene) image_info->scene=first; if (last > image_info->number_scenes) image_info->number_scenes=last; p=q; } image_info->number_scenes-=image_info->scene-1; } } *component='\0'; if (*image_info->magick == '\0') GetPathComponent(image_info->filename,ExtensionPath,component); if (*component != '\0') { /* Base path sans any compression extension. */ GetPathComponent(image_info->filename,BasePathSansCompressExtension,path); GetPathComponent(path,ExtensionPath,component); } image_info->affirm=MagickFalse; sans_exception=AcquireExceptionInfo(); if ((*component != '\0') && (IsGlob(component) == MagickFalse)) { MagickFormatType format_type; ssize_t i; static const char *format_type_formats[] = { "AUTOTRACE", "BROWSE", "DCRAW", "EDIT", "LAUNCH", "MPEG:DECODE", "MPEG:ENCODE", "PRINT", "PS:ALPHA", "PS:CMYK", "PS:COLOR", "PS:GRAY", "PS:MONO", "SCAN", "SHOW", "WIN", (char *) NULL }; /* User specified image format. */ (void) CopyMagickString(magic,component,MagickPathExtent); LocaleUpper(magic); /* Look for explicit image formats. */ format_type=UndefinedFormatType; magick_info=GetMagickInfo(magic,sans_exception); if ((magick_info != (const MagickInfo *) NULL) && (magick_info->format_type != UndefinedFormatType)) format_type=magick_info->format_type; i=0; while ((format_type == UndefinedFormatType) && (format_type_formats[i] != (char *) NULL)) { if ((*magic == *format_type_formats[i]) && (LocaleCompare(magic,format_type_formats[i]) == 0)) format_type=ExplicitFormatType; i++; } if (format_type == UndefinedFormatType) (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); else if (format_type == ExplicitFormatType) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); } if (LocaleCompare(magic,"RGB") == 0) image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */ } /* Look for explicit 'format:image' in filename. */ *magic='\0'; GetPathComponent(image_info->filename,MagickPath,magic); if (*magic == '\0') { (void) CopyMagickString(magic,image_info->magick,MagickPathExtent); magick_info=GetMagickInfo(magic,sans_exception); if (frames == 0) GetPathComponent(image_info->filename,CanonicalPath,component); else GetPathComponent(image_info->filename,SubcanonicalPath,component); (void) CopyMagickString(image_info->filename,component,MagickPathExtent); } else { const DelegateInfo *delegate_info; /* User specified image format. */ LocaleUpper(magic); magick_info=GetMagickInfo(magic,sans_exception); delegate_info=GetDelegateInfo(magic,"*",sans_exception); if (delegate_info == (const DelegateInfo *) NULL) delegate_info=GetDelegateInfo("*",magic,sans_exception); if (((magick_info != (const MagickInfo *) NULL) || (delegate_info != (const DelegateInfo *) NULL)) && (IsMagickConflict(magic) == MagickFalse)) { image_info->affirm=MagickTrue; (void) CopyMagickString(image_info->magick,magic,MagickPathExtent); GetPathComponent(image_info->filename,CanonicalPath,component); (void) CopyMagickString(image_info->filename,component, MagickPathExtent); } } sans_exception=DestroyExceptionInfo(sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; if ((image_info->adjoin != MagickFalse) && (frames > 1)) { /* Test for multiple image support (e.g. image%02d.png). */ (void) InterpretImageFilename(image_info,(Image *) NULL, image_info->filename,(int) image_info->scene,component,exception); if ((LocaleCompare(component,image_info->filename) != 0) && (strchr(component,'%') == (char *) NULL)) image_info->adjoin=MagickFalse; } if ((image_info->adjoin != MagickFalse) && (frames > 0)) { /* Some image formats do not support multiple frames per file. */ magick_info=GetMagickInfo(magic,exception); if (magick_info != (const MagickInfo *) NULL) if (GetMagickAdjoin(magick_info) == MagickFalse) image_info->adjoin=MagickFalse; } if (image_info->affirm != MagickFalse) return(MagickTrue); if (frames == 0) { unsigned char *magick; size_t magick_size; /* Determine the image format from the first few bytes of the file. */ magick_size=GetMagicPatternExtent(exception); if (magick_size == 0) return(MagickFalse); image=AcquireImage(image_info,exception); (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImage(image); return(MagickFalse); } if ((IsBlobSeekable(image) == MagickFalse) || (IsBlobExempt(image) != MagickFalse)) { /* Copy image to seekable temporary file. */ *component='\0'; status=ImageToFile(image,component,exception); (void) CloseBlob(image); if (status == MagickFalse) { (void) RelinquishUniqueFileResource(component); image=DestroyImage(image); return(MagickFalse); } SetImageInfoFile(image_info,(FILE *) NULL); (void) CopyMagickString(image->filename,component,MagickPathExtent); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { (void) RelinquishUniqueFileResource(component); image=DestroyImage(image); return(MagickFalse); } (void) CopyMagickString(image_info->filename,component, MagickPathExtent); image_info->temporary=MagickTrue; } magick=(unsigned char *) AcquireQuantumMemory(1,magick_size); if (magick == (unsigned char *) NULL) { (void) CloseBlob(image); image=DestroyImage(image); return(MagickFalse); } (void) memset(magick,0,magick_size); count=ReadBlob(image,magick_size,magick); (void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR); (void) CloseBlob(image); image=DestroyImage(image); /* Check magic cache. */ sans_exception=AcquireExceptionInfo(); magic_info=GetMagicInfo(magick,(size_t) count,sans_exception); magick=(unsigned char *) RelinquishMagickMemory(magick); if ((magic_info != (const MagicInfo *) NULL) && (GetMagicName(magic_info) != (char *) NULL)) { /* Try to use magick_info that was determined earlier by the extension */ if ((magick_info != (const MagickInfo *) NULL) && (GetMagickUseExtension(magick_info) != MagickFalse) && (LocaleCompare(magick_info->magick_module,GetMagicName( magic_info)) == 0)) (void) CopyMagickString(image_info->magick,magick_info->name, MagickPathExtent); else { (void) CopyMagickString(image_info->magick,GetMagicName( magic_info),MagickPathExtent); magick_info=GetMagickInfo(image_info->magick,sans_exception); } if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); return(MagickTrue); } magick_info=GetMagickInfo(image_info->magick,sans_exception); if ((magick_info == (const MagickInfo *) NULL) || (GetMagickEndianSupport(magick_info) == MagickFalse)) image_info->endian=UndefinedEndian; sans_exception=DestroyExceptionInfo(sans_exception); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoBlob() sets the image info blob member. % % The format of the SetImageInfoBlob method is: % % void SetImageInfoBlob(ImageInfo *image_info,const void *blob, % const size_t length) % % A description of each parameter follows: % % o image_info: the image info. % % o blob: the blob. % % o length: the blob length. % */ MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob, const size_t length) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->blob=(void *) blob; image_info->length=length; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o C u s t o m S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoCustomStream() sets the image info custom stream handlers. % % The format of the SetImageInfoCustomStream method is: % % void SetImageInfoCustomStream(ImageInfo *image_info, % CustomStreamInfo *custom_stream) % % A description of each parameter follows: % % o image_info: the image info. % % o custom_stream: your custom stream methods. % */ MagickExport void SetImageInfoCustomStream(ImageInfo *image_info, CustomStreamInfo *custom_stream) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->custom_stream=(CustomStreamInfo *) custom_stream; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e I n f o F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageInfoFile() sets the image info file member. % % The format of the SetImageInfoFile method is: % % void SetImageInfoFile(ImageInfo *image_info,FILE *file) % % A description of each parameter follows: % % o image_info: the image info. % % o file: the file. % */ MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file) { assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); image_info->file=file; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageMask() associates a mask with the image. The mask must be the same % dimensions as the image. % % The format of the SetImageMask method is: % % MagickBooleanType SetImageMask(Image *image,const PixelMask type, % const Image *mask,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o mask: the image mask. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type, const Image *mask,ExceptionInfo *exception) { CacheView *mask_view, *image_view; MagickBooleanType status; ssize_t y; /* Set image mask. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (mask == (const Image *) NULL) { switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels & ~ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels & ~WriteMaskChannel); } default: { image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel); break; } } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels | ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels | WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels | CompositeMaskChannel); break; } } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; mask_view=AcquireVirtualCacheView(mask,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(mask,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity; intensity=0.0; if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows)) intensity=GetPixelIntensity(mask,p); switch (type) { case ReadPixelMask: { SetPixelReadMask(image,ClampToQuantum(intensity),q); break; } case WritePixelMask: { SetPixelWriteMask(image,ClampToQuantum(intensity),q); break; } default: { SetPixelCompositeMask(image,ClampToQuantum(intensity),q); break; } } p+=GetPixelChannels(mask); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e R e g i o n M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageRegionMask() associates a mask with the image as defined by the % specified region. % % The format of the SetImageRegionMask method is: % % MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type, % const RectangleInfo *region,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the mask type, ReadPixelMask or WritePixelMask. % % o geometry: the mask region. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageRegionMask(Image *image, const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; ssize_t y; /* Set image mask as defined by the region. */ assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (region == (const RectangleInfo *) NULL) { switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels & ~ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels & ~WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel); break; } } return(SyncImagePixelCache(image,exception)); } switch (type) { case ReadPixelMask: { image->channels=(ChannelType) (image->channels | ReadMaskChannel); break; } case WritePixelMask: { image->channels=(ChannelType) (image->channels | WriteMaskChannel); break; } default: { image->channels=(ChannelType) (image->channels | CompositeMaskChannel); break; } } if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; image->mask_trait=UpdatePixelTrait; image_view=AcquireAuthenticCacheView(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++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; pixel=QuantumRange; if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) && ((y >= region->y) && (y < (region->y+(ssize_t) region->height)))) pixel=(Quantum) 0; switch (type) { case ReadPixelMask: { SetPixelReadMask(image,pixel,q); break; } case WritePixelMask: { SetPixelWriteMask(image,pixel,q); break; } default: { SetPixelCompositeMask(image,pixel,q); break; } } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image->mask_trait=UndefinedPixelTrait; image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e V i r t u a l P i x e l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageVirtualPixelMethod() sets the "virtual pixels" method for the % image and returns the previous setting. A virtual pixel is any pixel access % that is outside the boundaries of the image cache. % % The format of the SetImageVirtualPixelMethod() method is: % % VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S m u s h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SmushImages() takes all images from the current image pointer to the end % of the image list and smushes them to each other top-to-bottom if the % stack parameter is true, otherwise left-to-right. % % The current gravity setting now effects how the image is justified in the % final image. % % The format of the SmushImages method is: % % Image *SmushImages(const Image *images,const MagickBooleanType stack, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o stack: A value other than 0 stacks the images top-to-bottom. % % o offset: minimum distance in pixels between images. % % o exception: return any errors or warnings in this structure. % */ static ssize_t SmushXGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *left_view, *right_view; const Image *left_image, *right_image; RectangleInfo left_geometry, right_geometry; const Quantum *p; ssize_t i, y; size_t gap; ssize_t x; if (images->previous == (Image *) NULL) return(0); right_image=images; SetGeometry(smush_image,&right_geometry); GravityAdjustGeometry(right_image->columns,right_image->rows, right_image->gravity,&right_geometry); left_image=images->previous; SetGeometry(smush_image,&left_geometry); GravityAdjustGeometry(left_image->columns,left_image->rows, left_image->gravity,&left_geometry); gap=right_image->columns; left_view=AcquireVirtualCacheView(left_image,exception); right_view=AcquireVirtualCacheView(right_image,exception); for (y=0; y < (ssize_t) smush_image->rows; y++) { for (x=(ssize_t) left_image->columns-1; x > 0; x--) { p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(left_image,p) != TransparentAlpha) || ((left_image->columns-x-1) >= gap)) break; } i=(ssize_t) left_image->columns-x-1; for (x=0; x < (ssize_t) right_image->columns; x++) { p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(right_image,p) != TransparentAlpha) || ((x+i) >= (ssize_t) gap)) break; } if ((x+i) < (ssize_t) gap) gap=(size_t) (x+i); } right_view=DestroyCacheView(right_view); left_view=DestroyCacheView(left_view); if (y < (ssize_t) smush_image->rows) return(offset); return((ssize_t) gap-offset); } static ssize_t SmushYGap(const Image *smush_image,const Image *images, const ssize_t offset,ExceptionInfo *exception) { CacheView *bottom_view, *top_view; const Image *bottom_image, *top_image; RectangleInfo bottom_geometry, top_geometry; const Quantum *p; ssize_t i, x; size_t gap; ssize_t y; if (images->previous == (Image *) NULL) return(0); bottom_image=images; SetGeometry(smush_image,&bottom_geometry); GravityAdjustGeometry(bottom_image->columns,bottom_image->rows, bottom_image->gravity,&bottom_geometry); top_image=images->previous; SetGeometry(smush_image,&top_geometry); GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity, &top_geometry); gap=bottom_image->rows; top_view=AcquireVirtualCacheView(top_image,exception); bottom_view=AcquireVirtualCacheView(bottom_image,exception); for (x=0; x < (ssize_t) smush_image->columns; x++) { for (y=(ssize_t) top_image->rows-1; y > 0; y--) { p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(top_image,p) != TransparentAlpha) || ((top_image->rows-y-1) >= gap)) break; } i=(ssize_t) top_image->rows-y-1; for (y=0; y < (ssize_t) bottom_image->rows; y++) { p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1, exception); if ((p == (const Quantum *) NULL) || (GetPixelAlpha(bottom_image,p) != TransparentAlpha) || ((y+i) >= (ssize_t) gap)) break; } if ((y+i) < (ssize_t) gap) gap=(size_t) (y+i); } bottom_view=DestroyCacheView(bottom_view); top_view=DestroyCacheView(top_view); if (x < (ssize_t) smush_image->columns) return(offset); return((ssize_t) gap-offset); } MagickExport Image *SmushImages(const Image *images, const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception) { #define SmushImageTag "Smush/Image" const Image *image; Image *smush_image; MagickBooleanType proceed, status; MagickOffsetType n; PixelTrait alpha_trait; RectangleInfo geometry; const Image *next; size_t height, number_images, width; ssize_t x_offset, y_offset; /* Compute maximum area of smushed area. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=images; alpha_trait=image->alpha_trait; number_images=1; width=image->columns; height=image->rows; next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (next->alpha_trait != UndefinedPixelTrait) alpha_trait=BlendPixelTrait; number_images++; if (stack != MagickFalse) { if (next->columns > width) width=next->columns; height+=next->rows; if (next->previous != (Image *) NULL) height+=offset; continue; } width+=next->columns; if (next->previous != (Image *) NULL) width+=offset; if (next->rows > height) height=next->rows; } /* Smush images. */ smush_image=CloneImage(image,width,height,MagickTrue,exception); if (smush_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse) { smush_image=DestroyImage(smush_image); return((Image *) NULL); } smush_image->alpha_trait=alpha_trait; (void) SetImageBackgroundColor(smush_image,exception); status=MagickTrue; x_offset=0; y_offset=0; for (n=0; n < (MagickOffsetType) number_images; n++) { SetGeometry(smush_image,&geometry); GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry); if (stack != MagickFalse) { x_offset-=geometry.x; y_offset-=SmushYGap(smush_image,image,offset,exception); } else { x_offset-=SmushXGap(smush_image,image,offset,exception); y_offset-=geometry.y; } status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset, y_offset,exception); proceed=SetImageProgress(image,SmushImageTag,n,number_images); if (proceed == MagickFalse) break; if (stack == MagickFalse) { x_offset+=(ssize_t) image->columns; y_offset=0; } else { x_offset=0; y_offset+=(ssize_t) image->rows; } image=GetNextImageInList(image); } if (stack == MagickFalse) smush_image->columns=(size_t) x_offset; else smush_image->rows=(size_t) y_offset; if (status == MagickFalse) smush_image=DestroyImage(smush_image); return(smush_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StripImage() strips an image of all profiles and comments. % % The format of the StripImage method is: % % MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType StripImage(Image *image,ExceptionInfo *exception) { MagickBooleanType status; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); (void) exception; DestroyImageProfiles(image); (void) DeleteImageProperty(image,"comment"); (void) DeleteImageProperty(image,"date:create"); (void) DeleteImageProperty(image,"date:modify"); status=SetImageArtifact(image,"png:exclude-chunk", "bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImage() initializes the red, green, and blue intensities of each pixel % as defined by the colormap index. % % The format of the SyncImage method is: % % MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PushColormapIndex(Image *image,const Quantum index, MagickBooleanType *range_exception) { if ((size_t) index < image->colors) return(index); *range_exception=MagickTrue; return((Quantum) 0); } MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType range_exception, status, taint; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->ping != MagickFalse) return(MagickTrue); if (image->storage_class != PseudoClass) return(MagickFalse); assert(image->colormap != (PixelInfo *) NULL); range_exception=MagickFalse; status=MagickTrue; taint=image->taint; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(range_exception,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum index; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->taint=taint; if ((image->ping == MagickFalse) && (range_exception != MagickFalse)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e S e t t i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageSettings() syncs any image_info global options into per-image % attributes. % % Note: in IMv6 free form 'options' were always mapped into 'artifacts', so % that operations and coders can find such settings. In IMv7 if a desired % per-image artifact is not set, then it will directly look for a global % option as a fallback, as such this copy is no longer needed, only the % link set up. % % The format of the SyncImageSettings method is: % % MagickBooleanType SyncImageSettings(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % MagickBooleanType SyncImagesSettings(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. % */ MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info, Image *images,ExceptionInfo *exception) { Image *image; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) (void) SyncImageSettings(image_info,image,exception); (void) DeleteImageOption(image_info,"page"); return(MagickTrue); } MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *option; GeometryInfo geometry_info; MagickStatusType flags; ResolutionType units; /* Sync image options. */ 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); option=GetImageOption(image_info,"background"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->background_color, exception); option=GetImageOption(image_info,"black-point-compensation"); if (option != (const char *) NULL) image->black_point_compensation=(MagickBooleanType) ParseCommandOption( MagickBooleanOptions,MagickFalse,option); option=GetImageOption(image_info,"blue-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x; } option=GetImageOption(image_info,"bordercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->border_color, exception); /* FUTURE: do not sync compose to per-image compose setting here */ option=GetImageOption(image_info,"compose"); if (option != (const char *) NULL) image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,option); /* -- */ option=GetImageOption(image_info,"compress"); if (option != (const char *) NULL) image->compression=(CompressionType) ParseCommandOption( MagickCompressOptions,MagickFalse,option); option=GetImageOption(image_info,"debug"); if (option != (const char *) NULL) image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } option=GetImageOption(image_info,"depth"); if (option != (const char *) NULL) image->depth=StringToUnsignedLong(option); option=GetImageOption(image_info,"endian"); if (option != (const char *) NULL) image->endian=(EndianType) ParseCommandOption(MagickEndianOptions, MagickFalse,option); option=GetImageOption(image_info,"filter"); if (option != (const char *) NULL) image->filter=(FilterType) ParseCommandOption(MagickFilterOptions, MagickFalse,option); option=GetImageOption(image_info,"fuzz"); if (option != (const char *) NULL) image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0); option=GetImageOption(image_info,"gravity"); if (option != (const char *) NULL) image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(image_info,"green-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y=image->chromaticity.green_primary.x; } option=GetImageOption(image_info,"intent"); if (option != (const char *) NULL) image->rendering_intent=(RenderingIntent) ParseCommandOption( MagickIntentOptions,MagickFalse,option); option=GetImageOption(image_info,"intensity"); if (option != (const char *) NULL) image->intensity=(PixelIntensityMethod) ParseCommandOption( MagickPixelIntensityOptions,MagickFalse,option); option=GetImageOption(image_info,"interlace"); if (option != (const char *) NULL) image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions, MagickFalse,option); option=GetImageOption(image_info,"interpolate"); if (option != (const char *) NULL) image->interpolate=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,option); option=GetImageOption(image_info,"loop"); if (option != (const char *) NULL) image->iterations=StringToUnsignedLong(option); option=GetImageOption(image_info,"mattecolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->matte_color, exception); option=GetImageOption(image_info,"orient"); if (option != (const char *) NULL) image->orientation=(OrientationType) ParseCommandOption( MagickOrientationOptions,MagickFalse,option); option=GetImageOption(image_info,"page"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) image->quality=StringToUnsignedLong(option); option=GetImageOption(image_info,"red-primary"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y=image->chromaticity.red_primary.x; } if (image_info->quality != UndefinedCompressionQuality) image->quality=image_info->quality; option=GetImageOption(image_info,"scene"); if (option != (const char *) NULL) image->scene=StringToUnsignedLong(option); option=GetImageOption(image_info,"taint"); if (option != (const char *) NULL) image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions, MagickFalse,option); option=GetImageOption(image_info,"tile-offset"); if (option != (const char *) NULL) { char *geometry; geometry=GetPageGeometry(option); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } option=GetImageOption(image_info,"transparent-color"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&image->transparent_color, exception); option=GetImageOption(image_info,"type"); if (option != (const char *) NULL) image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse, option); option=GetImageOption(image_info,"units"); units=image_info->units; if (option != (const char *) NULL) units=(ResolutionType) ParseCommandOption(MagickResolutionOptions, MagickFalse,option); if (units != UndefinedResolution) { if (image->units != units) switch (image->units) { case PixelsPerInchResolution: { if (units == PixelsPerCentimeterResolution) { image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case PixelsPerCentimeterResolution: { if (units == PixelsPerInchResolution) { image->resolution.x=(double) ((size_t) (100.0*2.54* image->resolution.x+0.5))/100.0; image->resolution.y=(double) ((size_t) (100.0*2.54* image->resolution.y+0.5))/100.0; } break; } default: break; } image->units=units; option=GetImageOption(image_info,"density"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } } option=GetImageOption(image_info,"virtual-pixel"); if (option != (const char *) NULL) (void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option), exception); option=GetImageOption(image_info,"white-point"); if (option != (const char *) NULL) { flags=ParseGeometry(option,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y=image->chromaticity.white_point.x; } /* Pointer to allow the lookup of pre-image artifact will fallback to a global option setting/define. This saves a lot of duplication of global options into per-image artifacts, while ensuring only specifically set per-image artifacts are preserved when parenthesis ends. */ if (image->image_info != (ImageInfo *) NULL) image->image_info=DestroyImageInfo(image->image_info); image->image_info=CloneImageInfo(image_info); return(MagickTrue); }
GB_binop__ge_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__ge_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__ge_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__ge_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__ge_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ge_uint64) // A*D function (colscale): GB (_AxD__ge_uint64) // D*A function (rowscale): GB (_DxB__ge_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__ge_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__ge_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ge_uint64) // C=scalar+B GB (_bind1st__ge_uint64) // C=scalar+B' GB (_bind1st_tran__ge_uint64) // C=A+scalar GB (_bind2nd__ge_uint64) // C=A'+scalar GB (_bind2nd_tran__ge_uint64) // C type: bool // 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 \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ 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) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x >= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_GE || GxB_NO_UINT64 || GxB_NO_GE_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__ge_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__ge_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 #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ge_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__ge_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 bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__ge_uint64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ge_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__ge_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__ge_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__ge_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__ge_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__ge_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 bool *Cx = (bool *) 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__ge_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 ; bool *Cx = (bool *) 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__ge_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__ge_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
fista.h
/* Software SPAMS v2.1 - Copyright 2009-2011 Julien Mairal * * This file is part of SPAMS. * * SPAMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SPAMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SPAMS. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FISTA_H #define FISTA_H #include <linalg.h> #include <project.h> namespace FISTA { enum loss_t { SQUARE, SQUARE_MISSING, LOG, LOGWEIGHT, MULTILOG, CUR, HINGE, INCORRECT_LOSS}; enum regul_t { L0, L1, RIDGE, L2, LINF, ELASTICNET, FUSEDLASSO, GROUPLASSO_L2, GROUPLASSO_LINF, GROUPLASSO_L2_L1, GROUPLASSO_LINF_L1, L1L2, L1LINF, L1L2_L1, L1LINF_L1, TREE_L0, TREE_L2, TREE_LINF, GRAPH, GRAPH_RIDGE, GRAPH_L2, TREEMULT, GRAPHMULT, L1LINFCR, NONE, TRACE_NORM, TRACE_NORM_VEC, RANK, RANK_VEC, INCORRECT_REG, GRAPH_PATH_L0, GRAPH_PATH_CONV}; regul_t regul_from_string(char* regul) { if (strcmp(regul,"l0")==0) return L0; if (strcmp(regul,"l1")==0) return L1; if (strcmp(regul,"l2")==0) return RIDGE; if (strcmp(regul,"linf")==0) return LINF; if (strcmp(regul,"l2-not-squared")==0) return L2; if (strcmp(regul,"elastic-net")==0) return ELASTICNET; if (strcmp(regul,"fused-lasso")==0) return FUSEDLASSO; if (strcmp(regul,"group-lasso-l2")==0) return GROUPLASSO_L2; if (strcmp(regul,"group-lasso-linf")==0) return GROUPLASSO_LINF; if (strcmp(regul,"sparse-group-lasso-l2")==0) return GROUPLASSO_L2_L1; if (strcmp(regul,"sparse-group-lasso-linf")==0) return GROUPLASSO_LINF_L1; if (strcmp(regul,"l1l2")==0) return L1L2; if (strcmp(regul,"l1linf")==0) return L1LINF; if (strcmp(regul,"l1l2+l1")==0) return L1L2_L1; if (strcmp(regul,"l1linf+l1")==0) return L1LINF_L1; if (strcmp(regul,"tree-l0")==0) return TREE_L0; if (strcmp(regul,"tree-l2")==0) return TREE_L2; if (strcmp(regul,"tree-linf")==0) return TREE_LINF; if (strcmp(regul,"graph")==0) return GRAPH; if (strcmp(regul,"graph-ridge")==0) return GRAPH_RIDGE; if (strcmp(regul,"graph-l2")==0) return GRAPH_L2; if (strcmp(regul,"multi-task-tree")==0) return TREEMULT; if (strcmp(regul,"multi-task-graph")==0) return GRAPHMULT; if (strcmp(regul,"l1linf-row-column")==0) return L1LINFCR; if (strcmp(regul,"trace-norm")==0) return TRACE_NORM; if (strcmp(regul,"trace-norm-vec")==0) return TRACE_NORM_VEC; if (strcmp(regul,"rank")==0) return RANK; if (strcmp(regul,"rank-vec")==0) return RANK_VEC; if (strcmp(regul,"graph-path-l0")==0) return GRAPH_PATH_L0; if (strcmp(regul,"graph-path-conv")==0) return GRAPH_PATH_CONV; if (strcmp(regul,"none")==0) return NONE; return INCORRECT_REG; } loss_t loss_from_string(char* loss) { if (strcmp(loss,"square")==0) return SQUARE; if (strcmp(loss,"square-missing")==0) return SQUARE_MISSING; if (strcmp(loss,"logistic")==0) return LOG; if (strcmp(loss,"weighted-logistic")==0) return LOGWEIGHT; if (strcmp(loss,"hinge")==0) return HINGE; if (strcmp(loss,"multi-logistic")==0) return MULTILOG; if (strcmp(loss,"cur")==0) return CUR; return INCORRECT_LOSS; } void print_loss(const loss_t& loss) { switch (loss) { case SQUARE: cout << "Square loss" << endl; break; case SQUARE_MISSING: cout << "Square loss with missing data" << endl; break; case LOG: cout << "Logistic loss" << endl; break; case LOGWEIGHT: cout << "Weighted Logistic loss" << endl; break; case HINGE: cout << "Hinge loss" << endl; break; case MULTILOG: cout << "Multiclass logistic Loss" << endl; break; case CUR: cout << "CUR decomposition" << endl; break; default: cerr << "Not implemented" << endl; } }; bool loss_for_matrices(const loss_t& loss) { return loss==MULTILOG || loss==CUR; } void print_regul(const regul_t& regul) { switch (regul) { case L0: cout << "L0 regularization" << endl; break; case L1: cout << "L1 regularization" << endl; break; case RIDGE: cout << "L2-squared regularization" << endl; break; case L2: cout << "L2-not-squared regularization" << endl; break; case LINF: cout << "Linf regularization" << endl; break; case ELASTICNET: cout << "Elastic-net regularization" << endl; break; case FUSEDLASSO: cout << "Fused Lasso or total variation regularization" << endl; break; case GROUPLASSO_L2: cout << "Group Lasso L2" << endl; break; case GROUPLASSO_LINF: cout << "Group Lasso LINF" << endl; break; case GROUPLASSO_L2_L1: cout << "Group Lasso L2 + L1" << endl; break; case GROUPLASSO_LINF_L1: cout << "Group Lasso LINF + L1" << endl; break; case L1L2: cout << "L1L2 regularization" << endl; break; case L1LINF: cout << "L1LINF regularization" << endl; break; case TRACE_NORM: cout << "Trace Norm regularization" << endl; break; case TRACE_NORM_VEC: cout << "Trace Norm regularization for vectors" << endl; break; case RANK: cout << "Rank regularization" << endl; break; case RANK_VEC: cout << "Rank regularization for vectors" << endl; break; case L1L2_L1: cout << "L1L2 regularization + L1" << endl; break; case L1LINF_L1: cout << "L1LINF regularization + L1" << endl; break; case TREE_L0: cout << "Tree-L0 regularization" << endl; break; case TREE_L2: cout << "Tree-L2 regularization" << endl; break; case TREE_LINF: cout << "Tree-Linf regularization" << endl; break; case GRAPH: cout << "Graph regularization" << endl; break; case GRAPH_RIDGE: cout << "Graph+ridge regularization" << endl; break; case GRAPH_L2: cout << "Graph regularization with l2" << endl; break; case TREEMULT: cout << "multitask tree regularization" << endl; break; case GRAPHMULT: cout << "multitask graph regularization" << endl; break; case L1LINFCR: cout << "L1LINF regularization on rows and columns" << endl; break; case GRAPH_PATH_L0: cout << "Graph path non-convex regularization" << endl; break; case GRAPH_PATH_CONV: cout << "Graph path convex regularization" << endl; break; case NONE: cout << "No regularization" << endl; break; default: cerr << "Not implemented" << endl; } }; bool regul_for_matrices(const regul_t& regul) { return regul==L1L2 || regul==L1LINF || regul==L1L2_L1 || regul==L1LINF_L1 || regul==TREEMULT || regul==GRAPHMULT || regul==L1LINFCR || regul==TRACE_NORM || regul==RANK; } template <typename T> struct ParamFISTA { ParamFISTA() { num_threads=1; max_it=100; L0=0.1; gamma=1.5; tol=1e-10; it0=10; max_iter_backtracking=1000; loss=SQUARE; compute_gram=false; admm=false; lin_admm=false; intercept=false; regul=RIDGE; resetflow=false; delta=0; lambda2=0; lambda3=0; verbose=false; pos=false; clever=true; a=1.0; b=0.0; c=1.0; log=false; logName=NULL; ista=false; subgrad=false; length_names=30; name_regul=new char[length_names]; name_loss=new char[length_names]; is_inner_weights=false; inner_weights=NULL; eval=false; size_group=1; sqrt_step=true; transpose=false; fixed_step=false; copied=false; groups=NULL; ngroups=0; } ~ParamFISTA() { if (!copied) { delete[](name_regul); delete[](name_loss); } }; int num_threads; int max_it; T L0; T gamma; int length_names; T lambda; T delta; T lambda2; T lambda3; T a; T b; T c; T tol; int it0; int max_iter_backtracking; loss_t loss; bool compute_gram; bool lin_admm; bool admm; bool intercept; bool resetflow; regul_t regul; char* name_regul; char* name_loss; bool verbose; bool pos; bool clever; bool log; bool ista; bool copied; bool subgrad; char* logName; bool is_inner_weights; T* inner_weights; bool eval; int size_group; bool sqrt_step; bool transpose; bool fixed_step; int* groups; int ngroups; }; template <typename T> struct ParamReg { ParamReg() { size_group=1; lambda2d1 = 0; lambda3d1 = 0; pos=false; intercept=false; num_cols=1; graph_st=NULL; tree_st=NULL; graph_path_st=NULL; resetflow=false; clever=false; linf=true; transpose=false; ngroups=0; groups=NULL;}; T lambda2d1; T lambda3d1; int size_group; bool pos; bool intercept; int num_cols; GraphPathStruct<T>* graph_path_st; GraphStruct<T>* graph_st; TreeStruct<T>* tree_st; bool resetflow; bool clever; bool linf; bool transpose; int ngroups; int* groups; }; template <typename T> bool param_for_admm(const ParamFISTA<T>& param) { return (param.admm) && (param.loss==SQUARE || param.loss == HINGE) && (param.regul==GRAPH_L2 || param.regul==GRAPH || param.regul == NONE); }; template <typename T, typename F = Matrix<T>, typename D = Vector<T> , typename E = Vector<T> > class SplittingFunction { public: SplittingFunction() { }; virtual ~SplittingFunction() { }; virtual void init(const E& y) { }; virtual T eval(const D& input) const = 0; virtual void reset() { }; virtual T eval_split(const F& input) const = 0; virtual T eval_weighted(const D& input,const F& input_struct, const T* weights) const { return this->eval(input);}; virtual int num_components() const = 0; virtual void prox_split(F& splitted_w, const T lambda) const = 0; virtual void init_split_variables(F& splitted_w) const = 0; virtual void init_prim_var(E& prim_var) const { }; virtual void prox_prim_var(E& out,const E& dual_var, const E& prim_var, const T gamma) const { }; virtual void compute_new_prim(E& prim, const E& prim_var, const E& dual_var, const T gamma, const T delta) const { }; virtual void add_mult_design_matrix(const E& prim, E& out, const T fact) const { }; private: explicit SplittingFunction<T,F,D,E>(const SplittingFunction<T,F,D,E>& loss); SplittingFunction<T,F,D,E>& operator=(const SplittingFunction<T,F,D,E>& loss); }; template <typename T, typename D = Vector<T> , typename E = Vector<T> > class Loss { public: Loss() { }; virtual ~Loss() { }; virtual void init(const E& input) = 0; virtual T eval(const D& input) const = 0; virtual void grad(const D& input, D& output) const = 0; virtual inline bool test_backtracking(const D& y, const D& grad, const D& prox, const T L) const { D tmp; tmp.copy(prox); tmp.sub(y); return (this->eval(prox) <= this->eval(y) + grad.dot(tmp) + 0.5*L*tmp.nrm2sq()); }; virtual T fenchel(const D& input) const = 0; virtual bool is_fenchel() const { return true; }; virtual void var_fenchel(const D& x, D& grad1, D& grad2, const bool intercept = false) const = 0; private: explicit Loss<T,D,E>(const Loss<T,D,E>& dict); Loss<T,D,E>& operator=(const Loss<T,D,E>& dict); }; template <typename T> class SqLossMissing : public Loss<T> { public: SqLossMissing(const AbstractMatrixB<T>& D) : _D(&D) { }; virtual ~SqLossMissing() { }; inline void init(const Vector<T>& x) { _x.copy(x); _missingvalues.clear(); for (int i = 0; i<_x.n(); ++i) { if (isnan(_x[i])) { _x[i]=0; _missingvalues.push_back(i); } } }; inline T eval(const Vector<T>& alpha) const { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _D->mult(spalpha,residual,T(-1.0),T(1.0)); for (ListIterator<int> it = _missingvalues.begin(); it != _missingvalues.end(); ++it) residual[*it]=0; return 0.5*residual.nrm2sq(); } inline void grad(const Vector<T>& alpha, Vector<T>& grad) const { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _D->mult(spalpha,residual,T(-1.0),T(1.0)); for (ListIterator<int> it = _missingvalues.begin(); it != _missingvalues.end(); ++it) residual[*it]=0; _D->multTrans(residual,grad,T(-1.0),T(0.0)); }; virtual T fenchel(const Vector<T>& input) const { return 0.5*input.nrm2sq()+input.dot(_x); }; virtual void var_fenchel(const Vector<T>& x, Vector<T>& grad1, Vector<T>& grad2, const bool intercept) const { grad1.copy(_x); SpVector<T> spalpha(x.n()); x.toSparse(spalpha); _D->mult(spalpha,grad1,T(1.0),T(-1.0)); for (ListIterator<int> it = _missingvalues.begin(); it != _missingvalues.end(); ++it) grad1[*it]=0; if (intercept) grad1.whiten(1); // remove the mean of grad1 _D->multTrans(grad1,grad2,T(1.0),T(0.0)); }; private: explicit SqLossMissing<T>(const SqLossMissing<T>& dict); SqLossMissing<T>& operator=(const SqLossMissing<T>& dict); const AbstractMatrixB<T>* _D; Vector<T> _x; List<int> _missingvalues; }; template <typename T> class SqLoss : public Loss<T>, public SplittingFunction<T> { public: SqLoss(const AbstractMatrixB<T>& D) : _D(&D) { _compute_gram = false; }; SqLoss(const AbstractMatrixB<T>& D, const Matrix<T>& G) : _D(&D), _G(&G) { _compute_gram = true; }; virtual ~SqLoss() { }; inline void init(const Vector<T>& x) { _x.copy(x); if (_compute_gram) { _D->multTrans(x,_DtX); } }; inline T eval(const Vector<T>& alpha) const { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); if (spalpha.L() < alpha.n()/2) { _D->mult(spalpha,residual,T(-1.0),T(1.0)); } else { _D->mult(alpha,residual,T(-1.0),T(1.0)); } return 0.5*residual.nrm2sq(); } inline void grad(const Vector<T>& alpha, Vector<T>& grad) const { if (_compute_gram) { grad.copy(_DtX); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _G->mult(spalpha,grad,T(1.0),-T(1.0)); } else { Vector<T> residual; residual.copy(_x); SpVector<T> spalpha(alpha.n()); alpha.toSparse(spalpha); _D->mult(spalpha,residual,T(-1.0),T(1.0)); _D->multTrans(residual,grad,T(-1.0),T(0.0)); } }; virtual inline bool test_backtracking(const Vector<T>& y, const Vector<T>& grad, const Vector<T>& prox, const T L) const { Vector<T> tmp; tmp.copy(y); tmp.sub(prox); SpVector<T> sptmp(tmp.n()); tmp.toSparse(sptmp); if (_compute_gram) { return (_G->quad(sptmp) <= L*sptmp.nrm2sq()); } else { Vector<T> tmp2(_D->m()); _D->mult(sptmp,tmp2); return (tmp2.nrm2sq() <= L*sptmp.nrm2sq()); } }; virtual T fenchel(const Vector<T>& input) const { return 0.5*input.nrm2sq()+input.dot(_x); }; virtual void var_fenchel(const Vector<T>& x, Vector<T>& grad1, Vector<T>& grad2, const bool intercept) const { grad1.copy(_x); SpVector<T> spalpha(x.n()); x.toSparse(spalpha); _D->mult(spalpha,grad1,T(1.0),T(-1.0)); if (intercept) grad1.whiten(1); // remove the mean of grad1 _D->multTrans(grad1,grad2,T(1.0),T(0.0)); }; inline int num_components() const { return _D->m();}; inline void prox_split(Matrix<T>& splitted_w, const T lambda) const { const int n = this->num_components(); Vector<T> row(_D->n()); Vector<T> wi; for (int i = 0; i<n; ++i) { _D->copyRow(i,row); splitted_w.refCol(i,wi); const T xtw=row.dot(wi); const T xtx=row.dot(row); wi.add(row,-lambda*(xtw-_x[i])/(T(1.0)+lambda*xtx)); } }; inline T eval_split(const Matrix<T>& input) const { const int n = this->num_components(); Vector<T> row(_D->n()); Vector<T> wi; T sum = 0; for (int i = 0; i<n; ++i) { _D->copyRow(i,row); input.refCol(i,wi); const T xtw=row.dot(wi); sum += 0.5*(_x[i]-xtw)*(_x[i]-xtw); } return sum; }; inline void init_split_variables(Matrix<T>& splitted_w) const { splitted_w.resize(_D->n(),_D->m()); splitted_w.setZeros(); }; inline void init_prim_var(Vector<T>& prim_var) const { prim_var.resize(_D->m()); prim_var.setZeros(); } virtual void prox_prim_var(Vector<T>& out,const Vector<T>& dual_var, const Vector<T>& prim_var, const T c) const { const T gamma=T(1.0)/c; out.copy(dual_var); out.scal(-gamma); _D->mult(prim_var,out,T(1.0),T(1.0)); out.add(_x,gamma); out.scal(T(1.0)/(T(1.0)+gamma)); }; inline void compute_new_prim(Vector<T>& prim, const Vector<T>& prim_var, const Vector<T>& dual_var, const T gamma, const T delta) const { Vector<T> tmp; _D->mult(prim,tmp); tmp.scal(-gamma); tmp.add(prim_var); tmp.add(dual_var,gamma); _D->multTrans(tmp,prim,T(1.0),delta); }; inline void add_mult_design_matrix(const Vector<T>& prim, Vector<T>& out, const T fact) const { _D->mult(prim,out,fact,T(1.0)); }; private: explicit SqLoss<T>(const SqLoss<T>& dict); SqLoss<T>& operator=(const SqLoss<T>& dict); const AbstractMatrixB<T>* _D; Vector<T> _x; bool _compute_gram; const Matrix<T>* _G; Vector<T> _DtX; }; template <typename T> class HingeLoss : public SplittingFunction<T > { public: HingeLoss(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~HingeLoss() { }; inline void init(const Vector<T>& y) { _y.copy(y); }; inline T eval(const Vector<T>& w) const { Vector<T> tmp(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,tmp); tmp.mult(_y,tmp); tmp.neg(); tmp.add(T(1.0)); tmp.thrsPos(); return tmp.sum()/tmp.n(); }; virtual T eval_split(const Matrix<T>& input) const { Vector<T> row(_X->n()); Vector<T> wi; T sum = 0; for (int i = 0; i<_X->n(); ++i) { _X->copyRow(i,row); input.refCol(i,wi); sum += MAX(0,T(1.0)-_y[i]*row.dot(wi)); } return sum/_X->m(); }; virtual int num_components() const { return _X->m(); }; inline void init_split_variables(Matrix<T>& splitted_w) const { splitted_w.resize(_X->n(),_X->m()); splitted_w.setZeros(); }; inline void init_prim_var(Vector<T>& prim_var) const { prim_var.resize(_X->m()); prim_var.setZeros(); } inline void prox_prim_var(Vector<T>& out,const Vector<T>& dual_var, const Vector<T>& prim_var, const T lambda, const T c) const { const T gamma=T(1.0)/c; out.copy(dual_var); out.scal(-gamma); _X->mult(prim_var,out,T(1.0),T(1.0)); const T thrs=T(1.0)-gamma; for (int i = 0; i<out.n(); ++i) { const T y = _y[i]*out[i]; if (y < thrs) { out[i]+=_y[i]*gamma; } else if (y < T(1.0)) { out[i]=_y[i]; } } } inline void compute_new_prim(Vector<T>& prim, const Vector<T>& prim_var, const Vector<T>& dual_var, const T gamma, const T delta) const { Vector<T> tmp; _X->mult(prim,tmp); tmp.scal(-gamma); tmp.add(prim_var); tmp.add(dual_var,gamma); _X->multTrans(tmp,prim,T(1.0),delta); }; inline void add_mult_design_matrix(const Vector<T>& prim, Vector<T>& out, const T fact) const { _X->mult(prim,out,fact,T(1.0)); }; inline void prox_split(Matrix<T>& splitted_w, const T lambda) const { const int n = this->num_components(); Vector<T> row(_X->n()); Vector<T> wi; for (int i = 0; i<n; ++i) { _X->copyRow(i,row); splitted_w.refCol(i,wi); const T xtw=row.dot(wi); const T xtx=row.dot(row); const T diff=1-_y[i]*xtw; if (diff > lambda*xtx) { wi.add(row,lambda*_y[i]); } else if (diff > 0) { wi.add(row,_y[i]*diff/xtx); } } }; private: explicit HingeLoss<T>(const HingeLoss<T>& dict); HingeLoss<T>& operator=(const HingeLoss<T>& dict); const AbstractMatrixB<T>* _X; Vector<T> _y; }; template <typename T, bool weighted = false> class LogLoss : public Loss<T> { public: LogLoss(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~LogLoss() { }; inline void init(const Vector<T>& y) { _y.copy(y); if (weighted) { int countpos=0; for (int i = 0; i<y.n(); ++i) if (y[i]>0) countpos++; _weightpos=T(1.0)/countpos; _weightneg=T(1.0)/MAX(1e-3,(y.n()-countpos)); } }; inline T eval(const Vector<T>& w) const { Vector<T> tmp(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,tmp); tmp.mult(_y,tmp); tmp.neg(); tmp.logexp(); if (weighted) { T sum=0; for (int i = 0; i<tmp.n(); ++i) sum+= _y[i]>0 ? _weightpos*tmp[i] : _weightneg*tmp[i]; return sum; } else { return tmp.sum()/tmp.n(); } }; inline void grad(const Vector<T>& w, Vector<T>& grad) const { Vector<T> tmp(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,tmp); tmp.mult(_y,tmp); tmp.exp(); tmp.add(T(1.0)); tmp.inv(); tmp.mult(_y,tmp); tmp.neg(); if (weighted) { for (int i = 0; i<tmp.n(); ++i) tmp[i] *= _y[i] > 0 ? _weightpos : _weightneg; _X->multTrans(tmp,grad); } else { _X->multTrans(tmp,grad); grad.scal(T(1.0)/_X->m()); } }; virtual bool is_fenchel() const { return !weighted; }; virtual T fenchel(const Vector<T>& input) const { T sum = 0; if (weighted) { for (int i = 0; i<input.n(); ++i) { T prod = _y[i]>0 ? input[i]/_weightpos : -input[i]/_weightneg; sum += _y[i] >0 ? _weightpos*(xlogx(1.0+prod)+xlogx(-prod)) : _weightneg*(xlogx(1.0+prod)+xlogx(-prod)); } return sum; } else { for (int i = 0; i<input.n(); ++i) { T prod = _y[i]*input[i]*_X->m(); sum += xlogx(1.0+prod)+xlogx(-prod); } return sum/_X->m(); } }; virtual void var_fenchel(const Vector<T>& w, Vector<T>& grad1, Vector<T>& grad2, const bool intercept) const { grad1.resize(_X->m()); SpVector<T> spw(w.n()); w.toSparse(spw); _X->mult(spw,grad1); grad1.mult(_y,grad1); grad1.exp(); grad1.add(T(1.0)); grad1.inv(); grad1.mult(_y,grad1); grad1.neg(); // -gradient (no normalization) if (intercept) grad1.project_sft_binary(_y); grad1.scal(T(1.0)/_X->m()); _X->multTrans(grad1,grad2); }; private: explicit LogLoss<T,weighted>(const LogLoss<T,weighted>& dict); LogLoss<T,weighted>& operator=(const LogLoss<T,weighted>& dict); const AbstractMatrixB<T>* _X; Vector<T> _y; T _weightpos; T _weightneg; }; template <typename T> class MultiLogLoss : public Loss<T, Matrix<T> > { public: MultiLogLoss(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~MultiLogLoss() { }; inline void init(const Vector<T>& y) { _y.resize(y.n()); for (int i = 0; i<y.n(); ++i) _y[i] = static_cast<int>(y[i]); }; inline T eval(const Matrix<T>& W) const { Matrix<T> tmp; _X->multSwitch(W,tmp,true,true); //W.mult(*_X,tmp,true,true); Vector<T> col; T sum=0; for (int i = 0; i<tmp.n(); ++i) { tmp.refCol(i,col); sum+=col.softmax(_y[i]); } return sum/tmp.n(); }; inline void grad(const Matrix<T>& W, Matrix<T>& grad) const { Matrix<T> tmp; _X->multSwitch(W,tmp,true,true); //W.mult(*_X,tmp,true,true); Vector<T> col; grad.resize(W.m(),W.n()); for (int i = 0; i<tmp.n(); ++i) { tmp.refCol(i,col); col.add(-col[_y[i]]); bool overweight=false; for (int j = 0; j<col.n(); ++j) if (col[j] > 1e2) overweight=true; if (overweight) { const int ind =col.fmax(); col.setZeros(); col[ind]=1; } else { col.exp(); col.scal(T(1.0)/col.sum()); col.scal(T(1.0)/col.sum()); } col[_y[i]] = col[_y[i]]-T(1.0); } _X->mult(tmp,grad,true,true); grad.scal(T(1.0)/_X->m()); }; virtual T fenchel(const Matrix<T>& input) const { T sum = 0; Vector<T> col; for (int i = 0; i<input.n(); ++i) { const int clas = _y[i]; input.refCol(i,col); for (int j = 0; j<input.m(); ++j) { if (j == clas) { sum += xlogx(_X->m()*input[i*input.m()+j]+1.0); } else { sum += xlogx(_X->m()*input[i*input.m()+j]); } } } return sum/_X->m(); }; virtual void var_fenchel(const Matrix<T>& W, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { _X->multSwitch(W,grad1,true,true); //W.mult(*_X,grad1,true,true); Vector<T> col; for (int i = 0; i<grad1.n(); ++i) { grad1.refCol(i,col); col.add(-col[_y[i]]); bool overweight=false; for (int j = 0; j<col.n(); ++j) if (col[j] > 1e2) overweight=true; if (overweight) { const int ind =col.fmax(); col.setZeros(); col[ind]=1; } else { col.exp(); col.scal(T(1.0)/col.sum()); col.scal(T(1.0)/col.sum()); } col[_y[i]] = col[_y[i]]-T(1.0); } if (intercept) { Vector<T> row; for (int i = 0; i<grad1.m(); ++i) { grad1.extractRow(i,row); row.project_sft(_y,i); grad1.setRow(i,row); } } grad1.scal(T(1.0)/_X->m()); grad2.resize(W.m(),W.n()); _X->mult(grad1,grad2,true,true); }; private: explicit MultiLogLoss<T>(const MultiLogLoss<T>& dict); MultiLogLoss<T>& operator=(const MultiLogLoss<T>& dict); const AbstractMatrixB<T>* _X; Vector<int> _y; }; template <typename T> class LossCur: public Loss<T, Matrix<T>, Matrix<T> > { public: LossCur(const AbstractMatrixB<T>& X) : _X(&X) { }; virtual ~LossCur() { }; inline void init(const Matrix<T>& y) { }; inline T eval(const Matrix<T>& A) const { Matrix<T> tmp(_X->m(),A.n()); _X->mult(A,tmp); Matrix<T> tmp2; //tmp2.copy(*_X); _X->copyTo(tmp2); //tmp.mult(*_X,tmp2,false,false,T(-1.0),T(1.0)); _X->multSwitch(tmp,tmp2,false,false,T(-1.0),T(1.0)); return 0.5*tmp2.normFsq(); }; inline void grad(const Matrix<T>& A, Matrix<T>& grad) const { Matrix<T> tmp(_X->m(),A.n()); _X->mult(A,tmp); Matrix<T> tmp2; //tmp2.copy(*_X); _X->copyTo(tmp2); //tmp.mult(*_X,tmp2,false,false,T(-1.0),T(1.0)); _X->multSwitch(tmp,tmp2,false,false,T(-1.0),T(1.0)); //tmp2.mult(*_X,tmp,false,true,T(-1.0),T(0.0)); _X->multSwitch(tmp2,tmp,true,false,T(-1.0),T(0.0)); grad.resize(A.m(),A.n()); _X->mult(tmp,grad,true,false); }; virtual T fenchel(const Matrix<T>& input) const { return 0.5*input.normFsq()+_X->dot(input); } virtual void var_fenchel(const Matrix<T>& A, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { Matrix<T> tmp(_X->m(),A.n()); _X->mult(A,tmp); //grad1.copy(*_X); _X->copyTo(grad1); //tmp.mult(*_X,grad1,false,false,T(1.0),T(-1.0)); _X->multSwitch(tmp,grad1,false,false,T(1.0),T(-1.0)); //grad1.mult(*_X,tmp,false,true,T(1.0),T(0.0)); _X->multSwitch(grad1,tmp,true,false,T(1.0),T(0.0)); grad2.resize(A.m(),A.n()); _X->mult(tmp,grad2,true,false); }; private: explicit LossCur<T>(const LossCur<T>& dict); LossCur<T>& operator=(const LossCur<T>& dict); const AbstractMatrixB<T>* _X; }; template <typename T> class SqLossMat : public Loss<T, Matrix<T> , Matrix<T> > { public: SqLossMat(const AbstractMatrixB<T>& D) : _D(&D) { _compute_gram = false; }; SqLossMat(const AbstractMatrixB<T>& D, const Matrix<T>& G) : _D(&D), _G(&G) { _compute_gram = true; }; virtual ~SqLossMat() { }; virtual inline void init(const Matrix<T>& x) { _x.copy(x); if (_compute_gram) { _D->mult(x,_DtX,true,false); } }; inline T eval(const Matrix<T>& alpha) const { Matrix<T> residual; residual.copy(_x); SpMatrix<T> spalpha; alpha.toSparse(spalpha); _D->mult(spalpha,residual,false,false,T(-1.0),T(1.0)); return 0.5*residual.normFsq(); } inline void grad(const Matrix<T>& alpha, Matrix<T>& grad) const { SpMatrix<T> spalpha; alpha.toSparse(spalpha); if (_compute_gram) { grad.copy(_DtX); _G->mult(spalpha,grad,false,false,T(1.0),-T(1.0)); } else { Matrix<T> residual; residual.copy(_x); _D->mult(spalpha,residual,false,false,T(-1.0),T(1.0)); _D->mult(residual,grad,true,false,T(-1.0),T(0.0)); } }; virtual inline bool test_backtracking(const Matrix<T>& y, const Matrix<T>& grad, const Matrix<T>& prox, const T L) const { Matrix<T> tmp; tmp.copy(y); tmp.sub(prox); SpMatrix<T> sptmp; tmp.toSparse(sptmp); if (_compute_gram) { SpVector<T> col; T sum=0; for (int i = 0; i<sptmp.n(); ++i) { sptmp.refCol(i,col); sum += _G->quad(col); } return (sum <= L*sptmp.normFsq()); } else { Matrix<T> tmp2; _D->mult(sptmp,tmp2); return (tmp2.normFsq() <= L*sptmp.normFsq()); } }; virtual T fenchel(const Matrix<T>& input) const { return 0.5*input.normFsq()+input.dot(_x); }; virtual void var_fenchel(const Matrix<T>& x, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { grad1.copy(_x); SpMatrix<T> spalpha; x.toSparse(spalpha); _D->mult(spalpha,grad1,false,false,T(1.0),T(-1.0)); if (intercept) grad1.center(); _D->mult(grad1,grad2,true,false,T(1.0),T(0.0)); }; private: explicit SqLossMat<T>(const SqLossMat<T>& dict); SqLossMat<T>& operator=(const SqLossMat<T>& dict); const AbstractMatrixB<T>* _D; Matrix<T> _x; bool _compute_gram; const Matrix<T>* _G; Matrix<T> _DtX; }; template <typename T, typename L> class LossMatSup : public Loss<T,Matrix<T>, Matrix<T> > { public: LossMatSup() { }; virtual ~LossMatSup() { for (int i = 0; i<_N; ++i) { delete(_losses[i]); _losses[i]=NULL; } delete[](_losses); }; virtual void init(const Matrix<T>& input) { Vector<T> col; _m=input.m(); for (int i = 0; i<_N; ++i) { input.refCol(i,col); _losses[i]->init(col); } }; inline T eval(const Matrix<T>& w) const { Vector<T> col; T sum = 0; for (int i = 0; i<_N; ++i) { w.refCol(i,col); sum+=_losses[i]->eval(col); } return sum; } inline void grad(const Matrix<T>& w, Matrix<T>& grad) const { Vector<T> col, col2; grad.resize(w.m(),w.n()); for (int i = 0; i<_N; ++i) { w.refCol(i,col); grad.refCol(i,col2); _losses[i]->grad(col,col2); } }; virtual T fenchel(const Matrix<T>& input) const { Vector<T> col; T sum = 0; for (int i = 0; i<_N; ++i) { input.refCol(i,col); sum += _losses[i]->fenchel(col); } return sum; } virtual void var_fenchel(const Matrix<T>& x, Matrix<T>& grad1, Matrix<T>& grad2, const bool intercept) const { grad1.resize(_m,x.n()); grad2.resize(x.m(),x.n()); Vector<T> col, col2, col3; for (int i = 0; i<_N; ++i) { x.refCol(i,col); grad1.refCol(i,col2); grad2.refCol(i,col3); _losses[i]->var_fenchel(col,col2,col3,intercept); } }; virtual bool is_fenchel() const { bool ok=true; for (int i = 0; i<_N; ++i) ok = ok && _losses[i]->is_fenchel(); return ok; }; virtual void dummy() = 0; private: explicit LossMatSup<T,L>(const LossMatSup<T,L>& dict); LossMatSup<T,L>& operator=(const LossMatSup<T,L>& dict); int _m; protected: int _N; L** _losses; }; template <typename T, typename L> class LossMat : public LossMatSup<T,L> { }; template <typename T, bool weighted> class LossMat<T, LogLoss<T,weighted> > : public LossMatSup<T, LogLoss<T,weighted> > { public: LossMat(const int N, const AbstractMatrixB<T>& X) { this->_N=N; this->_losses=new LogLoss<T,weighted>*[this->_N]; Vector<T> col; for (int i = 0; i<this->_N; ++i) this->_losses[i]=new LogLoss<T,weighted>(X); } virtual void dummy() { }; virtual ~LossMat() { }; }; template <typename T> class LossMat<T, SqLossMissing<T> > : public LossMatSup<T, SqLossMissing<T> > { public: LossMat(const int N, const AbstractMatrixB<T>& X) { this->_N=N; this->_losses=new SqLossMissing<T>*[this->_N]; Vector<T> col; for (int i = 0; i<this->_N; ++i) this->_losses[i]=new SqLossMissing<T>(X); } virtual void dummy() { }; virtual ~LossMat() { }; }; template <typename T, typename D = Vector<T> > class Regularizer { public: Regularizer() { }; Regularizer(const ParamReg<T>& param) { _intercept=param.intercept; _pos=param.pos; } virtual ~Regularizer() { }; virtual void reset() { }; virtual void prox(const D& input, D& output, const T lambda) = 0; virtual T eval(const D& input) const = 0; /// returns phi^star( input ) and ouput=input if the fenchel is unconstrained /// returns 0 and scale input such that phi^star(output)=0 otherwise virtual void fenchel(const D& input, T& val, T& scal) const = 0; virtual bool is_fenchel() const { return !_pos; }; virtual bool is_intercept() const { return _intercept; }; virtual bool is_subgrad() const { return false; }; virtual void sub_grad(const D& input, D& output) const { }; virtual T eval_paths(const D& x, SpMatrix<T>& paths_mat) const { return this->eval(x); }; protected: bool _pos; bool _intercept; private: explicit Regularizer<T,D>(const Regularizer<T,D>& reg); Regularizer<T,D>& operator=(const Regularizer<T,D>& reg); }; template <typename T> class Lasso : public Regularizer<T> { public: Lasso(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~Lasso() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); y.softThrshold(lambda); if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { return (this->_intercept ? x.asum() - abs(x[x.n()-1]) : x.asum()); }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Vector<T> output; output.copy(input); if (this->_intercept) output[output.n()-1]=0; T mm = output.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.resize(input.n()); if (!this->_pos) { for (int i = 0; i<input.n(); ++i) { output[i] = input[i] > 0 ? T(1.0) : input[i] < 0 ? -T(1.0) : 0; } } else { for (int i = 0; i<input.n(); ++i) { output[i] = input[i] > 0 ? T(1.0) : 0; } } if (this->_intercept) output[output.n()-1]=0; } }; template <typename T> class Lzero : public Regularizer<T> { public: Lzero(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~Lzero() { }; virtual bool is_fenchel() const { return false; }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); y.hardThrshold(sqrt(2*lambda)); if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { return (this->_intercept ? x.lzero() - 1 : x.lzero()); }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; }; template <typename T> class None: public Regularizer<T>, public SplittingFunction<T, SpMatrix<T> > { public: None() { }; None(const ParamReg<T>& param) { }; virtual ~None() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); }; T inline eval(const Vector<T>& x) const { return 0; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; virtual bool is_fenchel() const { return false; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.setZeros(); } virtual void reset() { }; virtual T eval_split(const SpMatrix<T>& input) const { return 0; }; virtual int num_components() const { return 0; }; virtual void prox_split(SpMatrix<T>& splitted_w, const T lambda) const { }; virtual void init_split_variables(SpMatrix<T>& splitted_w) const { }; virtual void init(const Vector<T>& y) { }; }; template <typename T> class Ridge: public Regularizer<T> { public: Ridge(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~Ridge() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); y.scal(T(1.0/(1.0+lambda))); if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { return (this->_intercept ? 0.5*x.nrm2sq() - 0.5*x[x.n()-1]*x[x.n()-1] : 0.5*x.nrm2sq()); }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { val=this->eval(input); scal=T(1.0); }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.resize(input.n()); if (!this->_pos) { for (int i = 0; i<input.n(); ++i) { output[i] = input[i] > 0 ? 0.5*input[i] : 0; } } else { output.copy(input); output.scal(0.5); } if (this->_intercept) output[output.n()-1]=0; } }; template <typename T> class normL2: public Regularizer<T> { public: normL2(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~normL2() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> xref(x.rawX(),this->_intercept ? x.n()-1 : x.n()); const T nrm=xref.nrm2(); if (nrm < lambda) { y.setZeros(); } else { y.scal(T(1.0) - lambda/nrm); } if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { Vector<T> xref(x.rawX(),this->_intercept ? x.n()-1 : x.n()); return xref.nrm2(); }; /// TODO add subgradient void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Vector<T> output; output.copy(input); if (this->_intercept) output[output.n()-1]=0; T mm = output.nrm2(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T> class normLINF: public Regularizer<T> { public: normLINF(const ParamReg<T>& param) : Regularizer<T>(param) { }; virtual ~normLINF() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> xref(y.rawX(),this->_intercept ? x.n()-1 : x.n()); Vector<T> row(xref.n()); xref.l1project(row,lambda); for (int j = 0; j<xref.n(); ++j) y[j]=y[j]-row[j]; if (this->_intercept) y[y.n()-1] = x[y.n()-1]; }; T inline eval(const Vector<T>& x) const { Vector<T> xref(x.rawX(),this->_intercept ? x.n()-1 : x.n()); return xref.fmaxval(); }; /// TODO add subgradient void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Vector<T> output; output.copy(input); if (this->_intercept) output[output.n()-1]=0; T mm = output.asum(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T, typename D, typename RegA, typename RegB, bool order = true, bool scale_lambda = false> class ComposeProx: public Regularizer<T,D> { public: ComposeProx(const ParamReg<T>& param) : Regularizer<T,D>(param) { _lambda2d1=param.lambda2d1; _regA=new RegA(param); _regB=new RegB(param); } virtual ~ComposeProx() { delete(_regA); delete(_regB); }; void inline prox(const D& x, D& y, const T lambda) { D tmp; if (scale_lambda) { if (order) { _regA->prox(x,tmp,lambda); _regB->prox(tmp,y,lambda*_lambda2d1/(T(1.0)+lambda)); } else { _regB->prox(x,tmp,lambda*_lambda2d1); _regA->prox(tmp,y,lambda/(T(1.0)+lambda*_lambda2d1)); } } else { if (order) { _regA->prox(x,tmp,lambda); _regB->prox(tmp,y,lambda*_lambda2d1); } else { _regB->prox(x,tmp,lambda*_lambda2d1); _regA->prox(tmp,y,lambda); } } }; T inline eval(const D& x) const { return _regA->eval(x) + _lambda2d1*_regB->eval(x); }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const D& input, T& val, T& scal) const { }; virtual bool is_subgrad() const { return _regA->is_subgrad() && _regB->is_subgrad(); }; virtual void sub_grad(const D& input, D& output) const { _regA->sub_grad(input,output); D tmp; _regB->sub_grad(input,tmp); output.add(tmp,_lambda2d1); }; private: RegA* _regA; RegB* _regB; T _lambda2d1; }; template <typename T> struct ElasticNet { typedef ComposeProx< T, Vector<T>, Lasso<T>, Ridge<T>, true > type; }; template <typename T> class FusedLasso: public Regularizer<T> { public: FusedLasso(const ParamReg<T>& param) : Regularizer<T>(param) { _lambda2d1=param.lambda2d1; _lambda3d1=param.lambda3d1; }; virtual ~FusedLasso() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.resize(x.n()); Vector<T> copyx; copyx.copy(x); copyx.fusedProjectHomotopy(y,_lambda2d1*lambda,lambda,_lambda3d1*lambda,true); }; T inline eval(const Vector<T>& x) const { T sum = T(); const int maxn = this->_intercept ? x.n()-1 : x.n(); for (int i = 0; i<maxn-1; ++i) sum += abs(x[i+1]-x[i]) + _lambda2d1*abs(x[i]) + 0.5*_lambda3d1*x[i]*x[i]; sum += _lambda2d1*abs(x[maxn-1])+0.5*_lambda3d1*x[maxn-1]*x[maxn-1]; return sum; }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; private: T _lambda2d1; T _lambda3d1; }; template <typename T> class GraphLasso : public Regularizer<T>, public SplittingFunction<T, SpMatrix<T> > { public: GraphLasso(const ParamReg<T>& param) : Regularizer<T>(param) { const bool resetflow = param.resetflow; const bool linf = param.linf; const bool clever = param.clever; const GraphStruct<T>& graph_st=*(param.graph_st); _clever=clever; _resetflow=resetflow; _graph.create_graph(graph_st.Nv,graph_st.Ng,graph_st.weights, graph_st.gv_ir,graph_st.gv_jc,graph_st.gg_ir,graph_st.gg_jc); _graph.save_capacities(); _work.resize(graph_st.Nv+graph_st.Ng+2); _weights.resize(graph_st.Ng); for (int i = 0; i<graph_st.Ng; ++i) _weights[i] = graph_st.weights[i]; _old_lambda=-1.0; _linf=linf; }; virtual ~GraphLasso() { }; void inline reset() { _old_lambda = -1.0; }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { if (!_linf) { cerr << "Not implemented" << endl; exit(1); } y.copy(x); _graph.restore_capacities(); _graph.set_weights(_weights.rawX(),lambda); if (_old_lambda < 0 || _resetflow) { _graph.reset_flow(); } else { if (lambda != _old_lambda) _graph.scale_flow(lambda/_old_lambda); } if (this->_pos) { Vector<T> xc; xc.copy(x); xc.thrsPos(); _graph.proximal_operator(xc.rawX(),y.rawX(),_clever); } else { _graph.proximal_operator(x.rawX(),y.rawX(),_clever); } #ifdef VERB2 T duality_gap2 = y.nrm2sq()-y.dot(x)+lambda*this->eval(y); cerr << "duality_gap2 " << duality_gap2 << endl; #endif _old_lambda=lambda; }; T inline eval(const Vector<T>& x) const { Graph<T>* gr = const_cast<Graph<T>* >(&_graph); gr->restore_capacities(); return gr->norm(x.rawX(),_work.rawX(),_weights.rawX(),_linf); }; virtual bool is_fenchel() const { return _linf; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { Graph<T>* gr = const_cast<Graph<T>* >(&_graph); if (!_resetflow) { gr->save_flow(); } gr->reset_flow(); gr->restore_capacities(); T mm = gr->dual_norm_inf(input,_weights); if (!_resetflow) gr->restore_flow(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; virtual void init(const Vector<T>& y) { }; inline int num_components() const { return _weights.n(); }; inline void prox_split(SpMatrix<T>& splitted_w, const T lambda) const { Vector<T> tmp; SpVector<T> col; if (_linf) { for (int i = 0; i<splitted_w.n(); ++i) { splitted_w.refCol(i,col); tmp.setData(col.rawX(),col.nzmax()); Vector<T> res; res.copy(tmp); vAbs<T>(res.n(),res.rawX(),res.rawX()); T thrs=project_tree_l1(res.rawX(),res.n(),lambda); tmp.thrsabsmin(thrs); } } else { for (int i = 0; i<splitted_w.n(); ++i) { splitted_w.refCol(i,col); tmp.setData(col.rawX(),col.nzmax()); const T nrm = tmp.nrm2(); if (nrm > lambda*_weights[i]) { tmp.scal(T(1.0)-lambda*_weights[i]/nrm); } else { tmp.setZeros(); } } } }; inline void init_split_variables(SpMatrix<T>& splitted_w) const { Graph<T>* gr = const_cast<Graph<T>* >(&_graph); gr->init_split_variables(splitted_w); }; inline T eval_split(const SpMatrix<T>& input) const { SpVector<T> col; T sum = 0; for (int i = 0; i<input.n(); ++i) { input.refCol(i,col); sum += _linf ? _weights[i]*col.fmaxval() : _weights[i]*col.nrm2(); } return sum; } inline T eval_weighted(const Vector<T>& input, const SpMatrix<T>& input_struct, const T* inner_weight) const { SpVector<T> col; T sum = 0; Vector<T> tmp(input_struct.m()); for (int i = 0; i<input_struct.n(); ++i) { input_struct.refCol(i,col); tmp.setn(col.L()); for (int j = 0; j<col.L(); ++j) tmp[j]=inner_weight[j]*input[col.r(j)]; sum += _linf ? _weights[i]*tmp.fmaxval() : _weights[i]*tmp.nrm2(); } return sum; } private: bool _clever; Graph<T> _graph; bool _resetflow; Vector<T> _work; Vector<T> _weights; T _old_lambda; bool _linf; }; template <typename T> struct GraphLassoRidge { typedef ComposeProx<T, Vector<T>, GraphLasso<T>, Ridge<T>, true> type; }; template <typename T> class TreeLasso : public Regularizer<T> { public: TreeLasso(const ParamReg<T>& param) : Regularizer<T>(param) { const TreeStruct<T>& tree_st=*(param.tree_st); const bool linf = param.linf; _tree.create_tree(tree_st.Nv,tree_st.own_variables, tree_st.N_own_variables,tree_st.weights, tree_st.groups_ir,tree_st.groups_jc, tree_st.Ng,0); _linf=linf; }; virtual ~TreeLasso() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> yp; if (this->_intercept) { yp.setData(y.rawX(),y.n()-1); } else { yp.setData(y.rawX(),y.n()); } _tree.proj(yp,_linf,lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<Tree_Seq<T>* >(&_tree)->val_norm(x.rawX(),0,_linf); }; void inline fenchel(const Vector<T>& y, T& val, T& scal) const { if (_linf) { Vector<T> yp; if (this->_intercept) { yp.setData(y.rawX(),y.n()-1); } else { yp.setData(y.rawX(),y.n()); } T mm = const_cast<Tree_Seq<T>* >(&_tree)->dual_norm_inf(yp); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; } }; virtual bool is_fenchel() const { return _linf; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Vector<T>& input, Vector<T>& output) const { output.resize(input.n()); const_cast<Tree_Seq<T>*>(&_tree)->sub_grad(input,output,_linf); if (this->_intercept) output[output.n()-1]=0; } private: Tree_Seq<T> _tree; bool _linf; }; template <typename T> class TreeLzero : public Regularizer<T> { public: TreeLzero(const ParamReg<T>& param) : Regularizer<T>(param) { const TreeStruct<T>& tree_st=*(param.tree_st); _tree.create_tree(tree_st.Nv,tree_st.own_variables, tree_st.N_own_variables,tree_st.weights, tree_st.groups_ir,tree_st.groups_jc, tree_st.Ng,0); }; virtual ~TreeLzero() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> yp; if (this->_intercept) { yp.setData(y.rawX(),y.n()-1); } else { yp.setData(y.rawX(),y.n()); } _tree.proj_zero(yp,lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<Tree_Seq<T>* >(&_tree)->val_zero(x.rawX(),0); }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const Vector<T>& y, T& val, T& scal) const { }; private: Tree_Seq<T> _tree; }; template <typename T, typename ProxMat> class ProxMatToVec : public Regularizer<T> { public: ProxMatToVec(const ParamReg<T>& param) : Regularizer<T>(param) { _size_group=param.size_group; ParamReg<T> param2=param; param2.intercept=false; _proxy = new ProxMat(param2); }; virtual ~ProxMatToVec() { delete(_proxy); }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.resize(x.n()); int size_vec=this->_intercept ? x.n()-1 : x.n(); Matrix<T> mX(x.rawX(),_size_group,size_vec/_size_group); Matrix<T> mY(y.rawX(),_size_group,size_vec/_size_group); _proxy->prox(mX,mY,lambda); if (this->_intercept) y[y.n()-1]=x[x.n()-1]; } T inline eval(const Vector<T>& x) const { int size_vec=this->_intercept ? x.n()-1 : x.n(); Matrix<T> mX(x.rawX(),_size_group,size_vec/_size_group); return _proxy->eval(mX); } virtual bool is_fenchel() const { return (_proxy->is_fenchel()); }; void inline fenchel(const Vector<T>& x, T& val, T& scal) const { int size_vec=this->_intercept ? x.n()-1 : x.n(); Matrix<T> mX(x.rawX(),_size_group,size_vec/_size_group); _proxy->fenchel(mX,val,scal); }; private: int _size_group; ProxMat* _proxy; }; template <typename T, typename Reg> class GroupProx : public Regularizer<T> { public: GroupProx(const ParamReg<T> & param) : Regularizer<T>(param) { ParamReg<T> param2=param; param2.intercept=false; _size_group=param.size_group; if (param.groups) { int num_groups=0; for (int i = 0; i<param.ngroups; ++i) num_groups=MAX(num_groups,param.groups[i]); _groups.resize(num_groups); for (int i = 0; i<num_groups; ++i) _groups[i]=new list_int(); for (int i = 0; i<param.ngroups; ++i) _groups[param.groups[i]-1]->push_back(i); } _prox = new Reg(param2); } virtual ~GroupProx() { delete(_prox); for (int i = 0; i<_groups.size(); ++i) delete(_groups[i]); }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); const int maxn= this->_intercept ? x.n()-1 : x.n(); if (!_groups.empty()) { for (int i = 0; i<_groups.size(); ++i) { list_int* group=_groups[i]; Vector<T> tmp(group->size()); Vector<T> tmp2(group->size()); int count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { tmp[count++]=x[*it]; } _prox->prox(tmp,tmp2,lambda); count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { y[*it]=tmp2[count++]; } } } else { Vector<T> tmp; Vector<T> tmp2; const int p = _size_group; for (int i = 0; i+p-1<maxn; i+=p) { tmp.setPointer(x.rawX()+i,p); tmp2.setPointer(y.rawX()+i,p); _prox->prox(tmp,tmp2,lambda); } } } T inline eval(const Vector<T>& x) const { const int maxn= this->_intercept ? x.n()-1 : x.n(); T sum=0; if (!_groups.empty()) { for (int i = 0; i<_groups.size(); ++i) { list_int* group=_groups[i]; Vector<T> tmp(group->size()); int count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { tmp[count++]=x[*it]; } sum+=_prox->eval(tmp); } } else { Vector<T> tmp; const int p = _size_group; for (int i = 0; i+p-1<maxn; i+=p) { tmp.setPointer(x.rawX()+i,p); sum+=_prox->eval(tmp); } } return sum; } virtual bool is_fenchel() const { return _prox->is_fenchel(); }; void inline fenchel(const Vector<T>& x, T& val, T& scal) const { const int maxn= this->_intercept ? x.n()-1 : x.n(); T val2; T scal2; scal=T(1.0); val=0; if (!_groups.empty()) { for (int i = 0; i<_groups.size(); ++i) { list_int* group=_groups[i]; Vector<T> tmp(group->size()); int count=0; for (const_iterator_int it = group->begin(); it != group->end(); ++it) { tmp[count++]=x[*it]; } _prox->fenchel(tmp,val2,scal2); val+=val2; scal=MIN(scal,scal2); } } else { const int p = _size_group; Vector<T> tmp; for (int i = 0; i+p-1<maxn; i+=p) { tmp.setPointer(x.rawX()+i,p); _prox->fenchel(tmp,val2,scal2); val+=val2; scal=MIN(scal,scal2); } } }; protected: int _size_group; std::vector<list_int*> _groups; Reg* _prox; }; template <typename T> struct GroupLassoL2 { typedef GroupProx<T, normL2<T> > type; }; template <typename T> struct GroupLassoLINF { typedef GroupProx<T, normLINF<T> > type; }; template <typename T> struct GroupLassoL2_L1 { typedef ComposeProx<T, Vector<T>, typename GroupLassoL2<T>::type, Lasso<T>, false> type; }; template <typename T> struct GroupLassoLINF_L1 { typedef ComposeProx<T, Vector<T>, typename GroupLassoLINF<T>::type, Lasso<T>, false> type; }; template <typename T> class MixedL1L2 : public Regularizer<T,Matrix<T> > { public: MixedL1L2(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { }; virtual ~MixedL1L2() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { Vector<T> norm; y.copy(x); if (this->_pos) y.thrsPos(); y.norm_2_rows(norm); y.setZeros(); const int m = x.m(); const int n = x.n(); for (int i = 0; i<m; ++i) { if (norm[i] > lambda) { T scal = (norm[i]-lambda)/norm[i]; for (int j = 0; j<n; ++j) y[j*m+i] = x[j*m+i]*scal; } } if (this->_pos) y.thrsPos(); if (this->_intercept) for (int j = 0; j<n; ++j) y[j*m+m-1]=x[j*m+m-1]; } T inline eval(const Matrix<T>& x) const { Vector<T> norm; x.norm_2_rows(norm); return this->_intercept ? norm.asum() - norm[norm.n() -1] : norm.asum(); } virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Matrix<T>& input, Matrix<T>& output) const { Vector<T> norm; input.norm_2_rows(norm); for (int i = 0; i<norm.n(); ++i) { if (norm[i] < 1e-20) norm[i]=T(1.0); } norm.inv(); if (this->_intercept) norm[norm.n()-1]=0; output.copy(input); output.multDiagLeft(norm); }; void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> norm; input.norm_2_rows(norm); if (this->_intercept) norm[norm.n()-1]=0; T mm = norm.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T> class MixedL1LINF : public Regularizer<T,Matrix<T> > { public: MixedL1LINF(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { }; virtual ~MixedL1LINF() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); Vector<T> row(x.n()); Vector<T> row2(x.n()); const int maxn= this->_intercept ? x.m()-1 : x.m(); for (int i = 0; i< maxn; ++i) { for (int j = 0; j<x.n(); ++j) row[j]=y(i,j); row.l1project(row2,lambda); for (int j = 0; j<x.n(); ++j) y(i,j) = row[j]-row2[j]; } } T inline eval(const Matrix<T>& x) const { Vector<T> norm; x.norm_inf_rows(norm); return this->_intercept ? norm.asum() - norm[norm.n() -1] : norm.asum(); } void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> norm; input.norm_l1_rows(norm); if (this->_intercept) norm[norm.n()-1]=0; T mm = norm.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; virtual bool is_subgrad() const { return true; }; virtual void sub_grad(const Matrix<T>& input, Matrix<T>& output) const { output.resize(input.m(),input.n()); output.setZeros(); const T maxm= this->_intercept ? input.m()-1 : input.m(); Vector<T> row(input.n()); for (int i = 0; i<maxm; ++i) { input.copyRow(i,row); T max=row.fmaxval(); if (max > 1e-15) { int num_max=0; for (int j = 0; j<row.n(); ++j) { if (abs<T>(max-abs<T>(row[j])) < 1e-15) num_max++; } T add = T(1.0)/num_max; for (int j = 0; j<row.n(); ++j) { if (abs<T>(max-abs<T>(row[j])) < 1e-15) row[j] = row[j] > 0 ? add : -add; } output.setRow(i,row); } } }; }; template <typename T> class TraceNorm : public Regularizer<T,Matrix<T> > { public: TraceNorm(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { if (param.intercept) { cerr << "Trace norm implementation is not compatible with intercept, intercept deactivated" << endl; } if (param.pos) { cerr << "Trace norm implementation is not compatible with non-negativity constraints" << endl; } }; virtual ~TraceNorm() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { //Matrix<T> tmp; //tmp.copy(x); Matrix<T> U; Matrix<T> V; Vector<T> S; x.svd(U,S,V); S.softThrshold(lambda); U.multDiagRight(S); U.mult(V,y); /* Vector<T> u0(x.m()); u0.setZeros(); Vector<T> u, v; for (int i = 0; i<MIN(x.m(),x.n()); ++i) { tmp.svdRankOne(u0,u,v); T val=v.nrm2(); if (val < lambda) break; y.rank1Update(u,v,(val-lambda)/val); tmp.rank1Update(u,v,-T(1.0)); }*/ } T inline eval(const Matrix<T>& x) const { Vector<T> tmp; x.singularValues(tmp); return tmp.sum(); /* Matrix<T> XtX; if (x.m() > x.n()) { x.XtX(XtX); } else { x.XXt(XtX); } T sum=0; Vector<T> u0(XtX.m()); u0.setAleat(); for (int i = 0; i<XtX.m(); ++i) { T val=XtX.eigLargestMagnSym(u0,u0); // uses power method XtX.rank1Update(u0,u0,-val); sum+=sqrt(val); if (val <= 1e-10) break; } return sum; */ } void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { //Vector<T> u0(input.m()); //u0.setZeros(); //Vector<T> u, v; //input.svdRankOne(u0,u,v); //T mm = v.nrm2(); Vector<T> tmp; input.singularValues(tmp); T mm = tmp.fmaxval(); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; }; template <typename T> class Rank : public Regularizer<T,Matrix<T> > { public: Rank(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { if (param.intercept) { cerr << "Rank implementation is not compatible with intercept, intercept deactivated" << endl; } if (param.pos) { cerr << "Rank implementation is not compatible with non-negativity constraints" << endl; } }; virtual ~Rank() { }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { Matrix<T> tmp; tmp.copy(x); y.resize(x.m(),x.n()); y.setZeros(); Vector<T> u0(x.m()); u0.setZeros(); Vector<T> u, v; for (int i = 0; i<MIN(x.m(),x.n()); ++i) { tmp.svdRankOne(u0,u,v); T val=v.nrm2(); if (val*val < lambda) break; y.rank1Update(u,v); tmp.rank1Update(u,v,-T(1.0)); } } T inline eval(const Matrix<T>& x) const { Matrix<T> XtX; if (x.m() > x.n()) { x.XtX(XtX); } else { x.XXt(XtX); } T sum=0; Vector<T> u0(XtX.m()); u0.setAleat(); for (int i = 0; i<XtX.m(); ++i) { T val=XtX.eigLargestMagnSym(u0,u0); // uses power method XtX.rank1Update(u0,u0,-val); sum++; if (val <= 1e-10) break; } return sum; } virtual bool is_fenchel() const { return false; }; void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { }; }; template <typename T> inline void convert_paths_to_mat(const List<Path<long long>*>& paths,SpMatrix<T>& paths_mat, const int n) { int nzmax=0; for (ListIterator<Path<long long>*> it=paths.begin(); it != paths.end(); ++it) nzmax+=it->nodes.size(); paths_mat.resize(n,paths.size(),nzmax); int* pB =paths_mat.pB(); int* pE =paths_mat.pE(); int* r =paths_mat.r(); T* v =paths_mat.v(); int count_col=0; int count=0; pB[0]=0; for (ListIterator<Path<long long>*> it_path=paths.begin(); it_path != paths.end(); ++it_path) { for (const_iterator_int it = it_path->nodes.begin(); it != it_path->nodes.end(); ++it) { r[count]= *it; v[count++]= it_path->flow; } pB[++count_col]=count; } for (int i = 0; i<paths_mat.n(); ++i) sort(r,v,pB[i],pE[i]-1); }; template <typename T> class GraphPathL0 : public Regularizer<T> { public: GraphPathL0(const ParamReg<T>& param) : Regularizer<T>(param) { const GraphPathStruct<T>& graph=*(param.graph_path_st); _graph.init_graph(graph); } virtual ~GraphPathL0() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { // DEBUG y.copy(x); if (this->_pos) y.thrsPos(); _graph.proximal_l0(y.rawX(),lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<GraphPath<T>* >(&_graph)->eval_l0(x.rawX()); }; T inline eval_paths(const Vector<T>& x, SpMatrix<T>& paths_mat) const { List<Path<long long>*> paths; T val=const_cast<GraphPath<T>* >(&_graph)->eval_l0(x.rawX(),&paths); convert_paths_to_mat<T>(paths,paths_mat,_graph.n()); for (ListIterator<Path<>*> it_path=paths.begin(); it_path != paths.end(); ++it_path) delete(*it_path); return val; }; virtual bool is_fenchel() const { return false; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { }; private: GraphPath<T> _graph; }; template <typename T> class GraphPathConv : public Regularizer<T> { public: GraphPathConv(const ParamReg<T>& param) : Regularizer<T>(param) { const GraphPathStruct<T>& graph=*(param.graph_path_st); _graph.init_graph(graph); } virtual ~GraphPathConv() { }; void inline prox(const Vector<T>& x, Vector<T>& y, const T lambda) { y.copy(x); if (this->_pos) y.thrsPos(); _graph.proximal_conv(y.rawX(),lambda); }; T inline eval(const Vector<T>& x) const { return const_cast<GraphPath<T>* >(&_graph)->eval_conv(x.rawX()); }; T inline eval_paths(const Vector<T>& x, SpMatrix<T>& paths_mat) const { List<Path<long long>*> paths; T val=const_cast<GraphPath<T>* >(&_graph)->eval_conv(x.rawX(),&paths); convert_paths_to_mat<T>(paths,paths_mat,_graph.n()); for (ListIterator<Path<long long>*> it_path=paths.begin(); it_path != paths.end(); ++it_path) delete(*it_path); return val; }; void inline fenchel(const Vector<T>& input, T& val, T& scal) const { T mm = const_cast<GraphPath<T>* >(&_graph)->eval_dual_norm(input.rawX()); scal= mm > 1.0 ? T(1.0)/mm : 1.0; val=0; }; private: GraphPath<T> _graph; }; template <typename T,typename Reg> class RegMat : public Regularizer<T,Matrix<T> > { public: RegMat(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { _transpose=param.transpose; const int N = param.num_cols; _regs=new Reg*[N]; _N=N; for (int i = 0; i<N; ++i) _regs[i]=new Reg(param); }; virtual ~RegMat() { for (int i = 0; i<_N; ++i) { delete(_regs[i]); _regs[i]=NULL; } delete[](_regs); }; void inline reset() { for (int i = 0; i<_N; ++i) _regs[i]->reset(); }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { y.copy(x); int i; if (_transpose) { #pragma omp parallel for private(i) for (i = 0; i<_N; ++i) { Vector<T> colx, coly; x.copyRow(i,colx); _regs[i]->prox(colx,coly,lambda); y.setRow(i,coly); } } else { #pragma omp parallel for private(i) for (i = 0; i<_N; ++i) { Vector<T> colx, coly; x.refCol(i,colx); y.refCol(i,coly); _regs[i]->prox(colx,coly,lambda); } } }; virtual bool is_subgrad() const { bool ok=true; for (int i = 0; i<_N; ++i) ok=ok && _regs[i]->is_subgrad(); return ok; }; void inline sub_grad(const Matrix<T>& x, Matrix<T>& y) const { y.resize(x.m(),x.n()); Vector<T> colx, coly, cold; if (_transpose) { for (int i = 0; i<_N; ++i) { x.copyRow(i,colx); _regs[i]->sub_grad(colx,coly); y.setRow(i,coly); } } else { for (int i = 0; i<_N; ++i) { x.refCol(i,colx); y.refCol(i,coly); _regs[i]->sub_grad(colx,coly); } } }; T inline eval(const Matrix<T>& x) const { T sum = 0; int i; #pragma omp parallel for private(i) for (i = 0; i<_N; ++i) { Vector<T> col; if (_transpose) { x.copyRow(i,col); } else { x.refCol(i,col); } #pragma omp critical sum += _regs[i]->eval(col); } return sum; }; void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> col; val = 0; scal = 1.0; for (int i = 0; i<_N; ++i) { if (_transpose) { input.copyRow(i,col); } else { input.refCol(i,col); } T val2 = 0; T scal2 = 1.0; _regs[i]->fenchel(col,val2,scal2); scal=MIN(scal,scal2); val += val2; } }; virtual bool is_fenchel() const { bool ok=true; for (int i = 0; i<_N; ++i) ok = ok && _regs[i]->is_fenchel(); return ok; }; protected: int _N; Reg** _regs; bool _transpose; }; template <typename T> struct MixedL1L2_L1 { typedef ComposeProx<T, Matrix<T>, MixedL1L2<T>, RegMat<T, Lasso<T> >, false> type; }; template <typename T> struct MixedL1LINF_L1 { typedef ComposeProx<T, Matrix<T>, MixedL1LINF<T>, RegMat<T, Lasso<T> >, false> type; }; template <typename T> class SpecGraphMat : public Regularizer<T,Matrix<T> > { public: SpecGraphMat(const ParamReg<T>& param) : Regularizer<T,Matrix<T> >(param) { }; virtual ~SpecGraphMat() { delete(_graphlasso); }; virtual void dummy() = 0; void inline reset() { _graphlasso->reset(); }; void inline prox(const Matrix<T>& x, Matrix<T>& y, const T lambda) { Vector<T> xv, yv; x.toVect(xv); y.resize(x.m(),x.n()); y.toVect(yv); _graphlasso->prox(xv,yv,lambda); } T inline eval(const Matrix<T>& X) const { Vector<T> xv; X.toVect(xv); return _graphlasso->eval(xv); } void inline fenchel(const Matrix<T>& input, T& val, T& scal) const { Vector<T> inv; input.toVect(inv); _graphlasso->fenchel(inv,val,scal); }; virtual bool is_fenchel() const { return _graphlasso->is_fenchel(); }; protected: GraphLasso<T>* _graphlasso; }; template <typename T> class MixedL1LINFCR : public SpecGraphMat<T> { public: MixedL1LINFCR(const int m, const ParamReg<T>& param) : SpecGraphMat<T>(param) { const int n = param.num_cols; const T l2dl1 = param.lambda2d1; GraphStruct<T> graph_st; graph_st.Nv=m*n; graph_st.Ng=m+n; T* weights = new T[graph_st.Ng]; for (int i = 0; i<n; ++i) weights[i]=T(1.0); for (int i = 0; i<m; ++i) weights[i+n]=l2dl1; graph_st.weights=weights; mwSize* gv_jc = new mwSize[graph_st.Ng+1]; mwSize* gv_ir = new mwSize[m*n*2]; for (int i = 0; i<n; ++i) { gv_jc[i]=i*m; for (int j = 0; j<m; ++j) gv_ir[i*m+j]=i*m+j; } for (int i = 0; i<m; ++i) { gv_jc[i+n]=i*n+n*m; for (int j = 0; j<n; ++j) gv_ir[i*n+n*m+j]=j*m+i; } gv_jc[m+n]=2*m*n; graph_st.gv_jc=gv_jc; graph_st.gv_ir=gv_ir; mwSize* gg_jc = new mwSize[graph_st.Ng+1]; mwSize* gg_ir = new mwSize[1]; for (int i = 0; i< graph_st.Ng+1; ++i) gg_jc[i]=0; graph_st.gg_jc=gg_jc; graph_st.gg_ir=gg_ir; ParamReg<T> param_lasso = param; param_lasso.graph_st = &graph_st; this->_graphlasso = new GraphLasso<T>(param_lasso); delete[](weights); delete[](gv_jc); delete[](gv_ir); delete[](gg_jc); delete[](gg_ir); }; virtual ~MixedL1LINFCR() { }; virtual void dummy() { }; }; template <typename T> class TreeMult : public SpecGraphMat<T> { public: TreeMult(const ParamReg<T>& param) : SpecGraphMat<T>(param) { const TreeStruct<T>& tree_st=*(param.tree_st); const int N = param.num_cols; const T l1dl2 = param.lambda2d1; GraphStruct<T> graph_st; int Nv=tree_st.Nv; if (param.intercept) ++Nv; int Ng=tree_st.Ng; graph_st.Nv=Nv*N; graph_st.Ng=Ng*(N+1); T* weights=new T[graph_st.Ng]; for (int i = 0; i<N+1; ++i) for (int j = 0; j<Ng; ++j) weights[i*Ng+j]=tree_st.weights[j]; for (int j = 0; j<Ng; ++j) weights[N*Ng+j]*=l1dl2; graph_st.weights=weights; int nzmax_tree=0; for (int i = 0; i<Ng; ++i) nzmax_tree += tree_st.N_own_variables[i]; int nzmax_v=nzmax_tree*N; mwSize* gv_jc = new mwSize[graph_st.Ng+1]; mwSize* gv_ir = new mwSize[nzmax_v]; int count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gv_jc[i*Ng+j]=count; for (int k = 0; k<tree_st.N_own_variables[j]; ++k) { gv_ir[gv_jc[i*Ng+j] + k] =Nv*i+tree_st.own_variables[j]+k; ++count; } } } for (int i = 0; i<Ng+1; ++i) { gv_jc[N*Ng+i]=count; } graph_st.gv_jc=gv_jc; graph_st.gv_ir=gv_ir; mwSize* gg_jc = new mwSize[graph_st.Ng+1]; int nzmax_tree2=tree_st.groups_jc[Ng]; int nzmax2=nzmax_tree2*(N+1)+Ng*N; mwSize* gg_ir = new mwSize[nzmax2]; count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gg_jc[i*Ng+j] = count; for (int k = tree_st.groups_jc[j]; k<static_cast<int>(tree_st.groups_jc[j+1]); ++k) { gg_ir[count++] = i*Ng+tree_st.groups_ir[k]; } } } for (int i = 0; i<Ng; ++i) { gg_jc[N*Ng+i] = count; for (int j = tree_st.groups_jc[i]; j<static_cast<int>(tree_st.groups_jc[i+1]); ++j) { gg_ir[count++] = N*Ng+tree_st.groups_ir[j]; } for (int j = 0; j<N; ++j) { gg_ir[count++] = j*Ng+i; } } gg_jc[(N+1)*Ng]=nzmax2; graph_st.gg_jc=gg_jc; graph_st.gg_ir=gg_ir; // param.graph_st=&graph_st; ParamReg<T> param_lasso = param; param_lasso.graph_st=&graph_st; this->_graphlasso = new GraphLasso<T>(param_lasso); delete[](weights); delete[](gv_ir); delete[](gv_jc); delete[](gg_ir); delete[](gg_jc); }; virtual void dummy() { }; virtual ~TreeMult() { }; }; template <typename T> class GraphMult : public SpecGraphMat<T> { public: GraphMult(const ParamReg<T>& param) : SpecGraphMat<T>(param) { const GraphStruct<T>& graph_st=*(param.graph_st); const int N = param.num_cols; const T l1dl2 = param.lambda2d1; GraphStruct<T> g_st; int Nv=graph_st.Nv; int Ng=graph_st.Ng; g_st.Nv=Nv*N; g_st.Ng=Ng*(N+1); T* weights=new T[g_st.Ng]; for (int i = 0; i<N+1; ++i) for (int j = 0; j<Ng; ++j) weights[i*Ng+j]=graph_st.weights[j]; for (int j = 0; j<Ng; ++j) weights[N*Ng+j]*=l1dl2; g_st.weights=weights; int nzmax_graph=graph_st.gv_jc[Ng]; //just corrected to gv int nzmax_v=nzmax_graph*N; mwSize* gv_jc = new mwSize[g_st.Ng+1]; mwSize* gv_ir = new mwSize[nzmax_v]; int count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gv_jc[i*Ng+j]=count; for (int k = graph_st.gv_jc[j]; k<graph_st.gv_jc[j+1]; ++k) { gv_ir[count++] =Nv*i+graph_st.gv_ir[k]; } } } for (int i = 0; i<Ng+1; ++i) { gv_jc[N*Ng+i]=count; } g_st.gv_jc=gv_jc; g_st.gv_ir=gv_ir; mwSize* gg_jc = new mwSize[g_st.Ng+1]; int nzmax_tree2=graph_st.gg_jc[Ng]; int nzmax2=nzmax_tree2*(N+1)+Ng*N; mwSize* gg_ir = new mwSize[nzmax2]; count=0; for (int i = 0; i<N; ++i) { for (int j = 0; j<Ng; ++j) { gg_jc[i*Ng+j] = count; for (int k = graph_st.gg_jc[j]; k<graph_st.gg_jc[j+1]; ++k) { gg_ir[count++] = i*Ng+graph_st.gg_ir[k]; } } } for (int i = 0; i<Ng; ++i) { gg_jc[N*Ng+i] = count; for (int j = graph_st.gg_jc[i]; j<static_cast<int>(graph_st.gg_jc[i+1]); ++j) { gg_ir[count++] = N*Ng+graph_st.gg_ir[j]; } for (int j = 0; j<N; ++j) { gg_ir[count++] = j*Ng+i; } } gg_jc[(N+1)*Ng]=nzmax2; g_st.gg_jc=gg_jc; g_st.gg_ir=gg_ir; ParamReg<T> param_lasso = param; param_lasso.graph_st = &g_st; this->_graphlasso = new GraphLasso<T>(param_lasso); delete[](weights); delete[](gv_ir); delete[](gv_jc); delete[](gg_ir); delete[](gg_jc); }; virtual void dummy() { }; virtual ~GraphMult() { }; }; template <typename T, typename D, typename E> T duality_gap(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x, const T lambda, T& best_dual, const bool verbose = false) { if (!regularizer.is_fenchel() || !loss.is_fenchel()) { cerr << "Error: no duality gap available" << endl; exit(1); } T primal= loss.eval(x)+lambda*regularizer.eval(x); bool intercept=regularizer.is_intercept(); D grad1, grad2; loss.var_fenchel(x,grad1,grad2,intercept); grad2.scal(-T(1.0)/lambda); T val=0; T scal=1.0; regularizer.fenchel(grad2,val,scal); T dual = -lambda*val; grad1.scal(scal); dual -= loss.fenchel(grad1); dual = MAX(dual,best_dual); T delta= primal == 0 ? 0 : (primal-dual)/primal; if (verbose) { cout << "Relative duality gap: " << delta << endl; flush(cout); } best_dual=dual; return delta; } template <typename T, typename D, typename E> T duality_gap(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x, const T lambda, const bool verbose = false) { T best_dual=-INFINITY; return duality_gap(loss,regularizer,x,lambda,best_dual,verbose); } template <typename T> void dualityGraph(const Matrix<T>& X, const Matrix<T>& D, const Matrix<T>& alpha0, Vector<T>& res, const ParamFISTA<T>& param, const GraphStruct<T>* graph_st) { Regularizer<T>* regularizer=new GraphLasso<T>(*graph_st, param.intercept,param.resetflow,param.pos,param.clever); Loss<T>* loss; switch (param.loss) { case SQUARE: loss=new SqLoss<T>(D); break; case LOG: loss = new LogLoss<T>(D); break; case LOGWEIGHT: loss = new LogLoss<T,true>(D); break; default: cerr << "Not implemented"; exit(1); } Vector<T> Xi; X.refCol(0,Xi); loss->init(Xi); Vector<T> alpha0i; alpha0.refCol(0,alpha0i); regularizer->reset(); res[0]=loss->eval(alpha0i)+param.lambda*regularizer->eval(alpha0i); res[1]=duality_gap(*loss,*regularizer,alpha0i,param.lambda); delete(loss); delete(regularizer); } template <typename T> void writeLog(const int iter, const T time, const T primal, const T dual, char* name) { std::ofstream f; f.precision(12); f.flags(std::ios_base::scientific); f.open(name, ofstream::app); f << iter << " " << primal << " " << dual << " " << time << std::endl; f.close(); }; template <typename T, typename D, typename E> void subGradientDescent_Generic(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x0, D& x, Vector<T>& optim_info, const ParamFISTA<T>& param) { D grad; D sub_grad; const T lambda=param.lambda; const int it0 = MAX(1,param.it0); const bool duality = loss.is_fenchel() && regularizer.is_fenchel(); optim_info.set(-1); T best_dual=-INFINITY; T rel_duality_gap=-INFINITY; Timer time; time.start(); int it; for (it = 1; it<=param.max_it; ++it) { /// print loss if (param.verbose && ((it % it0) == 0)) { time.stop(); T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << " "; if (param.log) writeLog(it,sec,los,best_dual,param.logName); if (param.verbose) cout << endl; flush(cout); time.start(); } /// compute gradient loss.grad(x,grad); regularizer.sub_grad(x,sub_grad); T step = param.sqrt_step ? param.a/(param.b+sqrt(static_cast<T>(it))) : param.a/(param.b+(static_cast<T>(it))); x.add(grad,-step); x.add(sub_grad,-lambda*step); if (duality && ((it % it0) == 0)) { time.stop(); rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; if (rel_duality_gap < param.tol) break; time.start(); } } if ((it % it0) != 0 || !param.verbose) { T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; if (duality) { rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; } } optim_info[3]=it; } template <typename T, typename D, typename E> void ISTA_Generic(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x0, D& x, Vector<T>& optim_info, const ParamFISTA<T>& param) { const int it0 = MAX(1,param.it0); const T lambda=param.lambda; T L=param.L0; T Lold=L; x.copy(x0); D grad, tmp, prox, old; const bool duality = loss.is_fenchel() && regularizer.is_fenchel(); optim_info.set(-1); Timer time; time.start(); T rel_duality_gap=-INFINITY; int it; T best_dual=-INFINITY; for (it = 1; it<=param.max_it; ++it) { /// print loss if (param.verbose && ((it % it0) == 0)) { time.stop(); T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L; flush(cout); if (param.log) writeLog(it,sec,los,best_dual,param.logName); time.start(); } /// compute gradient loss.grad(x,grad); int iter=1; while (iter < param.max_iter_backtracking) { prox.copy(x); prox.add(grad,-T(1.0)/L); regularizer.prox(prox,tmp,lambda/L); Lold=L; if (loss.test_backtracking(x,grad,tmp,L)) { break; } L *= param.gamma; if (param.verbose && ((it % it0) == 0)) cout << " " << L; ++iter; } if (param.verbose && ((it % it0) == 0)) cout << endl; old.copy(x); x.copy(tmp); if (duality) { if ((it % it0) == 0) { time.stop(); rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; if (rel_duality_gap < param.tol) break; time.start(); } } else { old.sub(x); if (sqrt(old.nrm2sq()/MAX(EPSILON,x.nrm2sq())) < param.tol) break; } } T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L << endl; flush(cout); } if (duality) { rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; } optim_info[3]=it; } template <typename T, typename D, typename E> void FISTA_Generic(Loss<T,D,E>& loss, Regularizer<T,D>& regularizer, const D& x0, D& x, Vector<T>& optim_info, const ParamFISTA<T>& param) { const int it0 = MAX(1,param.it0); const T lambda=param.lambda; T L=param.L0; T t = 1.0; T Lold=L; T old_t; D y, grad, prox, tmp; y.copy(x0); x.copy(x0); const bool duality = loss.is_fenchel() && regularizer.is_fenchel(); T rel_duality_gap=-INFINITY; optim_info.set(-1); Timer time; time.start(); int it; T best_dual=-INFINITY; for (it = 1; it<=param.max_it; ++it) { /// print loss if (param.verbose && ((it % it0) == 0)) { time.stop(); T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L; flush(cout); if (param.log) writeLog(it,sec,los,best_dual,param.logName); time.start(); } /// compute gradient loss.grad(y,grad); int iter=1; while (iter < param.max_iter_backtracking) { prox.copy(y); prox.add(grad,-T(1.0)/L); regularizer.prox(prox,tmp,lambda/L); Lold=L; if (param.fixed_step || loss.test_backtracking(y,grad,tmp,L)) break; L *= param.gamma; if (param.verbose && ((it % it0) == 0)) cout << " " << L; ++iter; } if (param.verbose && ((it % it0) == 0)) cout << endl; prox.copy(x); prox.sub(tmp); x.copy(tmp); old_t=t; t=(1.0+sqrt(1+4*t*t))/2; y.copy(x); y.add(prox,(1-old_t)/t); if (duality) { if ((it % it0) == 0) { time.stop(); rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; if (rel_duality_gap < param.tol) break; time.start(); } } else { if (sqrt(prox.nrm2sq()/MAX(EPSILON,x.nrm2sq())) < param.tol) break; } } T los=loss.eval(x) + lambda*regularizer.eval(x); optim_info[0]=los; T sec=time.getElapsed(); if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << ", L: " << L << endl; flush(cout); } if (duality) { rel_duality_gap=duality_gap(loss,regularizer,x,lambda,best_dual,param.verbose); optim_info[1]=best_dual; optim_info[2]=rel_duality_gap; } optim_info[3]=it; }; template <typename T> T LagrangianADMM(const SplittingFunction<T, Matrix<T> >& loss, const SplittingFunction<T, SpMatrix<T> >& reg, const T lambda, const T gamma, const Vector<T>& w, const Matrix<T>& splitted_loss, const SpMatrix<T>& splitted_reg, const Matrix<T>& multi_loss, const SpMatrix<T>& multi_reg, T& los, const T* weights = NULL) { const int n_reg=reg.num_components(); //T loss_val = loss.eval(w) + lambda*reg.eval(w); T lagrangian = loss.eval_split(splitted_loss) + lambda*reg.eval_split(splitted_reg); Matrix<T> tmp; tmp.copy(splitted_loss); tmp.addVecToCols(w,-T(1.0)); T add =0.5*gamma*tmp.normFsq(); lagrangian += add; los+=add; if (n_reg > 0) { SpMatrix<T> stmp; stmp.copy(splitted_reg); stmp.addVecToCols(w,-T(1.0)); add=0.5*gamma*stmp.normFsq(); lagrangian += add; los+=add; lagrangian -= multi_reg.dot_direct(stmp); } lagrangian -= multi_loss.dot(tmp); return lagrangian; }; template <typename T> void update_multipliers_ADMM(Vector<T>& w, const Matrix<T>& splitted_w_loss, const Matrix<T>& multipliers_w_loss, const SpMatrix<T>& splitted_w_reg, const SpMatrix<T>& multipliers_w_reg, const T gamma) { Vector<T> mean(w.n()); splitted_w_loss.sum_cols(mean); w.copy(mean); multipliers_w_loss.sum_cols(mean); w.add(mean,-T(1.0)/gamma); Vector<T> number_occurences(w.n()); number_occurences.set(splitted_w_loss.n()); const int n_reg=splitted_w_reg.n(); if (n_reg > 0) { SpVector<T> col; mean.setZeros(); for (int i = 0; i<n_reg; ++i) { splitted_w_reg.refCol(i,col); mean.add(col); for (int j = 0; j<col.L(); ++j) number_occurences[col.r(j)]++; } w.add(mean); mean.setZeros(); for (int i = 0; i<n_reg; ++i) { multipliers_w_reg.refCol(i,col); mean.add(col); } w.add(mean,-T(1.0)/gamma); }; w.div(number_occurences); }; template <typename T> void update_multipliers_weighted_ADMM(Vector<T>& w, const Matrix<T>& splitted_w_loss, const Matrix<T>& multipliers_w_loss, const SpMatrix<T>& splitted_w_reg, const SpMatrix<T>& multipliers_w_reg, const T gamma, const T* inner_weights) { Vector<T> mean(w.n()); splitted_w_loss.sum_cols(mean); w.copy(mean); multipliers_w_loss.sum_cols(mean); w.add(mean,-T(1.0)/gamma); Vector<T> number_occurences(w.n()); number_occurences.set(splitted_w_loss.n()); const int n_reg=splitted_w_reg.n(); if (n_reg > 0) { SpVector<T> col; mean.setZeros(); for (int i = 0; i<n_reg; ++i) { splitted_w_reg.refCol(i,col); for (int j = 0; j<col.L(); ++j) { mean[col.r(j)]+=inner_weights[j]*col.v(j); number_occurences[col.r(j)]+=inner_weights[j]*inner_weights[j]; } } w.add(mean); mean.setZeros(); for (int i = 0; i<n_reg; ++i) { multipliers_w_reg.refCol(i,col); for (int j = 0; j<col.L(); ++j) mean[col.r(j)]+=inner_weights[j]*col.v(j); } w.add(mean,-T(1.0)/gamma); }; w.div(number_occurences); }; template <typename T> void ADMM(const SplittingFunction<T, Matrix<T> >& loss, const SplittingFunction<T, SpMatrix<T> >& reg, const Vector<T>& w0, Vector<T>& w, Vector<T>& optim_info, const ParamFISTA<T>& param) { const T gamma = param.c; const int n_reg=reg.num_components(); const int it0 = MAX(1,param.it0); const T lambda=param.lambda; w.copy(w0); Matrix<T> splitted_w_loss; SpMatrix<T> splitted_w_reg; Matrix<T> multipliers_w_loss; SpMatrix<T> multipliers_w_reg; loss.init_split_variables(multipliers_w_loss); reg.init_split_variables(multipliers_w_reg); splitted_w_loss.copy(multipliers_w_loss); splitted_w_loss.addVecToCols(w); if (n_reg > 0) { splitted_w_reg.copy(multipliers_w_reg); splitted_w_reg.addVecToCols(w); } Timer time; time.start(); int it=0; T los; T old_los=INFINITY; for (it = 0; it<param.max_it; ++it) { if (((it % it0) == 0)) { time.stop(); if (param.is_inner_weights) { los= loss.eval(w)+lambda*reg.eval_weighted(w,splitted_w_reg, param.inner_weights); } else { los= loss.eval(w)+lambda*reg.eval(w); } optim_info[0]=los; T sec=time.getElapsed(); optim_info[2]=sec; if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << endl; flush(cout); if (param.log) writeLog(it,sec,los,T(0),param.logName); } time.start(); } if (param.is_inner_weights) { /// update w update_multipliers_weighted_ADMM(w,splitted_w_loss,multipliers_w_loss,splitted_w_reg,multipliers_w_reg,gamma,param.inner_weights); /// update the splitting variables splitted_w_loss.copy(multipliers_w_loss); splitted_w_loss.scal((1.0)/gamma); splitted_w_loss.addVecToCols(w); loss.prox_split(splitted_w_loss,T(1.0)/gamma); if (n_reg > 0) { splitted_w_reg.copy(multipliers_w_reg); splitted_w_reg.scal((1.0)/gamma); splitted_w_reg.addVecToColsWeighted(w,param.inner_weights); reg.prox_split(splitted_w_reg,lambda/gamma); } /// update multipliers multipliers_w_loss.addVecToCols(w,gamma); multipliers_w_loss.add(splitted_w_loss,-gamma); if (n_reg > 0) { multipliers_w_reg.addVecToColsWeighted(w,param.inner_weights, gamma); multipliers_w_reg.add_direct(splitted_w_reg,-gamma); } } else { /// update w update_multipliers_ADMM(w,splitted_w_loss,multipliers_w_loss,splitted_w_reg,multipliers_w_reg,gamma); /// update the splitting variables splitted_w_loss.copy(multipliers_w_loss); splitted_w_loss.scal((1.0)/gamma); splitted_w_loss.addVecToCols(w); loss.prox_split(splitted_w_loss,T(1.0)/gamma); if (n_reg > 0) { splitted_w_reg.copy(multipliers_w_reg); splitted_w_reg.scal((1.0)/gamma); splitted_w_reg.addVecToCols(w); reg.prox_split(splitted_w_reg,lambda/gamma); } /// update multipliers multipliers_w_loss.addVecToCols(w,gamma); multipliers_w_loss.add(splitted_w_loss,-gamma); if (n_reg > 0) { multipliers_w_reg.addVecToCols(w,gamma); multipliers_w_reg.add_direct(splitted_w_reg,-gamma); } } /// stopping criterion if ((it % it0) == 0) { if (it > 0 && (old_los-los)/old_los < param.tol) break; old_los=los; } } if (param.is_inner_weights) { los= loss.eval(w)+lambda*reg.eval_weighted(w,splitted_w_reg, param.inner_weights); } else { los= loss.eval(w)+lambda*reg.eval(w); } optim_info[0]=los; optim_info[3]=it; }; template <typename T> void update_multipliers_LinADMM(Vector<T>& w, const SpMatrix<T>& splitted_w_reg, const SpMatrix<T>& multipliers_w_reg, const T gamma, const T delta) { Vector<T> mean(w.n()); Vector<T> number_occurences(w.n()); number_occurences.set(delta); const int n_reg=splitted_w_reg.n(); if (n_reg > 0) { SpVector<T> col; mean.setZeros(); for (int i = 0; i<n_reg; ++i) { splitted_w_reg.refCol(i,col); mean.add(col); for (int j = 0; j<col.L(); ++j) number_occurences[col.r(j)]+=gamma; } mean.scal(gamma); for (int i = 0; i<n_reg; ++i) { multipliers_w_reg.refCol(i,col); mean.add(col); } w.add(mean); }; w.div(number_occurences); }; template <typename T> void LinADMM(const SplittingFunction<T, Matrix<T> >& loss, const SplittingFunction<T, SpMatrix<T> >& reg, const Vector<T>& w0, Vector<T>& w, Vector<T>& optim_info, const ParamFISTA<T>& param) { const T gamma = param.c; const int n_reg=reg.num_components(); const int it0 = MAX(1,param.it0); const T lambda=param.lambda; w.copy(w0); SpMatrix<T> primal_reg; SpMatrix<T> dual_reg; reg.init_split_variables(dual_reg); if (n_reg > 0) { primal_reg.copy(dual_reg); primal_reg.addVecToCols(w); } Vector<T> prim_loss; loss.init_prim_var(prim_loss); Vector<T> dual_loss; dual_loss.copy(prim_loss); Timer time; time.start(); int it=0; T los; T old_los=INFINITY; for (it = 0; it<param.max_it; ++it) { /*w.print("w"); prim_loss.print("z"); dual_loss.print("nu"); primal_reg.print("zg"); dual_reg.print("nug");*/ if (((it % it0) == 0)) { time.stop(); los= loss.eval(w)+lambda*reg.eval(w); optim_info[0]=los; T sec=time.getElapsed(); optim_info[2]=sec; if (param.verbose) { cout << "Iter: " << it << ", loss: " << los << ", time: " << sec << endl; flush(cout); if (param.log) writeLog(it,sec,los,T(0),param.logName); } time.start(); } /// update primal_loss variables loss.prox_prim_var(prim_loss,dual_loss,w,gamma); /// update primal_reg variables if (n_reg > 0) { primal_reg.copy(dual_reg); primal_reg.scal(-(1.0)/gamma); primal_reg.addVecToCols(w); reg.prox_split(primal_reg,lambda/gamma); } /// update w loss.compute_new_prim(w,prim_loss,dual_loss,gamma,param.delta); update_multipliers_LinADMM(w,primal_reg,dual_reg,gamma,param.delta); /// update multipliers if (n_reg > 0) { dual_reg.addVecToCols(w,-gamma); dual_reg.add_direct(primal_reg,gamma); } loss.add_mult_design_matrix(w,dual_loss,-gamma); dual_loss.add(prim_loss,gamma); /// stopping criterion if ((it % it0) == 0) { if (it > 0 && (old_los-los)/old_los < param.tol) break; old_los=los; } } los= loss.eval(w)+lambda*reg.eval(w); optim_info[0]=los; optim_info[3]=it; }; template <typename T> SplittingFunction<T, SpMatrix<T> >* setRegularizerADMM(const ParamFISTA<T>& param, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL) { SplittingFunction<T, SpMatrix<T> >* reg; ParamReg<T> param_reg; param_reg.pos=param.pos; param_reg.intercept=param.intercept; param_reg.tree_st=const_cast<TreeStruct<T>* >(tree_st); param_reg.graph_st=const_cast<GraphStruct<T>* >(graph_st); param_reg.resetflow=param.resetflow; param_reg.clever=param.clever; switch (param.regul) { case GRAPH: param_reg.linf=true; reg=new GraphLasso<T>(param_reg); break; case GRAPH_L2: param_reg.linf=false; reg=new GraphLasso<T>(param_reg); break; case NONE: reg=new None<T>(); break; default: cerr << "Not implemented"; exit(1); } return reg; }; template <typename T> Regularizer<T>* setRegularizerVectors(const ParamFISTA<T>& param, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st=NULL) { ParamReg<T> param_reg; param_reg.pos=param.pos; param_reg.intercept=param.intercept; param_reg.lambda2d1=param.lambda2/param.lambda; param_reg.lambda3d1=param.lambda3/param.lambda; param_reg.size_group=param.size_group; param_reg.tree_st=const_cast<TreeStruct<T>* >(tree_st); param_reg.graph_st=const_cast<GraphStruct<T>* >(graph_st); param_reg.graph_path_st=const_cast<GraphPathStruct<T>* >(graph_path_st); param_reg.resetflow=param.resetflow; param_reg.clever=param.clever; param_reg.ngroups=param.ngroups; param_reg.groups=param.groups; Regularizer<T>* reg; switch (param.regul) { case L0: reg=new Lzero<T>(param_reg); break; case L1: reg=new Lasso<T>(param_reg); break; case L2: reg=new normL2<T>(param_reg); break; case LINF: reg=new normLINF<T>(param_reg); break; case RIDGE: reg=new Ridge<T>(param_reg); break; case ELASTICNET: reg=new typename ElasticNet<T>::type(param_reg); break; case FUSEDLASSO: reg=new FusedLasso<T>(param_reg); break; case TREE_L0: reg=new TreeLzero<T>(param_reg); break; case TREE_L2: param_reg.linf=false; reg=new TreeLasso<T>(param_reg); break; case TREE_LINF: param_reg.linf=true; reg=new TreeLasso<T>(param_reg); break; case GRAPH: param_reg.linf=true; reg=new GraphLasso<T>(param_reg); break; case GRAPH_RIDGE: param_reg.linf=true; reg=new typename GraphLassoRidge<T>::type(param_reg); break; case GRAPH_L2: param_reg.linf=false; reg=new GraphLasso<T>(param_reg); break; case TRACE_NORM_VEC: reg=new ProxMatToVec<T, TraceNorm<T> >(param_reg); break; case RANK_VEC: reg=new ProxMatToVec<T, Rank<T> >(param_reg); break; case GROUPLASSO_L2: reg=new typename GroupLassoL2<T>::type(param_reg); break; case GROUPLASSO_LINF: reg=new typename GroupLassoLINF<T>::type(param_reg); break; case GROUPLASSO_L2_L1: reg=new typename GroupLassoL2_L1<T>::type(param_reg); break; case GROUPLASSO_LINF_L1: reg=new typename GroupLassoLINF_L1<T>::type(param_reg); break; case GRAPH_PATH_L0: reg = new GraphPathL0<T>(param_reg); break; case GRAPH_PATH_CONV: reg = new GraphPathConv<T>(param_reg); break; case NONE: reg=new None<T>(); break; default: cerr << "Not implemented"; exit(1); } return reg; }; template <typename T> Regularizer<T, Matrix<T> >* setRegularizerMatrices(const ParamFISTA<T>& param, const int m, const int n, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st=NULL) { ParamReg<T> param_reg; param_reg.transpose=param.transpose; param_reg.pos=param.pos; param_reg.intercept=param.intercept; param_reg.lambda2d1=param.lambda2/param.lambda; param_reg.lambda3d1=param.lambda3/param.lambda; param_reg.size_group=param.size_group; param_reg.num_cols=param.transpose ? m : n; param_reg.tree_st=const_cast<TreeStruct<T>* >(tree_st); param_reg.graph_st=const_cast<GraphStruct<T>* >(graph_st); param_reg.resetflow=param.resetflow; param_reg.clever=param.clever; Regularizer<T, Matrix<T> >* reg; switch (param.regul) { case L0: reg=new RegMat<T, Lzero<T> >(param_reg); break; case L1: reg=new RegMat<T, Lasso<T> >(param_reg); break; case L2: reg=new RegMat<T, normL2<T> >(param_reg); break; case LINF: reg=new RegMat<T, normLINF<T> >(param_reg); break; case RIDGE: reg=new RegMat<T, Ridge<T> >(param_reg); break; case ELASTICNET: reg=new RegMat<T, typename ElasticNet<T>::type >(param_reg); break; case FUSEDLASSO: reg=new RegMat<T, FusedLasso<T> >(param_reg); break; case L1L2: reg=new MixedL1L2<T>(param_reg); break; case L1LINF: reg=new MixedL1LINF<T>(param_reg); break; case TRACE_NORM: reg=new TraceNorm<T>(param_reg); break; case RANK: reg=new Rank<T>(param_reg); break; case L1L2_L1: reg=new typename MixedL1L2_L1<T>::type(param_reg); break; case L1LINF_L1: reg=new typename MixedL1LINF_L1<T>::type(param_reg); break; case TREE_L0: reg=new RegMat<T, TreeLzero<T> >(param_reg); break; case TREE_L2: param_reg.linf=false; reg=new RegMat<T, TreeLasso<T> >(param_reg); break; case TREE_LINF: param_reg.linf=true; reg=new RegMat<T, TreeLasso<T> >(param_reg); break; case GRAPH: reg=new RegMat<T, GraphLasso<T> >(param_reg); break; case TREEMULT: reg = new TreeMult<T>(param_reg); break; case GRAPHMULT: reg=new GraphMult<T>(param_reg); break; case L1LINFCR: reg = new MixedL1LINFCR<T>(m,param_reg); break; case GRAPH_PATH_L0: reg = new RegMat<T, GraphPathL0<T> >(param_reg); break; case GRAPH_PATH_CONV: reg = new RegMat<T, GraphPathConv<T> >(param_reg); break; case NONE: reg=new RegMat<T, None<T> >(param_reg); break; default: cerr << "not implemented"; exit(1); } return reg; } template <typename T> void print_info_solver(const ParamFISTA<T>& param) { if (param.verbose) { print_loss(param.loss); print_regul(param.regul); if (param_for_admm(param)) { if (param.admm || param.lin_admm) { if (param.lin_admm) { cout << "Linearized ADMM algorithm" << endl; } else { cout << "ADMM algorithm" << endl; } } } else { if (param.ista) { cout << "ISTA algorithm" << endl; } else if (param.subgrad) { cout << "Subgradient descent" << endl; } else { cout << "FISTA algorithm" << endl; } if ((param.regul == GRAPH || param.regul == TREEMULT || param.regul == GRAPHMULT || param.regul==L1LINFCR) && param.clever) cout << "Projections with arc capacities" << endl; if (param.intercept) cout << "with intercept" << endl; if (param.log && param.logName) { cout << "log activated " << endl; cout << param.logName << endl; cout << endl; } } flush(cout); } }; template <typename T> void solver_admm(const Matrix<T>& X, const Matrix<T>& alpha0, Matrix<T>& alpha, Matrix<T>& optim_info, SplittingFunction<T, SpMatrix<T> >** regularizers, SplittingFunction<T, Matrix<T> >** losses, const ParamFISTA<T>& param) { const int M = X.n(); optim_info.resize(4,M); int i1; #pragma omp parallel for private(i1) for (i1 = 0; i1< M; ++i1) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i1,Xi); losses[numT]->init(Xi); Vector<T> alpha0i; alpha0.refCol(i1,alpha0i); Vector<T> alphai; alpha.refCol(i1,alphai); regularizers[numT]->reset(); Vector<T> optim_infoi; optim_info.refCol(i1,optim_infoi); if (param.admm || param.lin_admm) { if (param.lin_admm) { LinADMM(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else { ADMM(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } } } } template <typename T> void solver_aux1(const Matrix<T>& X, const Matrix<T>& alpha0, Matrix<T>& alpha, Matrix<T>& optim_info, Regularizer<T, Vector<T> >** regularizers, Loss<T, Vector<T> >** losses, const ParamFISTA<T>& param) { const int M = X.n(); if (param.verbose) { const bool duality = losses[0]->is_fenchel() && regularizers[0]->is_fenchel(); if (duality) cout << "Duality gap via Fenchel duality" << endl; if (!param.ista && param.subgrad && !regularizers[0]->is_subgrad()) { cerr << "Subgradient algorithm is not implemented for this combination of loss/regularization" << endl; exit(1); } cout << "Timings reported do not include loss and fenchel evaluation" << endl; flush(cout); } optim_info.resize(4,M); int i1; #pragma omp parallel for private(i1) for (i1 = 0; i1< M; ++i1) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i1,Xi); losses[numT]->init(Xi); Vector<T> alpha0i; alpha0.refCol(i1,alpha0i); Vector<T> alphai; alpha.refCol(i1,alphai); regularizers[numT]->reset(); Vector<T> optim_infoi; optim_info.refCol(i1,optim_infoi); if (param.ista) { ISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else if (param.subgrad) { subGradientDescent_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else { FISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } } } template <typename T> void solver_aux2(const Matrix<T>& X, const Matrix<T>& alpha0, Matrix<T>& alpha, Matrix<T>& optim_info, Regularizer<T, Matrix<T> >** regularizers, Loss<T, Matrix<T> >** losses, const ParamFISTA<T>& param) { const int M = X.n(); if (param.verbose) { const bool duality = losses[0]->is_fenchel() && regularizers[0]->is_fenchel(); if (duality) cout << "Duality gap via Fenchel duality" << endl; flush(cout); } optim_info.resize(4,M); int i2; #pragma omp parallel for private(i2) for (i2 = 0; i2< M; ++i2) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> Xi; X.refCol(i2,Xi); losses[numT]->init(Xi); const int N = alpha0.n()/X.n(); Matrix<T> alpha0i; alpha0.refSubMat(i2*N,N,alpha0i); Matrix<T> alphai; alpha.refSubMat(i2*N,N,alphai); regularizers[numT]->reset(); Vector<T> optim_infoi; optim_info.refCol(i2,optim_infoi); if (param.ista) { ISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else if (param.subgrad) { subGradientDescent_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } else { FISTA_Generic(*(losses[numT]),*(regularizers[numT]),alpha0i,alphai,optim_infoi,param); } } } /// AbstractMatrixB is basically either SpMatrix or Matrix template <typename T> void solver(const Matrix<T>& X, const AbstractMatrixB<T>& D, const Matrix<T>& alpha0, Matrix<T>& alpha, const ParamFISTA<T>& param1, Matrix<T>& optim_info, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st=NULL) { print_info_solver(param1); int num_threads=MIN(X.n(),param1.num_threads); num_threads=init_omp(num_threads); ParamFISTA<T> param=param1; param.copied=true; if (param_for_admm(param)) { if (num_threads > 1) param.verbose=false; SplittingFunction<T>** losses = new SplittingFunction<T>*[num_threads]; SplittingFunction<T, SpMatrix<T> >** regularizers= new SplittingFunction<T, SpMatrix<T> >*[num_threads]; for (int i = 0; i<num_threads; ++i) { regularizers[i]=setRegularizerADMM(param,graph_st,tree_st); switch (param.loss) { case SQUARE: losses[i]=new SqLoss<T>(D); break; case HINGE: losses[i] = new HingeLoss<T>(D); break; default: cerr << "Not implemented" << endl; exit(1); } } solver_admm(X, alpha0, alpha, optim_info, regularizers,losses,param); for (int i = 0; i<num_threads; ++i) { delete(losses[i]); delete(regularizers[i]); } delete[](losses); delete[](regularizers); } else { Matrix<T> G; if (param.loss==HINGE) { cerr << "Loss only implemented for ADMM" << endl; return; } if (param.compute_gram && (param.loss==SQUARE)) D.XtX(G); if (!loss_for_matrices(param.loss) && !(param.transpose || regul_for_matrices(param.regul))) { if (num_threads > 1) param.verbose=false; Loss<T>** losses = new Loss<T>*[num_threads]; Regularizer<T>** regularizers= new Regularizer<T>*[num_threads]; for (int i = 0; i<num_threads; ++i) { regularizers[i]=setRegularizerVectors(param,graph_st,tree_st,graph_path_st); switch (param.loss) { case SQUARE: if (param.compute_gram) { losses[i]=new SqLoss<T>(D,G); } else { losses[i]=new SqLoss<T>(D); } break; case SQUARE_MISSING: losses[i]=new SqLossMissing<T>(D); break; case LOG: losses[i] = new LogLoss<T>(D); break; case LOGWEIGHT: losses[i] = new LogLoss<T,true>(D); break; default: cerr << "Not implemented"; exit(1); } } solver_aux1(X, alpha0, alpha, optim_info, regularizers,losses,param); for (int i = 0; i<num_threads; ++i) { delete(losses[i]); losses[i]=NULL; delete(regularizers[i]); regularizers[i]=NULL; } delete[](losses); delete[](regularizers); } else if (loss_for_matrices(param.loss) && param.loss != CUR) { if (num_threads > 1) param.verbose=false; Loss<T, Matrix<T> >** losses = new Loss<T, Matrix<T> >*[num_threads]; Regularizer<T, Matrix<T> >** regularizers= new Regularizer<T, Matrix<T> >*[num_threads]; const int N = alpha0.n()/X.n(); for (int i = 0; i<num_threads; ++i) { regularizers[i]=setRegularizerMatrices(param,alpha0.m(),N,graph_st,tree_st,graph_path_st); switch (param.loss) { case MULTILOG: losses[i] = new MultiLogLoss<T>(D); break; default: cerr << "Not implemented"; exit(1); } } solver_aux2(X, alpha0, alpha, optim_info, regularizers,losses,param); for (int i = 0; i<num_threads; ++i) { delete(losses[i]); losses[i]=NULL; delete(regularizers[i]); regularizers[i]=NULL; } delete[](losses); delete[](regularizers); } else { /// (loss not for matrices and regul for matrices) or CUR Loss<T, Matrix<T>, Matrix<T> >* loss; Regularizer<T, Matrix<T> >* regularizer; switch (param.loss) { case SQUARE: if (param.compute_gram) { loss=new SqLossMat<T>(D,G); } else { loss=new SqLossMat<T>(D); } break; case SQUARE_MISSING: loss=new LossMat<T, SqLossMissing<T> >(X.n(),D); break; case LOG: loss = new LossMat<T, LogLoss<T,false> >(X.n(),D); break; case LOGWEIGHT: loss = new LossMat<T, LogLoss<T,true> >(X.n(),D); break; case CUR: loss = new LossCur<T>(D); break; default: cerr << "Not implemented"; exit(1); } regularizer=setRegularizerMatrices(param,alpha0.m(),alpha0.n(),graph_st,tree_st,graph_path_st); if (param.verbose) { const bool duality = loss->is_fenchel() && regularizer->is_fenchel(); if (duality) cout << "Duality gap via Fenchel duality" << endl; } loss->init(X); optim_info.resize(4,1); Vector<T> optim_infoi; optim_info.refCol(0,optim_infoi); if (param.ista) { ISTA_Generic(*loss,*regularizer,alpha0,alpha,optim_infoi,param); } else if (param.subgrad) { subGradientDescent_Generic(*loss,*regularizer,alpha0,alpha,optim_infoi,param); } else { FISTA_Generic(*loss,*regularizer,alpha0,alpha,optim_infoi,param); } delete(regularizer); delete(loss); } } }; template <typename T> void PROX(const Matrix<T>& alpha0, Matrix<T>& alpha, const ParamFISTA<T>& param, Vector<T>& val_loss, const GraphStruct<T>* graph_st = NULL, const TreeStruct<T>* tree_st = NULL, const GraphPathStruct<T>* graph_path_st = NULL) { if (param.verbose) { print_regul(param.regul); if ((param.regul == GRAPH || param.regul == TREEMULT || param.regul == GRAPHMULT || param.regul==L1LINFCR) && param.clever) cout << "Projections with arc capacities" << endl; if (param.intercept) cout << "with intercept" << endl; flush(cout); } int num_threads=MIN(alpha.n(),param.num_threads); num_threads=init_omp(num_threads); const int M = alpha.n(); if (!graph_st && param.regul==GRAPH) { cerr << "Graph structure should be provided" << endl; return; } if (!regul_for_matrices(param.regul)) { Regularizer<T>** regularizers= new Regularizer<T>*[num_threads]; for (int i = 0; i<num_threads; ++i) regularizers[i]=setRegularizerVectors(param,graph_st,tree_st,graph_path_st); int i; if (param.eval) val_loss.resize(M); #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> alpha0i; alpha0.refCol(i,alpha0i); Vector<T> alphai; alpha.refCol(i,alphai); regularizers[numT]->reset(); regularizers[numT]->prox(alpha0i,alphai,param.lambda); if (param.eval) val_loss[i]=regularizers[numT]->eval(alphai); } for (i = 0; i<num_threads; ++i) { delete(regularizers[i]); regularizers[i]=NULL; } delete[](regularizers); } else { /// regul for matrices if (param.eval) val_loss.resize(1); Regularizer<T, Matrix<T> >* regularizer; regularizer=setRegularizerMatrices(param,alpha0.m(),alpha0.n(),graph_st,tree_st,graph_path_st); regularizer->prox(alpha0,alpha,param.lambda); if (param.eval) val_loss[0]=regularizer->eval(alpha); delete(regularizer); } }; template <typename T> void EvalGraphPath(const Matrix<T>& alpha0, const ParamFISTA<T>& param, Vector<T>& val_loss, const GraphPathStruct<T>* graph_path_st, SpMatrix<T>* paths = NULL) { if (param.verbose) { print_regul(param.regul); if (param.intercept) cout << "with intercept" << endl; flush(cout); } int num_threads=MIN(alpha0.n(),param.num_threads); num_threads=init_omp(num_threads); const int M = alpha0.n(); if (!regul_for_matrices(param.regul)) { Regularizer<T>** regularizers= new Regularizer<T>*[num_threads]; for (int i = 0; i<num_threads; ++i) regularizers[i]=setRegularizerVectors<T>(param,NULL,NULL,graph_path_st); int i; val_loss.resize(M); #pragma omp parallel for private(i) for (i = 0; i< M; ++i) { #ifdef _OPENMP int numT=omp_get_thread_num(); #else int numT=0; #endif Vector<T> alphai; alpha0.refCol(i,alphai); regularizers[numT]->reset(); if (i==0 && paths) { val_loss[i]=regularizers[numT]->eval_paths(alphai,*paths); } else { val_loss[i]=regularizers[numT]->eval(alphai); } } for (i = 0; i<num_threads; ++i) { delete(regularizers[i]); regularizers[i]=NULL; } delete[](regularizers); } else { cerr << "Not implemented" << endl; return; } }; } #endif
DRACC_OMP_040_Wrong_ordered_clause_yes.c
/* Data race between the values in countervar leading to changing results, by utilising the ordered construct the execution will be sequentially consistent. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define N 42000 int countervar[N]; int init(){ for(int i=0; i<N; i++){ countervar[i]=0; } return 0; } int count(){ #pragma omp target map(tofrom:countervar[0:N]) device(0) #pragma omp teams distribute parallel for for (int i=1; i<N; i++){ countervar[i]=countervar[i-1]+1; } return 0; } int check(){ bool test = false; for(int i=0; i<N; i++){ if(countervar[i]!=i){ test = true; } } printf("Memory Access Issue visible: %s\n",test ? "true" : "false"); return 0; } int main(){ init(); count(); check(); return 0; }
delete_inf_refcount.c
// RUN: %libomptarget-compile-run-and-check-generic // fails with error message 'Unable to generate target entries' on amdgcn // XFAIL: amdgcn-amd-amdhsa // XFAIL: amdgcn-amd-amdhsa-newRTL #include <stdio.h> #include <omp.h> #pragma omp declare target int isHost; #pragma omp end declare target int main(void) { isHost = -1; #pragma omp target enter data map(to: isHost) #pragma omp target { isHost = omp_is_initial_device(); } #pragma omp target update from(isHost) if (isHost < 0) { printf("Runtime error, isHost=%d\n", isHost); } #pragma omp target exit data map(delete: isHost) // CHECK: Target region executed on the device printf("Target region executed on the %s\n", isHost ? "host" : "device"); return isHost; }
opencl_zip_fmt_plug.c
/* * * This software is Copyright (c) 2012 Dhiru Kholia <dhiru at openwall.com> * with some code (c) 2012 Lukas Odzioba <ukasz@openwall.net> * and improvements (c) 2014 by magnum and JimF. * * This is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_zip; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_zip); #else #include <string.h> #include <openssl/des.h> #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "common.h" #include "misc.h" #include "common-opencl.h" #include "pkzip.h" #include "dyna_salt.h" #include "hmac_sha.h" #include "options.h" #include "stdint.h" #define OPENCL_FORMAT 1 #include "pbkdf2_hmac_sha1.h" #define FORMAT_LABEL "zip-opencl" #define FORMAT_NAME "ZIP" #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL AES" #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 # define SWAP(n) \ (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24)) #define BINARY_ALIGN MEM_ALIGN_NONE #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(my_salt*) #define SALT_ALIGN 4 typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH]; } zip_password; typedef struct { uint32_t v[(2 * KEY_LENGTH(3) + PWD_VER_LENGTH + 3) / 4]; } zip_hash; typedef struct { uint32_t iterations; uint32_t outlen; uint32_t skip_bytes; uint8_t length; uint8_t salt[64]; } zip_salt; typedef struct my_salt_t { dyna_salt dsalt; uint32_t comp_len; struct { uint16_t type : 4; uint16_t mode : 4; } v; unsigned char passverify[2]; unsigned char salt[SALT_LENGTH(3)]; //uint64_t data_key; // MSB of md5(data blob). We lookup using this. unsigned char datablob[1]; } my_salt; static my_salt *saved_salt; static unsigned char (*crypt_key)[WINZIP_BINARY_SIZE]; static cl_int cl_error; static zip_password *inbuffer; static zip_hash *outbuffer; static zip_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; static struct fmt_main *self; static size_t insize, outsize, settingsize; #define STEP 0 #define SEED 256 // This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" static const char * warn[] = { "xfer: ", ", crypt: ", ", xfer: " }; /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel); } static void create_clobj(size_t gws, struct fmt_main *self) { insize = sizeof(zip_password) * gws; outsize = sizeof(zip_hash) * gws; settingsize = sizeof(zip_salt); inbuffer = mem_calloc(1, insize); outbuffer = mem_alloc(outsize); crypt_key = mem_calloc(gws, sizeof(*crypt_key)); mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_setting = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting), &mem_setting), "Error while setting mem_salt kernel argument"); } static void release_clobj(void) { if (crypt_key) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(crypt_key); MEM_FREE(inbuffer); MEM_FREE(outbuffer); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { self = _self; opencl_prepare_dev(gpu_id); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d", PLAINTEXT_LENGTH, (int)sizeof(currentsalt.salt), (int)sizeof(outbuffer->v)); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl", gpu_id, build_opts); crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self, create_clobj, release_clobj, sizeof(zip_password), 0, db); // Auto tune execution from shared/included code. autotune_run(self, 1, 0, 1000); } } static void *get_salt(char *ciphertext) { int i; my_salt salt, *psalt; static unsigned char *ptr; /* extract data from "ciphertext" */ c8 *copy_mem = strdup(ciphertext); c8 *cp, *p; if (!ptr) ptr = mem_alloc_tiny(sizeof(my_salt*),sizeof(my_salt*)); p = copy_mem + WINZIP_TAG_LENGTH+1; /* skip over "$zip2$*" */ memset(&salt, 0, sizeof(salt)); cp = strtokm(p, "*"); // type salt.v.type = atoi((const char*)cp); cp = strtokm(NULL, "*"); // mode salt.v.mode = atoi((const char*)cp); cp = strtokm(NULL, "*"); // file_magic enum (ignored) cp = strtokm(NULL, "*"); // salt for (i = 0; i < SALT_LENGTH(salt.v.mode); i++) salt.salt[i] = (atoi16[ARCH_INDEX(cp[i<<1])]<<4) | atoi16[ARCH_INDEX(cp[(i<<1)+1])]; cp = strtokm(NULL, "*"); // validator salt.passverify[0] = (atoi16[ARCH_INDEX(cp[0])]<<4) | atoi16[ARCH_INDEX(cp[1])]; salt.passverify[1] = (atoi16[ARCH_INDEX(cp[2])]<<4) | atoi16[ARCH_INDEX(cp[3])]; cp = strtokm(NULL, "*"); // data len sscanf((const char *)cp, "%x", &salt.comp_len); // later we will store the data blob in our own static data structure, and place the 64 bit LSB of the // MD5 of the data blob into a field in the salt. For the first POC I store the entire blob and just // make sure all my test data is small enough to fit. cp = strtokm(NULL, "*"); // data blob // Ok, now create the allocated salt record we are going to return back to John, using the dynamic // sized data buffer. psalt = (my_salt*)mem_calloc(1, sizeof(my_salt) + salt.comp_len); psalt->v.type = salt.v.type; psalt->v.mode = salt.v.mode; psalt->comp_len = salt.comp_len; psalt->dsalt.salt_alloc_needs_free = 1; // we used mem_calloc, so JtR CAN free our pointer when done with them. memcpy(psalt->salt, salt.salt, sizeof(salt.salt)); psalt->passverify[0] = salt.passverify[0]; psalt->passverify[1] = salt.passverify[1]; // set the JtR core linkage stuff for this dyna_salt psalt->dsalt.salt_cmp_offset = SALT_CMP_OFF(my_salt, comp_len); psalt->dsalt.salt_cmp_size = SALT_CMP_SIZE(my_salt, comp_len, datablob, psalt->comp_len); if (strcmp((const char*)cp, "ZFILE")) { for (i = 0; i < psalt->comp_len; i++) psalt->datablob[i] = (atoi16[ARCH_INDEX(cp[i<<1])]<<4) | atoi16[ARCH_INDEX(cp[(i<<1)+1])]; } else { c8 *Fn, *Oh, *Ob; long len; uint32_t id; FILE *fp; Fn = strtokm(NULL, "*"); Oh = strtokm(NULL, "*"); Ob = strtokm(NULL, "*"); fp = fopen((const char*)Fn, "rb"); if (!fp) { psalt->v.type = 1; // this will tell the format to 'skip' this salt, it is garbage goto Bail; } sscanf((const char*)Oh, "%lx", &len); if (fseek(fp, len, SEEK_SET)) { fclose(fp); psalt->v.type = 1; goto Bail; } id = fget32LE(fp); if (id != 0x04034b50U) { fclose(fp); psalt->v.type = 1; goto Bail; } sscanf((const char*)Ob, "%lx", &len); if (fseek(fp, len, SEEK_SET)) { fclose(fp); psalt->v.type = 1; goto Bail; } if (fread(psalt->datablob, 1, psalt->comp_len, fp) != psalt->comp_len) { fclose(fp); psalt->v.type = 1; goto Bail; } fclose(fp); } Bail:; MEM_FREE(copy_mem); memcpy(ptr, &psalt, sizeof(my_salt*)); return (void*)ptr; } static void set_salt(void *salt) { saved_salt = *((my_salt**)salt); memcpy((char*)currentsalt.salt, saved_salt->salt, SALT_LENGTH(saved_salt->v.mode)); currentsalt.length = SALT_LENGTH(saved_salt->v.mode); currentsalt.iterations = KEYING_ITERATIONS; currentsalt.outlen = PWD_VER_LENGTH; currentsalt.skip_bytes = 2 * KEY_LENGTH(saved_salt->v.mode); HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy setting to gpu"); } #undef set_key static void set_key(char *key, int index) { uint8_t length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; inbuffer[index].length = length; memcpy(inbuffer[index].v, key, length); } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; uint8_t length = inbuffer[index].length; memcpy(ret, inbuffer[index].v, length); ret[length] = '\0'; return ret; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); if (saved_salt->v.type) { // This salt passed valid() but failed get_salt(). // Should never happen. memset(crypt_key, 0, count * WINZIP_BINARY_SIZE); return count; } /// Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run kernel"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); if (ocl_autotune_running) return count; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { if (!memcmp((unsigned char*)outbuffer[index].v, saved_salt->passverify, 2)) { unsigned char pwd_ver[4+64]; pbkdf2_sha1(inbuffer[index].v, inbuffer[index].length, saved_salt->salt, SALT_LENGTH(saved_salt->v.mode), KEYING_ITERATIONS, pwd_ver, KEY_LENGTH(saved_salt->v.mode), KEY_LENGTH(saved_salt->v.mode)); hmac_sha1(pwd_ver, KEY_LENGTH(saved_salt->v.mode), (const unsigned char*)saved_salt->datablob, saved_salt->comp_len, crypt_key[index], WINZIP_BINARY_SIZE); } else memset(crypt_key[index], 0, WINZIP_BINARY_SIZE); } return count; } static int cmp_all(void *binary, int count) { int i; for (i = 0; i < count; i++) if (((ARCH_WORD_32*)&(crypt_key[i]))[0] == ((ARCH_WORD_32*)binary)[0]) return 1; return 0; } static int cmp_one(void *binary, int index) { return (((ARCH_WORD_32*)&(crypt_key[index]))[0] == ((ARCH_WORD_32*)binary)[0]); } static int cmp_exact(char *source, int index) { void *b = winzip_common_binary(source); return !memcmp(b, crypt_key[index], sizeof(crypt_key[index])); } struct fmt_main fmt_opencl_zip = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, WINZIP_BENCHMARK_COMMENT, WINZIP_BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, WINZIP_BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_DYNA_SALT, { NULL }, { WINZIP_FORMAT_TAG }, winzip_common_tests }, { init, done, reset, fmt_default_prepare, winzip_common_valid, winzip_common_split, winzip_common_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash /* Not usable with $SOURCE_HASH$ */ }, fmt_default_dyna_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash /* Not usable with $SOURCE_HASH$ */ }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
GB_assign_zombie1.c
//------------------------------------------------------------------------------ // GB_assign_zombie1: delete all entries in C(:,j) for GB_assign //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // C(:,j)<!> = anything: GrB_Row_assign or GrB_Col_assign with an empty // complemented mask requires all entries in the C(:,j) vector to be deleted. #include "GB_assign.h" void GB_assign_zombie1 ( GrB_Matrix C, const int64_t j, GB_Context Context ) { //-------------------------------------------------------------------------- // get C(:,j) //-------------------------------------------------------------------------- int64_t *GB_RESTRICT Ci = C->i ; int64_t pC_start, pC_end, pleft = 0, pright = C->nvec-1 ; GB_lookup (C->is_hyper, C->h, C->p, &pleft, pright, j, &pC_start, &pC_end) ; int64_t cjnz = pC_end - pC_start ; int64_t nzombies = C->nzombies ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (cjnz, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // C(:,j) = empty //-------------------------------------------------------------------------- int64_t pC ; #pragma omp parallel for num_threads(nthreads) schedule(static) \ reduction(+:nzombies) for (pC = pC_start ; pC < pC_end ; pC++) { int64_t i = Ci [pC] ; if (!GB_IS_ZOMBIE (i)) { // delete C(i,j) by marking it as a zombie nzombies++ ; Ci [pC] = GB_FLIP (i) ; } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- C->nzombies = nzombies ; }
bfs_replicated.c
/* 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 */ #define _GNU_SOURCE #include "common.h" #include "oned_csr.h" #include "onesided.h" #include <mpi.h> #include <stdint.h> #include <inttypes.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <limits.h> #include <assert.h> char IMPLEMENTATION[] = "MPI BFS_REPLICATED"; static oned_csr_graph g; static int g_lg_local_queue_size; static int64_t g_local_queue_summary_size; static int64_t g_local_queue_size; static int64_t g_global_queue_summary_size; static int64_t g_global_queue_size; static unsigned long* g_in_queue; static unsigned long* g_in_queue_summary; static unsigned long* g_out_queue; static unsigned long* g_out_queue_summary; static unsigned long* g_visited; static void allocate_memory(void) { int64_t maxlocalverts = g.max_nlocalverts; int lg_local_queue_size = lg_int64_t((maxlocalverts + ulong_bits_squared - 1) / ulong_bits_squared * ulong_bits_squared); g_lg_local_queue_size = lg_local_queue_size; int64_t local_queue_summary_size = (INT64_C(1) << lg_local_queue_size) / ulong_bits_squared; int64_t local_queue_size = local_queue_summary_size * ulong_bits; g_local_queue_summary_size = local_queue_summary_size; g_local_queue_size = local_queue_size; int64_t global_queue_summary_size = MUL_SIZE(local_queue_summary_size); int64_t global_queue_size = MUL_SIZE(local_queue_size); g_global_queue_summary_size = global_queue_summary_size; g_global_queue_size = global_queue_size; g_in_queue = (unsigned long*)xmalloc(global_queue_size * sizeof(unsigned long)); g_in_queue_summary = (unsigned long*)xmalloc(global_queue_summary_size * sizeof(unsigned long)); g_out_queue = (unsigned long*)xmalloc(local_queue_size * sizeof(unsigned long)); g_out_queue_summary = (unsigned long*)xmalloc(local_queue_summary_size * sizeof(unsigned long)); g_visited = (unsigned long*)xmalloc(local_queue_size * sizeof(unsigned long)); } static void deallocate_memory(void) { free(g_in_queue); g_in_queue = NULL; free(g_in_queue_summary); g_in_queue_summary = NULL; free(g_out_queue); g_out_queue = NULL; free(g_out_queue_summary); g_out_queue_summary = NULL; free(g_visited); g_visited = NULL; } void make_graph_data_structure(const tuple_graph* const tg) { convert_graph_to_oned_csr(tg, &g); allocate_memory(); /* Make sure all of the space is available */ deallocate_memory(); } void free_graph_data_structure(void) { free_oned_csr_graph(&g); /* deallocate_memory(); */ } int bfs_writes_depth_map(void) {return 1;} /* This version is the traditional level-synchronized BFS using two queues. A * bitmap is used to indicate which vertices have been visited. Messages are * sent and processed asynchronously throughout the code to hopefully overlap * communication with computation. */ void run_bfs(int64_t root, int64_t* pred) { allocate_memory(); const ptrdiff_t nlocalverts = g.nlocalverts; const size_t* const restrict rowstarts = g.rowstarts; const int64_t* const restrict column = g.column; /* Set up the visited bitmap. */ const int ulong_bits = sizeof(unsigned long) * CHAR_BIT; const int ulong_bits_squared = ulong_bits * ulong_bits; int64_t local_queue_summary_size = g_local_queue_summary_size; int64_t local_queue_size = g_local_queue_size; int lg_local_queue_size = g_lg_local_queue_size; int64_t global_queue_summary_size = g_global_queue_summary_size; int64_t global_queue_size = g_global_queue_size; #define SWIZZLE_VERTEX(c) (((int64_t)(VERTEX_OWNER(c)) << lg_local_queue_size) | (int64_t)(VERTEX_LOCAL(c))) #if 0 int64_t* restrict column_swizzled = (int64_t*)xmalloc(nlocaledges * sizeof(int64_t)); { size_t i; for (i = 0; i < nlocaledges; ++i) { int64_t c = column[i]; column_swizzled[i] = SWIZZLE_VERTEX(c); } } #endif unsigned long* restrict in_queue = g_in_queue; memset(in_queue, 0, global_queue_size * sizeof(unsigned long)); unsigned long* restrict in_queue_summary = g_in_queue_summary; memset(in_queue_summary, 0, global_queue_summary_size * sizeof(unsigned long)); unsigned long* restrict out_queue = g_out_queue; unsigned long* restrict out_queue_summary = g_out_queue_summary; unsigned long* restrict visited = g_visited; memset(visited, 0, local_queue_size * sizeof(unsigned long)); #define SET_IN(v) do {int64_t vs = SWIZZLE_VERTEX(v); size_t word_idx = vs / ulong_bits; int bit_idx = vs % ulong_bits; unsigned long mask = (1UL << bit_idx); in_queue_summary[word_idx / ulong_bits] |= (1UL << (word_idx % ulong_bits)); in_queue[word_idx] |= mask;} while (0) #define TEST_IN(vs) (((in_queue_summary[vs / ulong_bits / ulong_bits] & (1UL << ((vs / ulong_bits) % ulong_bits))) != 0) && ((in_queue[vs / ulong_bits] & (1UL << (vs % ulong_bits))) != 0)) #define TEST_VISITED_LOCAL(v) ((visited[(v) / ulong_bits] & (1UL << ((v) % ulong_bits))) != 0) // #define SET_VISITED_LOCAL(v) do {size_t word_idx = (v) / ulong_bits; int bit_idx = (v) % ulong_bits; unsigned long mask = (1UL << bit_idx); __sync_fetch_and_or(&visited[word_idx], mask); __sync_fetch_and_or(&out_queue[word_idx], mask);} while (0) #define SET_VISITED_LOCAL(v) do {size_t word_idx = (v) / ulong_bits; int bit_idx = (v) % ulong_bits; unsigned long mask = (1UL << bit_idx); visited[word_idx] |= mask; out_queue[word_idx] |= mask;} while (0) SET_IN(root); {ptrdiff_t i; _Pragma("omp parallel for schedule(static)") for (i = 0; i < nlocalverts; ++i) pred[i] = -1;} if (VERTEX_OWNER(root) == rank) { pred[VERTEX_LOCAL(root)] = root; SET_VISITED_LOCAL(VERTEX_LOCAL(root)); } uint16_t cur_level = 0; while (1) { ++cur_level; #if 0 if (rank == 0) fprintf(stderr, "BFS level %" PRIu16 "\n", cur_level); #endif memset(out_queue, 0, (nlocalverts + ulong_bits - 1) / ulong_bits * sizeof(unsigned long)); // memset(out_queue_summary, 0, (nlocalverts + ulong_bits_squared - 1) / ulong_bits_squared * sizeof(unsigned long)); ptrdiff_t i, ii; #if 0 #pragma omp parallel for schedule(static) for (i = 0; i < global_queue_summary_size; ++i) { unsigned long val = 0UL; int j; unsigned long mask = 1UL; for (j = 0; j < ulong_bits; ++j, mask <<= 1) { if (in_queue[i * ulong_bits + j]) val |= mask; } in_queue_summary[i] = val; } #endif unsigned long not_done = 0; #pragma omp parallel for schedule(static) reduction(|:not_done) for (ii = 0; ii < nlocalverts; ii += ulong_bits) { size_t i, i_end = ii + ulong_bits; if (i_end > nlocalverts) i_end = nlocalverts; for (i = ii; i < i_end; ++i) { if (!TEST_VISITED_LOCAL(i)) { size_t j, j_end = rowstarts[i + 1]; for (j = rowstarts[i]; j < j_end; ++j) { int64_t v1 = column[j]; int64_t v1_swizzled = SWIZZLE_VERTEX(v1); if (TEST_IN(v1_swizzled)) { pred[i] = (v1 & INT64_C(0xFFFFFFFFFFFF)) | ((int64_t)cur_level << 48); not_done |= 1; SET_VISITED_LOCAL(i); break; } } } } } #if 1 #pragma omp parallel for schedule(static) for (i = 0; i < local_queue_summary_size; ++i) { unsigned long val = 0UL; int j; unsigned long mask = 1UL; for (j = 0; j < ulong_bits; ++j, mask <<= 1) { unsigned long full_val = out_queue[i * ulong_bits + j]; visited[i * ulong_bits + j] |= full_val; if (full_val) val |= mask; } out_queue_summary[i] = val; // not_done |= val; } #endif MPI_Allreduce(MPI_IN_PLACE, &not_done, 1, MPI_UNSIGNED_LONG, MPI_BOR, MPI_COMM_WORLD); if (not_done == 0) break; MPI_Allgather(out_queue, local_queue_size, MPI_UNSIGNED_LONG, in_queue, local_queue_size, MPI_UNSIGNED_LONG, MPI_COMM_WORLD); MPI_Allgather(out_queue_summary, local_queue_summary_size, MPI_UNSIGNED_LONG, in_queue_summary, local_queue_summary_size, MPI_UNSIGNED_LONG, MPI_COMM_WORLD); } deallocate_memory(); } void get_vertex_distribution_for_pred(size_t count, const int64_t* vertex_p, int* owner_p, size_t* local_p) { const int64_t* restrict vertex = vertex_p; int* restrict owner = owner_p; size_t* restrict local = local_p; ptrdiff_t i; #pragma omp parallel for for (i = 0; i < (ptrdiff_t)count; ++i) { int64_t v = vertex[i]; owner[i] = VERTEX_OWNER(v); local[i] = VERTEX_LOCAL(v); } } int64_t vertex_to_global_for_pred(int v_rank, size_t v_local) { return VERTEX_TO_GLOBAL(v_rank, v_local); } size_t get_nlocalverts_for_pred(void) { return g.nlocalverts; }
cvsAdvDiff_bnd_omp.c
/* ----------------------------------------------------------------- * Programmer(s): Daniel Reynolds and Ting Yan @ SMU * Based on cvsAdvDiff_bnd.c and parallelized with OpenMP * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2020, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example problem: * * The following is a simple example problem with a banded Jacobian, * solved using CVODES. * The problem is the semi-discrete form of the advection-diffusion * equation in 2-D: * du/dt = d^2 u / dx^2 + .5 du/dx + d^2 u / dy^2 * on the rectangle 0 <= x <= 2, 0 <= y <= 1, and the time * interval 0 <= t <= 1. Homogeneous Dirichlet boundary conditions * are posed, and the initial condition is * u(x,y,t=0) = x(2-x)y(1-y)exp(5xy). * The PDE is discretized on a uniform MX+2 by MY+2 grid with * central differencing, and with boundary values eliminated, * leaving an ODE system of size NEQ = MX*MY. * This program solves the problem with the BDF method, Newton * iteration with the BAND linear solver, and a user-supplied * Jacobian routine. * It uses scalar relative and absolute tolerances. * Output is printed at t = .1, .2, ..., 1. * Run statistics (optional outputs) are printed at the end. * * Optionally, we can set the number of threads from environment * variable or command line. To check the current value for number * of threads from environment: * % echo $OMP_NUM_THREADS * * Execution: * * To use the default value or the number of threads from the * environment value, run without arguments: * % ./cvsAdvDiff_bnd_omp * The environment variable can be over-ridden with a command line * argument specifying the number of threads to use, e.g: * % ./cvsAdvDiff_bnd_omp 5 * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> /* Header files with a description of contents */ #include <cvodes/cvodes.h> /* prototypes for CVODE fcts., consts. */ #include <nvector/nvector_openmp.h> /* serial N_Vector types, fcts., macros */ #include <sunmatrix/sunmatrix_band.h> /* access to band SUNMatrix */ #include <sunlinsol/sunlinsol_band.h> /* access to band SUNLinearSolver */ #include <sundials/sundials_types.h> /* definition of type realtype */ #ifdef _OPENMP #include <omp.h> #endif /* Problem Constants */ #define XMAX RCONST(2.0) /* domain boundaries */ #define YMAX RCONST(1.0) #define MX 10 /* mesh dimensions */ #define MY 5 #define NEQ MX*MY /* number of equations */ #define ATOL RCONST(1.0e-5) /* scalar absolute tolerance */ #define T0 RCONST(0.0) /* initial time */ #define T1 RCONST(0.1) /* first output time */ #define DTOUT RCONST(0.1) /* output time increment */ #define NOUT 10 /* number of output times */ #define ZERO RCONST(0.0) #define HALF RCONST(0.5) #define ONE RCONST(1.0) #define TWO RCONST(2.0) #define FIVE RCONST(5.0) /* User-defined vector access macro IJth */ /* IJth is defined in order to isolate the translation from the mathematical 2-dimensional structure of the dependent variable vector to the underlying 1-dimensional storage. IJth(vdata,i,j) references the element in the vdata array for u at mesh point (i,j), where 1 <= i <= MX, 1 <= j <= MY. The vdata array is obtained via the macro call vdata = NV_DATA_S(v), where v is an N_Vector. The variables are ordered by the y index j, then by the x index i. */ #define IJth(vdata,i,j) (vdata[(j-1) + (i-1)*MY]) /* Type : UserData (contains grid constants) */ typedef struct { realtype dx, dy, hdcoef, hacoef, vdcoef; int nthreads; } *UserData; /* Private Helper Functions */ static void SetIC(N_Vector u, UserData data); static void PrintHeader(realtype reltol, realtype abstol, realtype umax); static void PrintOutput(realtype t, realtype umax, long int nst); static void PrintFinalStats(void *cvode_mem); /* Private function to check function return values */ static int check_retval(void *returnvalue, char *funcname, int opt); /* Functions Called by the Solver */ static int f(realtype t, N_Vector u, N_Vector udot, void *user_data); static int Jac(realtype t, N_Vector u, N_Vector fu, SUNMatrix J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3); /* *------------------------------- * Main Program *------------------------------- */ int main(int argc, char *argv[]) { realtype dx, dy, reltol, abstol, t, tout, umax; N_Vector u; UserData data; SUNMatrix A; SUNLinearSolver LS; void *cvode_mem; int iout, retval; long int nst; int num_threads; u = NULL; data = NULL; A = NULL; LS = NULL; cvode_mem = NULL; /* Set the number of threads to use */ num_threads = 1; /* default value */ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* Overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrite with command line value, if supplied */ num_threads = (int) strtol(argv[1], NULL, 0); /* Create an OpenMP vector */ u = N_VNew_OpenMP(NEQ, num_threads); /* Allocate u vector */ if(check_retval((void*)u, "N_VNew_OpenMP", 0)) return(1); reltol = ZERO; /* Set the tolerances */ abstol = ATOL; data = (UserData) malloc(sizeof *data); /* Allocate data memory */ if(check_retval((void *)data, "malloc", 2)) return(1); dx = data->dx = XMAX/(MX+1); /* Set grid coefficients in data */ dy = data->dy = YMAX/(MY+1); data->hdcoef = ONE/(dx*dx); data->hacoef = HALF/(TWO*dx); data->vdcoef = ONE/(dy*dy); data->nthreads = num_threads; SetIC(u, data); /* Initialize u vector */ /* Call CVodeCreate to create the solver memory and specify the * Backward Differentiation Formula */ cvode_mem = CVodeCreate(CV_BDF); if(check_retval((void *)cvode_mem, "CVodeCreate", 0)) return(1); /* Call CVodeInit to initialize the integrator memory and specify the * user's right hand side function in u'=f(t,u), the inital time T0, and * the initial dependent variable vector u. */ retval = CVodeInit(cvode_mem, f, T0, u); if(check_retval(&retval, "CVodeInit", 1)) return(1); /* Call CVodeSStolerances to specify the scalar relative tolerance * and scalar absolute tolerance */ retval = CVodeSStolerances(cvode_mem, reltol, abstol); if (check_retval(&retval, "CVodeSStolerances", 1)) return(1); /* Set the pointer to user-defined data */ retval = CVodeSetUserData(cvode_mem, data); if(check_retval(&retval, "CVodeSetUserData", 1)) return(1); /* Create banded SUNMatrix for use in linear solves -- since this will be factored, set the storage bandwidth to be the sum of upper and lower bandwidths */ A = SUNBandMatrix(NEQ, MY, MY); if(check_retval((void *)A, "SUNBandMatrix", 0)) return(1); /* Create banded SUNLinearSolver object for use by CVode */ LS = SUNLinSol_Band(u, A); if(check_retval((void *)LS, "SUNLinSol_Band", 0)) return(1); /* Call CVodeSetLinearSolver to attach the matrix and linear solver to CVode */ retval = CVodeSetLinearSolver(cvode_mem, LS, A); if(check_retval(&retval, "CVodeSetLinearSolver", 1)) return(1); /* Set the user-supplied Jacobian routine Jac */ retval = CVodeSetJacFn(cvode_mem, Jac); if(check_retval(&retval, "CVodeSetJacFn", 1)) return(1); /* In loop over output points: call CVode, print results, test for errors */ umax = N_VMaxNorm(u); PrintHeader(reltol, abstol, umax); for(iout=1, tout=T1; iout <= NOUT; iout++, tout += DTOUT) { retval = CVode(cvode_mem, tout, u, &t, CV_NORMAL); if(check_retval(&retval, "CVode", 1)) break; umax = N_VMaxNorm(u); retval = CVodeGetNumSteps(cvode_mem, &nst); check_retval(&retval, "CVodeGetNumSteps", 1); PrintOutput(t, umax, nst); } PrintFinalStats(cvode_mem); /* Print some final statistics */ printf("num_threads = %i\n\n", num_threads); N_VDestroy(u); /* Free the u vector */ CVodeFree(&cvode_mem); /* Free the integrator memory */ SUNLinSolFree(LS); /* Free the linear solver memory */ SUNMatDestroy(A); /* Free the matrix memory */ free(data); /* Free the user data */ return(0); } /* *------------------------------- * Functions called by the solver *------------------------------- */ /* f routine. Compute f(t,u). */ static int f(realtype t, N_Vector u,N_Vector udot, void *user_data) { realtype uij, udn, uup, ult, urt, hordc, horac, verdc, hdiff, hadv, vdiff; realtype *udata, *dudata; sunindextype i, j; UserData data; i = j = 0; udata = NV_DATA_OMP(u); dudata = NV_DATA_OMP(udot); /* Extract needed constants from data */ data = (UserData) user_data; hordc = data->hdcoef; horac = data->hacoef; verdc = data->vdcoef; /* Loop over all grid points. */ #pragma omp parallel for default(shared) private(j, i, uij, udn, uup, ult, urt, hdiff, hadv, vdiff) num_threads(data->nthreads) for (j=1; j <= MY; j++) { for (i=1; i <= MX; i++) { /* Extract u at x_i, y_j and four neighboring points */ uij = IJth(udata, i, j); udn = (j == 1) ? ZERO : IJth(udata, i, j-1); uup = (j == MY) ? ZERO : IJth(udata, i, j+1); ult = (i == 1) ? ZERO : IJth(udata, i-1, j); urt = (i == MX) ? ZERO : IJth(udata, i+1, j); /* Set diffusion and advection terms and load into udot */ hdiff = hordc*(ult - TWO*uij + urt); hadv = horac*(urt - ult); vdiff = verdc*(uup - TWO*uij + udn); IJth(dudata, i, j) = hdiff + hadv + vdiff; } } return(0); } /* Jacobian routine. Compute J(t,u). */ static int Jac(realtype t, N_Vector u, N_Vector fu, SUNMatrix J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3) { sunindextype i, j, k; realtype *kthCol, hordc, horac, verdc; UserData data; /* The components of f = udot that depend on u(i,j) are f(i,j), f(i-1,j), f(i+1,j), f(i,j-1), f(i,j+1), with df(i,j)/du(i,j) = -2 (1/dx^2 + 1/dy^2) df(i-1,j)/du(i,j) = 1/dx^2 + .25/dx (if i > 1) df(i+1,j)/du(i,j) = 1/dx^2 - .25/dx (if i < MX) df(i,j-1)/du(i,j) = 1/dy^2 (if j > 1) df(i,j+1)/du(i,j) = 1/dy^2 (if j < MY) */ i = j = k = 0; data = (UserData) user_data; hordc = data->hdcoef; horac = data->hacoef; verdc = data->vdcoef; #pragma omp parallel for collapse(2) default(shared) private(i, j, k, kthCol) num_threads(data->nthreads) for (j=1; j <= MY; j++) { for (i=1; i <= MX; i++) { k = j-1 + (i-1)*MY; kthCol = SUNBandMatrix_Column(J,k); /* set the kth column of J */ SM_COLUMN_ELEMENT_B(kthCol,k,k) = -TWO*(verdc+hordc); if (i != 1) SM_COLUMN_ELEMENT_B(kthCol,k-MY,k) = hordc + horac; if (i != MX) SM_COLUMN_ELEMENT_B(kthCol,k+MY,k) = hordc - horac; if (j != 1) SM_COLUMN_ELEMENT_B(kthCol,k-1,k) = verdc; if (j != MY) SM_COLUMN_ELEMENT_B(kthCol,k+1,k) = verdc; } } return(0); } /* *------------------------------- * Private helper functions *------------------------------- */ /* Set initial conditions in u vector */ static void SetIC(N_Vector u, UserData data) { sunindextype i, j; realtype x, y, dx, dy; realtype *udata; i = j = 0; /* Extract needed constants from data */ dx = data->dx; dy = data->dy; /* Set pointer to data array in vector u. */ udata = NV_DATA_OMP(u); /* Load initial profile into u vector */ #pragma omp parallel for default(shared) private(j, i, y, x) for (j=1; j <= MY; j++) { y = j*dy; for (i=1; i <= MX; i++) { x = i*dx; IJth(udata,i,j) = x*(XMAX - x)*y*(YMAX - y)*exp(FIVE*x*y); } } } /* Print first lines of output (problem description) */ static void PrintHeader(realtype reltol, realtype abstol, realtype umax) { printf("\n2-D Advection-Diffusion Equation\n"); printf("Mesh dimensions = %d X %d\n", MX, MY); printf("Total system size = %d\n", NEQ); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: reltol = %Lg abstol = %Lg\n\n", reltol, abstol); printf("At t = %Lg max.norm(u) =%14.6Le \n", T0, umax); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: reltol = %g abstol = %g\n\n", reltol, abstol); printf("At t = %g max.norm(u) =%14.6e \n", T0, umax); #else printf("Tolerance parameters: reltol = %g abstol = %g\n\n", reltol, abstol); printf("At t = %g max.norm(u) =%14.6e \n", T0, umax); #endif return; } /* Print current value */ static void PrintOutput(realtype t, realtype umax, long int nst) { #if defined(SUNDIALS_EXTENDED_PRECISION) printf("At t = %4.2Lf max.norm(u) =%14.6Le nst = %4ld\n", t, umax, nst); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("At t = %4.2f max.norm(u) =%14.6e nst = %4ld\n", t, umax, nst); #else printf("At t = %4.2f max.norm(u) =%14.6e nst = %4ld\n", t, umax, nst); #endif return; } /* Get and print some final statistics */ static void PrintFinalStats(void *cvode_mem) { int retval; long int nst, nfe, nsetups, netf, nni, ncfn, nje, nfeLS; retval = CVodeGetNumSteps(cvode_mem, &nst); check_retval(&retval, "CVodeGetNumSteps", 1); retval = CVodeGetNumRhsEvals(cvode_mem, &nfe); check_retval(&retval, "CVodeGetNumRhsEvals", 1); retval = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups); check_retval(&retval, "CVodeGetNumLinSolvSetups", 1); retval = CVodeGetNumErrTestFails(cvode_mem, &netf); check_retval(&retval, "CVodeGetNumErrTestFails", 1); retval = CVodeGetNumNonlinSolvIters(cvode_mem, &nni); check_retval(&retval, "CVodeGetNumNonlinSolvIters", 1); retval = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn); check_retval(&retval, "CVodeGetNumNonlinSolvConvFails", 1); retval = CVodeGetNumJacEvals(cvode_mem, &nje); check_retval(&retval, "CVodeGetNumJacEvals", 1); retval = CVodeGetNumLinRhsEvals(cvode_mem, &nfeLS); check_retval(&retval, "CVodeGetNumLinRhsEvals", 1); printf("\nFinal Statistics:\n"); printf("nst = %-6ld nfe = %-6ld nsetups = %-6ld nfeLS = %-6ld nje = %ld\n", nst, nfe, nsetups, nfeLS, nje); printf("nni = %-6ld ncfn = %-6ld netf = %ld\n", nni, ncfn, netf); return; } /* Check function return value... opt == 0 means SUNDIALS function allocates memory so check if returned NULL pointer opt == 1 means SUNDIALS function returns an integer value so check if retval < 0 opt == 2 means function allocates memory so check if returned NULL pointer */ static int check_retval(void *returnvalue, char *funcname, int opt) { int *retval; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && returnvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } /* Check if retval < 0 */ else if (opt == 1) { retval = (int *) returnvalue; if (*retval < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n", funcname, *retval); return(1); }} /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && returnvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
deriche-dace.c
/* DaCe AUTO-GENERATED FILE. DO NOT MODIFY */ ////__DACE:0 #include <dace/dace.h> ////__DACE:0 ////__DACE:0 void FOR26_2_3_0(int& ___w, int& ___h, float* ___imgIn, int _argcount, int i) { ////__DACE:2:3:0 long long j; ////__DACE:3 ////__DACE:3 for (j = 0; (j < ___h); j = j+1) { ////__DACE:3:2 { ////__DACE:3:3 { ////__DACE:3:3:1 float imgIn; ////__DACE:3:3:1 ////__DACE:3:3:1 ////__DACE:3:3:1 ////__DACE:3:3:1 /////////////////// ////__DACE:3:3:1 ////__DACE:3:3:1 imgIn=float)(((313*i+991*j)%65536)/65535.0f; ////__DACE:3:3:1 ////__DACE:3:3:1 /////////////////// ////__DACE:3:3:1 ////__DACE:3:3:1 ////__DACE:3:3:1 ////__DACE:3:3:1 ___imgIn[((4096 * i) + j)] = imgIn; ////__DACE:3:3:1 ////__DACE:3:3:1 } ////__DACE:3:3:1 } ////__DACE:3:3 } ////__DACE:3:2 } ////__DACE:2:3:0 ////__DACE:2:3:0 void init_array_1_0_4(int& __w, int& __h, float& __alpha, float* __imgIn, int _argcount) { ////__DACE:1:0:4 long long i; ////__DACE:2 ////__DACE:2 { ////__DACE:2:0 { ////__DACE:2:0:0 float alpha; ////__DACE:2:0:0 ////__DACE:2:0:0 ////__DACE:2:0:0 ////__DACE:2:0:0 /////////////////// ////__DACE:2:0:0 ////__DACE:2:0:0 *alpha=0.25; ////__DACE:2:0:0 ////__DACE:2:0:0 /////////////////// ////__DACE:2:0:0 ////__DACE:2:0:0 ////__DACE:2:0:0 ////__DACE:2:0:0 __alpha = alpha; ////__DACE:2:0:0 ////__DACE:2:0:0 } ////__DACE:2:0:0 } ////__DACE:2:0 for (i = 0; (i < __w); i = i+1) { ////__DACE:2:2 { ////__DACE:2:3 FOR26_2_3_0(__w, __h, &__imgIn[0], _argcount, i); ////__DACE:2:3:0 } ////__DACE:2:3 } ////__DACE:2:2 } ////__DACE:1:0:4 ////__DACE:1:0:4 void FOR87_5_3_0(int& ____h, float* ____imgIn, float* ____y1, float& ___xm1, float& ___ym1, float& ___ym2, float& ___a1, float& ___a2, float& ___b1, float& ___b2, int _argcount, int i, int j) { ////__DACE:5:3:0 ////__DACE:6 { ////__DACE:6:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:6:0:0 float a1 = ___a1; ////__DACE:6:0:1,0 ////__DACE:6:0:0 float imgIn = ____imgIn[((4096 * i) + j)]; ////__DACE:6:0:2,0 ////__DACE:6:0:0 float a2 = ___a2; ////__DACE:6:0:3,0 ////__DACE:6:0:0 float xm1 = ___xm1; ////__DACE:6:0:4,0 ////__DACE:6:0:0 float b1 = ___b1; ////__DACE:6:0:5,0 ////__DACE:6:0:0 float ym1 = ___ym1; ////__DACE:6:0:6,0 ////__DACE:6:0:0 float b2 = ___b2; ////__DACE:6:0:7,0 ////__DACE:6:0:0 float ym2 = ___ym2; ////__DACE:6:0:8,0 ////__DACE:6:0:0 float y1; ////__DACE:6:0:0 ////__DACE:6:0:0 ////__DACE:6:0:0 ////__DACE:6:0:0 /////////////////// ////__DACE:6:0:0 ////__DACE:6:0:0 y1=a1*imgIn+a2*xm1+b1*ym1+b2*ym2; ////__DACE:6:0:0 ////__DACE:6:0:0 /////////////////// ////__DACE:6:0:0 ////__DACE:6:0:0 ////__DACE:6:0:0 ////__DACE:6:0:0 ____y1[((4096 * i) + j)] = y1; ////__DACE:6:0:0 ////__DACE:6:0:0 } ////__DACE:6:0:0 { ////__DACE:6:0:14 float y1 = ____y1[((4096 * i) + j)]; ////__DACE:6:0:9,14 ////__DACE:6:0:14 float ym1; ////__DACE:6:0:14 ////__DACE:6:0:14 ////__DACE:6:0:14 ////__DACE:6:0:14 /////////////////// ////__DACE:6:0:14 ////__DACE:6:0:14 ym1=y1; ////__DACE:6:0:14 ////__DACE:6:0:14 /////////////////// ////__DACE:6:0:14 ////__DACE:6:0:14 ////__DACE:6:0:14 ////__DACE:6:0:14 ___ym1 = ym1; ////__DACE:6:0:14 ////__DACE:6:0:14 } ////__DACE:6:0:14 } // End omp section #pragma omp section { { ////__DACE:6:0:10 float imgIn = ____imgIn[((4096 * i) + j)]; ////__DACE:6:0:2,10 ////__DACE:6:0:10 float xm1; ////__DACE:6:0:10 ////__DACE:6:0:10 ////__DACE:6:0:10 ////__DACE:6:0:10 /////////////////// ////__DACE:6:0:10 ////__DACE:6:0:10 xm1=imgIn; ////__DACE:6:0:10 ////__DACE:6:0:10 /////////////////// ////__DACE:6:0:10 ////__DACE:6:0:10 ////__DACE:6:0:10 ////__DACE:6:0:10 ___xm1 = xm1; ////__DACE:6:0:10 ////__DACE:6:0:10 } ////__DACE:6:0:10 } // End omp section #pragma omp section { { ////__DACE:6:0:12 float ym1 = ___ym1; ////__DACE:6:0:6,12 ////__DACE:6:0:12 float ym2; ////__DACE:6:0:12 ////__DACE:6:0:12 ////__DACE:6:0:12 ////__DACE:6:0:12 /////////////////// ////__DACE:6:0:12 ////__DACE:6:0:12 ym2=ym1; ////__DACE:6:0:12 ////__DACE:6:0:12 /////////////////// ////__DACE:6:0:12 ////__DACE:6:0:12 ////__DACE:6:0:12 ////__DACE:6:0:12 ___ym2 = ym2; ////__DACE:6:0:12 ////__DACE:6:0:12 } ////__DACE:6:0:12 } // End omp section } // End omp sections } ////__DACE:6:0 } ////__DACE:5:3:0 ////__DACE:5:3:0 void FOR83_4_2_0(int& ___w, int& ___h, float* ___imgIn, float* ___y1, float& __xm1, float& __ym1, float& __ym2, float& __a1, float& __a2, float& __b1, float& __b2, int _argcount, int i) { ////__DACE:4:2:0 long long j; ////__DACE:5 ////__DACE:5 { ////__DACE:5:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:5:0:0 float ym1; ////__DACE:5:0:0 ////__DACE:5:0:0 ////__DACE:5:0:0 ////__DACE:5:0:0 /////////////////// ////__DACE:5:0:0 ////__DACE:5:0:0 ym1=0.0f; ////__DACE:5:0:0 ////__DACE:5:0:0 /////////////////// ////__DACE:5:0:0 ////__DACE:5:0:0 ////__DACE:5:0:0 ////__DACE:5:0:0 __ym1 = ym1; ////__DACE:5:0:0 ////__DACE:5:0:0 } ////__DACE:5:0:0 } // End omp section #pragma omp section { { ////__DACE:5:0:2 float ym2; ////__DACE:5:0:2 ////__DACE:5:0:2 ////__DACE:5:0:2 ////__DACE:5:0:2 /////////////////// ////__DACE:5:0:2 ////__DACE:5:0:2 ym2=0.0f; ////__DACE:5:0:2 ////__DACE:5:0:2 /////////////////// ////__DACE:5:0:2 ////__DACE:5:0:2 ////__DACE:5:0:2 ////__DACE:5:0:2 __ym2 = ym2; ////__DACE:5:0:2 ////__DACE:5:0:2 } ////__DACE:5:0:2 } // End omp section #pragma omp section { { ////__DACE:5:0:4 float xm1; ////__DACE:5:0:4 ////__DACE:5:0:4 ////__DACE:5:0:4 ////__DACE:5:0:4 /////////////////// ////__DACE:5:0:4 ////__DACE:5:0:4 xm1=0.0f; ////__DACE:5:0:4 ////__DACE:5:0:4 /////////////////// ////__DACE:5:0:4 ////__DACE:5:0:4 ////__DACE:5:0:4 ////__DACE:5:0:4 __xm1 = xm1; ////__DACE:5:0:4 ////__DACE:5:0:4 } ////__DACE:5:0:4 } // End omp section } // End omp sections } ////__DACE:5:0 for (j = 0; (j < ___h); j = j+1) { ////__DACE:5:2 { ////__DACE:5:3 FOR87_5_3_0(___h, &___imgIn[0], &___y1[0], __xm1, __ym1, __ym2, __a1, __a2, __b1, __b2, _argcount, i, j); ////__DACE:5:3:0 } ////__DACE:5:3 } ////__DACE:5:2 } ////__DACE:4:2:0 ////__DACE:4:2:0 void FOR100_7_2_0(int& ____h, float* ____imgIn, float* ____y2, float& ___xp1, float& ___xp2, float& ___yp1, float& ___yp2, float& ___a3, float& ___a4, float& ___b1, float& ___b2, int _argcount, int i, int j) { ////__DACE:7:2:0 ////__DACE:8 { ////__DACE:8:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:8:0:0 float a3 = ___a3; ////__DACE:8:0:1,0 ////__DACE:8:0:0 float xp1 = ___xp1; ////__DACE:8:0:2,0 ////__DACE:8:0:0 float a4 = ___a4; ////__DACE:8:0:3,0 ////__DACE:8:0:0 float xp2 = ___xp2; ////__DACE:8:0:4,0 ////__DACE:8:0:0 float b1 = ___b1; ////__DACE:8:0:5,0 ////__DACE:8:0:0 float yp1 = ___yp1; ////__DACE:8:0:6,0 ////__DACE:8:0:0 float b2 = ___b2; ////__DACE:8:0:7,0 ////__DACE:8:0:0 float yp2 = ___yp2; ////__DACE:8:0:8,0 ////__DACE:8:0:0 float y2; ////__DACE:8:0:0 ////__DACE:8:0:0 ////__DACE:8:0:0 ////__DACE:8:0:0 /////////////////// ////__DACE:8:0:0 ////__DACE:8:0:0 y2=a3*xp1+a4*xp2+b1*yp1+b2*yp2; ////__DACE:8:0:0 ////__DACE:8:0:0 /////////////////// ////__DACE:8:0:0 ////__DACE:8:0:0 ////__DACE:8:0:0 ////__DACE:8:0:0 ____y2[((4096 * i) + j)] = y2; ////__DACE:8:0:0 ////__DACE:8:0:0 } ////__DACE:8:0:0 { ////__DACE:8:0:17 float y2 = ____y2[((4096 * i) + j)]; ////__DACE:8:0:9,17 ////__DACE:8:0:17 float yp1; ////__DACE:8:0:17 ////__DACE:8:0:17 ////__DACE:8:0:17 ////__DACE:8:0:17 /////////////////// ////__DACE:8:0:17 ////__DACE:8:0:17 yp1=y2; ////__DACE:8:0:17 ////__DACE:8:0:17 /////////////////// ////__DACE:8:0:17 ////__DACE:8:0:17 ////__DACE:8:0:17 ////__DACE:8:0:17 ___yp1 = yp1; ////__DACE:8:0:17 ////__DACE:8:0:17 } ////__DACE:8:0:17 } // End omp section #pragma omp section { { ////__DACE:8:0:10 float xp1 = ___xp1; ////__DACE:8:0:2,10 ////__DACE:8:0:10 float xp2; ////__DACE:8:0:10 ////__DACE:8:0:10 ////__DACE:8:0:10 ////__DACE:8:0:10 /////////////////// ////__DACE:8:0:10 ////__DACE:8:0:10 xp2=xp1; ////__DACE:8:0:10 ////__DACE:8:0:10 /////////////////// ////__DACE:8:0:10 ////__DACE:8:0:10 ////__DACE:8:0:10 ////__DACE:8:0:10 ___xp2 = xp2; ////__DACE:8:0:10 ////__DACE:8:0:10 } ////__DACE:8:0:10 } // End omp section #pragma omp section { { ////__DACE:8:0:15 float yp1 = ___yp1; ////__DACE:8:0:6,15 ////__DACE:8:0:15 float yp2; ////__DACE:8:0:15 ////__DACE:8:0:15 ////__DACE:8:0:15 ////__DACE:8:0:15 /////////////////// ////__DACE:8:0:15 ////__DACE:8:0:15 yp2=yp1; ////__DACE:8:0:15 ////__DACE:8:0:15 /////////////////// ////__DACE:8:0:15 ////__DACE:8:0:15 ////__DACE:8:0:15 ////__DACE:8:0:15 ___yp2 = yp2; ////__DACE:8:0:15 ////__DACE:8:0:15 } ////__DACE:8:0:15 } // End omp section #pragma omp section { { ////__DACE:8:0:12 float imgIn = ____imgIn[((4096 * i) + j)]; ////__DACE:8:0:13,12 ////__DACE:8:0:12 float xp1; ////__DACE:8:0:12 ////__DACE:8:0:12 ////__DACE:8:0:12 ////__DACE:8:0:12 /////////////////// ////__DACE:8:0:12 ////__DACE:8:0:12 xp1=imgIn; ////__DACE:8:0:12 ////__DACE:8:0:12 /////////////////// ////__DACE:8:0:12 ////__DACE:8:0:12 ////__DACE:8:0:12 ////__DACE:8:0:12 ___xp1 = xp1; ////__DACE:8:0:12 ////__DACE:8:0:12 } ////__DACE:8:0:12 } // End omp section } // End omp sections } ////__DACE:8:0 } ////__DACE:7:2:0 ////__DACE:7:2:0 void FOR95_4_4_0(int& ___w, int& ___h, float* ___imgIn, float* ___y2, float& __xp1, float& __xp2, float& __yp1, float& __yp2, float& __a3, float& __a4, float& __b1, float& __b2, int _argcount, int i) { ////__DACE:4:4:0 long long j; ////__DACE:7 ////__DACE:7 __state_7_state96:; ////__DACE:7:0 { ////__DACE:7:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:7:0:0 float yp1; ////__DACE:7:0:0 ////__DACE:7:0:0 ////__DACE:7:0:0 ////__DACE:7:0:0 /////////////////// ////__DACE:7:0:0 ////__DACE:7:0:0 yp1=0.0f; ////__DACE:7:0:0 ////__DACE:7:0:0 /////////////////// ////__DACE:7:0:0 ////__DACE:7:0:0 ////__DACE:7:0:0 ////__DACE:7:0:0 __yp1 = yp1; ////__DACE:7:0:0 ////__DACE:7:0:0 } ////__DACE:7:0:0 } // End omp section #pragma omp section { { ////__DACE:7:0:2 float yp2; ////__DACE:7:0:2 ////__DACE:7:0:2 ////__DACE:7:0:2 ////__DACE:7:0:2 /////////////////// ////__DACE:7:0:2 ////__DACE:7:0:2 yp2=0.0f; ////__DACE:7:0:2 ////__DACE:7:0:2 /////////////////// ////__DACE:7:0:2 ////__DACE:7:0:2 ////__DACE:7:0:2 ////__DACE:7:0:2 __yp2 = yp2; ////__DACE:7:0:2 ////__DACE:7:0:2 } ////__DACE:7:0:2 } // End omp section #pragma omp section { { ////__DACE:7:0:4 float xp1; ////__DACE:7:0:4 ////__DACE:7:0:4 ////__DACE:7:0:4 ////__DACE:7:0:4 /////////////////// ////__DACE:7:0:4 ////__DACE:7:0:4 xp1=0.0f; ////__DACE:7:0:4 ////__DACE:7:0:4 /////////////////// ////__DACE:7:0:4 ////__DACE:7:0:4 ////__DACE:7:0:4 ////__DACE:7:0:4 __xp1 = xp1; ////__DACE:7:0:4 ////__DACE:7:0:4 } ////__DACE:7:0:4 } // End omp section #pragma omp section { { ////__DACE:7:0:6 float xp2; ////__DACE:7:0:6 ////__DACE:7:0:6 ////__DACE:7:0:6 ////__DACE:7:0:6 /////////////////// ////__DACE:7:0:6 ////__DACE:7:0:6 xp2=0.0f; ////__DACE:7:0:6 ////__DACE:7:0:6 /////////////////// ////__DACE:7:0:6 ////__DACE:7:0:6 ////__DACE:7:0:6 ////__DACE:7:0:6 __xp2 = xp2; ////__DACE:7:0:6 ////__DACE:7:0:6 } ////__DACE:7:0:6 } // End omp section } // End omp sections } ////__DACE:7:0 if ((j >= 0)) { ////__DACE:7:0 goto __state_7_stateFOR100; ////__DACE:7:0 } if (((j >= 0) == false)) { ////__DACE:7:0 goto __state_7_MergeState100; ////__DACE:7:0 } __state_7_stateFOR100:; ////__DACE:7:2 { ////__DACE:7:2 FOR100_7_2_0(___h, &___imgIn[0], &___y2[0], __xp1, __xp2, __yp1, __yp2, __a3, __a4, __b1, __b2, _argcount, i, j); ////__DACE:7:2:0 } ////__DACE:7:2 j = j-1; ////__DACE:7:2 goto __state_7_state96; ////__DACE:7:2 __state_7_MergeState100:; ////__DACE:7:1 } ////__DACE:4:4:0 ////__DACE:4:4:0 void FOR118_9_3_0(int& ____w, float* ____imgOut, float* ____y1, float& ___tm1, float& ___ym1, float& ___ym2, float& ___a5, float& ___a6, float& ___b1, float& ___b2, int _argcount, int i, int j) { ////__DACE:9:3:0 ////__DACE:10 { ////__DACE:10:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:10:0:0 float a5 = ___a5; ////__DACE:10:0:1,0 ////__DACE:10:0:0 float imgOut = ____imgOut[((4096 * i) + j)]; ////__DACE:10:0:2,0 ////__DACE:10:0:0 float a6 = ___a6; ////__DACE:10:0:3,0 ////__DACE:10:0:0 float tm1 = ___tm1; ////__DACE:10:0:4,0 ////__DACE:10:0:0 float b1 = ___b1; ////__DACE:10:0:5,0 ////__DACE:10:0:0 float ym1 = ___ym1; ////__DACE:10:0:6,0 ////__DACE:10:0:0 float b2 = ___b2; ////__DACE:10:0:7,0 ////__DACE:10:0:0 float ym2 = ___ym2; ////__DACE:10:0:8,0 ////__DACE:10:0:0 float y1; ////__DACE:10:0:0 ////__DACE:10:0:0 ////__DACE:10:0:0 ////__DACE:10:0:0 /////////////////// ////__DACE:10:0:0 ////__DACE:10:0:0 y1=a5*imgOut+a6*tm1+b1*ym1+b2*ym2; ////__DACE:10:0:0 ////__DACE:10:0:0 /////////////////// ////__DACE:10:0:0 ////__DACE:10:0:0 ////__DACE:10:0:0 ////__DACE:10:0:0 ____y1[((4096 * i) + j)] = y1; ////__DACE:10:0:0 ////__DACE:10:0:0 } ////__DACE:10:0:0 { ////__DACE:10:0:14 float y1 = ____y1[((4096 * i) + j)]; ////__DACE:10:0:9,14 ////__DACE:10:0:14 float ym1; ////__DACE:10:0:14 ////__DACE:10:0:14 ////__DACE:10:0:14 ////__DACE:10:0:14 /////////////////// ////__DACE:10:0:14 ////__DACE:10:0:14 ym1=y1; ////__DACE:10:0:14 ////__DACE:10:0:14 /////////////////// ////__DACE:10:0:14 ////__DACE:10:0:14 ////__DACE:10:0:14 ////__DACE:10:0:14 ___ym1 = ym1; ////__DACE:10:0:14 ////__DACE:10:0:14 } ////__DACE:10:0:14 } // End omp section #pragma omp section { { ////__DACE:10:0:10 float imgOut = ____imgOut[((4096 * i) + j)]; ////__DACE:10:0:2,10 ////__DACE:10:0:10 float tm1; ////__DACE:10:0:10 ////__DACE:10:0:10 ////__DACE:10:0:10 ////__DACE:10:0:10 /////////////////// ////__DACE:10:0:10 ////__DACE:10:0:10 tm1=imgOut; ////__DACE:10:0:10 ////__DACE:10:0:10 /////////////////// ////__DACE:10:0:10 ////__DACE:10:0:10 ////__DACE:10:0:10 ////__DACE:10:0:10 ___tm1 = tm1; ////__DACE:10:0:10 ////__DACE:10:0:10 } ////__DACE:10:0:10 } // End omp section #pragma omp section { { ////__DACE:10:0:12 float ym1 = ___ym1; ////__DACE:10:0:6,12 ////__DACE:10:0:12 float ym2; ////__DACE:10:0:12 ////__DACE:10:0:12 ////__DACE:10:0:12 ////__DACE:10:0:12 /////////////////// ////__DACE:10:0:12 ////__DACE:10:0:12 ym2=ym1; ////__DACE:10:0:12 ////__DACE:10:0:12 /////////////////// ////__DACE:10:0:12 ////__DACE:10:0:12 ////__DACE:10:0:12 ////__DACE:10:0:12 ___ym2 = ym2; ////__DACE:10:0:12 ////__DACE:10:0:12 } ////__DACE:10:0:12 } // End omp section } // End omp sections } ////__DACE:10:0 } ////__DACE:9:3:0 ////__DACE:9:3:0 void FOR114_4_6_0(int& ___w, int& ___h, float* ___imgOut, float* ___y1, float& __tm1, float& __ym1, float& __ym2, float& __a5, float& __a6, float& __b1, float& __b2, int _argcount, int i, int j) { ////__DACE:4:6:0 long long i; ////__DACE:9 ////__DACE:9 { ////__DACE:9:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:9:0:0 float tm1; ////__DACE:9:0:0 ////__DACE:9:0:0 ////__DACE:9:0:0 ////__DACE:9:0:0 /////////////////// ////__DACE:9:0:0 ////__DACE:9:0:0 tm1=0.0f; ////__DACE:9:0:0 ////__DACE:9:0:0 /////////////////// ////__DACE:9:0:0 ////__DACE:9:0:0 ////__DACE:9:0:0 ////__DACE:9:0:0 __tm1 = tm1; ////__DACE:9:0:0 ////__DACE:9:0:0 } ////__DACE:9:0:0 } // End omp section #pragma omp section { { ////__DACE:9:0:2 float ym1; ////__DACE:9:0:2 ////__DACE:9:0:2 ////__DACE:9:0:2 ////__DACE:9:0:2 /////////////////// ////__DACE:9:0:2 ////__DACE:9:0:2 ym1=0.0f; ////__DACE:9:0:2 ////__DACE:9:0:2 /////////////////// ////__DACE:9:0:2 ////__DACE:9:0:2 ////__DACE:9:0:2 ////__DACE:9:0:2 __ym1 = ym1; ////__DACE:9:0:2 ////__DACE:9:0:2 } ////__DACE:9:0:2 } // End omp section #pragma omp section { { ////__DACE:9:0:4 float ym2; ////__DACE:9:0:4 ////__DACE:9:0:4 ////__DACE:9:0:4 ////__DACE:9:0:4 /////////////////// ////__DACE:9:0:4 ////__DACE:9:0:4 ym2=0.0f; ////__DACE:9:0:4 ////__DACE:9:0:4 /////////////////// ////__DACE:9:0:4 ////__DACE:9:0:4 ////__DACE:9:0:4 ////__DACE:9:0:4 __ym2 = ym2; ////__DACE:9:0:4 ////__DACE:9:0:4 } ////__DACE:9:0:4 } // End omp section } // End omp sections } ////__DACE:9:0 for (i = 0; (i < ___w); i = i+1) { ////__DACE:9:2 { ////__DACE:9:3 FOR118_9_3_0(___w, &___imgOut[0], &___y1[0], __tm1, __ym1, __ym2, __a5, __a6, __b1, __b2, _argcount, i, j); ////__DACE:9:3:0 } ////__DACE:9:3 } ////__DACE:9:2 } ////__DACE:4:6:0 ////__DACE:4:6:0 void FOR132_11_2_0(int& ____w, float* ____imgOut, float* ____y2, float& ___tp1, float& ___tp2, float& ___yp1, float& ___yp2, float& ___a7, float& ___a8, float& ___b1, float& ___b2, int _argcount, int i, int j) { ////__DACE:11:2:0 ////__DACE:12 { ////__DACE:12:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:12:0:0 float a7 = ___a7; ////__DACE:12:0:1,0 ////__DACE:12:0:0 float tp1 = ___tp1; ////__DACE:12:0:2,0 ////__DACE:12:0:0 float a8 = ___a8; ////__DACE:12:0:3,0 ////__DACE:12:0:0 float tp2 = ___tp2; ////__DACE:12:0:4,0 ////__DACE:12:0:0 float b1 = ___b1; ////__DACE:12:0:5,0 ////__DACE:12:0:0 float yp1 = ___yp1; ////__DACE:12:0:6,0 ////__DACE:12:0:0 float b2 = ___b2; ////__DACE:12:0:7,0 ////__DACE:12:0:0 float yp2 = ___yp2; ////__DACE:12:0:8,0 ////__DACE:12:0:0 float y2; ////__DACE:12:0:0 ////__DACE:12:0:0 ////__DACE:12:0:0 ////__DACE:12:0:0 /////////////////// ////__DACE:12:0:0 ////__DACE:12:0:0 y2=a7*tp1+a8*tp2+b1*yp1+b2*yp2; ////__DACE:12:0:0 ////__DACE:12:0:0 /////////////////// ////__DACE:12:0:0 ////__DACE:12:0:0 ////__DACE:12:0:0 ////__DACE:12:0:0 ____y2[((4096 * i) + j)] = y2; ////__DACE:12:0:0 ////__DACE:12:0:0 } ////__DACE:12:0:0 { ////__DACE:12:0:17 float y2 = ____y2[((4096 * i) + j)]; ////__DACE:12:0:9,17 ////__DACE:12:0:17 float yp1; ////__DACE:12:0:17 ////__DACE:12:0:17 ////__DACE:12:0:17 ////__DACE:12:0:17 /////////////////// ////__DACE:12:0:17 ////__DACE:12:0:17 yp1=y2; ////__DACE:12:0:17 ////__DACE:12:0:17 /////////////////// ////__DACE:12:0:17 ////__DACE:12:0:17 ////__DACE:12:0:17 ////__DACE:12:0:17 ___yp1 = yp1; ////__DACE:12:0:17 ////__DACE:12:0:17 } ////__DACE:12:0:17 } // End omp section #pragma omp section { { ////__DACE:12:0:10 float tp1 = ___tp1; ////__DACE:12:0:2,10 ////__DACE:12:0:10 float tp2; ////__DACE:12:0:10 ////__DACE:12:0:10 ////__DACE:12:0:10 ////__DACE:12:0:10 /////////////////// ////__DACE:12:0:10 ////__DACE:12:0:10 tp2=tp1; ////__DACE:12:0:10 ////__DACE:12:0:10 /////////////////// ////__DACE:12:0:10 ////__DACE:12:0:10 ////__DACE:12:0:10 ////__DACE:12:0:10 ___tp2 = tp2; ////__DACE:12:0:10 ////__DACE:12:0:10 } ////__DACE:12:0:10 } // End omp section #pragma omp section { { ////__DACE:12:0:15 float yp1 = ___yp1; ////__DACE:12:0:6,15 ////__DACE:12:0:15 float yp2; ////__DACE:12:0:15 ////__DACE:12:0:15 ////__DACE:12:0:15 ////__DACE:12:0:15 /////////////////// ////__DACE:12:0:15 ////__DACE:12:0:15 yp2=yp1; ////__DACE:12:0:15 ////__DACE:12:0:15 /////////////////// ////__DACE:12:0:15 ////__DACE:12:0:15 ////__DACE:12:0:15 ////__DACE:12:0:15 ___yp2 = yp2; ////__DACE:12:0:15 ////__DACE:12:0:15 } ////__DACE:12:0:15 } // End omp section #pragma omp section { { ////__DACE:12:0:12 float imgOut = ____imgOut[((4096 * i) + j)]; ////__DACE:12:0:13,12 ////__DACE:12:0:12 float tp1; ////__DACE:12:0:12 ////__DACE:12:0:12 ////__DACE:12:0:12 ////__DACE:12:0:12 /////////////////// ////__DACE:12:0:12 ////__DACE:12:0:12 tp1=imgOut; ////__DACE:12:0:12 ////__DACE:12:0:12 /////////////////// ////__DACE:12:0:12 ////__DACE:12:0:12 ////__DACE:12:0:12 ////__DACE:12:0:12 ___tp1 = tp1; ////__DACE:12:0:12 ////__DACE:12:0:12 } ////__DACE:12:0:12 } // End omp section } // End omp sections } ////__DACE:12:0 } ////__DACE:11:2:0 ////__DACE:11:2:0 void FOR127_4_8_0(int& ___w, int& ___h, float* ___imgOut, float* ___y2, float& __tp1, float& __tp2, float& __yp1, float& __yp2, float& __a7, float& __a8, float& __b1, float& __b2, int _argcount, int i, int j) { ////__DACE:4:8:0 long long i; ////__DACE:11 ////__DACE:11 __state_11_state128:; ////__DACE:11:0 { ////__DACE:11:0 #pragma omp parallel sections { #pragma omp section { { ////__DACE:11:0:0 float tp1; ////__DACE:11:0:0 ////__DACE:11:0:0 ////__DACE:11:0:0 ////__DACE:11:0:0 /////////////////// ////__DACE:11:0:0 ////__DACE:11:0:0 tp1=0.0f; ////__DACE:11:0:0 ////__DACE:11:0:0 /////////////////// ////__DACE:11:0:0 ////__DACE:11:0:0 ////__DACE:11:0:0 ////__DACE:11:0:0 __tp1 = tp1; ////__DACE:11:0:0 ////__DACE:11:0:0 } ////__DACE:11:0:0 } // End omp section #pragma omp section { { ////__DACE:11:0:2 float tp2; ////__DACE:11:0:2 ////__DACE:11:0:2 ////__DACE:11:0:2 ////__DACE:11:0:2 /////////////////// ////__DACE:11:0:2 ////__DACE:11:0:2 tp2=0.0f; ////__DACE:11:0:2 ////__DACE:11:0:2 /////////////////// ////__DACE:11:0:2 ////__DACE:11:0:2 ////__DACE:11:0:2 ////__DACE:11:0:2 __tp2 = tp2; ////__DACE:11:0:2 ////__DACE:11:0:2 } ////__DACE:11:0:2 } // End omp section #pragma omp section { { ////__DACE:11:0:4 float yp1; ////__DACE:11:0:4 ////__DACE:11:0:4 ////__DACE:11:0:4 ////__DACE:11:0:4 /////////////////// ////__DACE:11:0:4 ////__DACE:11:0:4 yp1=0.0f; ////__DACE:11:0:4 ////__DACE:11:0:4 /////////////////// ////__DACE:11:0:4 ////__DACE:11:0:4 ////__DACE:11:0:4 ////__DACE:11:0:4 __yp1 = yp1; ////__DACE:11:0:4 ////__DACE:11:0:4 } ////__DACE:11:0:4 } // End omp section #pragma omp section { { ////__DACE:11:0:6 float yp2; ////__DACE:11:0:6 ////__DACE:11:0:6 ////__DACE:11:0:6 ////__DACE:11:0:6 /////////////////// ////__DACE:11:0:6 ////__DACE:11:0:6 yp2=0.0f; ////__DACE:11:0:6 ////__DACE:11:0:6 /////////////////// ////__DACE:11:0:6 ////__DACE:11:0:6 ////__DACE:11:0:6 ////__DACE:11:0:6 __yp2 = yp2; ////__DACE:11:0:6 ////__DACE:11:0:6 } ////__DACE:11:0:6 } // End omp section } // End omp sections } ////__DACE:11:0 if ((i >= 0)) { ////__DACE:11:0 goto __state_11_stateFOR132; ////__DACE:11:0 } if (((i >= 0) == false)) { ////__DACE:11:0 goto __state_11_MergeState132; ////__DACE:11:0 } __state_11_stateFOR132:; ////__DACE:11:2 { ////__DACE:11:2 FOR132_11_2_0(___w, &___imgOut[0], &___y2[0], __tp1, __tp2, __yp1, __yp2, __a7, __a8, __b1, __b2, _argcount, i, j); ////__DACE:11:2:0 } ////__DACE:11:2 i = i-1; ////__DACE:11:2 goto __state_11_state128; ////__DACE:11:2 __state_11_MergeState132:; ////__DACE:11:1 } ////__DACE:4:8:0 ////__DACE:4:8:0 void FOR141_4_11_0(int& ___w, int& ___h, float* ___imgOut, float* ___y1, float* ___y2, float& __c2, int _argcount, int i, int j) { ////__DACE:4:11:0 long long j; ////__DACE:13 ////__DACE:13 for (j = 0; (j < ___h); j = j+1) { ////__DACE:13:2 { ////__DACE:13:3 { ////__DACE:13:3:4 float c2 = __c2; ////__DACE:13:3:3,4 ////__DACE:13:3:4 float y1 = ___y1[((4096 * i) + j)]; ////__DACE:13:3:1,4 ////__DACE:13:3:4 float y2 = ___y2[((4096 * i) + j)]; ////__DACE:13:3:2,4 ////__DACE:13:3:4 float imgOut; ////__DACE:13:3:4 ////__DACE:13:3:4 ////__DACE:13:3:4 ////__DACE:13:3:4 /////////////////// ////__DACE:13:3:4 ////__DACE:13:3:4 imgOut=c2*(y1+y2); ////__DACE:13:3:4 ////__DACE:13:3:4 /////////////////// ////__DACE:13:3:4 ////__DACE:13:3:4 ////__DACE:13:3:4 ////__DACE:13:3:4 ___imgOut[((4096 * i) + j)] = imgOut; ////__DACE:13:3:4 ////__DACE:13:3:4 } ////__DACE:13:3:4 } ////__DACE:13:3 } ////__DACE:13:2 } ////__DACE:4:11:0 ////__DACE:4:11:0 void kernel_deriche_1_0_11(int& __w, int& __h, float& __alpha, float* __imgIn, float* __imgOut, float* __y1, float* __y2, int _argcount) { ////__DACE:1:0:11 float _a1; ////__DACE:4 float _a5; ////__DACE:4 float _a2; ////__DACE:4 float _a6; ////__DACE:4 float _a3; ////__DACE:4 float _a7; ////__DACE:4 float _a4; ////__DACE:4 float _a8; ////__DACE:4 float _b1; ////__DACE:4 float _b2; ////__DACE:4 float _c2; ////__DACE:4 float _ym1; ////__DACE:4 float _ym2; ////__DACE:4 float _yp1; ////__DACE:4 float _yp2; ////__DACE:4 long long i; ////__DACE:4 long long j; ////__DACE:4 ////__DACE:4 { ////__DACE:4:0 float _k; ////__DACE:4:0:2 float _c1; ////__DACE:4:0:20 #pragma omp parallel sections { #pragma omp section { { ////__DACE:4:0:0 float alpha = __alpha; ////__DACE:4:0:1,0 ////__DACE:4:0:0 float k; ////__DACE:4:0:0 ////__DACE:4:0:0 ////__DACE:4:0:0 ////__DACE:4:0:0 /////////////////// ////__DACE:4:0:0 ////__DACE:4:0:0 k=(1.0f-expf(-alpha))*(1.0f-expf(-alpha))/(1.0f+2.0f*alpha*expf(-alpha)-expf(2.0f*alpha)); ////__DACE:4:0:0 ////__DACE:4:0:0 /////////////////// ////__DACE:4:0:0 ////__DACE:4:0:0 ////__DACE:4:0:0 ////__DACE:4:0:0 _k = k; ////__DACE:4:0:0 ////__DACE:4:0:0 } ////__DACE:4:0:0 { ////__DACE:4:0:3 float k = _k; ////__DACE:4:0:2,3 ////__DACE:4:0:3 float a1; ////__DACE:4:0:3 ////__DACE:4:0:3 float a5; ////__DACE:4:0:3 ////__DACE:4:0:3 ////__DACE:4:0:3 ////__DACE:4:0:3 /////////////////// ////__DACE:4:0:3 ////__DACE:4:0:3 a1=a5=k; ////__DACE:4:0:3 ////__DACE:4:0:3 /////////////////// ////__DACE:4:0:3 ////__DACE:4:0:3 ////__DACE:4:0:3 ////__DACE:4:0:3 _a1 = a1; ////__DACE:4:0:3 ////__DACE:4:0:3 _a5 = a5; ////__DACE:4:0:3 ////__DACE:4:0:3 } ////__DACE:4:0:3 { ////__DACE:4:0:6 float k = _k; ////__DACE:4:0:2,6 ////__DACE:4:0:6 float alpha = __alpha; ////__DACE:4:0:1,6 ////__DACE:4:0:6 float a2; ////__DACE:4:0:6 ////__DACE:4:0:6 float a6; ////__DACE:4:0:6 ////__DACE:4:0:6 ////__DACE:4:0:6 ////__DACE:4:0:6 /////////////////// ////__DACE:4:0:6 ////__DACE:4:0:6 a2=a6=k*expf(-alpha)*(alpha-1.0f); ////__DACE:4:0:6 ////__DACE:4:0:6 /////////////////// ////__DACE:4:0:6 ////__DACE:4:0:6 ////__DACE:4:0:6 ////__DACE:4:0:6 _a2 = a2; ////__DACE:4:0:6 ////__DACE:4:0:6 _a6 = a6; ////__DACE:4:0:6 ////__DACE:4:0:6 } ////__DACE:4:0:6 { ////__DACE:4:0:9 float k = _k; ////__DACE:4:0:2,9 ////__DACE:4:0:9 float alpha = __alpha; ////__DACE:4:0:1,9 ////__DACE:4:0:9 float a3; ////__DACE:4:0:9 ////__DACE:4:0:9 float a7; ////__DACE:4:0:9 ////__DACE:4:0:9 ////__DACE:4:0:9 ////__DACE:4:0:9 /////////////////// ////__DACE:4:0:9 ////__DACE:4:0:9 a3=a7=k*expf(-alpha)*(alpha+1.0f); ////__DACE:4:0:9 ////__DACE:4:0:9 /////////////////// ////__DACE:4:0:9 ////__DACE:4:0:9 ////__DACE:4:0:9 ////__DACE:4:0:9 _a3 = a3; ////__DACE:4:0:9 ////__DACE:4:0:9 _a7 = a7; ////__DACE:4:0:9 ////__DACE:4:0:9 } ////__DACE:4:0:9 { ////__DACE:4:0:12 float k = _k; ////__DACE:4:0:2,12 ////__DACE:4:0:12 float a4; ////__DACE:4:0:12 ////__DACE:4:0:12 float a8; ////__DACE:4:0:12 ////__DACE:4:0:12 ////__DACE:4:0:12 ////__DACE:4:0:12 /////////////////// ////__DACE:4:0:12 ////__DACE:4:0:12 a4=a8=-k*expf(-2.0f*alpha); ////__DACE:4:0:12 ////__DACE:4:0:12 /////////////////// ////__DACE:4:0:12 ////__DACE:4:0:12 ////__DACE:4:0:12 ////__DACE:4:0:12 _a4 = a4; ////__DACE:4:0:12 ////__DACE:4:0:12 _a8 = a8; ////__DACE:4:0:12 ////__DACE:4:0:12 } ////__DACE:4:0:12 } // End omp section #pragma omp section { { ////__DACE:4:0:15 float b1; ////__DACE:4:0:15 ////__DACE:4:0:15 ////__DACE:4:0:15 ////__DACE:4:0:15 /////////////////// ////__DACE:4:0:15 ////__DACE:4:0:15 b1=powf(2.0f,-alpha); ////__DACE:4:0:15 ////__DACE:4:0:15 /////////////////// ////__DACE:4:0:15 ////__DACE:4:0:15 ////__DACE:4:0:15 ////__DACE:4:0:15 _b1 = b1; ////__DACE:4:0:15 ////__DACE:4:0:15 } ////__DACE:4:0:15 } // End omp section #pragma omp section { { ////__DACE:4:0:17 float b2; ////__DACE:4:0:17 ////__DACE:4:0:17 ////__DACE:4:0:17 ////__DACE:4:0:17 /////////////////// ////__DACE:4:0:17 ////__DACE:4:0:17 b2=-expf(-2.0f*alpha); ////__DACE:4:0:17 ////__DACE:4:0:17 /////////////////// ////__DACE:4:0:17 ////__DACE:4:0:17 ////__DACE:4:0:17 ////__DACE:4:0:17 _b2 = b2; ////__DACE:4:0:17 ////__DACE:4:0:17 } ////__DACE:4:0:17 } // End omp section #pragma omp section { { ////__DACE:4:0:19 float c1; ////__DACE:4:0:19 ////__DACE:4:0:19 float c2; ////__DACE:4:0:19 ////__DACE:4:0:19 ////__DACE:4:0:19 ////__DACE:4:0:19 /////////////////// ////__DACE:4:0:19 ////__DACE:4:0:19 c1=c2=1; ////__DACE:4:0:19 ////__DACE:4:0:19 /////////////////// ////__DACE:4:0:19 ////__DACE:4:0:19 ////__DACE:4:0:19 ////__DACE:4:0:19 _c1 = c1; ////__DACE:4:0:19 ////__DACE:4:0:19 _c2 = c2; ////__DACE:4:0:19 ////__DACE:4:0:19 } ////__DACE:4:0:19 } // End omp section } // End omp sections } ////__DACE:4:0 for (i = 0; (i < __w); i = i+1) { ////__DACE:4:1 { ////__DACE:4:2 float _xm1; ////__DACE:4:2:9 FOR83_4_2_0(__w, __h, &__imgIn[0], &__y1[0], _xm1, _ym1, _ym2, _a1, _a2, _b1, _b2, _argcount, i); ////__DACE:4:2:0 } ////__DACE:4:2 } ////__DACE:4:1 i = 0; ////__DACE:4:1 for (; (i < __w); i = i+1) { ////__DACE:4:3 { ////__DACE:4:4 float _xp1; ////__DACE:4:4:9 float _xp2; ////__DACE:4:4:11 FOR95_4_4_0(__w, __h, &__imgIn[0], &__y2[0], _xp1, _xp2, _yp1, _yp2, _a3, _a4, _b1, _b2, _argcount, i); ////__DACE:4:4:0 } ////__DACE:4:4 } ////__DACE:4:3 j = 0; ////__DACE:4:3 for (; (j < __h); j = j+1) { ////__DACE:4:5 { ////__DACE:4:6 float _tm1; ////__DACE:4:6:9 FOR114_4_6_0(__w, __h, &__imgOut[0], &__y1[0], _tm1, _ym1, _ym2, _a5, _a6, _b1, _b2, _argcount, i, j); ////__DACE:4:6:0 } ////__DACE:4:6 } ////__DACE:4:5 j = 0; ////__DACE:4:5 for (; (j < __h); j = j+1) { ////__DACE:4:7 { ////__DACE:4:8 float _tp1; ////__DACE:4:8:9 float _tp2; ////__DACE:4:8:11 FOR127_4_8_0(__w, __h, &__imgOut[0], &__y2[0], _tp1, _tp2, _yp1, _yp2, _a7, _a8, _b1, _b2, _argcount, i, j); ////__DACE:4:8:0 } ////__DACE:4:8 } ////__DACE:4:7 i = 0; ////__DACE:4:7 for (; (i < __w); i = i+1) { ////__DACE:4:10 { ////__DACE:4:11 FOR141_4_11_0(__w, __h, &__imgOut[0], &__y1[0], &__y2[0], _c2, _argcount, i, j); ////__DACE:4:11:0 } ////__DACE:4:11 } ////__DACE:4:10 } ////__DACE:1:0:11 ////__DACE:1:0:11 void main_0_0_0(int& __argc, double* __argv, int _argcount) { ////__DACE:0:0:0 ////__DACE:1 { ////__DACE:1:0 int _w; ////__DACE:1:0:1 int _h; ////__DACE:1:0:3 float _alpha; ////__DACE:1:0:7 float *_imgIn = new float DACE_ALIGN(64)[8847360]; ////__DACE:1:0:9 float *_imgOut = new float DACE_ALIGN(64)[8847360]; ////__DACE:1:0:16 float *_y1 = new float DACE_ALIGN(64)[8847360]; ////__DACE:1:0:18 float *_y2 = new float DACE_ALIGN(64)[8847360]; ////__DACE:1:0:20 #pragma omp parallel sections { #pragma omp section { { ////__DACE:1:0:0 int w; ////__DACE:1:0:0 ////__DACE:1:0:0 ////__DACE:1:0:0 ////__DACE:1:0:0 /////////////////// ////__DACE:1:0:0 ////__DACE:1:0:0 w=4096; ////__DACE:1:0:0 ////__DACE:1:0:0 /////////////////// ////__DACE:1:0:0 ////__DACE:1:0:0 ////__DACE:1:0:0 ////__DACE:1:0:0 _w = w; ////__DACE:1:0:0 ////__DACE:1:0:0 } ////__DACE:1:0:0 { ////__DACE:1:0:2 int h; ////__DACE:1:0:2 ////__DACE:1:0:2 ////__DACE:1:0:2 ////__DACE:1:0:2 /////////////////// ////__DACE:1:0:2 ////__DACE:1:0:2 h=2160; ////__DACE:1:0:2 ////__DACE:1:0:2 /////////////////// ////__DACE:1:0:2 ////__DACE:1:0:2 ////__DACE:1:0:2 ////__DACE:1:0:2 _h = h; ////__DACE:1:0:2 ////__DACE:1:0:2 } ////__DACE:1:0:2 init_array_1_0_4(_w, _h, _alpha, &_imgIn[0], _argcount); ////__DACE:1:0:4 kernel_deriche_1_0_11(_w, _h, _alpha, &_imgIn[0], &_imgOut[0], &_y1[0], &_y2[0], _argcount); ////__DACE:1:0:11 } // End omp section #pragma omp section { { ////__DACE:1:0:22 int argc; ////__DACE:1:0:22 ////__DACE:1:0:22 ////__DACE:1:0:22 ////__DACE:1:0:22 /////////////////// ////__DACE:1:0:22 ////__DACE:1:0:22 argc=0; ////__DACE:1:0:22 ////__DACE:1:0:22 /////////////////// ////__DACE:1:0:22 ////__DACE:1:0:22 ////__DACE:1:0:22 ////__DACE:1:0:22 __argc = argc; ////__DACE:1:0:22 ////__DACE:1:0:22 } ////__DACE:1:0:22 } // End omp section #pragma omp section { { ////__DACE:1:0:24 double argv; ////__DACE:1:0:24 ////__DACE:1:0:24 ////__DACE:1:0:24 ////__DACE:1:0:24 /////////////////// ////__DACE:1:0:24 ////__DACE:1:0:24 argv=0; ////__DACE:1:0:24 ////__DACE:1:0:24 /////////////////// ////__DACE:1:0:24 ////__DACE:1:0:24 ////__DACE:1:0:24 ////__DACE:1:0:24 __argv[0] = argv; ////__DACE:1:0:24 ////__DACE:1:0:24 } ////__DACE:1:0:24 } // End omp section } // End omp sections delete[] _imgIn; ////__DACE:1:0:9 delete[] _imgOut; ////__DACE:1:0:16 delete[] _y1; ////__DACE:1:0:18 delete[] _y2; ////__DACE:1:0:20 } ////__DACE:1:0 } ////__DACE:0:0:0 ////__DACE:0:0:0 void __program_Top_internal(double * __restrict__ _argv, int _argc, int _argcount) { ////__DACE:0 { ////__DACE:0:0 main_0_0_0(_argc, &_argv[0], _argcount); ////__DACE:0:0:0 } ////__DACE:0:0 } ////__DACE:0 ////__DACE:0 DACE_EXPORTED void __program_Top(double * __restrict__ _argv, int _argc, int _argcount) ////__DACE:0 { ////__DACE:0 __program_Top_internal(_argv, _argc, _argcount); ////__DACE:0 } ////__DACE:0 ////__DACE:0 DACE_EXPORTED int __dace_init_Top(double * __restrict__ _argv, int _argc, int _argcount) ////__DACE:0 { ////__DACE:0 int __result = 0; ////__DACE:0 ////__DACE:0 return __result; ////__DACE:0 } ////__DACE:0 ////__DACE:0 DACE_EXPORTED void __dace_exit_Top(double * __restrict__ _argv, int _argc, int _argcount) ////__DACE:0 { ////__DACE:0 } ////__DACE:0
GB_unaryop__minv_uint8_bool.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_uint8_bool // op(A') function: GB_tran__minv_uint8_bool // C type: uint8_t // A type: bool // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 8) #define GB_ATYPE \ bool #define GB_CTYPE \ uint8_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 = GB_IMINV_UNSIGNED (x, 8) ; // casting #define GB_CASTING(z, x) \ uint8_t z = (uint8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_UINT8 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint8_bool ( uint8_t *restrict Cx, const bool *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_uint8_bool ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
transfer.c
/** @file transfer.c Documented transfer module. * * Julien Lesgourgues, 28.07.2013 * * This module has two purposes: * * - at the beginning, to compute the transfer functions \f$ * \Delta_l^{X} (q) \f$, and store them in tables used for * interpolation in other modules. * * - at any time in the code, to evaluate the transfer functions (for * a given mode, initial condition, type and multipole l) at any * wavenumber q (by interpolating within the interpolation table). * * Hence the following functions can be called from other modules: * * -# transfer_init() at the beginning (but after perturb_init() * and bessel_init()) * * -# transfer_functions_at_q() at any later time * * -# transfer_free() at the end, when no more calls to * transfer_functions_at_q() are needed * * Note that in the standard implementation of CLASS, only the pre-computed * values of the transfer functions are used, no interpolation is necessary; * hence the routine transfer_functions_at_q() is actually never called. */ #include "transfer.h" /** * Transfer function \f$ \Delta_l^{X} (q) \f$ at a given wavenumber q. * * For a given mode (scalar, vector, tensor), initial condition, type * (temperature, polarization, lensing, etc) and multipole, computes * the transfer function for an arbitrary value of q by interpolating * between pre-computed values of q. This * function can be called from whatever module at whatever time, * provided that transfer_init() has been called before, and * transfer_free() has not been called yet. * * Wavenumbers are called q in this module and k in the perturbation * module. In flat universes k=q. In non-flat universes q and k differ * through \f$ q2 = k2 + K(1+m)\f$, where m=0,1,2 for scalar, vector, * tensor. q should be used throughout the transfer module, excepted * when interpolating or manipulating the source functions S(k,tau) * calculated in the perturbation module: for a given value of q, this * should be done at the corresponding k(q). * * @param ptr Input: pointer to transfer structure * @param index_md Input: index of requested mode * @param index_ic Input: index of requested initial condition * @param index_tt Input: index of requested type * @param index_l Input: index of requested multipole * @param q Input: any wavenumber * @param transfer_function Output: transfer function * @return the error status */ int transfer_functions_at_q( struct transfers * ptr, int index_md, int index_ic, int index_tt, int index_l, double q, double * transfer_function ) { /** Summary: */ /** - interpolate in pre-computed table using array_interpolate_two() */ class_call(array_interpolate_two( ptr->q, 1, 0, ptr->transfer[index_md] +((index_ic * ptr->tt_size[index_md] + index_tt) * ptr->l_size[index_md] + index_l) * ptr->q_size, 1, ptr->q_size, q, transfer_function, 1, ptr->error_message), ptr->error_message, ptr->error_message); return _SUCCESS_; } /** * This routine initializes the transfers structure, (in particular, * computes table of transfer functions \f$ \Delta_l^{X} (q) \f$) * * Main steps: * * - initialize all indices in the transfers structure * and allocate all its arrays using transfer_indices_of_transfers(). * * - for each thread (in case of parallel run), initialize the fields of a memory zone called the transfer_workspace with transfer_workspace_init() * * - loop over q values. For each q, compute the Bessel functions if needed with transfer_update_HIS(), and defer the calculation of all transfer functions to transfer_compute_for_each_q() * - for each thread, free the the workspace with transfer_workspace_free() * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param pth Input: pointer to thermodynamics structure * @param ppt Input: pointer to perturbation structure * @param pnl Input: pointer to nonlinear structure * @param ptr Output: pointer to initialized transfers structure * @return the error status */ int transfer_init( struct precision * ppr, struct background * pba, struct thermo * pth, struct perturbs * ppt, struct nonlinear * pnl, struct transfers * ptr ) { /** Summary: */ /** - define local variables */ /* running index for wavenumbers */ int index_q; /* conformal time today */ double tau0; /* conformal time at recombination */ double tau_rec; /* order of magnitude of the oscillation period of transfer functions */ double q_period; /* maximum number of sampling times for transfer sources */ int tau_size_max; /* array of sources S(k,tau), just taken from perturbation module, or transformed if non-linear corrections are needed sources[index_md][index_ic * ppt->tp_size[index_md] + index_tp][index_tau * ppt->k_size[index_md] + index_k] */ double *** sources; /* array of source derivatives S''(k,tau) (second derivative with respect to k, not tau!), used to interpolate sources at the right values of k, sources_spline[index_md][index_ic * ppt->tp_size[index_md] + index_tp][index_tau * ppt->k_size[index_md] + index_k] */ double *** sources_spline; /* pointer on workspace (one per thread if openmp) */ struct transfer_workspace * ptw; /** - array with the correspondence between the index of sources in the perturbation module and in the transfer module, tp_of_tt[index_md][index_tt] */ int ** tp_of_tt; /* structure containing the flat spherical bessel functions */ HyperInterpStruct BIS; double xmax; /* This code can be optionally compiled with the openmp option for parallel computation. Inside parallel regions, the use of the command "return" is forbidden. For error management, instead of "return _FAILURE_", we will set the variable below to "abort = _TRUE_". This will lead to a "return _FAILURE_" just after leaving the parallel region. */ int abort; #ifdef _OPENMP /* instrumentation times */ double tstart, tstop, tspent; #endif /** - check whether any spectrum in harmonic space (i.e., any \f$C_l\f$'s) is actually requested */ if (ppt->has_cls == _FALSE_) { ptr->has_cls = _FALSE_; if (ptr->transfer_verbose > 0) printf("No harmonic space transfer functions to compute. Transfer module skipped.\n"); return _SUCCESS_; } else ptr->has_cls = _TRUE_; if (ptr->transfer_verbose > 0) fprintf(stdout,"Computing transfers\n"); /** - get number of modes (scalars, tensors...) */ ptr->md_size = ppt->md_size; /** - get conformal age / recombination time from background / thermodynamics structures (only place where these structures are used in this module) */ tau0 = pba->conformal_age; tau_rec = pth->tau_rec; /** - correspondence between k and l depend on angular diameter distance, i.e. on curvature. */ ptr->angular_rescaling = pth->angular_rescaling; /** - order of magnitude of the oscillation period of transfer functions */ q_period = 2.*_PI_/(tau0-tau_rec)*ptr->angular_rescaling; /** - initialize all indices in the transfers structure and allocate all its arrays using transfer_indices_of_transfers() */ class_call(transfer_indices_of_transfers(ppr,ppt,ptr,q_period,pba->K,pba->sgnK), ptr->error_message, ptr->error_message); /** - copy sources to a local array sources (in fact, only the pointers are copied, not the data), and eventually apply non-linear corrections to the sources */ class_alloc(sources, ptr->md_size*sizeof(double**), ptr->error_message); class_call(transfer_perturbation_copy_sources_and_nl_corrections(ppt,pnl,ptr,sources), ptr->error_message, ptr->error_message); /** - spline all the sources passed by the perturbation module with respect to k (in order to interpolate later at a given value of k) */ class_alloc(sources_spline, ptr->md_size*sizeof(double**), ptr->error_message); class_call(transfer_perturbation_source_spline(ppt,ptr,sources,sources_spline), ptr->error_message, ptr->error_message); /** - allocate and fill array describing the correspondence between perturbation types and transfer types */ class_alloc(tp_of_tt, ptr->md_size*sizeof(int*), ptr->error_message); class_call(transfer_get_source_correspondence(ppt,ptr,tp_of_tt), ptr->error_message, ptr->error_message); /** - evaluate maximum number of sampled times in the transfer sources: needs to be known here, in order to allocate a large enough workspace */ class_call(transfer_source_tau_size_max(ppr,pba,ppt,ptr,tau_rec,tau0,&tau_size_max), ptr->error_message, ptr->error_message); /** - compute flat spherical bessel functions */ xmax = ptr->q[ptr->q_size-1]*tau0; if (pba->sgnK == -1) xmax *= (ptr->l[ptr->l_size_max-1]/ppr->hyper_flat_approximation_nu)/asinh(ptr->l[ptr->l_size_max-1]/ppr->hyper_flat_approximation_nu)*1.01; class_call(hyperspherical_HIS_create(0, 1., ptr->l_size_max, ptr->l, ppr->hyper_x_min, xmax, ppr->hyper_sampling_flat, ptr->l[ptr->l_size_max-1]+1, ppr->hyper_phi_min_abs, &BIS, ptr->error_message), ptr->error_message, ptr->error_message); /* fprintf(stderr,"tau:%d l:%d q:%d\n", ppt->tau_size, ptr->l_size_max, ptr->q_size ); */ /** - eventually read the selection and evolution functions */ class_call(transfer_global_selection_read(ptr), ptr->error_message, ptr->error_message); /** - precompute window function for integrated nCl/sCl quantities*/ double* window; class_call(transfer_precompute_selection(ppr, pba, ppt, ptr, tau_rec, tau_size_max, &(window)), ptr->error_message, ptr->error_message); /* (a.3.) workspace, allocated in a parallel zone since in openmp version there is one workspace per thread */ /* initialize error management flag */ abort = _FALSE_; /* beginning of parallel region */ #pragma omp parallel \ shared(tau_size_max,ptr,ppr,pba,ppt,tp_of_tt,tau_rec,sources_spline,abort,BIS,tau0) \ private(ptw,index_q,tstart,tstop,tspent) { #ifdef _OPENMP tspent = 0.; #endif /* allocate workspace */ ptw = NULL; class_call_parallel(transfer_workspace_init(ptr, ppr, &ptw, ppt->tau_size, tau_size_max, pba->K, pba->sgnK, tau0-pth->tau_cut, &BIS), ptr->error_message, ptr->error_message); /** - loop over all wavenumbers (parallelized).*/ /* For each wavenumber: */ #pragma omp for schedule (dynamic) for (index_q = 0; index_q < ptr->q_size; index_q++) { #ifdef _OPENMP tstart = omp_get_wtime(); #endif if (ptr->transfer_verbose > 2) printf("Compute transfer for wavenumber [%d/%zu]\n",index_q,ptr->q_size-1); /* Update interpolation structure: */ class_call_parallel(transfer_update_HIS(ppr, ptr, ptw, index_q, tau0), ptr->error_message, ptr->error_message); class_call_parallel(transfer_compute_for_each_q(ppr, pba, ppt, ptr, tp_of_tt, index_q, tau_size_max, tau_rec, sources, sources_spline, window, ptw), ptr->error_message, ptr->error_message); #ifdef _OPENMP tstop = omp_get_wtime(); tspent += tstop-tstart; #endif #pragma omp flush(abort) } /* end of loop over wavenumber */ /* free workspace allocated inside parallel zone */ class_call_parallel(transfer_workspace_free(ptr,ptw), ptr->error_message, ptr->error_message); #ifdef _OPENMP if (ptr->transfer_verbose>1) printf("In %s: time spent in parallel region (loop over k's) = %e s for thread %d\n", __func__,tspent,omp_get_thread_num()); #endif } /* end of parallel region */ if (abort == _TRUE_) return _FAILURE_; /** - finally, free arrays allocated outside parallel zone */ free(window); class_call(transfer_perturbation_sources_spline_free(ppt,ptr,sources_spline), ptr->error_message, ptr->error_message); class_call(transfer_perturbation_sources_free(ppt,pnl,ptr,sources), ptr->error_message, ptr->error_message); class_call(transfer_free_source_correspondence(ptr,tp_of_tt), ptr->error_message, ptr->error_message); class_call(hyperspherical_HIS_free(&BIS,ptr->error_message), ptr->error_message, ptr->error_message); return _SUCCESS_; } /** * This routine frees all the memory space allocated by transfer_init(). * * To be called at the end of each run, only when no further calls to * transfer_functions_at_k() are needed. * * @param ptr Input: pointer to transfers structure (which fields must be freed) * @return the error status */ int transfer_free( struct transfers * ptr ) { int index_md; if (ptr->has_cls == _TRUE_) { for (index_md = 0; index_md < ptr->md_size; index_md++) { free(ptr->l_size_tt[index_md]); free(ptr->transfer[index_md]); free(ptr->k[index_md]); } free(ptr->tt_size); free(ptr->l_size_tt); free(ptr->l_size); free(ptr->l); free(ptr->q); free(ptr->k); free(ptr->transfer); if (ptr->nz_size > 0) { free(ptr->nz_z); free(ptr->nz_nz); free(ptr->nz_ddnz); } if (ptr->nz_evo_size > 0) { free(ptr->nz_evo_z); free(ptr->nz_evo_nz); free(ptr->nz_evo_dlog_nz); free(ptr->nz_evo_dd_dlog_nz); } } return _SUCCESS_; } /** * This routine defines all indices and allocates all tables * in the transfers structure * * Compute list of (k, l) values, allocate and fill corresponding * arrays in the transfers structure. Allocate the array of transfer * function tables. * * @param ppr Input: pointer to precision structure * @param ppt Input: pointer to perturbation structure * @param ptr Input/Output: pointer to transfer structure * @param q_period Input: order of magnitude of the oscillation period of transfer functions * @param K Input: spatial curvature (in absolute value) * @param sgnK Input: spatial curvature sign (open/closed/flat) * @return the error status */ int transfer_indices_of_transfers( struct precision * ppr, struct perturbs * ppt, struct transfers * ptr, double q_period, double K, int sgnK ) { /** Summary: */ /** - define local variables */ int index_md,index_tt,index_tt_common; /** - define indices for transfer types */ class_alloc(ptr->tt_size,ptr->md_size * sizeof(int),ptr->error_message); /** - type indices common to scalars and tensors */ index_tt = 0; class_define_index(ptr->index_tt_t2,ppt->has_cl_cmb_temperature, index_tt,1); class_define_index(ptr->index_tt_e, ppt->has_cl_cmb_polarization,index_tt,1); index_tt_common=index_tt; /** - type indices for scalars */ if (ppt->has_scalars == _TRUE_) { index_tt = index_tt_common; class_define_index(ptr->index_tt_t0, ppt->has_cl_cmb_temperature, index_tt,1); class_define_index(ptr->index_tt_t1, ppt->has_cl_cmb_temperature, index_tt,1); class_define_index(ptr->index_tt_lcmb, ppt->has_cl_cmb_lensing_potential,index_tt,1); class_define_index(ptr->index_tt_density,ppt->has_nc_density, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_rsd, ppt->has_nc_rsd, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_d0, ppt->has_nc_rsd, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_d1, ppt->has_nc_rsd, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_nc_lens,ppt->has_nc_lens, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_nc_g1, ppt->has_nc_gr, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_nc_g2, ppt->has_nc_gr, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_nc_g3, ppt->has_nc_gr, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_nc_g4, ppt->has_nc_gr, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_nc_g5, ppt->has_nc_gr, index_tt,ppt->selection_num); class_define_index(ptr->index_tt_lensing,ppt->has_cl_lensing_potential, index_tt,ppt->selection_num); ptr->tt_size[ppt->index_md_scalars]=index_tt; } /** - type indices for vectors */ if (ppt->has_vectors == _TRUE_) { index_tt = index_tt_common; class_define_index(ptr->index_tt_t1,ppt->has_cl_cmb_temperature, index_tt,1); class_define_index(ptr->index_tt_b, ppt->has_cl_cmb_polarization,index_tt,1); ptr->tt_size[ppt->index_md_vectors]=index_tt; } /** - type indices for tensors */ if (ppt->has_tensors == _TRUE_) { index_tt = index_tt_common; class_define_index(ptr->index_tt_b, ppt->has_cl_cmb_polarization,index_tt,1); ptr->tt_size[ppt->index_md_tensors]=index_tt; } /** - allocate arrays of (k, l) values and transfer functions */ /* number of l values for each mode and type, l_size_tt[index_md][index_tt], and maximized for each mode, l_size[index_md] */ class_alloc(ptr->l_size,ptr->md_size * sizeof(int),ptr->error_message); class_alloc(ptr->l_size_tt,ptr->md_size * sizeof(int *),ptr->error_message); for (index_md = 0; index_md < ptr->md_size; index_md++) { class_alloc(ptr->l_size_tt[index_md],ptr->tt_size[index_md] * sizeof(int),ptr->error_message); } /* array (of array) of transfer functions for each mode, transfer[index_md] */ class_alloc(ptr->transfer,ptr->md_size * sizeof(double *),ptr->error_message); /** - get q values using transfer_get_q_list() */ class_call(transfer_get_q_list(ppr,ppt,ptr,q_period,K,sgnK), ptr->error_message, ptr->error_message); /** - get k values using transfer_get_k_list() */ class_call(transfer_get_k_list(ppt,ptr,K), ptr->error_message, ptr->error_message); /* for testing, it can be useful to print the q list in a file: */ /* FILE * out=fopen("output/q","w"); int index_q; for (index_q=0; index_q < ptr->q_size; index_q++) { fprintf(out,"%d %e %e %e %e\n", index_q, ptr->q[index_q], ptr->k[0][index_q], ptr->q[index_q]/sqrt(sgnK*K), ptr->q[index_q+1]-ptr->q[index_q]); } fclose(out); */ /** - get l values using transfer_get_l_list() */ class_call(transfer_get_l_list(ppr,ppt,ptr), ptr->error_message, ptr->error_message); /** - loop over modes (scalar, etc). For each mode: */ for (index_md = 0; index_md < ptr->md_size; index_md++) { /** - allocate arrays of transfer functions, (ptr->transfer[index_md])[index_ic][index_tt][index_l][index_k] */ class_alloc(ptr->transfer[index_md], ppt->ic_size[index_md] * ptr->tt_size[index_md] * ptr->l_size[index_md] * ptr->q_size * sizeof(double), ptr->error_message); } return _SUCCESS_; } int transfer_perturbation_copy_sources_and_nl_corrections( struct perturbs * ppt, struct nonlinear * pnl, struct transfers * ptr, double *** sources ) { int index_md; int index_ic; int index_tp; int index_k; int index_tau; for (index_md = 0; index_md < ptr->md_size; index_md++) { class_alloc(sources[index_md], ppt->ic_size[index_md]*ppt->tp_size[index_md]*sizeof(double*), ptr->error_message); for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) { for (index_tp = 0; index_tp < ppt->tp_size[index_md]; index_tp++) { if ((pnl->method != nl_none) && (_scalars_) && (((ppt->has_source_delta_m == _TRUE_) && (index_tp == ppt->index_tp_delta_m)) || ((ppt->has_source_delta_cb == _TRUE_) && (index_tp == ppt->index_tp_delta_cb)) || ((ppt->has_source_theta_m == _TRUE_) && (index_tp == ppt->index_tp_theta_m)) || ((ppt->has_source_theta_cb == _TRUE_) && (index_tp == ppt->index_tp_theta_cb)) || ((ppt->has_source_phi == _TRUE_) && (index_tp == ppt->index_tp_phi)) || ((ppt->has_source_phi_prime == _TRUE_) && (index_tp == ppt->index_tp_phi_prime)) || ((ppt->has_source_phi_plus_psi == _TRUE_) && (index_tp == ppt->index_tp_phi_plus_psi)) || ((ppt->has_source_psi == _TRUE_) && (index_tp == ppt->index_tp_psi)))) { class_alloc(sources[index_md][index_ic * ppt->tp_size[index_md] + index_tp], ppt->k_size[index_md]*ppt->tau_size*sizeof(double), ptr->error_message); for (index_tau=0; index_tau<ppt->tau_size; index_tau++) { for (index_k=0; index_k<ppt->k_size[index_md]; index_k++) { if (((ppt->has_source_delta_cb == _TRUE_) && (index_tp == ppt->index_tp_delta_cb)) || ((ppt->has_source_theta_cb == _TRUE_) && (index_tp == ppt->index_tp_theta_cb))){ sources[index_md] [index_ic * ppt->tp_size[index_md] + index_tp] [index_tau * ppt->k_size[index_md] + index_k] = ppt->sources[index_md] [index_ic * ppt->tp_size[index_md] + index_tp] [index_tau * ppt->k_size[index_md] + index_k] * pnl->nl_corr_density[pnl->index_pk_cb][index_tau * ppt->k_size[index_md] + index_k]; } else{ sources[index_md] [index_ic * ppt->tp_size[index_md] + index_tp] [index_tau * ppt->k_size[index_md] + index_k] = ppt->sources[index_md] [index_ic * ppt->tp_size[index_md] + index_tp] [index_tau * ppt->k_size[index_md] + index_k] * pnl->nl_corr_density[pnl->index_pk_m][index_tau * ppt->k_size[index_md] + index_k]; } } } } else { sources[index_md][index_ic * ppt->tp_size[index_md] + index_tp] = ppt->sources[index_md][index_ic * ppt->tp_size[index_md] + index_tp]; } } } } return _SUCCESS_; } int transfer_perturbation_source_spline( struct perturbs * ppt, struct transfers * ptr, double *** sources, double *** sources_spline ) { int index_md; int index_ic; int index_tp; for (index_md = 0; index_md < ptr->md_size; index_md++) { class_alloc(sources_spline[index_md], ppt->ic_size[index_md]*ppt->tp_size[index_md]*sizeof(double*), ptr->error_message); for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) { for (index_tp = 0; index_tp < ppt->tp_size[index_md]; index_tp++) { class_alloc(sources_spline[index_md][index_ic * ppt->tp_size[index_md] + index_tp], ppt->k_size[index_md]*ppt->tau_size*sizeof(double), ptr->error_message); class_call(array_spline_table_columns2(ppt->k[index_md], ppt->k_size[index_md], sources[index_md][index_ic * ppt->tp_size[index_md] + index_tp], ppt->tau_size, sources_spline[index_md][index_ic * ppt->tp_size[index_md] + index_tp], _SPLINE_EST_DERIV_, ptr->error_message), ptr->error_message, ptr->error_message); } } } return _SUCCESS_; } int transfer_perturbation_sources_free( struct perturbs * ppt, struct nonlinear * pnl, struct transfers * ptr, double *** sources ) { int index_md; int index_ic; int index_tp; for (index_md = 0; index_md < ptr->md_size; index_md++) { for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) { for (index_tp = 0; index_tp < ppt->tp_size[index_md]; index_tp++) { if ((pnl->method != nl_none) && (_scalars_) && (((ppt->has_source_delta_m == _TRUE_) && (index_tp == ppt->index_tp_delta_m)) || ((ppt->has_source_theta_m == _TRUE_) && (index_tp == ppt->index_tp_theta_m)) || ((ppt->has_source_delta_cb == _TRUE_) && (index_tp == ppt->index_tp_delta_cb)) || ((ppt->has_source_theta_cb == _TRUE_) && (index_tp == ppt->index_tp_theta_cb)) || ((ppt->has_source_phi == _TRUE_) && (index_tp == ppt->index_tp_phi)) || ((ppt->has_source_phi_prime == _TRUE_) && (index_tp == ppt->index_tp_phi_prime)) || ((ppt->has_source_phi_plus_psi == _TRUE_) && (index_tp == ppt->index_tp_phi_plus_psi)) || ((ppt->has_source_psi == _TRUE_) && (index_tp == ppt->index_tp_psi)))) { free(sources[index_md][index_ic * ppt->tp_size[index_md] + index_tp]); } } } free(sources[index_md]); } free(sources); return _SUCCESS_; } int transfer_perturbation_sources_spline_free( struct perturbs * ppt, struct transfers * ptr, double *** sources_spline ) { int index_md; int index_ic; int index_tp; for (index_md = 0; index_md < ptr->md_size; index_md++) { for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) { for (index_tp = 0; index_tp < ppt->tp_size[index_md]; index_tp++) { free(sources_spline[index_md][index_ic * ppt->tp_size[index_md] + index_tp]); } } free(sources_spline[index_md]); } free(sources_spline); return _SUCCESS_; } /** * This routine defines the number and values of multipoles l for all modes. * * @param ppr Input: pointer to precision structure * @param ppt Input: pointer to perturbation structure * @param ptr Input/Output: pointer to transfers structure containing l's * @return the error status */ int transfer_get_l_list( struct precision * ppr, struct perturbs * ppt, struct transfers * ptr ) { int index_l; int l_max=0; int index_md; int index_tt; int increment,current_l; /** Summary: */ /* fprintf(stderr,"rescaling %e logstep %e linstep %e\n", ptr->angular_rescaling, pow(ppr->l_logstep,ptr->angular_rescaling), ppr->l_linstep*ptr->angular_rescaling); */ /* check that largests need value of l_max */ if (ppt->has_cls == _TRUE_) { if (ppt->has_scalars == _TRUE_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) || (ppt->has_cl_cmb_polarization == _TRUE_) || (ppt->has_cl_cmb_lensing_potential == _TRUE_)) l_max=MAX(ppt->l_scalar_max,l_max); if ((ppt->has_cl_lensing_potential == _TRUE_) || (ppt->has_cl_number_count == _TRUE_)) l_max=MAX(ppt->l_lss_max,l_max); } if (ppt->has_tensors == _TRUE_) l_max=MAX(ppt->l_tensor_max,l_max); } /** - allocate and fill l array */ /** - start from l = 2 and increase with logarithmic step */ index_l = 0; current_l = 2; increment = MAX((int)(current_l * (pow(ppr->l_logstep,ptr->angular_rescaling)-1.)),1); while (((current_l+increment) < l_max) && (increment < ppr->l_linstep*ptr->angular_rescaling)) { index_l ++; current_l += increment; increment = MAX((int)(current_l * (pow(ppr->l_logstep,ptr->angular_rescaling)-1.)),1); } /** - when the logarithmic step becomes larger than some linear step, stick to this linear step till l_max */ increment = ppr->l_linstep*ptr->angular_rescaling; while ((current_l+increment) <= l_max) { index_l ++; current_l += increment; } /** - last value set to exactly l_max */ if (current_l != l_max) { index_l ++; current_l = l_max; } ptr->l_size_max = index_l+1; /** - so far we just counted the number of values. Now repeat the whole thing but fill array with values. */ class_alloc(ptr->l,ptr->l_size_max*sizeof(int),ptr->error_message); index_l = 0; ptr->l[0] = 2; increment = MAX((int)(ptr->l[0] * (pow(ppr->l_logstep,ptr->angular_rescaling)-1.)),1); while (((ptr->l[index_l]+increment) < l_max) && (increment < ppr->l_linstep*ptr->angular_rescaling)) { index_l ++; ptr->l[index_l]=ptr->l[index_l-1]+increment; increment = MAX((int)(ptr->l[index_l] * (pow(ppr->l_logstep,ptr->angular_rescaling)-1.)),1); } increment = ppr->l_linstep*ptr->angular_rescaling; while ((ptr->l[index_l]+increment) <= l_max) { index_l ++; ptr->l[index_l]=ptr->l[index_l-1]+increment; } if (ptr->l[index_l] != l_max) { index_l ++; ptr->l[index_l]= l_max; } /* for each mode and type, find relevant size of l array, l_size_tt[index_md][index_tt] (since for some modes and types l_max can be smaller). Also, maximize this size for each mode to find l_size[index_md]. */ for (index_md=0; index_md < ppt->md_size; index_md++) { ptr->l_size[index_md] = 0; for (index_tt=0;index_tt<ptr->tt_size[index_md];index_tt++) { if (_scalars_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) && ((index_tt == ptr->index_tt_t0) || (index_tt == ptr->index_tt_t1) || (index_tt == ptr->index_tt_t2))) l_max=ppt->l_scalar_max; if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e)) l_max=ppt->l_scalar_max; if ((ppt->has_cl_cmb_lensing_potential == _TRUE_) && (index_tt == ptr->index_tt_lcmb)) l_max=ppt->l_scalar_max; if ((_index_tt_in_range_(ptr->index_tt_density, ppt->selection_num, ppt->has_nc_density)) || (_index_tt_in_range_(ptr->index_tt_rsd, ppt->selection_num, ppt->has_nc_rsd)) || (_index_tt_in_range_(ptr->index_tt_d0, ppt->selection_num, ppt->has_nc_rsd)) || (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd)) || (_index_tt_in_range_(ptr->index_tt_nc_lens, ppt->selection_num, ppt->has_nc_lens))|| (_index_tt_in_range_(ptr->index_tt_nc_g1, ppt->selection_num, ppt->has_nc_gr)) || (_index_tt_in_range_(ptr->index_tt_nc_g2, ppt->selection_num, ppt->has_nc_gr)) || (_index_tt_in_range_(ptr->index_tt_nc_g3, ppt->selection_num, ppt->has_nc_gr)) || (_index_tt_in_range_(ptr->index_tt_nc_g4, ppt->selection_num, ppt->has_nc_gr)) || (_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr)) ) l_max=ppt->l_lss_max; if ((ppt->has_cl_lensing_potential == _TRUE_) && (index_tt >= ptr->index_tt_lensing) && (index_tt < ptr->index_tt_lensing+ppt->selection_num)) l_max=ppt->l_lss_max; } if (_tensors_) { l_max = ppt->l_tensor_max; } class_test(l_max > ptr->l[ptr->l_size_max-1], ptr->error_message, "For mode %d, type %d, asked for l_max=%d greater than in Bessel table where l_max=%d", index_md, index_tt, l_max, ptr->l[ptr->l_size_max-1]); index_l=0; while (ptr->l[index_l] < l_max) index_l++; ptr->l_size_tt[index_md][index_tt]=index_l+1; if (ptr->l_size_tt[index_md][index_tt] < ptr->l_size_max) ptr->l_size_tt[index_md][index_tt]++; if (ptr->l_size_tt[index_md][index_tt] < ptr->l_size_max) ptr->l_size_tt[index_md][index_tt]++; ptr->l_size[index_md] = MAX(ptr->l_size[index_md],ptr->l_size_tt[index_md][index_tt]); } } return _SUCCESS_; } /** * This routine defines the number and values of wavenumbers q for * each mode (goes smoothly from logarithmic step for small q's to * linear step for large q's). * * @param ppr Input: pointer to precision structure * @param ppt Input: pointer to perturbation structure * @param ptr Input/Output: pointer to transfers structure containing q's * @param q_period Input: order of magnitude of the oscillation period of transfer functions * @param K Input: spatial curvature (in absolute value) * @param sgnK Input: spatial curvature sign (open/closed/flat) * @return the error status */ int transfer_get_q_list( struct precision * ppr, struct perturbs * ppt, struct transfers * ptr, double q_period, double K, int sgnK ) { int index_q; double q,q_min=0.,q_max=0.,q_step,k_max; int nu, nu_min, nu_proposed; int q_size_max; double q_approximation; double last_step=0.; int last_index=0; double q_logstep_spline; double q_logstep_trapzd; int index_md; /* first and last value in flat case*/ if (sgnK == 0) { q_min = ppt->k_min; q_max = 0.; for (index_md=0; index_md<ppt->md_size; index_md++) { q_max = MAX(q_max,ppt->k[index_md][ppt->k_size_cl[index_md]-1]); } K=0; } /* first and last value in open case*/ else if (sgnK == -1) { q_min = sqrt(ppt->k_min*ppt->k_min+K); k_max = 0.; for (index_md=0; index_md<ppt->md_size; index_md++) { k_max = MAX(k_max,ppt->k[index_md][ppt->k_size_cl[index_md]-1]); } q_max = sqrt(k_max*k_max+K); if (ppt->has_vectors == _TRUE_) q_max = MIN(q_max,sqrt(k_max*k_max+2.*K)); if (ppt->has_tensors == _TRUE_) q_max = MIN(q_max,sqrt(k_max*k_max+3.*K)); } /* first and last value in closed case*/ else if (sgnK == 1) { nu_min = 3; q_min = nu_min * sqrt(K); q_max = 0.; for (index_md=0; index_md<ppt->md_size; index_md++) { q_max = MAX(q_max,ppt->k[index_md][ppt->k_size_cl[index_md]-1]); } } /* adjust the parameter governing the log step size to curvature */ q_logstep_spline = ppr->q_logstep_spline/pow(ptr->angular_rescaling,ppr->q_logstep_open); q_logstep_trapzd = ppr->q_logstep_trapzd; /* very conservative estimate of number of values */ if (sgnK == 1) { q_approximation = MIN(ppr->hyper_flat_approximation_nu,(q_max/sqrt(K))); /* max contribution from integer nu values */ q_step = 1.+q_period*ppr->q_logstep_trapzd; q_size_max = 2*(int)(log(q_approximation/q_min)/log(q_step)); q_step = q_period*ppr->q_linstep; q_size_max += 2*(int)((q_approximation-q_min)/q_step); /* max contribution from non-integer nu values */ q_step = 1.+q_period*ppr->q_logstep_spline; q_size_max += 2*(int)(log(q_max/q_approximation)/log(q_step)); q_step = q_period*ppr->q_linstep; q_size_max += 2*(int)((q_max-q_approximation)/q_step); } else { /* max contribution from non-integer nu values */ q_step = 1.+q_period*ppr->q_logstep_spline; q_size_max = 5*(int)(log(q_max/q_min)/log(q_step)); q_step = q_period*ppr->q_linstep; q_size_max += 5*(int)((q_max-q_min)/q_step); } /* create array with this conservative size estimate. The exact size will be readjusted below, after filling the array. */ class_alloc(ptr->q, q_size_max*sizeof(double), ptr->error_message); /* assign the first value before starting the loop */ index_q = 0; ptr->q[index_q] = q_min; nu = 3; index_q++; /* loop over the values */ while (ptr->q[index_q-1] < q_max) { class_test(index_q >= q_size_max,ptr->error_message,"buggy q-list definition"); /* step size formula in flat/open case. Step goes gradually from logarithmic to linear: - in the small q limit, it is logarithmic with: (delta q / q) = q_period * q_logstep_spline - in the large q limit, it is linear with: (delta q) = q_period * ppr->q_linstep */ if (sgnK<=0) { q = ptr->q[index_q-1] + q_period * ppr->q_linstep * ptr->q[index_q-1] / (ptr->q[index_q-1] + ppr->q_linstep/q_logstep_spline); } /* step size formula in closed case. Same thing excepted that: - in the small q limit, the logarithmic step is reduced, being given by q_logstep_trapzd, and values are rounded to integer values of nu=q/sqrt(K). This happens as long as nu<nu_flat_approximation - for nu>nu_flat_approximation, the step gradually catches up the same expression as in the flat/open case, and there is no need to round up to integer nu's. */ else { if (nu < (int)ppr->hyper_flat_approximation_nu) { q = ptr->q[index_q-1] + q_period * ppr->q_linstep * ptr->q[index_q-1] / (ptr->q[index_q-1] + ppr->q_linstep/q_logstep_trapzd); nu_proposed = (int)(q/sqrt(K)); if (nu_proposed <= nu+1) nu = nu+1; else nu = nu_proposed; q = nu*sqrt(K); last_step = q - ptr->q[index_q-1]; last_index = index_q+1; } else { q_step = q_period * ppr->q_linstep * ptr->q[index_q-1] / (ptr->q[index_q-1] + ppr->q_linstep/q_logstep_spline); if (index_q-last_index < (int)ppr->q_numstep_transition) q = ptr->q[index_q-1] + (1-(double)(index_q-last_index)/ppr->q_numstep_transition) * last_step + (double)(index_q-last_index)/ppr->q_numstep_transition * q_step; else q = ptr->q[index_q-1] + q_step; } } ptr->q[index_q] = q; index_q++; } /* infer total number of values (also checking if we overshot the last point) */ if (ptr->q[index_q-1] > q_max) ptr->q_size=index_q-1; else ptr->q_size=index_q; class_test(ptr->q_size<2,ptr->error_message,"buggy q-list definition"); //fprintf(stderr,"q_size_max=%d q_size = %d\n",q_size_max,ptr->q_size); //fprintf(stderr,"q_size = %d\n",ptr->q_size); /* now, readjust array size */ class_realloc(ptr->q, ptr->q, ptr->q_size*sizeof(double), ptr->error_message); /* in curved universe, check at which index the flat rescaling approximation will start being used */ if (sgnK != 0) { q_approximation = ppr->hyper_flat_approximation_nu * sqrt(sgnK*K); for (ptr->index_q_flat_approximation=0; ptr->index_q_flat_approximation < ptr->q_size-1; ptr->index_q_flat_approximation++) { if (ptr->q[ptr->index_q_flat_approximation] > q_approximation) break; } if (ptr->transfer_verbose > 1) printf("Flat bessel approximation spares hyperspherical bessel computations for %zu wavenumebrs over a total of %zu\n", ptr->q_size-ptr->index_q_flat_approximation,ptr->q_size); } return _SUCCESS_; } /** * This routine infers from the q values a list of corresponding k * values for each mode. * * @param ppt Input: pointer to perturbation structure * @param ptr Input/Output: pointer to transfers structure containing q's * @param K Input: spatial curvature * @return the error status */ int transfer_get_k_list( struct perturbs * ppt, struct transfers * ptr, double K ) { int index_md; int index_q; double m=0.; class_alloc(ptr->k,ptr->md_size*sizeof(double*),ptr->error_message); for (index_md = 0; index_md < ptr->md_size; index_md++) { class_alloc(ptr->k[index_md],ptr->q_size*sizeof(double),ptr->error_message); if (_scalars_) { m=0.; } if (_vectors_) { m=1.; } if (_tensors_) { m=2.; } for (index_q=0; index_q < ptr->q_size; index_q++) { ptr->k[index_md][index_q] = sqrt(ptr->q[index_q]*ptr->q[index_q]-K*(m+1.)); } if (ptr->k[index_md][0] < ppt->k[index_md][0]){ /* If ptr->k[index_md][0] < ppt->k[index_md][0] at the level of rounding, adjust first value of k_list to avoid interpolation errors: */ if ((ppt->k[index_md][0]-ptr->k[index_md][0]) < 10.*DBL_EPSILON){ ptr->k[index_md][0] = ppt->k[index_md][0]; } else{ class_stop(ptr->error_message, "bug in k_list calculation: in perturbation module k_min=%e, in transfer module k_min[mode=%d]=%e, interpolation impossible", ppt->k[0][0], index_md, ptr->k[index_md][0]); } } /* class_test(ptr->k[index_md][0] < ppt->k[index_md][0], ptr->error_message, "bug in k_list calculation: in perturbation module k_min=%e, in transfer module k_min[mode=%d]=%e, interpolation impossible", ppt->k[0][0], index_md, ptr->k[index_md][0]); */ class_test(ptr->k[index_md][ptr->q_size-1] > ppt->k[0][ppt->k_size_cl[0]-1], ptr->error_message, "bug in k_list calculation: in perturbation module k_max=%e, in transfer module k_max[mode=%d]=%e, interpolation impossible", ppt->k[0][ppt->k_size_cl[0]], index_md, ptr->k[index_md][ptr->q_size-1]); } return _SUCCESS_; } /** * This routine defines the correspondence between the sources in the * perturbation and transfer module. * * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure containing l's * @param tp_of_tt Input/Output: array with the correspondence (allocated before, filled here) * @return the error status */ int transfer_get_source_correspondence( struct perturbs * ppt, struct transfers * ptr, int ** tp_of_tt ) { /** Summary: */ /** - running index on modes */ int index_md; /** - running index on transfer types */ int index_tt; /** - which source are we considering? Define correspondence between transfer types and source types */ for (index_md = 0; index_md < ptr->md_size; index_md++) { class_alloc(tp_of_tt[index_md],ptr->tt_size[index_md]*sizeof(int),ptr->error_message); for (index_tt=0; index_tt<ptr->tt_size[index_md]; index_tt++) { if (_scalars_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t0)) tp_of_tt[index_md][index_tt]=ppt->index_tp_t0; if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t1)) tp_of_tt[index_md][index_tt]=ppt->index_tp_t1; if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t2)) tp_of_tt[index_md][index_tt]=ppt->index_tp_t2; if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e)) tp_of_tt[index_md][index_tt]=ppt->index_tp_p; if ((ppt->has_cl_cmb_lensing_potential == _TRUE_) && (index_tt == ptr->index_tt_lcmb)) tp_of_tt[index_md][index_tt]=ppt->index_tp_phi_plus_psi; if (_index_tt_in_range_(ptr->index_tt_density, ppt->selection_num, ppt->has_nc_density)) /* use here delta_cb rather than delta_m if density number counts calculated only for cold dark matter + baryon */ /* (this important comment is referenced in a WARNING message in perturbations.c) */ tp_of_tt[index_md][index_tt]=ppt->index_tp_delta_m; if (_index_tt_in_range_(ptr->index_tt_rsd, ppt->selection_num, ppt->has_nc_rsd)) tp_of_tt[index_md][index_tt]=ppt->index_tp_theta_m; if (_index_tt_in_range_(ptr->index_tt_d0, ppt->selection_num, ppt->has_nc_rsd)) tp_of_tt[index_md][index_tt]=ppt->index_tp_theta_m; if (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd)) tp_of_tt[index_md][index_tt]=ppt->index_tp_theta_m; if (_index_tt_in_range_(ptr->index_tt_nc_lens, ppt->selection_num, ppt->has_nc_lens)) tp_of_tt[index_md][index_tt]=ppt->index_tp_phi_plus_psi; if (_index_tt_in_range_(ptr->index_tt_nc_g1, ppt->selection_num, ppt->has_nc_gr)) tp_of_tt[index_md][index_tt]=ppt->index_tp_psi; if (_index_tt_in_range_(ptr->index_tt_nc_g2, ppt->selection_num, ppt->has_nc_gr)) tp_of_tt[index_md][index_tt]=ppt->index_tp_phi; if (_index_tt_in_range_(ptr->index_tt_nc_g3, ppt->selection_num, ppt->has_nc_gr)) tp_of_tt[index_md][index_tt]=ppt->index_tp_phi_prime; if (_index_tt_in_range_(ptr->index_tt_nc_g4, ppt->selection_num, ppt->has_nc_gr)) tp_of_tt[index_md][index_tt]=ppt->index_tp_phi_plus_psi; if (_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr)) tp_of_tt[index_md][index_tt]=ppt->index_tp_phi_plus_psi; if ((ppt->has_cl_lensing_potential == _TRUE_) && (index_tt >= ptr->index_tt_lensing) && (index_tt < ptr->index_tt_lensing+ppt->selection_num)) tp_of_tt[index_md][index_tt]=ppt->index_tp_phi_plus_psi; } if (_vectors_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t1)) tp_of_tt[index_md][index_tt]=ppt->index_tp_t1; if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t2)) tp_of_tt[index_md][index_tt]=ppt->index_tp_t2; if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e)) tp_of_tt[index_md][index_tt]=ppt->index_tp_p; if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_b)) tp_of_tt[index_md][index_tt]=ppt->index_tp_p; } if (_tensors_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t2)) tp_of_tt[index_md][index_tt]=ppt->index_tp_t2; if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e)) tp_of_tt[index_md][index_tt]=ppt->index_tp_p; if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_b)) tp_of_tt[index_md][index_tt]=ppt->index_tp_p; } } } return _SUCCESS_; } int transfer_free_source_correspondence( struct transfers * ptr, int ** tp_of_tt ) { int index_md; for (index_md = 0; index_md < ptr->md_size; index_md++) { free(tp_of_tt[index_md]); } free(tp_of_tt); return _SUCCESS_; } int transfer_source_tau_size_max( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, double tau_rec, double tau0, int * tau_size_max ) { int index_md; int index_tt; int tau_size_tt=0; *tau_size_max = 0; for (index_md = 0; index_md < ptr->md_size; index_md++) { for (index_tt = 0; index_tt < ptr->tt_size[index_md]; index_tt++) { class_call(transfer_source_tau_size(ppr, pba, ppt, ptr, tau_rec, tau0, index_md, index_tt, &tau_size_tt), ptr->error_message, ptr->error_message); *tau_size_max = MAX(*tau_size_max,tau_size_tt); } } return _SUCCESS_; } /** * the code makes a distinction between "perturbation sources" * (e.g. gravitational potential) and "transfer sources" (e.g. total * density fluctuations, obtained through the Poisson equation, and * observed with a given selection function). * * This routine computes the number of sampled time values for each type * of transfer sources. * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param tau_rec Input: recombination time * @param tau0 Input: time today * @param index_md Input: index of the mode (scalar, tensor) * @param index_tt Input: index of transfer type * @param tau_size Output: pointer to number of sampled times * @return the error status */ int transfer_source_tau_size( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, double tau_rec, double tau0, int index_md, int index_tt, int * tau_size) { /* values of conformal time */ double tau_min,tau_mean,tau_max; /* minimum value of index_tt */ int index_tau_min; /* value of l at which limber approximation is switched on */ int l_limber; /* current redshift bin number */ int bin=0; /* scalar mode */ if (_scalars_) { /* scalar temperature */ if ((ppt->has_cl_cmb_temperature == _TRUE_) && ((index_tt == ptr->index_tt_t0) || (index_tt == ptr->index_tt_t1) || (index_tt == ptr->index_tt_t2))) *tau_size = ppt->tau_size; /* scalar polarization */ if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e)) *tau_size = ppt->tau_size; /* cmb lensing potential */ if ((ppt->has_cl_cmb_lensing_potential == _TRUE_) && (index_tt == ptr->index_tt_lcmb)) { /* find times before recombination, that will be thrown away */ index_tau_min=0; while (ppt->tau_sampling[index_tau_min]<=tau_rec) index_tau_min++; /* infer number of time steps after removing early times */ *tau_size = ppt->tau_size-index_tau_min; } /* density Cl's */ if (_nonintegrated_ncl_) { /* bin number associated to particular redshift bin and selection function */ if (_index_tt_in_range_(ptr->index_tt_density, ppt->selection_num, ppt->has_nc_density)) bin = index_tt - ptr->index_tt_density; if (_index_tt_in_range_(ptr->index_tt_rsd, ppt->selection_num, ppt->has_nc_rsd)) bin = index_tt - ptr->index_tt_rsd; if (_index_tt_in_range_(ptr->index_tt_d0, ppt->selection_num, ppt->has_nc_rsd)) bin = index_tt - ptr->index_tt_d0; if (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd)) bin = index_tt - ptr->index_tt_d1; if (_index_tt_in_range_(ptr->index_tt_nc_g1, ppt->selection_num, ppt->has_nc_gr)) bin = index_tt - ptr->index_tt_nc_g1; if (_index_tt_in_range_(ptr->index_tt_nc_g2, ppt->selection_num, ppt->has_nc_gr)) bin = index_tt - ptr->index_tt_nc_g2; if (_index_tt_in_range_(ptr->index_tt_nc_g3, ppt->selection_num, ppt->has_nc_gr)) bin = index_tt - ptr->index_tt_nc_g3; /* time interval for this bin */ class_call(transfer_selection_times(ppr, pba, ppt, ptr, bin, &tau_min, &tau_mean, &tau_max), ptr->error_message, ptr->error_message); /* case selection=dirac */ if (tau_min == tau_max) { *tau_size = 1; } /* other cases (gaussian, top-hat...) */ else { /* check that selection function well sampled */ *tau_size = (int)ppr->selection_sampling; /* value of l at which the code switches to Limber approximation (necessary for next step) */ l_limber=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[bin]; /* check that bessel well sampled, if not define finer sampling overwriting the previous one. One Bessel oscillations corresponds to [Delta tau]=2pi/k. This is minimal for largest relevant k_max, namely k_max=l_limber/(tau0-tau_mean). We need to cut the interval (tau_max-tau_min) in pieces of size [Delta tau]=2pi/k_max. This gives the number below. */ *tau_size=MAX(*tau_size,(int)((tau_max-tau_min)/((tau0-tau_mean)/MIN(l_limber,ppt->l_lss_max)))*ppr->selection_sampling_bessel); } } /* galaxy lensing Cl's, differs from density Cl's since the source function will spread from the selection function region up to tau0 */ if (_integrated_ncl_) { /* bin number associated to particular redshift bin and selection function */ if (_index_tt_in_range_(ptr->index_tt_lensing, ppt->selection_num, ppt->has_cl_lensing_potential)) bin = index_tt - ptr->index_tt_lensing; if (_index_tt_in_range_(ptr->index_tt_nc_lens, ppt->selection_num, ppt->has_nc_lens)) bin = index_tt - ptr->index_tt_nc_lens; if (_index_tt_in_range_(ptr->index_tt_nc_g4, ppt->selection_num, ppt->has_nc_gr)) bin = index_tt - ptr->index_tt_nc_g4; if (_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr)) bin = index_tt - ptr->index_tt_nc_g5; /* time interval for this bin */ class_call(transfer_selection_times(ppr, pba, ppt, ptr, bin, &tau_min, &tau_mean, &tau_max), ptr->error_message, ptr->error_message); /* check that selection function well sampled */ *tau_size = (int)ppr->selection_sampling; /* value of l at which the code switches to Limber approximation (necessary for next step) */ if(_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr)) { /* Even if G5 is integrated along the line-of-sight, we do not apply the same Limber criteria as for the other integrated terms, because here we have the derivative of the Bessel. */ l_limber=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[bin]; *tau_size=MAX(*tau_size,(int)((tau0-tau_min)/((tau0-tau_mean)/2./MIN(l_limber,ppt->l_lss_max)))*ppr->selection_sampling_bessel); } else { l_limber=ppr->l_switch_limber_for_nc_los_over_z*ppt->selection_mean[bin]; /* check that bessel well sampled, if not define finer sampling overwriting the previous one. One Bessel oscillations corresponds to [Delta tau]=2pi/k. This is minimal for largest relevant k_max, namely k_max=l_limber/((tau0-tau_mean)/2). We need to cut the interval (tau_0-tau_min) in pieces of size [Delta tau]=2pi/k_max. This gives the number below. */ *tau_size=MAX(*tau_size,(int)((tau0-tau_min)/((tau0-tau_mean)/2./MIN(l_limber,ppt->l_lss_max)))*ppr->selection_sampling_bessel_los); } } } /* tensor mode */ if (_tensors_) { /* for all tensor types */ *tau_size = ppt->tau_size; } return _SUCCESS_; } int transfer_compute_for_each_q( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, int ** tp_of_tt, int index_q, int tau_size_max, double tau_rec, double *** pert_sources, double *** pert_sources_spline, double * window, struct transfer_workspace * ptw ) { /** Summary: */ /** - define local variables */ /* running index for modes */ int index_md; /* running index for initial conditions */ int index_ic; /* running index for transfer types */ int index_tt; /* running index for multipoles */ int index_l; /** - we deal with workspaces, i.e. with contiguous memory zones (one per thread) containing various fields used by the integration routine */ /* - first workspace field: perturbation source interpolated from perturbation structure */ double * interpolated_sources; /* - second workspace field: list of tau0-tau values, tau0_minus_tau[index_tau] */ double * tau0_minus_tau; /* - third workspace field: list of trapezoidal weights for integration over tau */ double * w_trapz; /* - fourth workspace field, containing just a double: number of time values */ int * tau_size; /* - fifth workspace field, identical to above interpolated sources: sources[index_tau] */ double * sources; /** - for a given l, maximum value of k such that we can convolve the source with Bessel functions j_l(x) without reaching x_max */ double q_max_bessel; /* a value of index_type */ int previous_type; double l; short neglect; radial_function_type radial_type; /** - store the sources in the workspace and define all fields in this workspace */ interpolated_sources = ptw->interpolated_sources; tau0_minus_tau = ptw->tau0_minus_tau; w_trapz = ptw->w_trapz; tau_size = &(ptw->tau_size); sources = ptw->sources; /** - loop over all modes. For each mode */ for (index_md = 0; index_md < ptr->md_size; index_md++) { /* if we reached q_max for this mode, there is nothing to be done */ if (ptr->k[index_md][index_q] <= ppt->k[index_md][ppt->k_size_cl[index_md]-1]) { /** - loop over initial conditions. */ /* For each of them: */ for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) { /* initialize the previous type index */ previous_type=-1; /* - loop over types. For each of them: */ for (index_tt = 0; index_tt < ptr->tt_size[index_md]; index_tt++) { /** - check if we must now deal with a new source with a new index ppt->index_type. If yes, interpolate it at the right values of k. */ if (tp_of_tt[index_md][index_tt] != previous_type) { class_call(transfer_interpolate_sources(ppt, ptr, index_q, index_md, index_ic, tp_of_tt[index_md][index_tt], pert_sources[index_md][index_ic * ppt->tp_size[index_md] + tp_of_tt[index_md][index_tt]], pert_sources_spline[index_md][index_ic * ppt->tp_size[index_md] + tp_of_tt[index_md][index_tt]], interpolated_sources), ptr->error_message, ptr->error_message); } previous_type = tp_of_tt[index_md][index_tt]; /* the code makes a distinction between "perturbation sources" (e.g. gravitational potential) and "transfer sources" (e.g. total density fluctuations, obtained through the Poisson equation, and observed with a given selection function). The next routine computes the transfer source given the interpolated perturbation source, and copies it in the workspace. */ class_call(transfer_sources(ppr, pba, ppt, ptr, interpolated_sources, tau_rec, index_q, index_md, index_tt, sources, window, tau_size_max, tau0_minus_tau, w_trapz, tau_size), ptr->error_message, ptr->error_message); /* now that the array of times tau0_minus_tau is known, we can infer the array of radial coordinates r(tau0_minus_tau) as well as a few other quantities related by trigonometric functions */ class_call(transfer_radial_coordinates(ptr,ptw,index_md,index_q), ptr->error_message, ptr->error_message); /** - Select radial function type */ class_call(transfer_select_radial_function( ppt, ptr, index_md, index_tt, &radial_type), ptr->error_message, ptr->error_message); for (index_l = 0; index_l < ptr->l_size[index_md]; index_l++) { l = (double)ptr->l[index_l]; /* neglect transfer function when l is much smaller than k*tau0 */ class_call(transfer_can_be_neglected(ppr, ppt, ptr, index_md, index_ic, index_tt, (pba->conformal_age-tau_rec)*ptr->angular_rescaling, ptr->q[index_q], l, &neglect), ptr->error_message, ptr->error_message); /* for K>0 (closed), transfer functions only defined for l<nu */ if ((ptw->sgnK == 1) && (ptr->l[index_l] >= (int)(ptr->q[index_q]/sqrt(ptw->K)+0.2))) { neglect = _TRUE_; } /* This would maybe go into transfer_can_be_neglected later: */ if ((ptw->sgnK != 0) && (index_l>=ptw->HIS.l_size) && (index_q < ptr->index_q_flat_approximation)) { neglect = _TRUE_; } if (neglect == _TRUE_) { ptr->transfer[index_md][((index_ic * ptr->tt_size[index_md] + index_tt) * ptr->l_size[index_md] + index_l) * ptr->q_size + index_q] = 0.; } else { /* for a given l, maximum value of k such that we can convolve the source with Bessel functions j_l(x) without reaching x_max (this is relevant in the flat case when the bessels are computed with the old bessel module. otherwise this condition is guaranteed by the choice of proper xmax when computing bessels) */ if (ptw->sgnK == 0) { q_max_bessel = ptw->pBIS->x[ptw->pBIS->x_size-1]/tau0_minus_tau[0]; } else { q_max_bessel = ptr->q[ptr->q_size-1]; } /* neglect late time CMB sources when l is above threshold */ class_call(transfer_late_source_can_be_neglected(ppr, ppt, ptr, index_md, index_tt, l, &(ptw->neglect_late_source)), ptr->error_message, ptr->error_message); /* compute the transfer function for this l */ class_call(transfer_compute_for_each_l( ptw, ppr, ppt, ptr, index_q, index_md, index_ic, index_tt, index_l, l, q_max_bessel, radial_type ), ptr->error_message, ptr->error_message); } } /* end of loop over l */ } /* end of loop over type */ } /* end of loop over initial condition */ } else { for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) { for (index_tt = 0; index_tt < ptr->tt_size[index_md]; index_tt++) { for (index_l = 0; index_l < ptr->l_size[index_md]; index_l++) { ptr->transfer[index_md][((index_ic * ptr->tt_size[index_md] + index_tt) * ptr->l_size[index_md] + index_l) * ptr->q_size + index_q] = 0.; } } } } } /* end of loop over mode */ return _SUCCESS_; } int transfer_radial_coordinates( struct transfers * ptr, struct transfer_workspace * ptw, int index_md, int index_q ) { int index_tau; double sqrt_absK=0.; switch (ptw->sgnK){ case 1: sqrt_absK = sqrt(ptw->K); for (index_tau=0; index_tau < ptw->tau_size; index_tau++) { ptw->chi[index_tau] = sqrt_absK*ptw->tau0_minus_tau[index_tau]; ptw->cscKgen[index_tau] = sqrt_absK/ptr->k[index_md][index_q]/sin(ptw->chi[index_tau]); ptw->cotKgen[index_tau] = ptw->cscKgen[index_tau]*cos(ptw->chi[index_tau]); } break; case 0: for (index_tau=0; index_tau < ptw->tau_size; index_tau++) { ptw->chi[index_tau] = ptr->k[index_md][index_q] * ptw->tau0_minus_tau[index_tau]; ptw->cscKgen[index_tau] = 1.0/ptw->chi[index_tau]; ptw->cotKgen[index_tau] = 1.0/ptw->chi[index_tau]; } break; case -1: sqrt_absK = sqrt(-ptw->K); for (index_tau=0; index_tau < ptw->tau_size; index_tau++) { ptw->chi[index_tau] = sqrt_absK*ptw->tau0_minus_tau[index_tau]; ptw->cscKgen[index_tau] = sqrt_absK/ptr->k[index_md][index_q]/sinh(ptw->chi[index_tau]); ptw->cotKgen[index_tau] = ptw->cscKgen[index_tau]*cosh(ptw->chi[index_tau]); } break; } return _SUCCESS_; } /** * This routine interpolates sources \f$ S(k, \tau) \f$ for each mode, * initial condition and type (of perturbation module), to get them at * the right values of k, using the spline interpolation method. * * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param index_q Input: index of wavenumber * @param index_md Input: index of mode * @param index_ic Input: index of initial condition * @param index_type Input: index of type of source (in perturbation module) * @param pert_source Input: array of sources * @param pert_source_spline Input: array of second derivative of sources * @param interpolated_sources Output: array of interpolated sources (filled here but allocated in transfer_init() to avoid numerous reallocation) * @return the error status */ int transfer_interpolate_sources( struct perturbs * ppt, struct transfers * ptr, int index_q, int index_md, int index_ic, int index_type, double * pert_source, /* array with argument pert_source[index_tau*ppt->k_size[index_md]+index_k] (must be allocated) */ double * pert_source_spline, /* array with argument pert_source_spline[index_tau*ppt->k_size[index_md]+index_k] (must be allocated) */ double * interpolated_sources /* array with argument interpolated_sources[index_q*ppt->tau_size+index_tau] (must be allocated) */ ) { /** Summary: */ /** - define local variables */ /* index running on k values in the original source array */ int index_k; /* index running on time */ int index_tau; /* variables used for spline interpolation algorithm */ double h, a, b; /** - interpolate at each k value using the usual spline interpolation algorithm. */ index_k = 0; h = ppt->k[index_md][index_k+1] - ppt->k[index_md][index_k]; while (((index_k+1) < ppt->k_size[index_md]) && (ppt->k[index_md][index_k+1] < ptr->k[index_md][index_q])) { index_k++; h = ppt->k[index_md][index_k+1] - ppt->k[index_md][index_k]; } class_test(h==0., ptr->error_message, "stop to avoid division by zero"); b = (ptr->k[index_md][index_q] - ppt->k[index_md][index_k])/h; a = 1.-b; for (index_tau = 0; index_tau < ppt->tau_size; index_tau++) { interpolated_sources[index_tau] = a * pert_source[index_tau*ppt->k_size[index_md]+index_k] + b * pert_source[index_tau*ppt->k_size[index_md]+index_k+1] + ((a*a*a-a) * pert_source_spline[index_tau*ppt->k_size[index_md]+index_k] +(b*b*b-b) * pert_source_spline[index_tau*ppt->k_size[index_md]+index_k+1])*h*h/6.0; } return _SUCCESS_; } /** * The code makes a distinction between "perturbation sources" * (e.g. gravitational potential) and "transfer sources" (e.g. total * density fluctuations, obtained through the Poisson equation, and * observed with a given selection function). * * This routine computes the transfer source given the interpolated * perturbation source, and copies it in the workspace. * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param interpolated_sources Input: interpolated perturbation source * @param tau_rec Input: recombination time * @param index_q Input: index of wavenumber * @param index_md Input: index of mode * @param index_tt Input: index of type of (transfer) source * @param sources Output: transfer source * @param window Input: window functions for each type and time * @param tau_size_max Input: number of times at wich window fucntions are sampled * @param tau0_minus_tau Output: values of (tau0-tau) at which source are sample * @param w_trapz Output: trapezoidal weights for integration over tau * @param tau_size_out Output: pointer to size of previous two arrays, converted to double * @return the error status */ int transfer_sources( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, double * interpolated_sources, double tau_rec, int index_q, int index_md, int index_tt, double * sources, double * window, int tau_size_max, double * tau0_minus_tau, double * w_trapz, int * tau_size_out ) { /** Summary: */ /** - define local variables */ /* index running on time */ int index_tau; /* bin for computation of cl_density */ int bin=0; /* number of tau values */ int tau_size; /* minimum tau index kept in transfer sources */ int index_tau_min; /* conformal time */ double tau, tau0; /* rescaling factor depending on the background at a given time */ double rescaling=0.; /* flag: is there any difference between the perturbation and transfer source? */ short redefine_source; /** - in which cases are perturbation and transfer sources are different? I.e., in which case do we need to multiply the sources by some background and/or window function, and eventually to resample it, or redefine its time limits? */ redefine_source = _FALSE_; if (_scalars_) { /* cmb lensing potential */ if ((ppt->has_cl_cmb_lensing_potential == _TRUE_) && (index_tt == ptr->index_tt_lcmb)) redefine_source = _TRUE_; /* number count Cl's */ if (_nonintegrated_ncl_ || _integrated_ncl_) redefine_source = _TRUE_; } /* conformal time today */ tau0 = pba->conformal_age; /** - case where we need to redefine by a window function (or any function of the background and of k) */ if (redefine_source == _TRUE_) { class_call(transfer_source_tau_size(ppr, pba, ppt, ptr, tau_rec, tau0, index_md, index_tt, &tau_size), ptr->error_message, ptr->error_message); if (_scalars_) { /* lensing source: throw away times before recombination, and multiply psi by window function */ if ((ppt->has_cl_cmb_lensing_potential == _TRUE_) && (index_tt == ptr->index_tt_lcmb)) { /* first time step after removing early times */ index_tau_min = ppt->tau_size - tau_size; /* loop over time and rescale */ for (index_tau = index_tau_min; index_tau < ppt->tau_size; index_tau++) { /* conformal time */ tau = ppt->tau_sampling[index_tau]; /* lensing source = - W(tau) (phi(k,tau) + psi(k,tau)) Heaviside(tau-tau_rec) with psi,phi = metric perturbation in newtonian gauge (phi+psi = Phi_A-Phi_H of Bardeen) W = (tau-tau_rec)/(tau_0-tau)/(tau_0-tau_rec) H(x) = Heaviside (in tau = tau_0, set source = 0 to avoid division by zero; regulated anyway by Bessel). */ if (index_tau == ppt->tau_size-1) { rescaling=0.; } else { switch (pba->sgnK){ case 1: rescaling = sqrt(pba->K) *sin((tau_rec-tau)*sqrt(pba->K)) /sin((tau0-tau)*sqrt(pba->K)) /sin((tau0-tau_rec)*sqrt(pba->K)); break; case 0: rescaling = (tau_rec-tau)/(tau0-tau)/(tau0-tau_rec); break; case -1: rescaling = sqrt(-pba->K) *sinh((tau_rec-tau)*sqrt(-pba->K)) /sinh((tau0-tau)*sqrt(-pba->K)) /sinh((tau0-tau_rec)*sqrt(-pba->K)); break; } // Note: until 2.4.3 there was a bug here: the curvature effects had been omitted. } /* copy from input array to output array */ sources[index_tau-index_tau_min] = interpolated_sources[index_tau] * rescaling * ptr->lcmb_rescale * pow(ptr->k[index_md][index_q]/ptr->lcmb_pivot,ptr->lcmb_tilt); /* store value of (tau0-tau) */ tau0_minus_tau[index_tau-index_tau_min] = tau0 - tau; } /* Compute trapezoidal weights for integration over tau */ class_call(array_trapezoidal_mweights(tau0_minus_tau, tau_size, w_trapz, ptr->error_message), ptr->error_message, ptr->error_message); } /* Non-integrated contributions to dCl/nCl need selection time sampling*/ if (_nonintegrated_ncl_) { _get_bin_nonintegrated_ncl_(index_tt) /* redefine the time sampling */ class_call(transfer_selection_sampling(ppr, pba, ppt, ptr, bin, tau0_minus_tau, tau_size), ptr->error_message, ptr->error_message); class_test(tau0 - tau0_minus_tau[0] > ppt->tau_sampling[ppt->tau_size-1], ptr->error_message, "this should not happen, there was probably a rounding error, if this error occurred, then this must be coded more carefully"); /* resample the source at those times */ class_call(transfer_source_resample(ppr, pba, ppt, ptr, bin, tau0_minus_tau, tau_size, index_md, tau0, interpolated_sources, sources), ptr->error_message, ptr->error_message); /* Compute trapezoidal weights for integration over tau */ class_call(array_trapezoidal_mweights(tau0_minus_tau, tau_size, w_trapz, ptr->error_message), ptr->error_message, ptr->error_message); /* loop over time and rescale */ for (index_tau = 0; index_tau < tau_size; index_tau++) { /* matter density source = [- (dz/dtau) W(z)] * delta_m(k,tau) = W(tau) delta_m(k,tau) with delta_m = total matter perturbation (defined in gauge-independent way, see arXiv 1307.1459) W(z) = redshift space selection function = dN/dz W(tau) = same wrt conformal time = dN/dtau (in tau = tau_0, set source = 0 to avoid division by zero; regulated anyway by Bessel). */ rescaling = window[index_tt*tau_size_max+index_tau]; if (_index_tt_in_range_(ptr->index_tt_d0, ppt->selection_num, ppt->has_nc_rsd)) rescaling *= 1./ptr->k[index_md][index_q]/ptr->k[index_md][index_q]; // Factor from original ClassGAL paper ( arXiv 1307.1459 ) if (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd)) rescaling *= 1./ptr->k[index_md][index_q]; // Factor from original ClassGAL paper ( arXiv 1307.1459 ) sources[index_tau] *= rescaling; } } /* End normal contributions */ /* Integrated contributions to dCl/nCl/sCl need integrated selection time sampling */ if (_integrated_ncl_) { _get_bin_integrated_ncl_(index_tt) /* redefine the time sampling */ class_call(transfer_lensing_sampling(ppr, pba, ppt, ptr, bin, tau0, tau0_minus_tau, tau_size), ptr->error_message, ptr->error_message); /* resample the source at those times */ class_call(transfer_source_resample(ppr, pba, ppt, ptr, bin, tau0_minus_tau, tau_size, index_md, tau0, interpolated_sources, sources), ptr->error_message, ptr->error_message); /* Compute trapezoidal weights for integration over tau */ class_call(array_trapezoidal_mweights(tau0_minus_tau, tau_size, w_trapz, ptr->error_message), ptr->error_message, ptr->error_message); /* loop over time and rescale */ for (index_tau = 0; index_tau < tau_size; index_tau++) { /* lensing source = - W(tau) (phi(k,tau) + psi(k,tau)) Heaviside(tau-tau_rec) with psi,phi = metric perturbation in newtonian gauge (phi+psi = Phi_A-Phi_H of Bardeen) W = (tau-tau_rec)/(tau_0-tau)/(tau_0-tau_rec) H(x) = Heaviside (in tau = tau_0, set source = 0 to avoid division by zero; regulated anyway by Bessel). */ /* copy from input array to output array */ sources[index_tau] *= window[index_tt*tau_size_max+index_tau]; if (_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr)) sources[index_tau] *= ptr->k[index_md][index_q]; // Factor from chi derivative of d/dchi j_ell(k*chi)= d/d(kchi) j_ell(k chi) * k = k * j_ell'(kchi) } } /* End integrated contributions */ } } /** - case where we do not need to redefine */ else { /* number of sampled time values */ tau_size = ppt->tau_size; /* plain copy from input array to output array */ memcpy(sources, interpolated_sources, ppt->tau_size*sizeof(double)); /* store values of (tau0-tau) */ for (index_tau=0; index_tau < ppt->tau_size; index_tau++) { tau0_minus_tau[index_tau] = tau0 - ppt->tau_sampling[index_tau]; } /* Compute trapezoidal weights for integration over tau */ class_call(array_trapezoidal_mweights(tau0_minus_tau, tau_size, w_trapz, ptr->error_message), ptr->error_message, ptr->error_message); } /** - return tau_size value that will be stored in the workspace (the workspace wants a double) */ *tau_size_out = tau_size; return _SUCCESS_; } /** * Arbitrarily normalized selection function dN/dz(z,bin) * * @param ppr Input: pointer to precision structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param bin Input: redshift bin number * @param z Input: one value of redshift * @param selection Output: pointer to selection function * @return the error status */ int transfer_selection_function( struct precision * ppr, struct perturbs * ppt, struct transfers * ptr, int bin, double z, double * selection) { double x; double dNdz; double dln_dNdz_dz; int last_index; /* trivial dirac case */ if (ppt->selection==dirac) { *selection=1.; return _SUCCESS_; } /* difference between z and the bin center (we can take the absolute value as long as all selection functions are symmetric around x=0) */ x=fabs(z-ppt->selection_mean[bin]); /* gaussian case (the function is anyway normalized later automatically, but could not resist to normalize it already here) */ if (ppt->selection==gaussian) { *selection = exp(-0.5*pow(x/ppt->selection_width[bin],2)) /ppt->selection_width[bin]/sqrt(2.*_PI_); if ((ptr->has_nz_file == _TRUE_) || (ptr->has_nz_analytic == _TRUE_)) { if (ptr->has_nz_file == _TRUE_) { class_test((z<ptr->nz_z[0]) || (z>ptr->nz_z[ptr->nz_size-1]), ptr->error_message, "Your input file for the selection function only covers the redshift range [%f : %f]. However, your input for the selection function requires z=%f", ptr->nz_z[0], ptr->nz_z[ptr->nz_size-1], z); class_call(array_interpolate_spline( ptr->nz_z, ptr->nz_size, ptr->nz_nz, ptr->nz_ddnz, 1, z, &last_index, &dNdz, 1, ptr->error_message), ptr->error_message, ptr->error_message); } else { class_call(transfer_dNdz_analytic(ptr, z, &dNdz, &dln_dNdz_dz), ptr->error_message, ptr->error_message); } *selection *= dNdz; } return _SUCCESS_; } /* top-hat case, with smoothed edges. The problem with sharp edges is that the final result will be affected by random noise. Indeed, the values of k at which the transfer functions Delta_l(k) are sampled will never coincide with the actual edges of the true transfer function (computed with or even without the Limber approximation). Hence the integral Cl=\int dk Delta_l(k)**2 (...) will be imprecise and will fluctuate randomly with the resolution along k. With smooth edges, the problem is solved, and the final Cls become mildly dependent on the resolution along k. */ if (ppt->selection==tophat) { /* selection function, centered on z=mean (i.e. on x=0), equal to one around x=0, with tanh step centered on x=width, of width delta x = 0.1*width */ *selection=(1.-tanh((x-ppt->selection_width[bin])/(ppr->selection_tophat_edge*ppt->selection_width[bin])))/2.; if ((ptr->has_nz_file == _TRUE_) || (ptr->has_nz_analytic == _TRUE_)) { if (ptr->has_nz_file == _TRUE_) { class_call(array_interpolate_spline( ptr->nz_z, ptr->nz_size, ptr->nz_nz, ptr->nz_ddnz, 1, z, &last_index, &dNdz, 1, ptr->error_message), ptr->error_message, ptr->error_message); } else { class_call(transfer_dNdz_analytic(ptr, z, &dNdz, &dln_dNdz_dz), ptr->error_message, ptr->error_message); } *selection *= dNdz; } return _SUCCESS_; } /* get here only if selection type was recognized */ class_stop(ptr->error_message, "invalid choice of selection function"); return _SUCCESS_; } /** * Analytic form for dNdz distribution, from arXiv:1004.4640 * * @param ptr Input: pointer to transfer structure * @param z Input: redshift * @param dNdz Output: density per redshift, dN/dZ * @param dln_dNdz_dz Output: dln(dN/dz)/dz, used optionally for the source evolution * @return the error status */ int transfer_dNdz_analytic( struct transfers * ptr, double z, double * dNdz, double * dln_dNdz_dz) { /* Implement here your favorite analytic ansatz for the selection function. Typical function for photometric sample: dN/dz = (z/z0)^alpha exp[-(z/z0)^beta]. Then: dln(dN/dz)/dz = (alpha - beta*(z/z0)^beta)/z. In principle, one is free to use different ansatz for the selection function and the evolution function. Since the selection function uses only dN/dz, while the evolution uses only dln(dN/dz)/dz, it is possible to use different functions for dN/dz and dln(dN/dz)/dz */ double z0,alpha,beta; //Euclid IST dNdz, do not change this! z0 = 0.9/pow(2.,1./2.); alpha = 2.0; beta = 1.5; *dNdz = pow(z/z0,alpha) * exp(-pow(z/z0,beta)); *dln_dNdz_dz = (alpha - pow(z/z0,beta)*beta)/z; return _SUCCESS_; } /** * For sources that need to be multiplied by a selection function, * redefine a finer time sampling in a small range * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param bin Input: redshift bin number * @param tau0_minus_tau Output: values of (tau0-tau) at which source are sample * @param tau_size Output: pointer to size of previous array * @return the error status */ int transfer_selection_sampling( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, int bin, double * tau0_minus_tau, int tau_size) { /* running index on time */ int index_tau; /* minimum and maximal value of time in new sampled interval */ double tau_min,tau_mean,tau_max; /* time interval for this bin */ class_call(transfer_selection_times(ppr, pba, ppt, ptr, bin, &tau_min, &tau_mean, &tau_max), ptr->error_message, ptr->error_message); class_test(tau_size <= 0, ptr->error_message, "should be at least one"); /* case selection == dirac */ if (tau_min == tau_max) { class_test(tau_size !=1, ptr->error_message, "for Dirac selection function tau_size should be 1, not %d",tau_size); tau0_minus_tau[0] = pba->conformal_age - tau_mean; } /* for other cases (gaussian, tophat...) define new sampled values of (tau0-tau) with even spacing */ else { for (index_tau=0; index_tau<tau_size-1; index_tau++) { tau0_minus_tau[index_tau]=pba->conformal_age-tau_min-((double)index_tau)/((double)tau_size-1.)*(tau_max-tau_min); } tau0_minus_tau[tau_size-1]=pba->conformal_age-tau_max; } return _SUCCESS_; } /** * For lensing sources that need to be convolved with a selection * function, redefine the sampling within the range extending from the * tau_min of the selection function up to tau0 * * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param bin Input: redshift bin number * @param tau0 Input: time today * @param tau0_minus_tau Output: values of (tau0-tau) at which source are sample * @param tau_size Output: pointer to size of previous array * @return the error status */ int transfer_lensing_sampling( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, int bin, double tau0, double * tau0_minus_tau, int tau_size) { /* running index on time */ int index_tau; /* minimum and maximal value of time in new sampled interval */ double tau_min,tau_mean,tau_max; /* time interval for this bin */ class_call(transfer_selection_times(ppr, pba, ppt, ptr, bin, &tau_min, &tau_mean, &tau_max), ptr->error_message, ptr->error_message); for (index_tau=0; index_tau<tau_size; index_tau++) { //tau0_minus_tau[index_tau]=pba->conformal_age-tau_min-((double)index_tau)/((double)tau_size-1.)*(tau0-tau_min); tau0_minus_tau[index_tau]=((double)(tau_size-1-index_tau))/((double)(tau_size-1))*(tau0-tau_min); } return _SUCCESS_; } /** * For sources that need to be multiplied by a selection function, * redefine a finer time sampling in a small range, and resample the * perturbation sources at the new value by linear interpolation * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param bin Input: redshift bin number * @param tau0_minus_tau Output: values of (tau0-tau) at which source are sample * @param tau_size Output: pointer to size of previous array * @param index_md Input: index of mode * @param tau0 Input: time today * @param interpolated_sources Input: interpolated perturbation source * @param sources Output: resampled transfer source * @return the error status */ int transfer_source_resample( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, int bin, double * tau0_minus_tau, int tau_size, int index_md, double tau0, double * interpolated_sources, double * sources) { /* running index on time */ int index_tau; /* array of values of source */ double * source_at_tau; /* array of source values for a given time and for all k's */ class_alloc(source_at_tau, sizeof(double), ptr->error_message); /* interpolate the sources linearly at the new time values */ for (index_tau=0; index_tau<tau_size; index_tau++) { class_call(array_interpolate_two(ppt->tau_sampling, 1, 0, interpolated_sources, 1, ppt->tau_size, tau0-tau0_minus_tau[index_tau], source_at_tau, 1, ptr->error_message), ptr->error_message, ptr->error_message); /* copy the new values in the output sources array */ sources[index_tau] = source_at_tau[0]; } /* deallocate the temporary array */ free(source_at_tau); return _SUCCESS_; } /** * For each selection function, compute the min, mean and max values * of conformal time (associated to the min, mean and max values of * redshift specified by the user) * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param bin Input: redshift bin number * @param tau_min Output: smallest time in the selection interval * @param tau_mean Output: time corresponding to z_mean * @param tau_max Output: largest time in the selection interval * @return the error status */ int transfer_selection_times( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, int bin, double * tau_min, double * tau_mean, double * tau_max) { /* a value of redshift */ double z=0.; /* lower edge of time interval for this bin */ /* the few lines below should be consistent with their counterpart in input.c */ if (ppt->selection==gaussian) { z = ppt->selection_mean[bin]+ppt->selection_width[bin]*ppr->selection_cut_at_sigma; } if (ppt->selection==tophat) { z = ppt->selection_mean[bin]+(1.+ppr->selection_cut_at_sigma*ppr->selection_tophat_edge)*ppt->selection_width[bin]; } if (ppt->selection==dirac) { z = ppt->selection_mean[bin]; } class_call(background_tau_of_z(pba, z, tau_min), pba->error_message, ppt->error_message); /* higher edge of time interval for this bin */ if (ppt->selection==gaussian) { z = MAX(ppt->selection_mean[bin]-ppt->selection_width[bin]*ppr->selection_cut_at_sigma,0.); } if (ppt->selection==tophat) { z = MAX(ppt->selection_mean[bin]-(1.+ppr->selection_cut_at_sigma*ppr->selection_tophat_edge)*ppt->selection_width[bin],0.); } if (ppt->selection==dirac) { z = ppt->selection_mean[bin]; } class_call(background_tau_of_z(pba, z, tau_max), pba->error_message, ppt->error_message); /* central value of time interval for this bin */ z = MAX(ppt->selection_mean[bin],0.); class_call(background_tau_of_z(pba, z, tau_mean), pba->error_message, ppt->error_message); return _SUCCESS_; } /** * Compute and normalize selection function for a set of time values * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param selection Output: normalized selection function * @param tau0_minus_tau Input: values of (tau0-tau) at which source are sample * @param w_trapz Input: trapezoidal weights for integration over tau * @param tau_size Input: size of previous two arrays * @param pvecback Input: allocated array of background values * @param tau0 Input: time today * @param bin Input: redshift bin number * @return the error status */ int transfer_selection_compute( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, double * selection, double * tau0_minus_tau, double * w_trapz, int tau_size, double * pvecback, double tau0, int bin) { /* running index over time */ int index_tau; /* running value of time */ double tau; /* used for normalizing the selection to one */ double norm; /* used for calling background_at_tau() */ int last_index; /* running value of redshift */ double z; if (tau_size > 1) { /* loop over time */ for (index_tau = 0; index_tau < tau_size; index_tau++) { /* running value of time */ tau = tau0 - tau0_minus_tau[index_tau]; /* get background quantities at this time */ class_call(background_at_tau(pba, tau, pba->long_info, pba->inter_normal, &last_index, pvecback), pba->error_message, ptr->error_message); /* infer redshift */ z = pba->a_today/pvecback[pba->index_bg_a]-1.; /* get corresponding dN/dz(z,bin) */ class_call(transfer_selection_function(ppr, ppt, ptr, bin, z, &(selection[index_tau])), ptr->error_message, ptr->error_message); /* get corresponding dN/dtau = dN/dz * dz/dtau = dN/dz * H */ selection[index_tau] *= pvecback[pba->index_bg_H]; } /* compute norm = \int W(tau) dtau */ class_call(array_trapezoidal_integral(selection, tau_size, w_trapz, &norm, ptr->error_message), ptr->error_message, ptr->error_message); /* divide W by norm so that \int W(tau) dtau = 1 */ for (index_tau = 0; index_tau < tau_size; index_tau++) { selection[index_tau]/=norm; } } /* trivial case: dirac distribution */ else { selection[0] = 1.; } return _SUCCESS_; } /** * This routine computes the transfer functions \f$ \Delta_l^{X} (k) \f$) * as a function of wavenumber k for a given mode, initial condition, * type and multipole l passed in input. * * For a given value of k, the transfer function is inferred from * the source function (passed in input in the array interpolated_sources) * and from Bessel functions (passed in input in the bessels structure), * either by convolving them along tau, or by a Limber approximation. * This elementary task is distributed either to transfer_integrate() * or to transfer_limber(). The task of this routine is mainly to * loop over k values, and to decide at which k_max the calculation can * be stopped, according to some approximation scheme designed to find a * compromise between execution time and precision. The approximation scheme * is defined by parameters in the precision structure. * * @param ptw Input: pointer to transfer_workspace structure (allocated in transfer_init() to avoid numerous reallocation) * @param ppr Input: pointer to precision structure * @param ppt Input: pointer to perturbation structure * @param ptr Input/output: pointer to transfers structure (result stored there) * @param index_q Input: index of wavenumber * @param index_md Input: index of mode * @param index_ic Input: index of initial condition * @param index_tt Input: index of type of transfer * @param index_l Input: index of multipole * @param l Input: multipole * @param q_max_bessel Input: maximum value of argument q at which Bessel functions are computed * @param radial_type Input: type of radial (Bessel) functions to convolve with * @return the error status */ int transfer_compute_for_each_l( struct transfer_workspace * ptw, struct precision * ppr, struct perturbs * ppt, struct transfers * ptr, int index_q, int index_md, int index_ic, int index_tt, int index_l, double l, double q_max_bessel, radial_function_type radial_type ){ /** Summary: */ /** - define local variables */ /* current wavenumber value */ double q,k; /* value of transfer function */ double transfer_function; /* whether to use the Limber approximation */ short use_limber; /** - return zero transfer function if l is above l_max */ if (index_l >= ptr->l_size_tt[index_md][index_tt]) { ptr->transfer[index_md][((index_ic * ptr->tt_size[index_md] + index_tt) * ptr->l_size[index_md] + index_l) * ptr->q_size + index_q] = 0.; return _SUCCESS_; } q = ptr->q[index_q]; k = ptr->k[index_md][index_q]; if (ptr->transfer_verbose > 3) printf("Compute transfer for l=%d type=%d\n",(int)l,index_tt); class_call(transfer_use_limber(ppr, ppt, ptr, q_max_bessel, index_md, index_tt, q, l, &use_limber), ptr->error_message, ptr->error_message); if (use_limber == _TRUE_) { class_call(transfer_limber(ptr, ptw, index_md, index_q, l, q, radial_type, &transfer_function), ptr->error_message, ptr->error_message); } else { class_call(transfer_integrate( ppt, ptr, ptw, index_q, index_md, index_tt, l, index_l, k, radial_type, &transfer_function ), ptr->error_message, ptr->error_message); } /** - store transfer function in transfer structure */ ptr->transfer[index_md][((index_ic * ptr->tt_size[index_md] + index_tt) * ptr->l_size[index_md] + index_l) * ptr->q_size + index_q] = transfer_function; return _SUCCESS_; } int transfer_use_limber( struct precision * ppr, struct perturbs * ppt, struct transfers * ptr, double q_max_bessel, int index_md, int index_tt, double q, double l, short * use_limber) { /* criteria for choosing between integration and Limber must be implemented here */ *use_limber = _FALSE_; if (q>q_max_bessel) { *use_limber = _TRUE_; } else { if (_scalars_) { //TBC: in principle the Limber condition should be adapted to account for curvature effects if ((ppt->has_cl_cmb_lensing_potential == _TRUE_) && (index_tt == ptr->index_tt_lcmb) && (l>ppr->l_switch_limber)) { *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_density, ppt->selection_num, ppt->has_nc_density) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_density])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_rsd, ppt->selection_num, ppt->has_nc_rsd) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_rsd])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_d0, ppt->selection_num, ppt->has_nc_rsd) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_d0])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_d1])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_nc_lens, ppt->selection_num, ppt->has_nc_lens) && (l>=ppr->l_switch_limber_for_nc_los_over_z*ppt->selection_mean[index_tt-ptr->index_tt_nc_lens])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_nc_g1, ppt->selection_num, ppt->has_nc_gr) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_nc_g1])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_nc_g2, ppt->selection_num, ppt->has_nc_gr) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_nc_g2])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_nc_g3, ppt->selection_num, ppt->has_nc_gr) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_nc_g3])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_nc_g4, ppt->selection_num, ppt->has_nc_gr) && (l>=ppr->l_switch_limber_for_nc_los_over_z*ppt->selection_mean[index_tt-ptr->index_tt_nc_g4])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr) && (l>=ppr->l_switch_limber_for_nc_local_over_z*ppt->selection_mean[index_tt-ptr->index_tt_nc_g5])) { if (ppt->selection != dirac) *use_limber = _TRUE_; } if (_index_tt_in_range_(ptr->index_tt_lensing, ppt->selection_num, ppt->has_cl_lensing_potential) && (l>=ppr->l_switch_limber_for_nc_los_over_z*ppt->selection_mean[index_tt-ptr->index_tt_lensing])) { *use_limber = _TRUE_; } } } return _SUCCESS_; } /** * This routine computes the transfer functions \f$ \Delta_l^{X} (k) \f$) * for each mode, initial condition, type, multipole l and wavenumber k, * by convolving the source function (passed in input in the array * interpolated_sources) with Bessel functions (passed in input in the * bessels structure). * * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param ptw Input: pointer to transfer_workspace structure (allocated in transfer_init() to avoid numerous reallocation) * @param index_q Input: index of wavenumber * @param index_md Input: index of mode * @param index_tt Input: index of type * @param l Input: multipole * @param index_l Input: index of multipole * @param k Input: wavenumber * @param radial_type Input: type of radial (Bessel) functions to convolve with * @param trsf Output: transfer function \f$ \Delta_l(k) \f$ * @return the error status */ int transfer_integrate( struct perturbs * ppt, struct transfers * ptr, struct transfer_workspace *ptw, int index_q, int index_md, int index_tt, double l, int index_l, double k, radial_function_type radial_type, double * trsf ) { /** Summary: */ /** - define local variables */ double * tau0_minus_tau = ptw->tau0_minus_tau; double * w_trapz = ptw->w_trapz; double * sources = ptw->sources; /* minimum value of \f$ (\tau0-\tau) \f$ at which \f$ j_l(k[\tau_0-\tau]) \f$ is known, given that \f$ j_l(x) \f$ is sampled above some finite value \f$ x_{\min} \f$ (below which it can be approximated by zero) */ double tau0_minus_tau_min_bessel; /* index in the source's tau list corresponding to the last point in the overlapping region between sources and bessels. Also the index of possible Bessel truncation. */ int index_tau_max, index_tau_max_Bessel; double bessel, *radial_function; double x_turning_point; /** - find minimum value of (tau0-tau) at which \f$ j_l(k[\tau_0-\tau]) \f$ is known, given that \f$ j_l(x) \f$ is sampled above some finite value \f$ x_{\min} \f$ (below which it can be approximated by zero) */ //tau0_minus_tau_min_bessel = x_min_l/k; /* segmentation fault impossible, checked before that k != 0 */ //printf("index_l=%d\n",index_l); if (ptw->sgnK==0){ tau0_minus_tau_min_bessel = ptw->pBIS->chi_at_phimin[index_l]/k; /* segmentation fault impossible, checked before that k != 0 */ } else{ if (index_q < ptr->index_q_flat_approximation) { tau0_minus_tau_min_bessel = ptw->HIS.chi_at_phimin[index_l]/sqrt(ptw->sgnK*ptw->K); } else { tau0_minus_tau_min_bessel = ptw->pBIS->chi_at_phimin[index_l]/sqrt(ptw->sgnK*ptw->K); if (ptw->sgnK == 1) { x_turning_point = asin(sqrt(l*(l+1.))/ptr->q[index_q]*sqrt(ptw->sgnK*ptw->K)); tau0_minus_tau_min_bessel *= x_turning_point/sqrt(l*(l+1.)); } else { x_turning_point = asinh(sqrt(l*(l+1.))/ptr->q[index_q]*sqrt(ptw->sgnK*ptw->K)); tau0_minus_tau_min_bessel *= x_turning_point/sqrt(l*(l+1.)); } } } /** - if there is no overlap between the region in which bessels and sources are non-zero, return zero */ if (tau0_minus_tau_min_bessel >= tau0_minus_tau[0]) { *trsf = 0.; return _SUCCESS_; } /** - if there is an overlap: */ /** - --> trivial case: the source is a Dirac function and is sampled in only one point */ if (ptw->tau_size == 1) { class_call(transfer_radial_function( ptw, ppt, ptr, k, index_q, index_l, 1, &bessel, radial_type ), ptr->error_message, ptr->error_message); *trsf = sources[0] * bessel; return _SUCCESS_; } /** - --> other cases */ /** - ---> (a) find index in the source's tau list corresponding to the last point in the overlapping region. After this step, index_tau_max can be as small as zero, but not negative. */ index_tau_max = ptw->tau_size-1; while (tau0_minus_tau[index_tau_max] < tau0_minus_tau_min_bessel) index_tau_max--; /* Set index so we know if the truncation of the convolution integral is due to Bessel and not due to the source. */ index_tau_max_Bessel = index_tau_max; /** - ---> (b) the source function can vanish at large \f$ \tau \f$. Check if further points can be eliminated. After this step and if we did not return a null transfer function, index_tau_max can be as small as zero, but not negative. */ while (sources[index_tau_max] == 0.) { index_tau_max--; if (index_tau_max < 0) { *trsf = 0.; return _SUCCESS_; } } if (ptw->neglect_late_source == _TRUE_) { while (tau0_minus_tau[index_tau_max] < ptw->tau0_minus_tau_cut) { index_tau_max--; if (index_tau_max < 0) { *trsf = 0.; return _SUCCESS_; } } } /** - Compute the radial function: */ class_alloc(radial_function,sizeof(double)*(index_tau_max+1),ptr->error_message); class_call(transfer_radial_function( ptw, ppt, ptr, k, index_q, index_l, index_tau_max+1, radial_function, radial_type ), ptr->error_message, ptr->error_message); /** - Now we do most of the convolution integral: */ class_call(array_trapezoidal_convolution(sources, radial_function, index_tau_max+1, w_trapz, trsf, ptr->error_message), ptr->error_message, ptr->error_message); /** - This integral is correct for the case where no truncation has occurred. If it has been truncated at some index_tau_max because f[index_tau_max+1]==0, it is still correct. The 'mistake' in using the wrong weight w_trapz[index_tau_max] is exactly compensated by the triangle we miss. However, for the Bessel cut off, we must subtract the wrong triangle and add the correct triangle. */ if ((index_tau_max!=(ptw->tau_size-1))&&(index_tau_max==index_tau_max_Bessel)){ //Bessel truncation *trsf -= 0.5*(tau0_minus_tau[index_tau_max+1]-tau0_minus_tau_min_bessel)* radial_function[index_tau_max]*sources[index_tau_max]; } free(radial_function); return _SUCCESS_; } /** * This routine computes the transfer functions \f$ \Delta_l^{X} (k) \f$) * for each mode, initial condition, type, multipole l and wavenumber k, * by using the Limber approximation, i.e by evaluating the source function * (passed in input in the array interpolated_sources) at a single value of * tau (the Bessel function being approximated as a Dirac distribution). * * * @param ptr Input: pointer to transfers structure * @param ptw Input: pointer to transfer workspace structure * @param index_md Input: index of mode * @param index_q Input: index of wavenumber * @param l Input: multipole * @param q Input: wavenumber * @param radial_type Input: type of radial (Bessel) functions to convolve with * @param trsf Output: transfer function \f$ \Delta_l(k) \f$ * @return the error status */ int transfer_limber( struct transfers * ptr, struct transfer_workspace * ptw, int index_md, int index_q, double l, double q, radial_function_type radial_type, double * trsf ){ /** Summary: */ /** - define local variables */ /* interpolated source and its derivatives at this value */ double S, Sp, Sm; double x_limber=0.; double tau0_minus_tau_limber=0.; double IPhiFlat = 0.; if (radial_type == SCALAR_TEMPERATURE_0) { /** - get k, l and infer tau such that k(tau0-tau)=l+1/2; check that tau is in appropriate range */ if (ptw->sgnK == 0) { tau0_minus_tau_limber = (l+0.5)/q; } else if (ptw->sgnK == 1) { x_limber = asin(sqrt(l*(l+1.))/q*sqrt(ptw->K)); tau0_minus_tau_limber = x_limber/sqrt(ptw->K); } else if (ptw->sgnK == -1) { x_limber = asinh((l+0.5)/q*sqrt(-ptw->K)); tau0_minus_tau_limber = x_limber/sqrt(-ptw->K); } if ((tau0_minus_tau_limber > ptw->tau0_minus_tau[0]) || (tau0_minus_tau_limber < ptw->tau0_minus_tau[ptw->tau_size-1])) { *trsf = 0.; return _SUCCESS_; } class_call(transfer_limber_interpolate(ptr, ptw->tau0_minus_tau, ptw->sources, ptw->tau_size, tau0_minus_tau_limber, &S), ptr->error_message, ptr->error_message); /** - get transfer = source * \f$ \sqrt{\pi/(2l+1)}/q \f$ = source*[tau0-tau] * \f$ \sqrt{\pi/(2l+1)}/(l+1/2)\f$ */ IPhiFlat = sqrt(_PI_/(2.*l))*(1.-0.25/l+1./32./(l*l)); *trsf = IPhiFlat*S; if (ptw->sgnK == 0) { *trsf /= (l+0.5); } else { *trsf *= pow(1.-ptw->K*l*l/q/q,-1./4.)/(tau0_minus_tau_limber*q); } } else if (radial_type == SCALAR_TEMPERATURE_1) { if (((l+1.5)/q > ptw->tau0_minus_tau[0]) || ((l-0.5)/q < ptw->tau0_minus_tau[ptw->tau_size-1])) { *trsf = 0.; return _SUCCESS_; } class_call(transfer_limber_interpolate(ptr, ptw->tau0_minus_tau, ptw->sources, ptw->tau_size, (l+1.5)/q, &Sp), ptr->error_message, ptr->error_message); class_call(transfer_limber_interpolate(ptr, ptw->tau0_minus_tau, ptw->sources, ptw->tau_size, (l-0.5)/q, &Sm), ptr->error_message, ptr->error_message); *trsf = -sqrt(_PI_/(2.*l+3.))*Sp/(l+1.5) * (l+1.)/(2.*l+1) +sqrt(_PI_/(2.*l-1.))*Sm/(l-0.5) * l/(2.*l+1.); } else if (radial_type == NC_RSD) { if (((l+2.5)/q > ptw->tau0_minus_tau[0]) || ((l-1.5)/q < ptw->tau0_minus_tau[ptw->tau_size-1])) { *trsf = 0.; return _SUCCESS_; } class_call(transfer_limber_interpolate(ptr, ptw->tau0_minus_tau, ptw->sources, ptw->tau_size, (l+2.5)/q, &Sp), ptr->error_message, ptr->error_message); class_call(transfer_limber_interpolate(ptr, ptw->tau0_minus_tau, ptw->sources, ptw->tau_size, (l-1.5)/q, &Sm), ptr->error_message, ptr->error_message); class_call(transfer_limber_interpolate(ptr, ptw->tau0_minus_tau, ptw->sources, ptw->tau_size, (l+0.5)/q, &S), ptr->error_message, ptr->error_message); *trsf = sqrt(_PI_/(2.*l+5.))*Sp/(l+2.5) * l*(l+2.)/(2.*l+1.)/(2.*l+3.) -sqrt(_PI_/(2.*l+1.))*S/(l+0.5) * l/(2.*l+1.)*(l/(2.*l-1.)+(l+1.)/(2.*l+3.)) +sqrt(_PI_/(2.*l-3.))*Sm/(l-1.5) * l*(l-1.)/(2.*l+1.)/(2.*l-1.); } else { class_stop(ptr->error_message, "Limber approximation has not been coded for the radial_type of index %d\n", radial_type); } return _SUCCESS_; } int transfer_limber_interpolate( struct transfers * ptr, double * tau0_minus_tau, double * sources, int tau_size, double tau0_minus_tau_limber, double * S ){ int index_tau; double dS,ddS; /** - find bracketing indices. index_tau must be at least 1 (so that index_tau-1 is at least 0) and at most tau_size-2 (so that index_tau+1 is at most tau_size-1). */ index_tau=1; while ((tau0_minus_tau[index_tau] > tau0_minus_tau_limber) && (index_tau<tau_size-2)) index_tau++; /** - interpolate by fitting a polynomial of order two; get source and its first two derivatives. Note that we are not interpolating S, but the product S*(tau0-tau). Indeed this product is regular in tau=tau0, while S alone diverges for lensing. */ /* the case where the last of the three point is the edge (tau0=tau) must be treated separately, see below */ if (index_tau < tau_size-2) { class_call(array_interpolate_parabola(tau0_minus_tau[index_tau-1], tau0_minus_tau[index_tau], tau0_minus_tau[index_tau+1], tau0_minus_tau_limber, sources[index_tau-1]*tau0_minus_tau[index_tau-1], sources[index_tau]*tau0_minus_tau[index_tau], sources[index_tau+1]*tau0_minus_tau[index_tau+1], S, &dS, &ddS, ptr->error_message), ptr->error_message, ptr->error_message); } /* in this case, we have stored a zero for sources[index_k*tau_size+index_tau+1]. But we can use in very good approximation the fact that S*(tau0-tau) is constant near tau=tau0 and replace sources[index_k*tau_size+index_tau+1]*tau0_minus_tau[index_tau+1] by sources[index_k*tau_size+index_tau]*tau0_minus_tau[index_tau] */ else { class_call(array_interpolate_parabola(tau0_minus_tau[index_tau-1], tau0_minus_tau[index_tau], tau0_minus_tau[index_tau+1], tau0_minus_tau_limber, sources[index_tau-1]*tau0_minus_tau[index_tau-1], sources[index_tau]*tau0_minus_tau[index_tau], sources[index_tau]*tau0_minus_tau[index_tau], S, &dS, &ddS, ptr->error_message), ptr->error_message, ptr->error_message); } return _SUCCESS_; } /** * This routine computes the transfer functions \f$ \Delta_l^{X} (k) * \f$) for each mode, initial condition, type, multipole l and * wavenumber k, by using the Limber approximation at order two, i.e * as a function of the source function and its first two derivatives * at a single value of tau * * @param tau_size Input: size of conformal time array * @param ptr Input: pointer to transfers structure * @param index_md Input: index of mode * @param index_k Input: index of wavenumber * @param l Input: multipole * @param k Input: wavenumber * @param tau0_minus_tau Input: array of values of (tau_today - tau) * @param sources Input: source functions * @param radial_type Input: type of radial (Bessel) functions to convolve with * @param trsf Output: transfer function \f$ \Delta_l(k) \f$ * @return the error status */ int transfer_limber2( int tau_size, struct transfers * ptr, int index_md, int index_k, double l, double k, double * tau0_minus_tau, double * sources, radial_function_type radial_type, double * trsf ){ /** Summary: */ /** - define local variables */ /* conformal time at which source must be computed */ double tau0_minus_tau_limber; int index_tau; /* interpolated source and its derivatives */ double S, dS, ddS; /** - get k, l and infer tau such that k(tau0-tau)=l+1/2; check that tau is in appropriate range */ tau0_minus_tau_limber = (l+0.5)/k; //TBC: to be updated to include curvature effects if ((tau0_minus_tau_limber > tau0_minus_tau[0]) || (tau0_minus_tau_limber < tau0_minus_tau[tau_size-1])) { *trsf = 0.; return _SUCCESS_; } /** - find bracketing indices */ index_tau=0; while ((tau0_minus_tau[index_tau] > tau0_minus_tau_limber) && (index_tau<tau_size-2)) index_tau++; /** - interpolate by fitting a polynomial of order two; get source and its first two derivatives */ class_call(array_interpolate_parabola(tau0_minus_tau[index_tau-1], tau0_minus_tau[index_tau], tau0_minus_tau[index_tau+1], tau0_minus_tau_limber, sources[index_tau-1], sources[index_tau], sources[index_tau+1], &S, &dS, &ddS, ptr->error_message), ptr->error_message, ptr->error_message); /** - get transfer from 2nd order Limber approx (inferred from 0809.5112 [astro-ph]) */ *trsf = sqrt(_PI_/(2.*l+1.))/k*((1.-3./2./(2.*l+1.)/(2.*l+1.))*S+dS/k/(2.*l+1.)-0.5*ddS/k/k); return _SUCCESS_; } int transfer_can_be_neglected( struct precision * ppr, struct perturbs * ppt, struct transfers * ptr, int index_md, int index_ic, int index_tt, double ra_rec, double k, double l, short * neglect) { *neglect = _FALSE_; if (_scalars_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t0) && (l < (k-ppr->transfer_neglect_delta_k_S_t0)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t1) && (l < (k-ppr->transfer_neglect_delta_k_S_t1)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t2) && (l < (k-ppr->transfer_neglect_delta_k_S_t2)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e) && (l < (k-ppr->transfer_neglect_delta_k_S_e)*ra_rec)) *neglect = _TRUE_; } else if (_vectors_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t1) && (l < (k-ppr->transfer_neglect_delta_k_V_t1)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t2) && (l < (k-ppr->transfer_neglect_delta_k_V_t2)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e) && (l < (k-ppr->transfer_neglect_delta_k_V_e)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_b) && (l < (k-ppr->transfer_neglect_delta_k_V_b)*ra_rec)) *neglect = _TRUE_; } else if (_tensors_) { if ((ppt->has_cl_cmb_temperature == _TRUE_) && (index_tt == ptr->index_tt_t2) && (l < (k-ppr->transfer_neglect_delta_k_T_t2)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_e) && (l < (k-ppr->transfer_neglect_delta_k_T_e)*ra_rec)) *neglect = _TRUE_; else if ((ppt->has_cl_cmb_polarization == _TRUE_) && (index_tt == ptr->index_tt_b) && (l < (k-ppr->transfer_neglect_delta_k_T_b)*ra_rec)) *neglect = _TRUE_; } return _SUCCESS_; } int transfer_late_source_can_be_neglected( struct precision * ppr, struct perturbs * ppt, struct transfers * ptr, int index_md, int index_tt, double l, short * neglect) { *neglect = _FALSE_; if (l > ppr->transfer_neglect_late_source*ptr->angular_rescaling) { /* sources at late times can be neglected for CMB, excepted when there is a LISW: this means for tt_t1, t2, e */ if (_scalars_) { if (ppt->has_cl_cmb_temperature == _TRUE_) { if ((index_tt == ptr->index_tt_t1) || (index_tt == ptr->index_tt_t2)) *neglect = _TRUE_; } if (ppt->has_cl_cmb_polarization == _TRUE_) { if (index_tt == ptr->index_tt_e) *neglect = _TRUE_; } } else if (_vectors_) { if (ppt->has_cl_cmb_temperature == _TRUE_) { if ((index_tt == ptr->index_tt_t1) || (index_tt == ptr->index_tt_t2)) *neglect = _TRUE_; } if (ppt->has_cl_cmb_polarization == _TRUE_) { if ((index_tt == ptr->index_tt_e) || (index_tt == ptr->index_tt_b)) *neglect = _TRUE_; } } else if (_tensors_) { if (ppt->has_cl_cmb_polarization == _TRUE_) { if ((index_tt == ptr->index_tt_e) || (index_tt == ptr->index_tt_b)) *neglect = _TRUE_; } } } return _SUCCESS_; } int transfer_radial_function( struct transfer_workspace * ptw, struct perturbs * ppt, struct transfers * ptr, double k, int index_q, int index_l, int x_size, double * radial_function, radial_function_type radial_type ){ HyperInterpStruct * pHIS; double *chi = ptw->chi; double *cscKgen = ptw->cscKgen; double *cotKgen = ptw->cotKgen; int j; double *Phi, *dPhi, *d2Phi, *chireverse; double K=0.,k2=1.0; double sqrt_absK_over_k; double absK_over_k2; double nu=0., chi_tp=0.; double factor, s0, s2, ssqrt3, si, ssqrt2, ssqrt2i; double l = (double)ptr->l[index_l]; double rescale_argument; double rescale_amplitude; double * rescale_function; int (*interpolate_Phi)(); int (*interpolate_dPhi)(); int (*interpolate_Phid2Phi)(); int (*interpolate_PhidPhi)(); int (*interpolate_PhidPhid2Phi)(); enum Hermite_Interpolation_Order HIorder; K = ptw->K; k2 = k*k; if (ptw->sgnK==0){ /* This is the choice consistent with chi=k*(tau0-tau) and nu=1 */ sqrt_absK_over_k = 1.0; } else { K=ptw->K; sqrt_absK_over_k = sqrt(ptw->sgnK*K)/k; } absK_over_k2 =sqrt_absK_over_k*sqrt_absK_over_k; class_alloc(Phi,sizeof(double)*x_size,ptr->error_message); class_alloc(dPhi,sizeof(double)*x_size,ptr->error_message); class_alloc(d2Phi,sizeof(double)*x_size,ptr->error_message); class_alloc(chireverse,sizeof(double)*x_size,ptr->error_message); class_alloc(rescale_function,sizeof(double)*x_size,ptr->error_message); if (ptw->sgnK == 0) { pHIS = ptw->pBIS; rescale_argument = 1.; rescale_amplitude = 1.; HIorder = HERMITE4; } else if (index_q < ptr->index_q_flat_approximation) { pHIS = &(ptw->HIS); rescale_argument = 1.; rescale_amplitude = 1.; HIorder = HERMITE6; } else { pHIS = ptw->pBIS; if (ptw->sgnK == 1){ nu = ptr->q[index_q]/sqrt(K); chi_tp = asin(sqrt(ptr->l[index_l]*(ptr->l[index_l]+1.))/nu); } else{ nu = ptr->q[index_q]/sqrt(-K); chi_tp = asinh(sqrt(ptr->l[index_l]*(ptr->l[index_l]+1.))/nu); } rescale_argument = sqrt(ptr->l[index_l]*(ptr->l[index_l]+1.))/chi_tp; rescale_amplitude = pow(1.-K*ptr->l[index_l]*(ptr->l[index_l]+1.)/ptr->q[index_q]/ptr->q[index_q],-1./12.); HIorder = HERMITE4; } switch (HIorder){ case HERMITE3: interpolate_Phi = hyperspherical_Hermite3_interpolation_vector_Phi; interpolate_dPhi = hyperspherical_Hermite3_interpolation_vector_dPhi; interpolate_PhidPhi = hyperspherical_Hermite3_interpolation_vector_PhidPhi; interpolate_Phid2Phi = hyperspherical_Hermite3_interpolation_vector_Phid2Phi; interpolate_PhidPhid2Phi = hyperspherical_Hermite3_interpolation_vector_PhidPhid2Phi; break; case HERMITE4: interpolate_Phi = hyperspherical_Hermite4_interpolation_vector_Phi; interpolate_dPhi = hyperspherical_Hermite4_interpolation_vector_dPhi; interpolate_PhidPhi = hyperspherical_Hermite4_interpolation_vector_PhidPhi; interpolate_Phid2Phi = hyperspherical_Hermite4_interpolation_vector_Phid2Phi; interpolate_PhidPhid2Phi = hyperspherical_Hermite4_interpolation_vector_PhidPhid2Phi; break; case HERMITE6: interpolate_Phi = hyperspherical_Hermite6_interpolation_vector_Phi; interpolate_dPhi = hyperspherical_Hermite6_interpolation_vector_dPhi; interpolate_PhidPhi = hyperspherical_Hermite6_interpolation_vector_PhidPhi; interpolate_Phid2Phi = hyperspherical_Hermite6_interpolation_vector_Phid2Phi; interpolate_PhidPhid2Phi = hyperspherical_Hermite6_interpolation_vector_PhidPhid2Phi; break; } //Reverse chi for (j=0; j<x_size; j++) { chireverse[j] = chi[x_size-1-j]*rescale_argument; if (rescale_amplitude == 1.) { rescale_function[j] = 1.; } else { if (ptw->sgnK == 1) { rescale_function[j] = MIN( rescale_amplitude * (1 + 0.34 * atan(ptr->l[index_l]/nu) * (chireverse[j]/rescale_argument-chi_tp) + 2.00 * pow(atan(ptr->l[index_l]/nu) * (chireverse[j]/rescale_argument-chi_tp),2)), chireverse[j]/rescale_argument/sin(chireverse[j]/rescale_argument) ); } else { rescale_function[j] = MAX( rescale_amplitude * (1 - 0.38 * atan(ptr->l[index_l]/nu) * (chireverse[j]/rescale_argument-chi_tp) + 0.40 * pow(atan(ptr->l[index_l]/nu) * (chireverse[j]/rescale_argument-chi_tp),2)), chireverse[j]/rescale_argument/sinh(chireverse[j]/rescale_argument) ); } } } /* class_test(pHIS->x[0] > chireverse[0], ptr->error_message, "Bessels need to be interpolated at %e, outside the range in which they have been computed (>%e). Decrease their x_min.", chireverse[0], pHIS->x[0]); */ class_test((pHIS->x[pHIS->x_size-1] < chireverse[x_size-1]) && (ptw->sgnK != 1), ptr->error_message, "Bessels need to be interpolated at %e, outside the range in which they have been computed (<%e). Increase their x_max.", chireverse[x_size-1], pHIS->x[pHIS->x_size-1] ); switch (radial_type){ case SCALAR_TEMPERATURE_0: class_call(interpolate_Phi(pHIS, x_size, index_l, chireverse, Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, NULL); for (j=0; j<x_size; j++) radial_function[x_size-1-j] = Phi[j]*rescale_function[j]; break; case SCALAR_TEMPERATURE_1: class_call(interpolate_dPhi(pHIS, x_size, index_l, chireverse, dPhi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, NULL, dPhi, NULL); for (j=0; j<x_size; j++) radial_function[x_size-1-j] = sqrt_absK_over_k*dPhi[j]*rescale_argument*rescale_function[j]; break; case SCALAR_TEMPERATURE_2: class_call(interpolate_Phid2Phi(pHIS, x_size, index_l, chireverse, Phi, d2Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, d2Phi); s2 = sqrt(1.0-3.0*K/k2); factor = 1.0/(2.0*s2); for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*(3*absK_over_k2*d2Phi[j]*rescale_argument*rescale_argument+Phi[j])*rescale_function[j]; break; case SCALAR_POLARISATION_E: class_call(interpolate_Phi(pHIS, x_size, index_l, chireverse, Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, NULL); s2 = sqrt(1.0-3.0*K/k2); factor = sqrt(3.0/8.0*(l+2.0)*(l+1.0)*l*(l-1.0))/s2; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*cscKgen[x_size-1-j]*cscKgen[x_size-1-j]*Phi[j]*rescale_function[j]; break; case VECTOR_TEMPERATURE_1: class_call(interpolate_Phi(pHIS, x_size, index_l, chireverse, Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, NULL); s0 = sqrt(1.0+K/k2); factor = sqrt(0.5*l*(l+1))/s0; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*cscKgen[x_size-1-j]*Phi[j]*rescale_function[j]; break; case VECTOR_TEMPERATURE_2: class_call(interpolate_PhidPhi(pHIS, x_size, index_l, chireverse, Phi, dPhi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, dPhi, NULL); s0 = sqrt(1.0+K/k2); ssqrt3 = sqrt(1.0-2.0*K/k2); factor = sqrt(1.5*l*(l+1))/s0/ssqrt3; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*cscKgen[x_size-1-j]*(sqrt_absK_over_k*dPhi[j]*rescale_argument-cotKgen[j]*Phi[j])*rescale_function[j]; break; case VECTOR_POLARISATION_E: class_call(interpolate_PhidPhi(pHIS, x_size, index_l, chireverse, Phi, dPhi, ptr->error_message), ptr->error_message, ptr->error_message); // hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, dPhi, NULL); s0 = sqrt(1.0+K/k2); ssqrt3 = sqrt(1.0-2.0*K/k2); factor = 0.5*sqrt((l-1.0)*(l+2.0))/s0/ssqrt3; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*cscKgen[x_size-1-j]*(cotKgen[j]*Phi[j]+sqrt_absK_over_k*dPhi[j]*rescale_argument)*rescale_function[j]; break; case VECTOR_POLARISATION_B: class_call(interpolate_Phi(pHIS, x_size, index_l, chireverse, Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, NULL); s0 = sqrt(1.0+K/k2); ssqrt3 = sqrt(1.0-2.0*K/k2); si = sqrt(1.0+2.0*K/k2); factor = 0.5*sqrt((l-1.0)*(l+2.0))*si/s0/ssqrt3; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*cscKgen[x_size-1-j]*Phi[j]*rescale_function[j]; break; case TENSOR_TEMPERATURE_2: class_call(interpolate_Phi(pHIS, x_size, index_l, chireverse, Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, NULL); ssqrt2 = sqrt(1.0-1.0*K/k2); si = sqrt(1.0+2.0*K/k2); factor = sqrt(3.0/8.0*(l+2.0)*(l+1.0)*l*(l-1.0))/si/ssqrt2; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*cscKgen[x_size-1-j]*cscKgen[x_size-1-j]*Phi[j]*rescale_function[j]; break; case TENSOR_POLARISATION_E: class_call(interpolate_PhidPhid2Phi(pHIS, x_size, index_l, chireverse, Phi, dPhi, d2Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, NULL); ssqrt2 = sqrt(1.0-1.0*K/k2); si = sqrt(1.0+2.0*K/k2); factor = 0.25/si/ssqrt2; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*(absK_over_k2*d2Phi[j]*rescale_argument*rescale_argument +4.0*cotKgen[x_size-1-j]*sqrt_absK_over_k*dPhi[j]*rescale_argument -(1.0+4*K/k2-2.0*cotKgen[x_size-1-j]*cotKgen[x_size-1-j])*Phi[j])*rescale_function[j]; break; case TENSOR_POLARISATION_B: class_call(interpolate_PhidPhi(pHIS, x_size, index_l, chireverse, Phi, dPhi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, dPhi, NULL); ssqrt2i = sqrt(1.0+3.0*K/k2); ssqrt2 = sqrt(1.0-1.0*K/k2); si = sqrt(1.0+2.0*K/k2); factor = 0.5*ssqrt2i/ssqrt2/si; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*(sqrt_absK_over_k*dPhi[j]*rescale_argument+2.0*cotKgen[x_size-1-j]*Phi[j])*rescale_function[j]; break; case NC_RSD: class_call(interpolate_Phid2Phi(pHIS, x_size, index_l, chireverse, Phi, d2Phi, ptr->error_message), ptr->error_message, ptr->error_message); //hyperspherical_Hermite_interpolation_vector(pHIS, x_size, index_l, chireverse, Phi, NULL, d2Phi); //s2 = sqrt(1.0-3.0*K/k2); factor = 1.0; for (j=0; j<x_size; j++) radial_function[x_size-1-j] = factor*absK_over_k2*d2Phi[j]*rescale_argument*rescale_argument*rescale_function[j]; // Note: in previous line there was a missing factor absK_over_k2 until version 2.4.3. Credits Francesco Montanari. break; } free(Phi); free(dPhi); free(d2Phi); free(chireverse); free(rescale_function); return _SUCCESS_; } int transfer_select_radial_function( struct perturbs * ppt, struct transfers * ptr, int index_md, int index_tt, radial_function_type * radial_type ) { /* generic case leading to generic bessel function (it applies also to all nonCMB types: lcmb, density, lensing) */ *radial_type = SCALAR_TEMPERATURE_0; /* other specific cases */ if (_scalars_) { if (ppt->has_cl_cmb_temperature == _TRUE_) { if (index_tt == ptr->index_tt_t0) { *radial_type = SCALAR_TEMPERATURE_0; } if (index_tt == ptr->index_tt_t1) { *radial_type = SCALAR_TEMPERATURE_1; } if (index_tt == ptr->index_tt_t2) { *radial_type = SCALAR_TEMPERATURE_2; } } if (ppt->has_cl_cmb_polarization == _TRUE_) { if (index_tt == ptr->index_tt_e) { *radial_type = SCALAR_POLARISATION_E; } } if (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd)) *radial_type = SCALAR_TEMPERATURE_1; if (_index_tt_in_range_(ptr->index_tt_rsd, ppt->selection_num, ppt->has_nc_rsd)) *radial_type = NC_RSD; if (_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr)) *radial_type = SCALAR_TEMPERATURE_1; } if (_vectors_) { if (ppt->has_cl_cmb_temperature == _TRUE_) { if (index_tt == ptr->index_tt_t1) { *radial_type = VECTOR_TEMPERATURE_1; } if (index_tt == ptr->index_tt_t2) { *radial_type = VECTOR_TEMPERATURE_2; } } if (ppt->has_cl_cmb_polarization == _TRUE_) { if (index_tt == ptr->index_tt_e) { *radial_type = VECTOR_POLARISATION_E; } if (index_tt == ptr->index_tt_b) { *radial_type = VECTOR_POLARISATION_B; } } } if (_tensors_) { if (ppt->has_cl_cmb_temperature == _TRUE_) { if (index_tt == ptr->index_tt_t2) { *radial_type = TENSOR_TEMPERATURE_2; } } if (ppt->has_cl_cmb_polarization == _TRUE_) { if (index_tt == ptr->index_tt_e) { *radial_type = TENSOR_POLARISATION_E; } if (index_tt == ptr->index_tt_b) { *radial_type = TENSOR_POLARISATION_B; } } } return _SUCCESS_; } /* for reading global selection function (ie the one multiplying the selection function of each bin) */ int transfer_global_selection_read( struct transfers * ptr ) { /* for reading selection function */ FILE * input_file; int row,status; double tmp1,tmp2; ptr->nz_size = 0; if (ptr->has_nz_file == _TRUE_) { input_file = fopen(ptr->nz_file_name,"r"); class_test(input_file == NULL, ptr->error_message, "Could not open file %s!",ptr->nz_file_name); /* Find size of table */ for (row=0,status=2; status==2; row++){ status = fscanf(input_file,"%lf %lf",&tmp1,&tmp2); } rewind(input_file); ptr->nz_size = row-1; /* Allocate room for interpolation table */ class_alloc(ptr->nz_z,sizeof(double)*ptr->nz_size,ptr->error_message); class_alloc(ptr->nz_nz,sizeof(double)*ptr->nz_size,ptr->error_message); class_alloc(ptr->nz_ddnz,sizeof(double)*ptr->nz_size,ptr->error_message); for (row=0; row<ptr->nz_size; row++){ status = fscanf(input_file,"%lf %lf", &ptr->nz_z[row],&ptr->nz_nz[row]); //printf("%d: (z,dNdz) = (%g,%g)\n",row,ptr->nz_z[row],ptr->nz_nz[row]); } fclose(input_file); /* Call spline interpolation: */ class_call(array_spline_table_lines(ptr->nz_z, ptr->nz_size, ptr->nz_nz, 1, ptr->nz_ddnz, _SPLINE_EST_DERIV_, ptr->error_message), ptr->error_message, ptr->error_message); } ptr->nz_evo_size = 0; if (ptr->has_nz_evo_file == _TRUE_) { input_file = fopen(ptr->nz_evo_file_name,"r"); class_test(input_file == NULL, ptr->error_message, "Could not open file %s!",ptr->nz_evo_file_name); /* Find size of table */ for (row=0,status=2; status==2; row++){ status = fscanf(input_file,"%lf %lf",&tmp1,&tmp2); } rewind(input_file); ptr->nz_evo_size = row-1; /* Allocate room for interpolation table */ class_alloc(ptr->nz_evo_z,sizeof(double)*ptr->nz_evo_size,ptr->error_message); class_alloc(ptr->nz_evo_nz,sizeof(double)*ptr->nz_evo_size,ptr->error_message); class_alloc(ptr->nz_evo_dlog_nz,sizeof(double)*ptr->nz_evo_size,ptr->error_message); class_alloc(ptr->nz_evo_dd_dlog_nz,sizeof(double)*ptr->nz_evo_size,ptr->error_message); for (row=0; row<ptr->nz_evo_size; row++){ status = fscanf(input_file,"%lf %lf", &ptr->nz_evo_z[row],&ptr->nz_evo_nz[row]); } fclose(input_file); /* infer dlog(dN/dz)/dz from dN/dz */ ptr->nz_evo_dlog_nz[0] = (log(ptr->nz_evo_nz[1])-log(ptr->nz_evo_nz[0])) /(ptr->nz_evo_z[1]-ptr->nz_evo_z[0]); for (row=1; row<ptr->nz_evo_size-1; row++){ ptr->nz_evo_dlog_nz[row] = (log(ptr->nz_evo_nz[row+1])-log(ptr->nz_evo_nz[row-1])) /(ptr->nz_evo_z[row+1]-ptr->nz_evo_z[row-1]); } ptr->nz_evo_dlog_nz[ptr->nz_evo_size-1] = (log(ptr->nz_evo_nz[ptr->nz_evo_size-1])-log(ptr->nz_evo_nz[ptr->nz_evo_size-2])) /(ptr->nz_evo_z[ptr->nz_evo_size-1]-ptr->nz_evo_z[ptr->nz_evo_size-2]); /* to test that the file is read: for (row=0; row<ptr->nz_evo_size; row++){ fprintf(stdout,"%d: (z,dNdz,dlndNdzdz) = (%g,%g,%g)\n",row,ptr->nz_evo_z[row],ptr->nz_evo_nz[row],ptr->nz_evo_dlog_nz[row]); } */ /* Call spline interpolation: */ class_call(array_spline_table_lines(ptr->nz_evo_z, ptr->nz_evo_size, ptr->nz_evo_dlog_nz, 1, ptr->nz_evo_dd_dlog_nz, _SPLINE_EST_DERIV_, ptr->error_message), ptr->error_message, ptr->error_message); } return _SUCCESS_; }; int transfer_workspace_init( struct transfers * ptr, struct precision * ppr, struct transfer_workspace **ptw, int perturb_tau_size, int tau_size_max, double K, int sgnK, double tau0_minus_tau_cut, HyperInterpStruct * pBIS){ class_calloc(*ptw,1,sizeof(struct transfer_workspace),ptr->error_message); (*ptw)->tau_size_max = tau_size_max; (*ptw)->l_size = ptr->l_size_max; (*ptw)->HIS_allocated=_FALSE_; (*ptw)->pBIS = pBIS; (*ptw)->K = K; (*ptw)->sgnK = sgnK; (*ptw)->tau0_minus_tau_cut = tau0_minus_tau_cut; (*ptw)->neglect_late_source = _FALSE_; class_alloc((*ptw)->interpolated_sources,perturb_tau_size*sizeof(double),ptr->error_message); class_alloc((*ptw)->sources,tau_size_max*sizeof(double),ptr->error_message); class_alloc((*ptw)->tau0_minus_tau,tau_size_max*sizeof(double),ptr->error_message); class_alloc((*ptw)->w_trapz,tau_size_max*sizeof(double),ptr->error_message); class_alloc((*ptw)->chi,tau_size_max*sizeof(double),ptr->error_message); class_alloc((*ptw)->cscKgen,tau_size_max*sizeof(double),ptr->error_message); class_alloc((*ptw)->cotKgen,tau_size_max*sizeof(double),ptr->error_message); return _SUCCESS_; } int transfer_workspace_free( struct transfers * ptr, struct transfer_workspace *ptw ) { if (ptw->HIS_allocated==_TRUE_){ //Free HIS structure: class_call(hyperspherical_HIS_free(&(ptw->HIS),ptr->error_message), ptr->error_message, ptr->error_message); } free(ptw->interpolated_sources); free(ptw->sources); free(ptw->tau0_minus_tau); free(ptw->w_trapz); free(ptw->chi); free(ptw->cscKgen); free(ptw->cotKgen); free(ptw); return _SUCCESS_; } int transfer_update_HIS( struct precision * ppr, struct transfers * ptr, struct transfer_workspace * ptw, int index_q, double tau0 ) { double nu,new_nu; int int_nu; double xmin, xmax, sampling, phiminabs, xtol; double sqrt_absK; int l_size_max; int index_l_left,index_l_right; if (ptw->HIS_allocated == _TRUE_) { class_call(hyperspherical_HIS_free(&(ptw->HIS),ptr->error_message), ptr->error_message, ptr->error_message); ptw->HIS_allocated = _FALSE_; } if ((ptw->sgnK!=0) && (index_q < ptr->index_q_flat_approximation)) { xmin = ppr->hyper_x_min; sqrt_absK = sqrt(ptw->sgnK*ptw->K); xmax = sqrt_absK*tau0; nu = ptr->q[index_q]/sqrt_absK; if (ptw->sgnK == 1) { xmax = MIN(xmax,_PI_/2.0-ppr->hyper_x_min); //We only need solution on [0;pi/2] int_nu = (int)(nu+0.2); new_nu = (double)int_nu; class_test(nu-new_nu > 1.e-6, ptr->error_message, "problem in q list definition in closed case for index_q=%d, nu=%e, nu-int(nu)=%e",index_q,nu,nu-new_nu); nu = new_nu; } if (nu > ppr->hyper_nu_sampling_step) sampling = ppr->hyper_sampling_curved_high_nu; else sampling = ppr->hyper_sampling_curved_low_nu; /* find the highest value of l such that x_nonzero < xmax = sqrt(|K|) tau0. That will be l_max. */ l_size_max = ptr->l_size_max; if (ptw->sgnK == 1) while ((double)ptr->l[l_size_max-1] >= nu) l_size_max--; if (ptw->sgnK == -1){ xtol = ppr->hyper_x_tol; phiminabs = ppr->hyper_phi_min_abs; /* First try to find lmax using fast approximation: */ index_l_left=0; index_l_right=l_size_max-1; class_call(transfer_get_lmax(hyperspherical_get_xmin_from_approx, ptw->sgnK, nu, ptr->l, l_size_max, phiminabs, xmax, xtol, &index_l_left, &index_l_right, ptr->error_message), ptr->error_message, ptr->error_message); /* Now use WKB approximation to eventually modify borders: */ class_call(transfer_get_lmax(hyperspherical_get_xmin_from_Airy, ptw->sgnK, nu, ptr->l, l_size_max, phiminabs, xmax, xtol, &index_l_left, &index_l_right, ptr->error_message), ptr->error_message, ptr->error_message); l_size_max = index_l_right+1; } class_test(nu <= 0., ptr->error_message, "nu=%e when index_q=%d, q=%e, K=%e, sqrt(|K|)=%e; instead nu should always be strictly positive", nu,index_q,ptr->q[index_q],ptw->K,sqrt_absK); class_call(hyperspherical_HIS_create(ptw->sgnK, nu, l_size_max, ptr->l, xmin, xmax, sampling, ptr->l[l_size_max-1]+1, ppr->hyper_phi_min_abs, &(ptw->HIS), ptr->error_message), ptr->error_message, ptr->error_message); ptw->HIS_allocated = _TRUE_; } return _SUCCESS_; } int transfer_get_lmax(int (*get_xmin_generic)(int sgnK, int l, double nu, double xtol, double phiminabs, double *x_nonzero, int *fevals), int sgnK, double nu, int *lvec, int lsize, double phiminabs, double xmax, double xtol, int *index_l_left, int *index_l_right, ErrorMsg error_message){ double x_nonzero; int fevals=0, index_l_mid; int multiplier; int right_boundary_checked = _FALSE_; int hil=0,hir=0,bini=0; class_call(get_xmin_generic(sgnK, lvec[0], nu, xtol, phiminabs, &x_nonzero, &fevals), error_message, error_message); if (x_nonzero >= xmax){ //printf("None relevant\n"); //x at left boundary is already larger than xmax. *index_l_right = MAX(lsize-1,1); return _SUCCESS_; } class_call(get_xmin_generic(sgnK, lvec[lsize-1], nu, xtol, phiminabs, &x_nonzero, &fevals), error_message, error_message); if (x_nonzero < xmax){ //All Bessels are relevant //printf("All relevant\n"); *index_l_left = MAX(0,(lsize-2)); return _SUCCESS_; } /* Hunt for left boundary: */ for (multiplier=1; ;multiplier *= 5){ hil++; class_call(get_xmin_generic(sgnK, lvec[*index_l_left], nu, xtol, phiminabs, &x_nonzero, &fevals), error_message, error_message); //printf("Hunt left, iter = %d, x_nonzero=%g\n",hil,x_nonzero); if (x_nonzero <= xmax){ //Boundary found break; } else{ //We can use current index_l_left as index_l_right: *index_l_right = *index_l_left; right_boundary_checked = _TRUE_; } //Update index_l_left: *index_l_left = (*index_l_left)-multiplier; if (*index_l_left<=0){ *index_l_left = 0; break; } } /* If not found, hunt for right boundary: */ if (right_boundary_checked == _FALSE_){ for (multiplier=1; ;multiplier *= 5){ hir++; //printf("right iteration %d,index_l_right:%d\n",hir,*index_l_right); class_call(get_xmin_generic(sgnK, lvec[*index_l_right], nu, xtol, phiminabs, &x_nonzero, &fevals), error_message, error_message); if (x_nonzero >= xmax){ //Boundary found break; } else{ //We can use current index_l_right as index_l_left: *index_l_left = *index_l_right; } //Update index_l_right: *index_l_right = (*index_l_right)+multiplier; if (*index_l_right>=(lsize-1)){ *index_l_right = lsize-1; break; } } } // int fevalshunt=fevals; fevals=0; //Do binary search // printf("Do binary search in get_lmax. \n"); //printf("Region: [%d, %d]\n",*index_l_left,*index_l_right); while (((*index_l_right) - (*index_l_left)) > 1) { bini++; index_l_mid= (int)(0.5*((*index_l_right)+(*index_l_left))); //printf("left:%d, mid=%d, right=%d\n",*index_l_left,index_l_mid,*index_l_right); class_call(get_xmin_generic(sgnK, lvec[index_l_mid], nu, xtol, phiminabs, &x_nonzero, &fevals), error_message, error_message); if (x_nonzero < xmax) *index_l_left=index_l_mid; else *index_l_right=index_l_mid; } //printf("Done\n"); /* printf("Hunt left iter=%d, hunt right iter=%d (fevals: %d). For binary search: %d (fevals: %d)\n", hil,hir,fevalshunt,bini,fevals); */ return _SUCCESS_; } /** * Here we can precompute the window functions for the final integration * For each type of nCl/dCl/sCl we combine the selection function * with the corresponding prefactor (e.g. 1/aH), and, if required, * we also integrate for integrated (lensed) contributions * (In the original ClassGAL paper these would be labeled g4,g5, and lens) * * All factors of k have to be added later (at least in the current version) * * @param ppr Input: pointer to precision structure * @param pba Input: pointer to background structure * @param ppt Input: pointer to perturbation structure * @param ptr Input: pointer to transfers structure * @param tau_rec Input: recombination time * @param tau_size_max Input: maximum size that tau array can have * @param window Output: pointer to array of selection functions * @return the error status */ int transfer_precompute_selection( struct precision * ppr, struct background * pba, struct perturbs * ppt, struct transfers * ptr, double tau_rec, int tau_size_max, double ** window /* Pass a pointer to the pointer, so the pointer can be allocated inside of the function */ ){ /** Summary: */ /** - define local variables */ double* tau0_minus_tau; double* w_trapz; /* index running on time */ int index_tau; /* bin for computation of cl_density */ int bin=0; /* number of tau values */ int tau_size; /* for calling background_at_eta */ int last_index; double * pvecback = NULL; /* conformal time */ double tau, tau0; /* geometrical quantities */ double sinKgen_source=0.; double sinKgen_source_to_lens=0.; double cotKgen_source=0.; double cscKgen_lens=0.; /* rescaling factor depending on the background at a given time */ double rescaling=0.; /* array of selection function values at different times */ double * selection; /* array of time sampling for lensing source selection function */ double * tau0_minus_tau_lensing_sources; /* trapezoidal weights for lensing source selection function */ double * w_trapz_lensing_sources; /* index running on time in previous two arrays */ int index_tau_sources; /* number of time values in previous two arrays */ int tau_sources_size; /* source evolution factor */ double f_evo = 0.; /* Setup initial variables and arrays*/ int index_md = ppt->index_md_scalars; int index_tt; /* allocate temporary arrays for storing selections, weights, times, and output; and for calling background */ class_alloc(tau0_minus_tau,tau_size_max*sizeof(double),ptr->error_message); class_alloc(selection,tau_size_max*sizeof(double),ptr->error_message); class_alloc(w_trapz,tau_size_max*sizeof(double),ptr->error_message); class_alloc((*window),tau_size_max*ptr->tt_size[index_md]*sizeof(double),ptr->error_message); class_alloc(pvecback,pba->bg_size*sizeof(double),ptr->error_message); /* conformal time today */ tau0 = pba->conformal_age; /* Loop through different types to be precomputed */ for (index_tt = 0; index_tt < ptr->tt_size[index_md]; index_tt++) { /* First set the corresponding tau size */ class_call(transfer_source_tau_size(ppr, pba, ppt, ptr, tau_rec, tau0, index_md, index_tt, &tau_size), ptr->error_message, ptr->error_message); /* Start with non-integrated contributions */ if (_nonintegrated_ncl_) { _get_bin_nonintegrated_ncl_(index_tt) /* redefine the time sampling */ class_call(transfer_selection_sampling(ppr, pba, ppt, ptr, bin, tau0_minus_tau, tau_size), ptr->error_message, ptr->error_message); class_test(tau0 - tau0_minus_tau[0] > ppt->tau_sampling[ppt->tau_size-1], ptr->error_message, "this should not happen, there was probably a rounding error, if this error occurred, then this must be coded more carefully"); /* Compute trapezoidal weights for integration over tau */ class_call(array_trapezoidal_mweights(tau0_minus_tau, tau_size, w_trapz, ptr->error_message), ptr->error_message, ptr->error_message); /* compute values of selection function at sampled values of tau */ class_call(transfer_selection_compute(ppr, pba, ppt, ptr, selection, tau0_minus_tau, w_trapz, tau_size, pvecback, tau0, bin), ptr->error_message, ptr->error_message); /* loop over time and rescale */ for (index_tau = 0; index_tau < tau_size; index_tau++) { /* conformal time */ tau = tau0 - tau0_minus_tau[index_tau]; /* geometrical quantity */ switch (pba->sgnK){ case 1: cotKgen_source = sqrt(pba->K) *cos(tau0_minus_tau[index_tau]*sqrt(pba->K)) /sin(tau0_minus_tau[index_tau]*sqrt(pba->K)); break; case 0: cotKgen_source = 1./(tau0_minus_tau[index_tau]); break; case -1: cotKgen_source = sqrt(-pba->K) *cosh(tau0_minus_tau[index_tau]*sqrt(-pba->K)) /sinh(tau0_minus_tau[index_tau]*sqrt(-pba->K)); break; } /* corresponding background quantities */ class_call(background_at_tau(pba, tau, pba->long_info, pba->inter_normal, &last_index, pvecback), pba->error_message, ptr->error_message); /* Source evolution, used by nCl doppler and nCl gravity terms */ if ((_index_tt_in_range_(ptr->index_tt_d0, ppt->selection_num, ppt->has_nc_rsd)) || (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd)) || (_index_tt_in_range_(ptr->index_tt_nc_g2, ppt->selection_num, ppt->has_nc_gr))) { class_call(transfer_f_evo(pba,ptr,pvecback,last_index,cotKgen_source,&f_evo), ptr->error_message, ptr->error_message); /* Error in old CLASS 2.6.3 : Number count evolution did not respect curvature */ } /* matter density source = [- (dz/dtau) W(z)] * delta_m(k,tau) = W(tau) delta_m(k,tau) with delta_m = total matter perturbation (defined in gauge-independent way, see arXiv 1307.1459) W(z) = redshift space selection function = dN/dz W(tau) = same wrt conformal time = dN/dtau (in tau = tau_0, set source = 0 to avoid division by zero; regulated anyway by Bessel). */ if (_index_tt_in_range_(ptr->index_tt_density, ppt->selection_num, ppt->has_nc_density)) rescaling = ptr->selection_bias[bin]*selection[index_tau]; /* redshift space distortion source = - [- (dz/dtau) W(z)] * (k/H) * theta(k,tau) */ if (_index_tt_in_range_(ptr->index_tt_rsd, ppt->selection_num, ppt->has_nc_rsd)) rescaling = selection[index_tau]/pvecback[pba->index_bg_H]/pvecback[pba->index_bg_a]; if (_index_tt_in_range_(ptr->index_tt_d0, ppt->selection_num, ppt->has_nc_rsd)) rescaling = (f_evo-3.)*selection[index_tau]*pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a]; if (_index_tt_in_range_(ptr->index_tt_d1, ppt->selection_num, ppt->has_nc_rsd)) rescaling = selection[index_tau]*(1. +pvecback[pba->index_bg_H_prime] /pvecback[pba->index_bg_a] /pvecback[pba->index_bg_H] /pvecback[pba->index_bg_H] +(2.-5.*ptr->selection_magnification_bias[bin]) // /tau0_minus_tau[index_tau] // in flat space *cotKgen_source // in general case /pvecback[pba->index_bg_a] /pvecback[pba->index_bg_H] +5.*ptr->selection_magnification_bias[bin] -f_evo ); if (_index_tt_in_range_(ptr->index_tt_nc_g1, ppt->selection_num, ppt->has_nc_gr)) rescaling = selection[index_tau]; if (_index_tt_in_range_(ptr->index_tt_nc_g2, ppt->selection_num, ppt->has_nc_gr)) rescaling = -selection[index_tau]*(3. +pvecback[pba->index_bg_H_prime] /pvecback[pba->index_bg_a] /pvecback[pba->index_bg_H] /pvecback[pba->index_bg_H] +(2.-5.*ptr->selection_magnification_bias[bin]) // /tau0_minus_tau[index_tau] // in flat space *cotKgen_source // in general case /pvecback[pba->index_bg_a] /pvecback[pba->index_bg_H] -f_evo ); if (_index_tt_in_range_(ptr->index_tt_nc_g3, ppt->selection_num, ppt->has_nc_gr)) rescaling = selection[index_tau]/pvecback[pba->index_bg_a]/pvecback[pba->index_bg_H]; /* finally store in array */ (*window)[index_tt*tau_size_max+index_tau] = rescaling; } } /* End non-integrated contribution */ /* Now deal with integrated contributions */ if (_integrated_ncl_) { _get_bin_integrated_ncl_(index_tt) /* dirac case */ if (ppt->selection == dirac) { tau_sources_size=1; } /* other cases (gaussian, tophat...) */ else { tau_sources_size=ppr->selection_sampling; } class_alloc(tau0_minus_tau_lensing_sources, tau_sources_size*sizeof(double), ptr->error_message); class_alloc(w_trapz_lensing_sources, tau_sources_size*sizeof(double), ptr->error_message); /* time sampling for source selection function */ class_call(transfer_selection_sampling(ppr, pba, ppt, ptr, bin, tau0_minus_tau_lensing_sources, tau_sources_size), ptr->error_message, ptr->error_message); /* Compute trapezoidal weights for integration over tau */ class_call(array_trapezoidal_mweights(tau0_minus_tau_lensing_sources, tau_sources_size, w_trapz_lensing_sources, ptr->error_message), ptr->error_message, ptr->error_message); /* compute values of selection function at sampled values of tau */ class_call(transfer_selection_compute(ppr, pba, ppt, ptr, selection, tau0_minus_tau_lensing_sources, w_trapz_lensing_sources, tau_sources_size, pvecback, tau0, bin), ptr->error_message, ptr->error_message); /* redefine the time sampling */ class_call(transfer_lensing_sampling(ppr, pba, ppt, ptr, bin, tau0, tau0_minus_tau, tau_size), ptr->error_message, ptr->error_message); /* Compute trapezoidal weights for integration over tau */ class_call(array_trapezoidal_mweights(tau0_minus_tau, tau_size, w_trapz, ptr->error_message), ptr->error_message, ptr->error_message); /* loop over time and rescale */ for (index_tau = 0; index_tau < tau_size; index_tau++) { /* lensing source = - W(tau) (phi(k,tau) + psi(k,tau)) Heaviside(tau-tau_rec) with psi,phi = metric perturbation in newtonian gauge (phi+psi = Phi_A-Phi_H of Bardeen) W = (tau-tau_rec)/(tau_0-tau)/(tau_0-tau_rec) H(x) = Heaviside (in tau = tau_0, set source = 0 to avoid division by zero; regulated anyway by Bessel). */ if (index_tau == tau_size-1) { rescaling=0.; } else { rescaling = 0.; for (index_tau_sources=0; index_tau_sources < tau_sources_size; index_tau_sources++) { switch (pba->sgnK){ case 1: sinKgen_source = sin(tau0_minus_tau_lensing_sources[index_tau_sources]*sqrt(pba->K))/sqrt(pba->K); sinKgen_source_to_lens = sin((tau0_minus_tau[index_tau]-tau0_minus_tau_lensing_sources[index_tau_sources])*sqrt(pba->K))/sqrt(pba->K); cotKgen_source = cos(tau0_minus_tau_lensing_sources[index_tau_sources]*sqrt(pba->K))/sinKgen_source; cscKgen_lens = sqrt(pba->K)/sin(sqrt(pba->K)*tau0_minus_tau[index_tau]); break; case 0: sinKgen_source = tau0_minus_tau_lensing_sources[index_tau_sources]; sinKgen_source_to_lens = (tau0_minus_tau[index_tau]-tau0_minus_tau_lensing_sources[index_tau_sources]); cotKgen_source = 1./(tau0_minus_tau_lensing_sources[index_tau_sources]); cscKgen_lens = 1./(tau0_minus_tau[index_tau]); break; case -1: sinKgen_source = sinh(tau0_minus_tau_lensing_sources[index_tau_sources]*sqrt(-pba->K))/sqrt(-pba->K); sinKgen_source_to_lens = sinh((tau0_minus_tau[index_tau]-tau0_minus_tau_lensing_sources[index_tau_sources])*sqrt(-pba->K))/sqrt(-pba->K); cotKgen_source = cosh(tau0_minus_tau_lensing_sources[index_tau_sources]*sqrt(-pba->K))/sinKgen_source; cscKgen_lens = sqrt(-pba->K)/sinh(sqrt(-pba->K)*tau0_minus_tau[index_tau]); break; } /* condition for excluding from the sum the sources located in z=zero */ if ((tau0_minus_tau_lensing_sources[index_tau_sources] > 0.) && (tau0_minus_tau_lensing_sources[index_tau_sources]-tau0_minus_tau[index_tau] > 0.)) { if (_index_tt_in_range_(ptr->index_tt_lensing, ppt->selection_num, ppt->has_cl_lensing_potential)) { rescaling += // *(tau0_minus_tau[index_tau]-tau0_minus_tau_lensing_sources[index_tau_sources]) // /tau0_minus_tau[index_tau] // /tau0_minus_tau_lensing_sources[index_tau_sources] sinKgen_source_to_lens *cscKgen_lens /sinKgen_source * selection[index_tau_sources] * w_trapz_lensing_sources[index_tau_sources]; } if (_index_tt_in_range_(ptr->index_tt_nc_lens, ppt->selection_num, ppt->has_nc_lens)) { rescaling -= (2.-5.*ptr->selection_magnification_bias[bin])/2. // *(tau0_minus_tau[index_tau]-tau0_minus_tau_lensing_sources[index_tau_sources]) // /tau0_minus_tau[index_tau] // /tau0_minus_tau_lensing_sources[index_tau_sources] *sinKgen_source_to_lens *cscKgen_lens /sinKgen_source * selection[index_tau_sources] * w_trapz_lensing_sources[index_tau_sources]; } if (_index_tt_in_range_(ptr->index_tt_nc_g4, ppt->selection_num, ppt->has_nc_gr)) { rescaling += (2.-5.*ptr->selection_magnification_bias[bin]) // /tau0_minus_tau_lensing_sources[index_tau_sources] * cotKgen_source * selection[index_tau_sources] * w_trapz_lensing_sources[index_tau_sources]; } if (_index_tt_in_range_(ptr->index_tt_nc_g5, ppt->selection_num, ppt->has_nc_gr)) { /* background quantities at time tau_lensing_source */ class_call(background_at_tau(pba, tau0-tau0_minus_tau_lensing_sources[index_tau_sources], pba->long_info, pba->inter_normal, &last_index, pvecback), pba->error_message, ptr->error_message); /* Source evolution at time tau_lensing_source */ class_call(transfer_f_evo(pba,ptr,pvecback,last_index,cotKgen_source,&f_evo), ptr->error_message, ptr->error_message); rescaling += (1. + pvecback[pba->index_bg_H_prime] /pvecback[pba->index_bg_a] /pvecback[pba->index_bg_H] /pvecback[pba->index_bg_H] + (2.-5.*ptr->selection_magnification_bias[bin]) // /tau0_minus_tau_lensing_sources[index_tau_sources] * cotKgen_source /pvecback[pba->index_bg_a] /pvecback[pba->index_bg_H] + 5.*ptr->selection_magnification_bias[bin] - f_evo) * selection[index_tau_sources] * w_trapz_lensing_sources[index_tau_sources]; } } } } /* Finally store integrated result for later use */ (*window)[index_tt*tau_size_max+index_tau] = rescaling; } /* deallocate temporary arrays */ free(tau0_minus_tau_lensing_sources); free(w_trapz_lensing_sources); } /* End integrated contribution */ } /* deallocate temporary arrays */ free(selection); free(tau0_minus_tau); free(w_trapz); free(pvecback); return _SUCCESS_; } int transfer_f_evo( struct background* pba, struct transfers * ptr, double* pvecback, int last_index, double cotKgen, /* Should be FILLED with values of corresponding time */ double* f_evo ){ /* Allocate temporary variables for calculation of f_evo */ double z; double dNdz; double dln_dNdz_dz; double temp_f_evo; if ((ptr->has_nz_evo_file == _TRUE_) || (ptr->has_nz_evo_analytic == _TRUE_)){ temp_f_evo = 2./pvecback[pba->index_bg_H]/pvecback[pba->index_bg_a]*cotKgen + pvecback[pba->index_bg_H_prime]/pvecback[pba->index_bg_H]/pvecback[pba->index_bg_H]/pvecback[pba->index_bg_a]; z = pba->a_today/pvecback[pba->index_bg_a]-1.; if (ptr->has_nz_evo_file ==_TRUE_) { class_test((z<ptr->nz_evo_z[0]) || (z>ptr->nz_evo_z[ptr->nz_evo_size-1]), ptr->error_message, "Your input file for the selection function only covers the redshift range [%f : %f]. However, your input for the selection function requires z=%f", ptr->nz_evo_z[0], ptr->nz_evo_z[ptr->nz_evo_size-1], z); class_call(array_interpolate_spline( ptr->nz_evo_z, ptr->nz_evo_size, ptr->nz_evo_dlog_nz, ptr->nz_evo_dd_dlog_nz, 1, z, &last_index, &dln_dNdz_dz, 1, ptr->error_message), ptr->error_message, ptr->error_message); } else { class_call(transfer_dNdz_analytic(ptr, z, &dNdz, &dln_dNdz_dz), ptr->error_message, ptr->error_message); } temp_f_evo -= dln_dNdz_dz/pvecback[pba->index_bg_a]; } else { temp_f_evo = 0.; } /* after obtaining f_evo, store it in output */ *f_evo = temp_f_evo; return _SUCCESS_; }
Partition.h
/* * Partition.h * * Created on: 03.10.2013 * Author: cls */ #ifndef PARTITION_H_ #define PARTITION_H_ #include <cinttypes> #include <set> #include <vector> #include <map> #include <cassert> #include <limits> #include "../graph/Graph.h" namespace NetworKit { /** * @ingroup structures * Implements a partition of a set, i.e. a subdivision of the * set into disjoint subsets. */ class Partition { public: Partition(); /** * Create a new partition data structure for @a z elements. * * @param[in] z maximum index */ Partition(index z); /** * Create a new partition data structure for @a z elements. * Initialize each entry to the default value. * WARNING: this circumvents the standard interface and may leave the object * in an inconsistent state. Use only in exceptional cases. * * @param[in] z maximum index * @param[in] defaultValue */ Partition(index z, index defaultValue); /** * Index operator. * * @param[in] e an element */ inline index& operator [](const index& e) { return this->data[e]; } /** * Index operator for const instances of this class. * * @param[in] e an element */ inline const index& operator [](const index& e) const { return this->data[e]; } /** * Get the set (id) in which the element @a e is contained. * * @param e Index of element. * @return The index of the set in which @a e is contained. */ inline index subsetOf(index e) const { assert (e < this->numberOfElements()); return this->data[e]; } /** * Extend the data structure and create a slot * for one more element. Initializes the entry to none * and returns the index of the entry. */ inline index extend() { data.push_back(none); z++; assert (z == data.size()); //(data.size() - 1) return z-1; } /** * Removes the entry for the given element * by setting it to none. */ inline void remove(index e) { assert (e < z); data[e] = none; } /** * Add a (previously unassigned) element @a e to the set @a s. * * @param s The index of the subset. * @param e The element to add. */ inline void addToSubset(index s, index e) { assert (data[e] == none); // guarantee that element was unassigned assert (s <= omega); // do not create new subset ids data[e] = s; } /** * Move the (previously assigned) element @a e to the set @a s. * * @param s The index of the subset. * @param e The element to move. */ inline void moveToSubset(index s, index e) { assert (this->contains(e)); assert (s <= omega); // do not create new subset ids data[e] = s; } /** * Creates a singleton set containing the element @a e. * * @param e The index of the element. */ inline void toSingleton(index e) { data[e] = newSubsetId(); } /** * Assigns every element to a singleton set. * Set id is equal to element id. */ void allToSingletons(); /** * Assigns every element to the same subset. * Set id is equal to zero. */ void allToOnePartition(); /** * Assigns the elements from both sets to a new set and returns the id of it. * * @param s Set to merge. * @param t Set to merge. * @return Id of newly created set. */ index mergeSubsets(index s, index t); /** * Check if partition is a 1-partition, * i.e. every element is assigned to the same set. */ //bool isOnePartition(Graph& G); /** * Check if partition is a singleton partition, * i.e. every element is assigned to a different set. */ //bool isSingletonPartition(Graph& G) const; /** * Sets an upper bound for the subset ids that CAN be assigned. * * @param[in] upper highest assigned subset ID + 1 */ inline void setUpperBound(index upper) { this->omega = upper-1; } /** * Return an upper bound for the subset ids that have been assigned. * (This is the maximum id + 1.) * * @return The upper bound. */ inline index upperBound() const { return omega+1; } /** * Get a lower bound for the subset ids that have been assigned. * * @return The lower bound. */ inline index lowerBound() const { return 0; } /** * Change subset IDs to be consecutive, starting at 0. * @param useTurbo Default: false. If set to true, a vector instead of a map to assign new ids * which results in a shorter running time but possibly a large space overhead. */ void compact(bool useTurbo = false); /** * Check if partition assigns a valid subset to the element @a e. * * @param e The element. * @return @c true if the assigned subset is valid, @c false otherwise. */ inline bool contains(index e) const { return (e < z) && (data[e] != none); // e is in the element index range and the entry is not empty } /** * Check if two elements @a e1 and @a e2 belong to the same subset. * * @param e1 Element. * @param e2 Element. * @return @c true if @a e1 and @a e2 belong to same subset, @c false otherwise. */ inline bool inSameSubset(index e1, index e2) const { assert (data[e1] != none); assert (data[e2] != none); return (data[e1] == data[e2]); } /** * Get a list of subset sizes. Indices do not necessarily correspond to subset ids. * * @return A vector of subset sizes. */ std::vector<count> subsetSizes() const; /** * Get a map from subset id to size of the subset. * * @return A map from subset id to size of the subset. */ std::map<index, count> subsetSizeMap() const; /** * Get the members of the subset @a s. * * @param s The subset. * @return A set containing the members of @a s. */ std::set<index> getMembers(const index s) const; /** * @return number of elements in the partition. */ inline count numberOfElements() const { return z; // z is the maximum element id } /** * Get the current number of sets in this partition. * * @return The current number of sets. */ count numberOfSubsets() const; /** * Get the actual vector representing the partition data structure. * @return vector containing information about partitions. */ std::vector<index> getVector() const; /** * @return the subsets of the partition as a set of sets. */ std::set<std::set<index> > getSubsets() const; /** * Get the ids of nonempty subsets. * * @return A set of ids of nonempty subsets. */ std::set<index> getSubsetIds() const; /** * Set a human-readable identifier @a name for the instance. * * @param name The name. */ inline void setName(std::string name) { this->name = name; } /** * Get the human-readable identifier. * * @return The name of this partition. */ inline std::string getName() const { return this->name; } /** * Iterate over all entries (node, cluster id) and execute callback function @a func (lambda closure). * * @param func Takes parameters <code>(node, index)</code> */ template<typename Callback> void forEntries(Callback func) const; /** * Iterate over all entries (node, cluster id) in parallel and execute callback function @a handle (lambda closure). * * @param handle Takes parameters <code>(node, index)</code> */ template<typename Callback> void parallelForEntries(Callback handle) const; private: index z; //!< maximum element index that can be mapped index omega; //!< maximum subset index ever assigned std::vector<index> data; //!< data container, indexed by element index, containing subset index std::string name; /** * Allocates and returns a new subset id. */ inline index newSubsetId() { index s = ++omega; return s; } }; template<typename Callback> inline void Partition::forEntries(Callback handle) const { for (index e = 0; e < this->z; e++) { handle(e, data[e]); } } template<typename Callback> inline void Partition::parallelForEntries(Callback handle) const { #pragma omp parallel for for (index e = 0; e < this->z; e++) { handle(e, this->data[e]); } } } /* namespace NetworKit */ #endif /* PARTITION_H_ */
esac_derivative.h
/* Based on the DSAC++ code. Copyright (c) 2016, TU Dresden Copyright (c) 2019, Heidelberg University 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 TU Dresden, Heidelberg University 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 TU DRESDEN OR HEIDELBERG UNIVERSITY 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. */ #pragma once #define PROB_THRESH 0.001 // ignore hypotheses with low probability for expectations namespace esac { /** * @brief Calculates the Jacobean of the projection function w.r.t the given 3D point, ie. the function has the form 3 -> 1 * @param pt Ground truth 2D location. * @param obj 3D point. * @param rot Rotation in axis-angle format (OpenCV convention) * @param trans Translation vector (OpenCV convention). * @param camMat Calibration matrix of the camera. * @param maxReproj Reprojection errors are clamped to this maximum value. * @return 1x3 Jacobean matrix of partial derivatives. */ cv::Mat_<double> dProjectdObj( const cv::Point2f& pt, const cv::Point3f& obj, const cv::Mat& rot, const cv::Mat& trans, const cv::Mat& camMat, float maxReproErr) { double f = camMat.at<float>(0, 0); double ppx = camMat.at<float>(0, 2); double ppy = camMat.at<float>(1, 2); //transform point cv::Mat objMat = cv::Mat(obj); objMat.convertTo(objMat, CV_64F); objMat = rot * objMat + trans; if(std::abs(objMat.at<double>(2, 0)) < EPS) // prevent division by zero return cv::Mat_<double>::zeros(1, 3); // project double px = f * objMat.at<double>(0, 0) / objMat.at<double>(2, 0) + ppx; double py = f * objMat.at<double>(1, 0) / objMat.at<double>(2, 0) + ppy; // calculate error double err = std::sqrt((pt.x - px) * (pt.x - px) + (pt.y - py) * (pt.y - py)); // early out if projection error is above threshold if(err > maxReproErr) return cv::Mat_<double>::zeros(1, 3); err += EPS; // avoid dividing by zero // derivative in x direction of obj coordinate double pxdx = f * rot.at<double>(0, 0) / objMat.at<double>(2, 0) - f * objMat.at<double>(0, 0) / objMat.at<double>(2, 0) / objMat.at<double>(2, 0) * rot.at<double>(2, 0); double pydx = f * rot.at<double>(1, 0) / objMat.at<double>(2, 0) - f * objMat.at<double>(1, 0) / objMat.at<double>(2, 0) / objMat.at<double>(2, 0) * rot.at<double>(2, 0); double dx = 0.5 / err * (2 * (pt.x - px) * -pxdx + 2 * (pt.y - py) * -pydx); // derivative in y direction of obj coordinate double pxdy = f * rot.at<double>(0, 1) / objMat.at<double>(2, 0) - f * objMat.at<double>(0, 0) / objMat.at<double>(2, 0) / objMat.at<double>(2, 0) * rot.at<double>(2, 1); double pydy = f * rot.at<double>(1, 1) / objMat.at<double>(2, 0) - f * objMat.at<double>(1, 0) / objMat.at<double>(2, 0) / objMat.at<double>(2, 0) * rot.at<double>(2, 1); double dy = 0.5 / err * (2 * (pt.x - px) * -pxdy + 2 * (pt.y - py) * -pydy); // derivative in z direction of obj coordinate double pxdz = f * rot.at<double>(0, 2) / objMat.at<double>(2, 0) - f * objMat.at<double>(0, 0) / objMat.at<double>(2, 0) / objMat.at<double>(2, 0) * rot.at<double>(2, 2); double pydz = f * rot.at<double>(1, 2) / objMat.at<double>(2, 0) - f * objMat.at<double>(1, 0) / objMat.at<double>(2, 0) / objMat.at<double>(2, 0) * rot.at<double>(2, 2); double dz = 0.5 / err * (2 * (pt.x - px) * -pxdz + 2 * (pt.y - py) * -pydz); cv::Mat_<double> jacobean(1, 3); jacobean(0, 0) = dx; jacobean(0, 1) = dy; jacobean(0, 2) = dz; return jacobean; } /** * @brief Checks whether the given matrix contains NaN entries. * @param m Input matrix. * @return True if m contrains NaN entries. */ inline bool containsNaNs(const cv::Mat& m) { return cv::sum(cv::Mat(m != m))[0] > 0; } /** * @brief Calculates the Jacobean of the PNP function w.r.t. the object coordinate inputs. * * PNP is treated as a n x 3 -> 6 fnuction, i.e. it takes n 3D coordinates and maps them to a 6D pose. * The Jacobean is therefore 6x3n. * The Jacobean is calculated using central differences, and hence only suitable for small point sets. * For gradients of large points sets, we use an analytical approximaten, see the backard function in esac.cpp. * * @param imgPts List of 2D points. * @param objPts List of corresponding 3D points. * @param camMat Camera calibration matrix. * @param eps Step size for central differences. * @return 6x3n Jacobean matrix of partial derivatives. */ cv::Mat_<double> dPNP( const std::vector<cv::Point2f>& imgPts, std::vector<cv::Point3f> objPts, const cv::Mat& camMat, float eps = 0.001f) { int pnpMethod = (imgPts.size() == 4) ? cv::SOLVEPNP_P3P : cv::SOLVEPNP_ITERATIVE; //in case of P3P the 4th point is needed to resolve ambiguities, its derivative is zero int effectiveObjPoints = (pnpMethod == cv::SOLVEPNP_P3P) ? 3 : objPts.size(); cv::Mat_<double> jacobean = cv::Mat_<double>::zeros(6, objPts.size() * 3); bool success; // central differences for(int i = 0; i < effectiveObjPoints; i++) for(unsigned j = 0; j < 3; j++) { if(j == 0) objPts[i].x += eps; else if(j == 1) objPts[i].y += eps; else if(j == 2) objPts[i].z += eps; // forward step esac::pose_t fStep; success = safeSolvePnP(objPts, imgPts, camMat, cv::Mat(), fStep.first, fStep.second, false, pnpMethod); if(!success) return cv::Mat_<double>::zeros(6, objPts.size() * 3); if(j == 0) objPts[i].x -= 2 * eps; else if(j == 1) objPts[i].y -= 2 * eps; else if(j == 2) objPts[i].z -= 2 * eps; // backward step esac::pose_t bStep; success = safeSolvePnP(objPts, imgPts, camMat, cv::Mat(), bStep.first, bStep.second, false, pnpMethod); if(!success) return cv::Mat_<double>::zeros(6, objPts.size() * 3); if(j == 0) objPts[i].x += eps; else if(j == 1) objPts[i].y += eps; else if(j == 2) objPts[i].z += eps; // gradient calculation fStep.first = (fStep.first - bStep.first) / (2 * eps); fStep.second = (fStep.second - bStep.second) / (2 * eps); fStep.first.copyTo(jacobean.col(i * 3 + j).rowRange(0, 3)); fStep.second.copyTo(jacobean.col(i * 3 + j).rowRange(3, 6)); if(containsNaNs(jacobean.col(i * 3 + j))) return cv::Mat_<double>::zeros(6, objPts.size() * 3); } return jacobean; } /** * @brief Calculates the Jacobean matrix of the function that maps n estimated object coordinates to a score, ie. the function has the form n x 3 -> 1. Returns one Jacobean matrix per hypothesis. * @param sceneCoordinates Scene coordinate prediction of each expert (Ex3xHxW). * @param hypAssignment 1D trensor specifying the responsible expert for each hypothesis. * @param sampling Contains original image coordinate for each scene coordinate predicted. * @param sampledPoints Corresponding minimal set for each hypotheses as scene coordinate indices. * @param jacobeansScore (output paramter) List of Jacobean matrices. One 1 x 3n matrix per pose hypothesis. * @param scoreOutputGradients Gradients w.r.t the score i.e. the gradients of the loss up to the soft inlier count. * @param hyps List of RANSAC hypotheses. * @param reproErrs Image of reprojection error for each pose hypothesis. * @param jacobeanHyps List of jacobean matrices with derivatives of the 6D pose wrt. the reprojection errors. * @param hypProbs Selection probabilities over all hypotheses. * @param camMat Camera calibration matrix. * @param inlierAlpha Alpha parameter for soft inlier counting. * @param inlierBeta Beta parameter for soft inlier counting. * @param inlierThreshold RANSAC inlier threshold. * @param maxReproj Reprojection errors are clamped to this maximum value. */ void dScore( esac::coord_t& sceneCoordinates, esac::hyp_assign_t& hypAssignment, const cv::Mat_<cv::Point2i>& sampling, const std::vector<std::vector<cv::Point2i>>& sampledPoints, std::vector<cv::Mat_<double>>& jacobeansScore, const std::vector<double>& scoreOutputGradients, const std::vector<esac::pose_t>& hyps, const std::vector<cv::Mat_<float>>& reproErrs, const std::vector<cv::Mat_<double>>& jacobeansHyps, const std::vector<double>& hypProbs, const cv::Mat& camMat, float inlierAlpha, float inlierBeta, float inlierThreshold, float maxReproErr) { int hypCount = sampledPoints.size(); // collect 2d-3D correspondences std::vector<std::vector<cv::Point2f>> imgPts(hypCount); std::vector<std::vector<cv::Point3f>> objPts(hypCount); #pragma omp parallel for for(int h = 0; h < hypCount; h++) { if(hypProbs[h] < PROB_THRESH) continue; int expert = hypAssignment[h]; for(unsigned i = 0; i < sampledPoints[h].size(); i++) { int x = sampledPoints[h][i].x; int y = sampledPoints[h][i].y; imgPts[h].push_back(sampling(y, x)); objPts[h].push_back(cv::Point3f( sceneCoordinates[expert][0][y][x], sceneCoordinates[expert][1][y][x], sceneCoordinates[expert][2][y][x])); } } // derivatives of the soft inlier scores std::vector<cv::Mat_<double>> dReproErrs(reproErrs.size()); #pragma omp parallel for for(int h = 0; h < hypCount; h++) { if(hypProbs[h] < PROB_THRESH) continue; dReproErrs[h] = cv::Mat_<double>::zeros(reproErrs[h].size()); for(int x = 0; x < sampling.cols; x++) for(int y = 0; y < sampling.rows; y++) { double softThreshold = inlierBeta * (reproErrs[h](y, x) - inlierThreshold); softThreshold = 1 / (1+std::exp(-softThreshold)); dReproErrs[h](y, x) = -softThreshold * (1 - softThreshold) * inlierBeta * scoreOutputGradients[h]; } dReproErrs[h] *= inlierAlpha / dReproErrs[h].cols / dReproErrs[h].rows; } jacobeansScore.resize(hypCount); // derivative of the loss wrt the score #pragma omp parallel for for(int h = 0; h < hypCount; h++) { cv::Mat_<double> jacobean = cv::Mat_<double>::zeros(1, sampling.cols * sampling.rows * 3); jacobeansScore[h] = jacobean; if(hypProbs[h] < PROB_THRESH) continue; int expert = hypAssignment[h]; // accumulate derivate of score wrt the object coordinates that are used to calculate the pose cv::Mat_<double> supportPointGradients = cv::Mat_<double>::zeros(1, 12); cv::Mat_<double> dHdO = dPNP(imgPts[h], objPts[h], camMat); // 6x12 if(esac::getMax(dHdO) > 10) dHdO = 0; // clamping for stability cv::Mat rot; cv::Rodrigues(hyps[h].first, rot); for(int x = 0; x < sampling.cols; x++) for(int y = 0; y < sampling.rows; y++) { int ptIdx = x * dReproErrs[h].rows + y; cv::Point2f pt(sampling(y, x).x, sampling(y, x).y); cv::Point3f obj = cv::Point3f( sceneCoordinates[expert][0][y][x], sceneCoordinates[expert][1][y][x], sceneCoordinates[expert][2][y][x]); // account for the direct influence of all object coordinates in the score cv::Mat_<double> dPdO = dProjectdObj(pt, obj, rot, hyps[h].second, camMat, maxReproErr); dPdO *= dReproErrs[h](y, x); dPdO.copyTo(jacobean.colRange(x * dReproErrs[h].rows * 3 + y * 3, x * dReproErrs[h].rows * 3 + y * 3 + 3)); // account for the indirect influence of the object coorindates that are used to calculate the pose cv::Mat_<double> dPdH = jacobeansHyps[h].row(ptIdx); supportPointGradients += dReproErrs[h](y, x) * dPdH * dHdO; } // add the accumulated derivatives for the object coordinates that are used to calculate the pose for(unsigned i = 0; i < sampledPoints[h].size(); i++) { unsigned x = sampledPoints[h][i].x; unsigned y = sampledPoints[h][i].y; jacobean.colRange(x * dReproErrs[h].rows * 3 + y * 3, x * dReproErrs[h].rows * 3 + y * 3 + 3) += supportPointGradients.colRange(i * 3, i * 3 + 3); } } } /** * @brief Calculates the Jacobean matrix of the function that maps n estimated object coordinates to a soft max score, ie. the function has the form n x 3 -> 1. Returns one Jacobean matrix per hypothesis. * * This is the Soft maxed version of dScore (see above). * * @param sceneCoordinates Scene coordinate prediction of each expert (Ex3xHxW). * @param hypAssignment 1D trensor specifying the responsible expert for each hypothesis. * @param sampling Contains original image coordinate for each scene coordinate predicted. * @param sampledPoints Corresponding minimal set for each hypotheses as scene coordinate indices. * @param losses Loss value for each hypothesis. * @param hypProbs Selection probabilities over all hypotheses. * @paran initHyps List of unrefined hypotheses. * @paran initReproErrs List of reprojection error images of unrefined hypotheses. * @param jacobeanHyps List of jacobean matrices with derivatives of the 6D pose wrt. the reprojection errors. * @param camMat Camera calibration matrix. * @param inlierAlpha Alpha parameter for soft inlier counting. * @param inlierBeta Beta parameter for soft inlier counting. * @param inlierThreshold RANSAC inlier threshold. * @param maxReproj Reprojection errors are clamped to this maximum value. * @return List of Jacobean matrices. One 1 x 3n matrix per pose hypothesis. */ std::vector<cv::Mat_<double>> dSMScore( esac::coord_t& sceneCoordinates, esac::hyp_assign_t& hypAssignment, const cv::Mat_<cv::Point2i>& sampling, const std::vector<std::vector<cv::Point2i>>& sampledPoints, const std::vector<double>& losses, const std::vector<double>& hypProbs, const std::vector<esac::pose_t>& initHyps, const std::vector<cv::Mat_<float>>& initReproErrs, const std::vector<cv::Mat_<double>>& jacobeansHyps, const cv::Mat& camMat, float inlierAlpha, float inlierBeta, float inlierThreshold, float maxReproErr) { // assemble the gradients wrt the scores, ie the gradients of soft max function std::vector<double> scoreOutputGradients(sampledPoints.size()); #pragma omp parallel for for(unsigned i = 0; i < sampledPoints.size(); i++) { if(hypProbs[i] < PROB_THRESH) continue; scoreOutputGradients[i] = hypProbs[i] * losses[i]; for(unsigned j = 0; j < sampledPoints.size(); j++) scoreOutputGradients[i] -= hypProbs[i] * hypProbs[j] * losses[j]; } // calculate gradients of the score function std::vector<cv::Mat_<double>> jacobeansScore; dScore( sceneCoordinates, hypAssignment, sampling, sampledPoints, jacobeansScore, scoreOutputGradients, initHyps, initReproErrs, jacobeansHyps, hypProbs, camMat, inlierAlpha, inlierBeta, inlierThreshold, maxReproErr); // data conversion #pragma omp parallel for for(unsigned i = 0; i < jacobeansScore.size(); i++) { // reorder to points row first into rows cv::Mat_<double> reformat = cv::Mat_<double>::zeros(sampling.cols * sampling.rows, 3); if(hypProbs[i] >= PROB_THRESH) { for(int x = 0; x < sampling.cols; x++) for(int y = 0; y < sampling.rows; y++) { cv::Mat_<double> patchGrad = jacobeansScore[i].colRange( x * sampling.rows * 3 + y * 3, x * sampling.rows * 3 + y * 3 + 3); patchGrad.copyTo(reformat.row(y * sampling.cols + x)); } } jacobeansScore[i] = reformat; } return jacobeansScore; } }
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-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % 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 "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache-private.h" #include "MagickCore/channel.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/list.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/shear.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + 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 double x_shear,const double x_shear, % const double width,const double 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 double x_shear,const double y_shear, const double width,const double height, const MagickBooleanType rotate,ExceptionInfo *exception) { Image *crop_image; PointInfo extent[4], min, max; RectangleInfo geometry, page; register ssize_t i; /* Calculate the rotated image size. */ extent[0].x=(double) (-width/2.0); extent[0].y=(double) (-height/2.0); extent[1].x=(double) width/2.0; extent[1].y=(double) (-height/2.0); extent[2].x=(double) (-width/2.0); extent[2].y=(double) height/2.0; extent[3].x=(double) width/2.0; extent[3].y=(double) height/2.0; for (i=0; i < 4; i++) { extent[i].x+=x_shear*extent[i].y; extent[i].y+=y_shear*extent[i].x; if (rotate != MagickFalse) extent[i].x+=x_shear*extent[i].y; extent[i].x+=(double) (*image)->columns/2.0; extent[i].y+=(double) (*image)->rows/2.0; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } geometry.x=(ssize_t) ceil(min.x-0.5); geometry.y=(ssize_t) ceil(min.y-0.5); geometry.width=(size_t) floor(max.x-min.x+0.5); geometry.height=(size_t) floor(max.y-min.y+0.5); page=(*image)->page; (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page); crop_image=CropImage(*image,&geometry,exception); if (crop_image == (Image *) NULL) return(MagickFalse); crop_image->page=page; *image=DestroyImage(*image); *image=crop_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s k e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeskewImage() removes skew from the image. Skew is an artifact that % occurs in scanned images because of the camera being misaligned, % imperfections in the scanning or surface, or simply because the paper was % not placed completely flat when scanned. % % The result will be auto-croped if the artifact "deskew:auto-crop" is % defined, while the amount the image is to be deskewed, in degrees is also % saved as the artifact "deskew:angle". % % 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_matrixs, MatrixInfo *destination_matrixs,const ssize_t sign,size_t *projection) { MatrixInfo *swap; register MatrixInfo *p, *q; register ssize_t x; size_t step; p=source_matrixs; q=destination_matrixs; for (step=1; step < GetMatrixColumns(p); step*=2) { for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step) { register ssize_t i; ssize_t y; unsigned short element, neighbor; for (i=0; i < (ssize_t) step; i++) { for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse) continue; } for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } for ( ; y < (ssize_t) GetMatrixRows(p); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } } } swap=p; p=q; q=swap; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,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_matrixs, *source_matrixs; MagickBooleanType status; size_t count, width; ssize_t j, y; unsigned char c; unsigned short bits[256]; for (width=1; width < ((image->columns+7)/8); width<<=1) ; source_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); destination_matrixs=AcquireMatrixInfo(width,image->rows, sizeof(unsigned short),exception); if ((source_matrixs == (MatrixInfo *) NULL) || (destination_matrixs == (MatrixInfo *) NULL)) { if (destination_matrixs != (MatrixInfo *) NULL) destination_matrixs=DestroyMatrixInfo(destination_matrixs); if (source_matrixs != (MatrixInfo *) NULL) source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } if (NullMatrix(source_matrixs) == MagickFalse) { destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } for (j=0; j < 256; j++) { c=(unsigned char) j; for (count=0; c != 0; c>>=1) count+=c & 0x01; bits[j]=(unsigned short) count; } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *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 Quantum *) 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(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,-1,projection); (void) NullMatrix(source_matrixs); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *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 Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,1,projection); image_view=DestroyCacheView(image_view); destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickTrue); } static void GetImageBackgroundColor(Image *image,const ssize_t offset, ExceptionInfo *exception) { CacheView *image_view; PixelInfo background; double count; ssize_t y; /* Compute average background color. */ if (offset <= 0) return; GetPixelInfo(image,&background); count=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *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 Quantum *) 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(image,p); background.green+=QuantumScale*GetPixelGreen(image,p); background.blue+=QuantumScale*GetPixelBlue(image,p); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) background.alpha+=QuantumScale*GetPixelAlpha(image,p); count++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); image->background_color.red=(double) ClampToQuantum(QuantumRange* background.red/count); image->background_color.green=(double) ClampToQuantum(QuantumRange* background.green/count); image->background_color.blue=(double) ClampToQuantum(QuantumRange* background.blue/count); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->background_color.alpha=(double) ClampToQuantum(QuantumRange* background.alpha/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[MagickPathExtent]; (void) FormatLocaleString(angle,MagickPathExtent,"%.20g",degrees); (void) SetImageArtifact(clone_image,"deskew:angle",angle); } (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod, exception); 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 (IsStringTrue(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; /* Initialize rotated image attributes. */ assert(image != (Image *) NULL); page=image->page; rotations%=4; if (rotations == 0) return(CloneImage(image,0,0,MagickTrue,exception)); if ((rotations == 1) || (rotations == 3)) rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); else rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (rotate_image == (Image *) NULL) return((Image *) NULL); /* Integral rotate the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); rotate_view=AcquireAuthenticCacheView(rotate_image,exception); switch (rotations) { case 1: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 90 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,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; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *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 Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *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 == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; if (GetPixelWriteMask(image,tile_pixels) == 0) { tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } case 2: { register ssize_t y; /* Rotate 180 degrees. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *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 Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(rotate_image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; q-=GetPixelChannels(rotate_image); if (GetPixelWriteMask(image,p) == 0) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,p[i],q); } p+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } case 3: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 270 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,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; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *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 Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *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 == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((width-1)-y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; if (GetPixelWriteMask(image,tile_pixels) == 0) { tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif 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 double 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 double 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 double 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; PixelInfo background; ssize_t y; /* X shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; background=image->background_color; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,height,1) #endif for (y=0; y < (ssize_t) height; y++) { PixelInfo pixel, source, destination; double area, displacement; register Quantum *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 == (Quantum *) NULL) { status=MagickFalse; continue; } p+=x_offset*GetPixelChannels(image); displacement=degrees*(double) (y-height/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=RIGHT; else { displacement*=(-1.0); direction=LEFT; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case LEFT: { /* Transfer pixels left-to-right. */ if (step > x_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { if ((x_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case RIGHT: { /* Transfer pixels right-to-left. */ p+=width*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (x_offset+width+step-i) > image->columns) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_XShearImage) #endif proceed=SetImageProgress(image,XShearImageTag,progress++,height); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Y S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % YShearImage shears the image in the Y direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a % horizontal X-axis. Y shears will increase the height of an image creating % 'empty' triangles on the top and bottom of the source image. % % The format of the YShearImage method is: % % MagickBooleanType YShearImage(Image *image,const double 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 double 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 double 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; PixelInfo background; ssize_t x; /* Y Shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; background=image->background_color; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,width,1) #endif for (x=0; x < (ssize_t) width; x++) { ssize_t step; double area, displacement; PixelInfo pixel, source, destination; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=y_offset*GetPixelChannels(image); displacement=degrees*(double) (x-width/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=DOWN; else { displacement*=(-1.0); direction=UP; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case UP: { /* Transfer pixels top-to-bottom. */ if (step > y_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { if ((y_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case DOWN: { /* Transfer pixels bottom-to-top. */ p+=height*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (y_offset+height+step-i) > image->rows) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_YShearImage) #endif proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearImage() creates a new image that is a shear_image copy of an existing % one. Shearing slides one edge of an image along the X or Y axis, creating % a parallelogram. An X direction shear slides an edge along the X axis, % while a Y direction shear slides an edge along the Y axis. The amount of % the shear is controlled by a shear angle. For X direction shears, x_shear % is measured relative to the Y axis, and similarly, for Y direction shears % y_shear is measured relative to the X axis. Empty triangles left over from % shearing the image are filled with the background color defined by member % 'background_color' of the image.. ShearImage() allocates the memory % necessary for the new Image structure and returns a pointer to the new image. % % ShearImage() is based on the paper "A Fast Algorithm for General Raster % Rotatation" by Alan W. Paeth. % % The format of the ShearImage method is: % % Image *ShearImage(const Image *image,const double x_shear, % const double y_shear,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear: Specifies the number of degrees to shear the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearImage(const Image *image,const double x_shear, const double y_shear,ExceptionInfo *exception) { Image *integral_image, *shear_image; MagickBooleanType status; PointInfo shear; RectangleInfo border_info, bounds; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); /* Initialize shear angle. */ integral_image=CloneImage(image,0,0,MagickTrue,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0)))); shear.y=tan(DegreesToRadians(fmod(y_shear,360.0))); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute image size. */ bounds.width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5); bounds.x=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)- image->columns)/2.0-0.5); bounds.y=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*bounds.width)- image->rows)/2.0-0.5); /* Surround image with border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; shear_image=BorderImage(integral_image,&border_info,image->compose,exception); integral_image=DestroyImage(integral_image); if (shear_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Shear the image. */ if (shear_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception); 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->alpha_trait=image->alpha_trait; shear_image->compose=image->compose; shear_image->page.width=0; shear_image->page.height=0; if (status == MagickFalse) shear_image=DestroyImage(shear_image); return(shear_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearRotateImage() creates a new image that is a rotated copy of an existing % one. Positive angles rotate counter-clockwise (right-hand rule), while % negative angles rotate clockwise. Rotated images are usually larger than % the originals and have 'empty' triangular corners. X axis. Empty % triangles left over from shearing the image are filled with the background % color defined by member 'background_color' of the image. ShearRotateImage % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % ShearRotateImage() is based on the paper "A Fast Algorithm for General % Raster Rotatation" by Alan W. Paeth. ShearRotateImage is adapted from a % similar method based on the Paeth paper written by Michael Halle of the % Spatial Imaging Group, MIT Media Lab. % % The format of the ShearRotateImage method is: % % Image *ShearRotateImage(const Image *image,const double degrees, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: Specifies the number of degrees to rotate the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearRotateImage(const Image *image,const double degrees, ExceptionInfo *exception) { Image *integral_image, *rotate_image; MagickBooleanType status; MagickRealType angle; PointInfo shear; RectangleInfo border_info, bounds; size_t height, rotations, shear_width, width; /* Adjust rotation angle. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); angle=degrees; while (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,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute maximum bounds for 3 shear operations. */ width=integral_image->columns; height=integral_image->rows; bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5); bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5); shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+ bounds.width+0.5); bounds.x=(ssize_t) floor((double) ((shear_width > bounds.width) ? width : bounds.width-shear_width+2)/2.0+0.5); bounds.y=(ssize_t) floor(((double) bounds.height-height+2)/2.0+0.5); /* Surround image with a border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; rotate_image=BorderImage(integral_image,&border_info,image->compose, 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->alpha_trait=image->alpha_trait; 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); }
DRB036-truedepscalar-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. */ /* Loop carried true dep between tmp =.. and ..= tmp. Data race pair: tmp@66:12 vs. tmp@67:5 */ #include <stdlib.h> int main(int argc, char* argv[]) { int i; int tmp; tmp = 10; int len=100; if (argc>1) len = atoi(argv[1]); int a[len]; #pragma omp parallel for schedule(dynamic) for (i=0;i<len;i++) { a[i] = tmp; tmp =a[i]+i; } return 0; }
GB_unaryop__abs_uint64_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint64_int16 // op(A') function: GB_tran__abs_uint64_int16 // C type: uint64_t // A type: int16_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT64 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint64_int16 ( uint64_t *Cx, // Cx and Ax may be aliased int16_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint64_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mat_default.c
// mat_default.c - default matrix implementation #include <cphis.h> #include <linalg.h> #include <stdlib.h> #include <string.h> CphisError CphisMatCreate_default( CphisMat *mat, CphisIndex numElements, int numLocalDOFRange ) { (*mat)->mat = malloc(sizeof(struct _CphisMat_default)); if (!(*mat)->mat) { CPHISCHECK(CPHIS_FAILED_ALLOC); } struct _CphisMat_default *matInternal = (*mat)->mat; // Create buffers. const CphisIndex numRows = numElements*numLocalDOFRange; matInternal->bufferCapacities = malloc(numRows*sizeof(CphisIndex)); matInternal->bufferSizes = malloc(numRows*sizeof(CphisIndex)); matInternal->colBuffers = malloc(numRows*sizeof(CphisIndex*)); matInternal->valBuffers = malloc(numRows*sizeof(CphisScalar*)); if ( !matInternal->bufferCapacities || !matInternal->bufferSizes || !matInternal->colBuffers || !matInternal->valBuffers ) { free(matInternal->bufferCapacities); free(matInternal->bufferSizes); free(matInternal->colBuffers); free(matInternal->valBuffers); free(matInternal); CPHISCHECK(CPHIS_FAILED_ALLOC); } for (CphisIndex i = 0; i < numRows; i++) { matInternal->bufferCapacities[i] = 0; matInternal->bufferSizes[i] = 0; matInternal->colBuffers[i] = NULL; matInternal->valBuffers[i] = NULL; } // Set the CRS pointers to NULL so it is always safe to call free(). matInternal->rows = NULL; matInternal->cols = NULL; matInternal->vals = NULL; return CPHIS_SUCCESS; } CphisError CphisMatDestroy_default(CphisMat mat) { struct _CphisMat_default *matInternal = mat->mat; // Clean up buffers if necessary. const CphisIndex numRows = mat->numElements*mat->numLocalDOFRange; if (matInternal->bufferSizes) { for (CphisIndex i = 0; i < numRows; i++) { free(matInternal->colBuffers[i]); free(matInternal->valBuffers[i]); } free(matInternal->bufferCapacities); free(matInternal->bufferSizes); free(matInternal->colBuffers); free(matInternal->valBuffers); } // Clean up CRS data if necessary. if (matInternal->rows) { free(matInternal->rows); free(matInternal->cols); free(matInternal->vals); } return CPHIS_SUCCESS; } CphisError CphisMatVec_default(const CphisMat A, const CphisVec x, CphisVec y) { CPHISCHECKMATVECCOMPAT(A, x, y); const struct _CphisMat_default *matInternal = A->mat; const CphisScalar *xData = x->vec; CphisScalar *yData = y->vec; const CphisIndex numRows = A->numElements*A->numLocalDOFRange; #pragma omp parallel for for (CphisIndex i = 0; i < numRows; i++) { CphisScalar result = 0.0; for ( size_t j = matInternal->rows[i]; j < matInternal->rows[i + 1]; j++ ) { result += matInternal->vals[j]*xData[matInternal->cols[j]]; } yData[i] = result; } return CPHIS_SUCCESS; } CphisError CphisMatGetData_default( const CphisMat mat, CphisIndex row, const CphisIndex **cols, const CphisScalar **vals, CphisIndex *numEntries ) { const struct _CphisMat_default *matInternal = mat->mat; const size_t j = matInternal->rows[row]; *cols = &(matInternal->cols[j]); *vals = &(matInternal->vals[j]); *numEntries = matInternal->rows[row + 1] - j; return CPHIS_SUCCESS; } CphisError CphisMatSet_default( CphisMat mat, CphisIndex i, CphisIndex j, CphisScalar aij ) { struct _CphisMat_default *matInternal = mat->mat; // Create buffer if it does not exist. if (matInternal->bufferCapacities[i] == 0) { matInternal->colBuffers[i] = malloc(sizeof(CphisIndex)); matInternal->valBuffers[i] = malloc(sizeof(CphisScalar)); if (!matInternal->colBuffers[i] || !matInternal->valBuffers[i]) { free(matInternal->colBuffers[i]); free(matInternal->valBuffers[i]); CPHISCHECK(CPHIS_FAILED_ALLOC); } matInternal->bufferCapacities[i] = 1; } // Increase buffer capacity if necessary. const CphisIndex size = matInternal->bufferSizes[i]; const CphisIndex capacity = matInternal->bufferCapacities[i]; if (size == capacity) { void *ptr; // Increase column buffer. ptr = realloc(matInternal->colBuffers[i], 2*capacity*sizeof(CphisIndex)); if (!ptr) { CPHISCHECK(CPHIS_FAILED_ALLOC); } matInternal->colBuffers[i] = ptr; // Increase value buffer. ptr = realloc(matInternal->valBuffers[i], 2*capacity*sizeof(CphisScalar)); if (!ptr) { CPHISCHECK(CPHIS_FAILED_ALLOC); } matInternal->valBuffers[i] = ptr; matInternal->bufferCapacities[i] *= 2; } // Add matrix entry. matInternal->colBuffers[i][size] = j; matInternal->valBuffers[i][size] = aij; matInternal->bufferSizes[i]++; return CPHIS_SUCCESS; } CphisError CphisMatFinalize_default(CphisMat mat) { struct _CphisMat_default *matInternal = mat->mat; // We begin by counting the matrix entries. size_t nnz = 0; const CphisIndex numRows = mat->numElements*mat->numLocalDOFRange; #pragma omp parallel for reduction(+:nnz) for (CphisIndex i = 0; i < numRows; i++) { nnz += matInternal->bufferSizes[i]; } // Allocate memory for CRS data. matInternal->rows = malloc((numRows + 1)*sizeof(size_t)); matInternal->cols = malloc(nnz*sizeof(CphisIndex)); matInternal->vals = malloc(nnz*sizeof(CphisScalar)); if ( !matInternal->rows || !matInternal->cols || !matInternal->vals ) { free(matInternal->rows); free(matInternal->cols); free(matInternal->vals); } // Populate row pointers. matInternal->rows[0] = 0; for (CphisIndex i = 1; i < numRows; i++) { matInternal->rows[i] = matInternal->rows[i - 1] + matInternal->bufferSizes[i - 1]; } matInternal->rows[numRows] = nnz; // Populate CRS arrays and clean up buffers. #pragma omp parallel for for (CphisIndex i = 0; i < numRows; i++) { const size_t offset = matInternal->rows[i]; memcpy( &(matInternal->cols[offset]), matInternal->colBuffers[i], matInternal->bufferSizes[i]*sizeof(CphisIndex) ); memcpy( &(matInternal->vals[offset]), matInternal->valBuffers[i], matInternal->bufferSizes[i]*sizeof(CphisScalar) ); free(matInternal->colBuffers[i]); free(matInternal->valBuffers[i]); } free(matInternal->bufferCapacities); free(matInternal->bufferSizes); free(matInternal->colBuffers); free(matInternal->valBuffers); // Prevent double free. matInternal->bufferCapacities = NULL; matInternal->bufferSizes = NULL; matInternal->colBuffers = NULL; matInternal->valBuffers = NULL; return CPHIS_SUCCESS; }
reduction-clause.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif main(int argc, char **argv) { int i, n=20, a[n],suma=0; if(argc < 2) { fprintf(stderr,"Falta iteraciones\n"); exit(-1); } n = atoi(argv[1]); if (n>20) { n=20; printf("n=%d",n); } for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for reduction(+:suma) for (i=0; i<n; i++) suma += a[i]; printf("Tras 'parallel' suma=%d\n",suma); }
convolution_7x7_pack1to4_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv7x7s2_pack1to4_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = 49; // im2col Mat bottom_im2col(size, maxk, inch, 1u, 1, opt.workspace_allocator); { const int gap = w * 2 - outw * 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); signed char* ptr = bottom_im2col.channel(p); for (int u = 0; u < 7; u++) { for (int v = 0; v < 7; v++) { const signed char* sptr = img.row<const signed char>(u) + v; for (int i = 0; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { ptr[0] = sptr[0]; ptr[1] = sptr[2]; ptr[2] = sptr[4]; ptr[3] = sptr[6]; sptr += 8; ptr += 4; } for (; j + 1 < outw; j += 2) { ptr[0] = sptr[0]; ptr[1] = sptr[2]; sptr += 4; ptr += 2; } for (; j < outw; j++) { ptr[0] = sptr[0]; sptr += 2; ptr += 1; } sptr += gap; } } } } } im2col_sgemm_pack1to4_int8_neon(bottom_im2col, top_blob, kernel, opt); }
fracstep_GLS_strategy.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Author Julio Marti. // #if !defined(KRATOS_GLS_STRATEGY) #define KRATOS_GLS_STRATEGY /* System includes */ /* External includes */ #include "boost/smart_ptr.hpp" /* Project includes */ #include "utilities/geometry_utilities.h" #include "pfem_2_application.h" #include "includes/define.h" #include "includes/model_part.h" #include "includes/deprecated_variables.h" #include "includes/cfd_variables.h" #include "utilities/openmp_utils.h" #include "processes/process.h" #include "solving_strategies/schemes/scheme.h" #include "solving_strategies/strategies/solving_strategy.h" #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme.h" #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme_slip.h" #include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver.h" #include "solving_strategies/builder_and_solvers/residualbased_elimination_builder_and_solver_componentwise.h" #include "solving_strategies/strategies/residualbased_linear_strategy.h" //#include "custom_utilities/solver_settings.h" #ifdef _OPENMP #include "omp.h" #endif #define QCOMP namespace Kratos { /**@name Kratos Globals */ /*@{ */ /*@} */ /**@name Type Definitions */ /*@{ */ /*@} */ /**@name Enum's */ /*@{ */ /*@} */ /**@name Functions */ /*@{ */ /*@} */ /**@name Kratos Classes */ /*@{ */ /// Short class definition. /** Detail class definition. \URL[Example of use html]{ extended_documentation/no_ex_of_use.html} \URL[Example of use pdf]{ extended_documentation/no_ex_of_use.pdf} \URL[Example of use doc]{ extended_documentation/no_ex_of_use.doc} \URL[Example of use ps]{ extended_documentation/no_ex_of_use.ps} \URL[Extended documentation html]{ extended_documentation/no_ext_doc.html} \URL[Extended documentation pdf]{ extended_documentation/no_ext_doc.pdf} \URL[Extended documentation doc]{ extended_documentation/no_ext_doc.doc} \URL[Extended documentation ps]{ extended_documentation/no_ext_doc.ps} */ template<class TSparseSpace, class TDenseSpace, class TLinearSolver > class FracStepStrategy : public SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> { public: /**@name Type Definitions */ /*@{ */ /** Counted pointer of ClassName */ KRATOS_CLASS_POINTER_DEFINITION( FracStepStrategy ); typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TDataType TDataType; //typedef typename BaseType::DofSetType DofSetType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef OpenMPUtils::PartitionVector PartitionVector; /*@} */ /**@name Life Cycle */ /*@{ */ /** * Constructor of the FracStepStrategy. Implements the solutions strategy for a Navier Stokes solver * using the fractional step approach. Prepared for both openmp parallelism and mpi parallelism. The function * also calls internally the "Check" function to verify that the input is complete * @param model_part - contains Nodes, elements, etc. * @param solver_config - auxiliary file to ease the configuration. Prescribes the linear solvers and builiding * strategies to be used in defining the current composite solver. * @see FractionalStepConfiguration for OpenMP setting or * @see TrilinosFractionalStepConfiguration (in the Trilinos application) for the MPI version * @param ReformDofAtEachIteration - if set to true the graph of the matrix is recomputed at each iteration * @param velocity_toll - tolerance used in the velocity convergence check * @param pressure_toll - pressure tolerance in finalizing the predictor corrector strategy * @param MaxVelocityIterations - maximum number of iterations of the velocity solver * @param MaxPressureIterations - max number of iteration for the predictor corrector strategy * @param time_order - 1=BDF1 , 2=BDF2 * @param domain_size 2=2D, 3=3D * @param predictor_corrector - true->for predictor corrector, false->standard Fractional Step (default = false) */ FracStepStrategy( ModelPart& model_part, typename TLinearSolver::Pointer pNewVelocityLinearSolver,typename TLinearSolver::Pointer pNewPressureLinearSolver, bool ReformDofAtEachIteration = true, double velocity_toll = 0.01, double pressure_toll = 0.01, int MaxVelocityIterations = 3, int MaxPressureIterations = 1, unsigned int time_order = 2, unsigned int domain_size = 2, bool predictor_corrector = false ) : SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>(model_part, false)//, msolver_config(solver_config) { KRATOS_TRY this->mvelocity_toll = velocity_toll; this->mpressure_toll = pressure_toll; this->mMaxVelIterations = MaxVelocityIterations; this->mMaxPressIterations = MaxPressureIterations; this->mtime_order = time_order; this->mprediction_order = time_order; this->mdomain_size = domain_size; this->mpredictor_corrector = predictor_corrector; this->mReformDofAtEachIteration = ReformDofAtEachIteration; this->proj_is_initialized = false; this->mecho_level = 1; bool CalculateReactions = false; bool CalculateNormDxFlag = true; bool ReformDofAtEachIteration = false; //computation of the fractional vel velocity (first step) //3 dimensional case //typedef typename Kratos::VariableComponent<Kratos::VectorComponentAdaptor<Kratos::array_1d<double, 3 > > > VarComponent; typedef typename BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>::Pointer BuilderSolverTypePointer; typedef SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; //initializing fractional velocity solution step typedef Scheme< TSparseSpace, TDenseSpace > SchemeType; typename SchemeType::Pointer pscheme = typename SchemeType::Pointer(new ResidualBasedIncrementalUpdateStaticScheme< TSparseSpace, TDenseSpace > ()); BuilderSolverTypePointer vel_build = BuilderSolverTypePointer(new ResidualBasedEliminationBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver > (pNewVelocityLinearSolver)); this->mpfracvel_strategy = typename BaseType::Pointer(new ResidualBasedLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver > (model_part, pscheme, pNewVelocityLinearSolver, vel_build, CalculateReactions, ReformDofAtEachIteration, CalculateNormDxFlag)); this->mpfracvel_strategy->SetEchoLevel(1); BuilderSolverTypePointer pressure_build = BuilderSolverTypePointer(new ResidualBasedEliminationBuilderAndSolverComponentwise<TSparseSpace, TDenseSpace, TLinearSolver, Variable<double> >(pNewPressureLinearSolver, PRESSURE)); this->mppressurestep = typename BaseType::Pointer(new ResidualBasedLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver > (model_part, pscheme,pNewPressureLinearSolver, pressure_build, CalculateReactions, ReformDofAtEachIteration, CalculateNormDxFlag)); this->mppressurestep->SetEchoLevel(2); this->m_step = 1; mHasSlipProcess = false; KRATOS_CATCH("") } /** Destructor. */ virtual ~FracStepStrategy() { } /** Destructor. */ double Solve() override { KRATOS_TRY Timer time; Timer::Start("Solve_strategy"); #if defined(QCOMP) double Dp_norm; Dp_norm = IterativeSolve(); #else //multifluids AssignInitialStepValues(); double Dp_norm = 1.00; //int iteration = 0; //int MaxPressureIterations = this->mMaxPressIterations; Dp_norm = IterativeSolve(); #endif //this->Clear(); this->m_step += 1; return Dp_norm; KRATOS_CATCH("") } double SolvePressure() { KRATOS_TRY //ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); this->SolveStep7(); //pold=pn+1 double Dp_norm = this->SolveStep2(); return Dp_norm; KRATOS_CATCH("") } double IterativeSolve() { KRATOS_TRY Timer time; Timer::Start("Solve_ambos"); double Dp_norm = 1.00; ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); //KRATOS_THROW_ERROR(std::logic_error, "method not implemented" , ""); rCurrentProcessInfo[VISCOSITY] = 1.0; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { i->FastGetSolutionStepValue(VELOCITY_X,1) = i->FastGetSolutionStepValue(VELOCITY_X); i->FastGetSolutionStepValue(VELOCITY_Y,1) = i->FastGetSolutionStepValue(VELOCITY_Y); i->FastGetSolutionStepValue(VELOCITY_Z,1) = i->FastGetSolutionStepValue(VELOCITY_Z); } #if defined(QCOMP) this->SolveStep1(this->mvelocity_toll, this->mMaxVelIterations); #else this->SolveStep3(); #endif //double p_norm=0.0; #if defined(QCOMP) //polimero this->SolveStepaux(); //int MaxPressureIterations = this->mMaxPressIterations; //int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); //double p_norm = SavePressureIteration(); Dp_norm = 1.0; //Timer::Stop("Solve_ambos"); //KRATOS_WATCH(time) #else int iteration = 0; while ( iteration++ < 3) { Dp_norm = SolvePressure(); double p_norm = SavePressureIteration(); if (fabs(p_norm) > 1e-10){ Dp_norm /= p_norm; } else Dp_norm = 1.0; this->SolveStep4(); } #endif this->Clear(); return Dp_norm; KRATOS_CATCH("") } /** * copies PRESSURE->PRESSURE_OLD_IT * @return the norm of the pressure vector */ double SavePressureIteration() { KRATOS_TRY double local_p_norm = 0.0; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin(); i != BaseType::GetModelPart().NodesEnd(); ++i) { //setting the old value of the pressure to the current one const double& p = (i)->FastGetSolutionStepValue(PRESSURE); local_p_norm += p*p; } double p_norm = local_p_norm; //TODO: prepare for parallelization p_norm = sqrt(p_norm); return p_norm; KRATOS_CATCH("") } void AssignInitialStepValues() { KRATOS_TRY ModelPart& model_part=BaseType::GetModelPart(); const double dt = model_part.GetProcessInfo()[DELTA_TIME]; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { (i)->FastGetSolutionStepValue(PRESSURE_OLD_IT) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE) = 0.0; (i)->FastGetSolutionStepValue(PRESSURE,1) = 0.0; } KRATOS_CATCH(""); } /** * this function performs the iterative solution of the non-linear velocity problem in the first step * of the fractional step procedure * @param velocity_toll - tolerance used in the velocity convergence check * @param MaxIterations - max number of iterations */ void SolveStep1(double velocity_toll, int MaxIterations) { KRATOS_TRY; Timer time; Timer::Start("SolveStep1"); int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); double normDx = 0.0; bool is_converged = false; int iteration = 0; //double iteration = 1; //ModelPart& model_part=BaseType::GetModelPart(); while (is_converged == false && iteration++<3) { //perform one iteration over the fractional step velocity normDx = FractionalVelocityIteration(); is_converged = ConvergenceCheck(normDx, velocity_toll); } if (is_converged == false) if (rank == 0) std::cout << "ATTENTION: convergence NOT achieved" << std::endl; KRATOS_CATCH(""); } double FractionalVelocityIteration() { KRATOS_TRY ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 1; double normDx = mpfracvel_strategy->Solve(); return normDx; KRATOS_CATCH(""); } void SolveStep4() { KRATOS_TRY; Timer time; Timer::Start("paso_4"); array_1d<double, 3 > zero = ZeroVector(3); //#ifdef _OPENMP // int number_of_threads = omp_get_max_threads(); //#else // int number_of_threads = 1; //#endif //ModelPart& model_part=BaseType::GetModelPart(); //double dt = model_part.GetProcessInfo()[DELTA_TIME]; //dt=0.005; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { array_1d<double, 3 > zero = ZeroVector(3); i->FastGetSolutionStepValue(FORCE)=ZeroVector(3); double & nodal_mass = (i)->FastGetSolutionStepValue(NODAL_MASS); nodal_mass = 0.0; } ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 6; for (ModelPart::ElementIterator i = BaseType::GetModelPart().ElementsBegin(); i != BaseType::GetModelPart().ElementsEnd(); ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin();i != BaseType::GetModelPart().NodesEnd(); ++i) { array_1d<double,3>& force_temp = i->FastGetSolutionStepValue(FORCE); double A = (i)->FastGetSolutionStepValue(NODAL_MASS); if(A<0.0000000000000001){ A=1.0; } double dt_Minv = 0.005 / A ; //dt_Minv=1.0; force_temp *= dt_Minv; //KRATOS_WATCH(force_temp); if(!i->IsFixed(VELOCITY_X)) //FRACT_VEL_X { i->FastGetSolutionStepValue(VELOCITY_X) += force_temp[0] ; } if(!i->IsFixed(VELOCITY_Y)) { i->FastGetSolutionStepValue(VELOCITY_Y) +=force_temp[1]; } if(!i->IsFixed(VELOCITY_Z)) { i->FastGetSolutionStepValue(VELOCITY_Z) +=force_temp[2] ; } if(i->IsFixed(VELOCITY_X)) { i->FastGetSolutionStepValue(VELOCITY_X)=0.0; //i->FastGetSolutionStepValue(VELOCITY_X,1); } if(i->IsFixed(VELOCITY_Y)) { i->FastGetSolutionStepValue(VELOCITY_Y)= 0.0; //i->FastGetSolutionStepValue(VELOCITY_Y,1) ; } if(i->IsFixed(VELOCITY_Z)) { i->FastGetSolutionStepValue(VELOCITY_Z)=0.0; //i->FastGetSolutionStepValue(VELOCITY_Z,1) ; } } KRATOS_CATCH(""); } void SolveStep7() { KRATOS_TRY; // ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); array_1d<double, 3 > zero = ZeroVector(3); //Vector& BDFcoeffs = rCurrentProcessInfo[BDF_COEFFICIENTS]; #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif //ModelPart& model_part=BaseType::GetModelPart(); //const double dt = model_part.GetProcessInfo()[DELTA_TIME]; vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); for (typename ModelPart::NodesContainerType::iterator it=it_begin; it!=it_end; ++it) { it->FastGetSolutionStepValue(PRESSURE_OLD_IT)=it->FastGetSolutionStepValue(PRESSURE); } } KRATOS_CATCH(""); } double SolveStep2() { KRATOS_TRY; Timer::Start("Presion"); BaseType::GetModelPart().GetProcessInfo()[FRACTIONAL_STEP] = 4; return mppressurestep->Solve(); Timer::Stop("Presion"); //KRATOS_WATCH(*time) //mppressurestep->Clear(); KRATOS_CATCH(""); } void SolveStep3() { KRATOS_TRY ModelPart& model_part=BaseType::GetModelPart(); const double dt = model_part.GetProcessInfo()[DELTA_TIME]; Timer time; Timer::Start("paso_3"); #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { double & nodal_mass = (i)->FastGetSolutionStepValue(NODAL_MASS); nodal_mass = 0.0; noalias(i->FastGetSolutionStepValue(FORCE)) = zero; //double & nodal_area = (i)->FastGetSolutionStepValue(NODAL_AREA); //nodal_area = 0.0; } } array_1d<double,3> zero = ZeroVector(3); ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 5; vector<unsigned int> elem_partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Elements().size(), elem_partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::ElementIterator it_begin = BaseType::GetModelPart().ElementsBegin() + elem_partition[k]; ModelPart::ElementIterator it_end = BaseType::GetModelPart().ElementsBegin() + elem_partition[k + 1]; for (ModelPart::ElementIterator i = it_begin; i != it_end; ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } } #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { array_1d<double,3>& force_temp = i->FastGetSolutionStepValue(FORCE); force_temp *=(1.0/ i->FastGetSolutionStepValue(NODAL_MASS)); //array_1d<double,3>& vel = i->FastGetSolutionStepValue(VELOCITY); i->FastGetSolutionStepValue(VELOCITY) = i->FastGetSolutionStepValue(VELOCITY,1) + dt * force_temp; } } KRATOS_CATCH(""); } void SolveStepaux() { KRATOS_TRY Timer time; Timer::Start("SolveStepaux"); //ModelPart& model_part=BaseType::GetModelPart(); //const double dt = model_part.GetProcessInfo()[DELTA_TIME]; #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif //number_of_threads = 1; vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { double & nodal_mass = (i)->FastGetSolutionStepValue(NODAL_MASS); nodal_mass = 0.0; i->FastGetSolutionStepValue(PRESSUREAUX)=0.0; i->FastGetSolutionStepValue(PRESSURE)=0.0; } } ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 7; vector<unsigned int> elem_partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Elements().size(), elem_partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::ElementIterator it_begin = BaseType::GetModelPart().ElementsBegin() + elem_partition[k]; ModelPart::ElementIterator it_end = BaseType::GetModelPart().ElementsBegin() + elem_partition[k + 1]; for (ModelPart::ElementIterator i = it_begin; i != it_end; ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } } #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { if(i->FastGetSolutionStepValue(NODAL_MASS)==0.0) { i->FastGetSolutionStepValue(PRESSURE)=0.0; } else { //if() i->FastGetSolutionStepValue(PRESSURE)=i->FastGetSolutionStepValue(PRESSUREAUX) * (1.0/ i->FastGetSolutionStepValue(NODAL_MASS)); } } } KRATOS_CATCH(""); } /** * implements the convergence check for the velocities * convergence is considered achieved when normDx/norm(v) is less than tol * @param normDx norm of the VELOCITY correction * @param toll tolerance accepted * @return true if converged */ bool ConvergenceCheck(const double& normDx, double tol) { KRATOS_TRY; double norm_v = 0.00; for (ModelPart::NodeIterator i = BaseType::GetModelPart().NodesBegin(); i != BaseType::GetModelPart().NodesEnd(); ++i) { const array_1d<double, 3 > & v = (i)->FastGetSolutionStepValue(VELOCITY); norm_v += v[0] * v[0]; norm_v += v[1] * v[1]; norm_v += v[2] * v[2]; } //BaseType::GetModelPart().GetCommunicator().SumAll(norm_v); double norm_v1 = sqrt(norm_v); if (norm_v1 == 0.0) norm_v1 = 1.00; double ratio = normDx / norm_v1; int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); if (rank == 0) std::cout << "velocity ratio = " << ratio << std::endl; if (ratio < tol) { if (rank == 0) std::cout << "convergence achieved" << std::endl; return true; } return false; KRATOS_CATCH(""); } void Compute() { KRATOS_TRY #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif array_1d<double,3> aux; array_1d<double,3> aux1; ModelPart& model_part=BaseType::GetModelPart(); const double dt = model_part.GetProcessInfo()[DELTA_TIME]; vector<unsigned int> partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Nodes().size(), partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); //first of all set to zero the nodal variables to be updated nodally for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { noalias(i->FastGetSolutionStepValue(FORCE)) = zero; (i)->FastGetSolutionStepValue(NODAL_MASS)=0.0; } } ProcessInfo& rCurrentProcessInfo = BaseType::GetModelPart().GetProcessInfo(); rCurrentProcessInfo[FRACTIONAL_STEP] = 6; vector<unsigned int> elem_partition; CreatePartition(number_of_threads, BaseType::GetModelPart().Elements().size(), elem_partition); #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::ElementIterator it_begin = BaseType::GetModelPart().ElementsBegin() + elem_partition[k]; ModelPart::ElementIterator it_end = BaseType::GetModelPart().ElementsBegin() + elem_partition[k + 1]; for (ModelPart::ElementIterator i = it_begin; i != it_end; ++i) { (i)->InitializeSolutionStep(BaseType::GetModelPart().GetProcessInfo()); } } #pragma omp parallel for schedule(static,1) for (int k = 0; k < number_of_threads; k++) { ModelPart::NodeIterator it_begin = BaseType::GetModelPart().NodesBegin() + partition[k]; ModelPart::NodeIterator it_end = BaseType::GetModelPart().NodesBegin() + partition[k + 1]; array_1d<double, 3 > zero = ZeroVector(3); //first of all set to zero the nodal variables to be updated nodally for (ModelPart::NodeIterator i = it_begin; i != it_end; ++i) { array_1d<double,3>& force_temp = i->FastGetSolutionStepValue(FORCE); force_temp -=i->FastGetSolutionStepValue(NODAL_MASS) * ((i)->FastGetSolutionStepValue(VELOCITY)-(i)->FastGetSolutionStepValue(VELOCITY,1))/dt; } } KRATOS_CATCH(""); } /** * * @param Level */ virtual void SetEchoLevel(int Level) override { mecho_level = Level; mpfracvel_strategy->SetEchoLevel(Level); mppressurestep->SetEchoLevel(Level); } virtual void Clear() override { int rank = BaseType::GetModelPart().GetCommunicator().MyPID(); if (rank == 0) KRATOS_WATCH("FracStepStrategy Clear Function called"); mpfracvel_strategy->Clear(); mppressurestep->Clear(); } virtual double GetStageResidualNorm(unsigned int step) { if (step <= 3) return mpfracvel_strategy->GetResidualNorm(); if (step == 4) return mppressurestep->GetResidualNorm(); else return 0.0; } /*@} */ /**@name Operators */ /*@{ */ /*@} */ /**@name Operations */ /*@{ */ /*@} */ /**@name Access */ /*@{ */ /*@} */ /**@name Inquiry */ /*@{ */ /*@} */ /**@name Friends */ /*@{ */ /*@} */ protected: /**@name Protected static Member Variables */ /*@{ */ /*@} */ /**@name Protected member Variables */ /*@{ */ typename BaseType::Pointer mpfracvel_strategy; typename BaseType::Pointer mppressurestep; double mvelocity_toll; double mpressure_toll; int mMaxVelIterations; int mMaxPressIterations; unsigned int mtime_order; unsigned int mprediction_order; bool mpredictor_corrector; bool mReformDofAtEachIteration; int mecho_level; bool muse_dt_in_stabilization; /*@} */ /**@name Protected Operators*/ /*@{ */ /*@} */ /**@name Protected Operations*/ /*@{ */ /*@} */ /**@name Protected Access */ /*@{ */ /*@} */ /**@name Protected Inquiry */ /*@{ */ /*@} */ /**@name Protected LifeCycle */ /*@{ */ /*@} */ private: /**@name Static Member Variables */ /*@{ */ /*@} */ /**@name Member Variables */ /*@{ */ unsigned int m_step; unsigned int mdomain_size; bool proj_is_initialized; //GenerateSlipConditionProcess::Pointer mpSlipProcess; bool mHasSlipProcess; std::vector< Process::Pointer > mInitializeIterationProcesses; inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, vector<unsigned int>& partitions) { partitions.resize(number_of_threads + 1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for (unsigned int i = 1; i < number_of_threads; i++) partitions[i] = partitions[i - 1] + partition_size; } /*@} */ /**@name Private Operators*/ /*@{ */ //this funcion is needed to ensure that all the memory is allocated correctly /*@} */ /**@name Private Operations*/ /*@{ */ /*@} */ /**@name Private Access */ /*@{ */ /*@} */ /**@name Private Inquiry */ /*@{ */ /*@} */ /**@name Un accessible methods */ /*@{ */ /** Copy constructor. */ FracStepStrategy(const FracStepStrategy& Other); /*@} */ }; /* Class FracStepStrategy */ /*@} */ /**@name Type Definitions */ /*@{ */ /*@} */ } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUALBASED_FRACTIONALSTEP_STRATEGY defined */
blas_server_omp.c
/*********************************************************************/ /* Copyright 2009, 2010 The University of Texas at Austin. */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */ /* AUSTIN ``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 UNIVERSITY OF TEXAS AT */ /* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */ /* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */ /* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ /* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */ /* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ #include <stdbool.h> #include <stdio.h> #include <stdlib.h> //#include <sys/mman.h> #include "common.h" #ifndef USE_OPENMP #include "blas_server.c" #else #ifndef OMP_SCHED #define OMP_SCHED static #endif int blas_server_avail = 0; static void * blas_thread_buffer[MAX_PARALLEL_NUMBER][MAX_CPU_NUMBER]; #ifdef HAVE_C11 static atomic_bool blas_buffer_inuse[MAX_PARALLEL_NUMBER]; #else static _Bool blas_buffer_inuse[MAX_PARALLEL_NUMBER]; #endif void goto_set_num_threads(int num_threads) { int i=0, j=0; if (num_threads < 1) num_threads = blas_num_threads; if (num_threads > MAX_CPU_NUMBER) num_threads = MAX_CPU_NUMBER; if (num_threads > blas_num_threads) { blas_num_threads = num_threads; } blas_cpu_number = num_threads; omp_set_num_threads(blas_cpu_number); //adjust buffer for each thread for(i=0; i<MAX_PARALLEL_NUMBER; i++) { for(j=0; j<blas_cpu_number; j++){ if(blas_thread_buffer[i][j]==NULL){ blas_thread_buffer[i][j]=blas_memory_alloc(2); } } for(; j<MAX_CPU_NUMBER; j++){ if(blas_thread_buffer[i][j]!=NULL){ blas_memory_free(blas_thread_buffer[i][j]); blas_thread_buffer[i][j]=NULL; } } } #if defined(ARCH_MIPS64) //set parameters for different number of threads. blas_set_parameter(); #endif } void openblas_set_num_threads(int num_threads) { goto_set_num_threads(num_threads); } int blas_thread_init(void){ int i=0, j=0; blas_get_cpu_number(); blas_server_avail = 1; for(i=0; i<MAX_PARALLEL_NUMBER; i++) { for(j=0; j<blas_num_threads; j++){ blas_thread_buffer[i][j]=blas_memory_alloc(2); } for(; j<MAX_CPU_NUMBER; j++){ blas_thread_buffer[i][j]=NULL; } } return 0; } int BLASFUNC(blas_thread_shutdown)(void){ int i=0, j=0; blas_server_avail = 0; for(i=0; i<MAX_PARALLEL_NUMBER; i++) { for(j=0; j<MAX_CPU_NUMBER; j++){ if(blas_thread_buffer[i][j]!=NULL){ blas_memory_free(blas_thread_buffer[i][j]); blas_thread_buffer[i][j]=NULL; } } } return 0; } static void legacy_exec(void *func, int mode, blas_arg_t *args, void *sb){ if (!(mode & BLAS_COMPLEX)){ #ifdef EXPRECISION if (mode & BLAS_XDOUBLE){ /* REAL / Extended Double */ void (*afunc)(BLASLONG, BLASLONG, BLASLONG, xdouble, xdouble *, BLASLONG, xdouble *, BLASLONG, xdouble *, BLASLONG, void *) = func; afunc(args -> m, args -> n, args -> k, ((xdouble *)args -> alpha)[0], args -> a, args -> lda, args -> b, args -> ldb, args -> c, args -> ldc, sb); } else #endif if (mode & BLAS_DOUBLE){ /* REAL / Double */ void (*afunc)(BLASLONG, BLASLONG, BLASLONG, double, double *, BLASLONG, double *, BLASLONG, double *, BLASLONG, void *) = func; afunc(args -> m, args -> n, args -> k, ((double *)args -> alpha)[0], args -> a, args -> lda, args -> b, args -> ldb, args -> c, args -> ldc, sb); } else { /* REAL / Single */ void (*afunc)(BLASLONG, BLASLONG, BLASLONG, float, float *, BLASLONG, float *, BLASLONG, float *, BLASLONG, void *) = func; afunc(args -> m, args -> n, args -> k, ((float *)args -> alpha)[0], args -> a, args -> lda, args -> b, args -> ldb, args -> c, args -> ldc, sb); } } else { #ifdef EXPRECISION if (mode & BLAS_XDOUBLE){ /* COMPLEX / Extended Double */ void (*afunc)(BLASLONG, BLASLONG, BLASLONG, xdouble, xdouble, xdouble *, BLASLONG, xdouble *, BLASLONG, xdouble *, BLASLONG, void *) = func; afunc(args -> m, args -> n, args -> k, ((xdouble *)args -> alpha)[0], ((xdouble *)args -> alpha)[1], args -> a, args -> lda, args -> b, args -> ldb, args -> c, args -> ldc, sb); } else #endif if (mode & BLAS_DOUBLE){ /* COMPLEX / Double */ void (*afunc)(BLASLONG, BLASLONG, BLASLONG, double, double, double *, BLASLONG, double *, BLASLONG, double *, BLASLONG, void *) = func; afunc(args -> m, args -> n, args -> k, ((double *)args -> alpha)[0], ((double *)args -> alpha)[1], args -> a, args -> lda, args -> b, args -> ldb, args -> c, args -> ldc, sb); } else { /* COMPLEX / Single */ void (*afunc)(BLASLONG, BLASLONG, BLASLONG, float, float, float *, BLASLONG, float *, BLASLONG, float *, BLASLONG, void *) = func; afunc(args -> m, args -> n, args -> k, ((float *)args -> alpha)[0], ((float *)args -> alpha)[1], args -> a, args -> lda, args -> b, args -> ldb, args -> c, args -> ldc, sb); } } } static void exec_threads(blas_queue_t *queue, int buf_index){ void *buffer, *sa, *sb; int pos=0, release_flag=0; buffer = NULL; sa = queue -> sa; sb = queue -> sb; #ifdef CONSISTENT_FPCSR __asm__ __volatile__ ("ldmxcsr %0" : : "m" (queue -> sse_mode)); __asm__ __volatile__ ("fldcw %0" : : "m" (queue -> x87_mode)); #endif if ((sa == NULL) && (sb == NULL) && ((queue -> mode & BLAS_PTHREAD) == 0)) { pos = omp_get_thread_num(); buffer = blas_thread_buffer[buf_index][pos]; //fallback if(buffer==NULL) { buffer = blas_memory_alloc(2); release_flag=1; } if (sa == NULL) { sa = (void *)((BLASLONG)buffer + GEMM_OFFSET_A); queue->sa=sa; } if (sb == NULL) { if (!(queue -> mode & BLAS_COMPLEX)){ #ifdef EXPRECISION if (queue -> mode & BLAS_XDOUBLE){ sb = (void *)(((BLASLONG)sa + ((QGEMM_P * QGEMM_Q * sizeof(xdouble) + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); } else #endif if (queue -> mode & BLAS_DOUBLE){ sb = (void *)(((BLASLONG)sa + ((DGEMM_P * DGEMM_Q * sizeof(double) + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); } else { sb = (void *)(((BLASLONG)sa + ((SGEMM_P * SGEMM_Q * sizeof(float) + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); } } else { #ifdef EXPRECISION if (queue -> mode & BLAS_XDOUBLE){ sb = (void *)(((BLASLONG)sa + ((XGEMM_P * XGEMM_Q * 2 * sizeof(xdouble) + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); } else #endif if (queue -> mode & BLAS_DOUBLE){ sb = (void *)(((BLASLONG)sa + ((ZGEMM_P * ZGEMM_Q * 2 * sizeof(double) + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); } else { sb = (void *)(((BLASLONG)sa + ((CGEMM_P * CGEMM_Q * 2 * sizeof(float) + GEMM_ALIGN) & ~GEMM_ALIGN)) + GEMM_OFFSET_B); } } queue->sb=sb; } } if (queue -> mode & BLAS_LEGACY) { legacy_exec(queue -> routine, queue -> mode, queue -> args, sb); } else if (queue -> mode & BLAS_PTHREAD) { void (*pthreadcompat)(void *) = queue -> routine; (pthreadcompat)(queue -> args); } else { int (*routine)(blas_arg_t *, void *, void *, void *, void *, BLASLONG) = queue -> routine; (routine)(queue -> args, queue -> range_m, queue -> range_n, sa, sb, queue -> position); } if (release_flag) blas_memory_free(buffer); } int exec_blas(BLASLONG num, blas_queue_t *queue){ BLASLONG i, buf_index; if ((num <= 0) || (queue == NULL)) return 0; #ifdef CONSISTENT_FPCSR for (i = 0; i < num; i ++) { __asm__ __volatile__ ("fnstcw %0" : "=m" (queue[i].x87_mode)); __asm__ __volatile__ ("stmxcsr %0" : "=m" (queue[i].sse_mode)); } #endif while(true) { for(i=0; i < MAX_PARALLEL_NUMBER; i++) { #ifdef HAVE_C11 _Bool inuse = false; if(atomic_compare_exchange_weak(&blas_buffer_inuse[i], &inuse, true)) { #else if(blas_buffer_inuse[i] == false) { blas_buffer_inuse[i] = true; #endif buf_index = i; break; } } if(i != MAX_PARALLEL_NUMBER) break; } #pragma omp parallel for schedule(OMP_SCHED) for (i = 0; i < num; i ++) { #ifndef USE_SIMPLE_THREADED_LEVEL3 queue[i].position = i; #endif exec_threads(&queue[i], buf_index); } #ifdef HAVE_C11 atomic_store(&blas_buffer_inuse[buf_index], false); #else blas_buffer_inuse[buf_index] = false; #endif return 0; } #endif
reduce3.h
/* * reduce3.h * * Created on: Dec 28, 2015 * Author: agibsonccc */ #ifndef REDUCE3_H_ #define REDUCE3_H_ #define EXTRA_PARAMS_LENGTH 10 #include <templatemath.h> #include <helper_cuda.h> #include <helpers/sharedmem.h> #ifdef _OPENMP #include <omp.h> #endif #include <pairwise_util.h> #include <dll.h> #include <helpers/shape.h> #include <ops/ops.h> #include <op_boilerplate.h> #ifdef __CUDACC__ #include <cuda.h> #include <cuda_runtime.h> #endif #ifndef _OPENMP #define omp_get_thread_num() 0 #define omp_get_max_threads() 1 #endif #include "legacy_ops.h" namespace functions { namespace reduce3 { /** * Reduce involving * 2 arrays */ template<typename T> class Reduce3 { public: #ifdef __CUDACC__ virtual __device__ inline T opAtomic(T d1, T d2, T *extraParamsRef) = 0; #endif #ifdef __CUDACC__ /** * Aggregate shared memory * @param sPartialsRef * @param tid * @param extraParams */ template<typename OpType> static __inline__ __device__ void aggregatePartials(T **sPartialsRef, Nd4jLong tid, Nd4jLong numItems, T *extraParamsRef) { // start the shared memory loop on the next power of 2 less // than the block size. If block size is not a power of 2, // accumulate the intermediate sums in the remainder range. T *sPartials = *sPartialsRef; Nd4jLong floorPow2 = numItems; if (floorPow2 & (floorPow2 - 1)) { while (floorPow2 & (floorPow2 - 1)) { floorPow2 &= floorPow2 - 1; } if (tid >= floorPow2) { sPartials[tid - floorPow2] = OpType::update(sPartials[tid - floorPow2], sPartials[tid], extraParamsRef); } __syncthreads(); } for (Nd4jLong activeThreads = floorPow2 >> 1; activeThreads; activeThreads >>= 1) { if (tid < activeThreads) { sPartials[tid] = OpType::update(sPartials[tid], sPartials[tid + activeThreads], extraParamsRef); } __syncthreads(); } } /** Perform a reduction @param n the number of elements @param xOffset the starting offset @param dx the data to perform the reduction on @param incx the increment on which to perform the reduction @param extraParams extra parameters used for calculations @param result where to store the result of the reduction */ virtual __inline__ __device__ void transformNoElementWiseStride( T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int postProcessOrNot, int *allocationPointer, UnifiedSharedMemory *manager, Nd4jLong *tadOnlyShapeInfo) { Nd4jLong n = shape::length(xShapeInfo); int rank = shape::rank(xShapeInfo); T *sPartials = (T *) manager->getSharedReductionBuffer(); //val.getPointer(); T startingVal = this->startingValue(dx); // FIXME: this ugly fast fix. __shared__ T extraZ[2]; if (threadIdx.x == 0) { extraZ[0] = (T) 0.0; extraZ[1] = (T) 0.0; } sPartials[threadIdx.x] = startingVal; __syncthreads(); Nd4jLong idx[MAX_RANK]; for(Nd4jLong i = blockIdx.x * gridDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) { shape::ind2subC(rank,shape::shapeOf(xShapeInfo),i, idx); auto offset = shape::getOffset(0,shape::shapeOf(xShapeInfo),shape::stride(xShapeInfo),idx,rank); auto yOffset = shape::getOffset(0,shape::shapeOf(yShapeInfo),shape::stride(yShapeInfo),idx,rank); sPartials[threadIdx.x] = update(sPartials[threadIdx.x], this->opAtomic(dx[offset], dy[yOffset], extraZ), extraZ); } T **sPartialsRef = (T **) &sPartials; aggregatePartials(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, n), extraZ); /** * Look at something that uses the extra params * and aggregates the extra values propelry. *This will be used in summary stats too. */ // write result for this block to global mem if (threadIdx.x == 0) { if (postProcessOrNot) { result[blockIdx.x] = postProcess(sPartials[0], n, extraZ); } else { result[blockIdx.x] = sPartials[0]; } } } /** * */ template<typename OpType> static inline __device__ void execScalarCuda( T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *allocationPointer, T *reductionBuffer, UnifiedSharedMemory *manager, Nd4jLong *tadOnlyShapeInfo) { // SharedMemory <T> val; T *sPartials = (T *) manager->getSharedReductionBuffer(); // val.getPointer(); // FIXME: this ugly fast fix. __shared__ T extraZ[3]; if (threadIdx.x == 0) { extraZ[0] = (T) 0.0f; extraZ[1] = (T) 0.0f; if (extraParams != NULL) { extraZ[2] = extraParams[0]; } else extraZ[2] = (T) 0.0f; } __syncthreads(); T startingVal = OpType::startingValue(dx); Nd4jLong length = shape::length(xShapeInfo); int xElementWiseStride = shape::elementWiseStride(xShapeInfo); int yElementWiseStride = shape::elementWiseStride(yShapeInfo); int tid = blockIdx.x * blockDim.x + threadIdx.x; char xOrder = shape::order(xShapeInfo); char yOrder = shape::order(yShapeInfo); if(xOrder == yOrder && (xElementWiseStride > 0 && yElementWiseStride > 0) && shape::strideDescendingCAscendingF(xShapeInfo) && shape::strideDescendingCAscendingF(yShapeInfo)) { if (xElementWiseStride == 1 && yElementWiseStride == 1) { for(Nd4jLong i = tid; i < length; i+= gridDim.x * blockDim.x) { startingVal = OpType::update(startingVal, OpType::opAtomic(dx[i], dy[i], extraZ), extraZ); } } else { for(Nd4jLong i = tid; i < length; i+= gridDim.x * blockDim.x) { startingVal = OpType::update(startingVal, OpType::opAtomic(dx[i * xElementWiseStride], dy[i * yElementWiseStride], extraZ), extraZ); } } sPartials[threadIdx.x] = startingVal; } else { __shared__ Nd4jLong *xShape; __shared__ Nd4jLong *yShape; __shared__ Nd4jLong *xStride; __shared__ Nd4jLong *yStride; __shared__ int rank; if (threadIdx.x == 0) { xShape = shape::shapeOf(xShapeInfo); yShape = shape::shapeOf(yShapeInfo); xStride = shape::stride(xShapeInfo); yStride = shape::stride(yShapeInfo); rank = shape::rank(xShapeInfo); } __syncthreads(); T startingVal = OpType::startingValue(dx); T *sPartials = (T *) manager->getSharedReductionBuffer(); Nd4jLong xCoords[MAX_RANK]; Nd4jLong yCoords[MAX_RANK]; sPartials[threadIdx.x] = startingVal; for(Nd4jLong i = tid ;i < length; i += gridDim.x * blockDim.x) { shape::ind2subC(rank,xShape,i,xCoords); shape::ind2subC(rank,yShape,i,yCoords); auto offset = shape::getOffset(0, xShape, xStride, xCoords,rank); auto yOffset = shape::getOffset(0,yShape, yStride, yCoords,rank); sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], OpType::opAtomic(dx[offset], dy[yOffset], extraZ), extraZ); } } __syncthreads(); T **sPartialsRef = (T **) &sPartials; aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, length), extraZ); __syncthreads(); if (gridDim.x > 1) { unsigned int *tc = (unsigned int *)reductionBuffer; __shared__ bool amLast; int rank = shape::rank(xShapeInfo); tid = threadIdx.x; T *extraBuffer = (T *) allocationPointer; if (threadIdx.x == 0) { reductionBuffer[blockIdx.x] = sPartials[0]; extraBuffer[blockIdx.x] = extraZ[0]; extraBuffer[gridDim.x + blockIdx.x] = extraZ[1]; } __threadfence(); __syncthreads(); if (threadIdx.x == 0) { unsigned int ticket = atomicInc(&tc[16384], gridDim.x); amLast = (ticket == gridDim.x - 1); } sPartials[tid] = startingVal; __syncthreads(); if (amLast) { tc[16384] = 0; sPartials[threadIdx.x] = OpType::startingValue(dx); // TODO: later probably replace this. Right now we need extraZ sync for CosineSimilarity ONLY if (tid == 0 && extraZ[0] != (T) 0.0 && extraZ[1] != (T) 0.0) { extraZ[0] = 0.0; extraZ[1] = 0.0; for (int i = 0; i < gridDim.x; i++) { extraZ[0] += extraBuffer[i]; extraZ[1] += extraBuffer[gridDim.x + i]; } } for (Nd4jLong i = threadIdx.x; i < gridDim.x; i += blockDim.x) { sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], reductionBuffer[i], extraZ); } __syncthreads(); aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(gridDim.x, blockDim.x), extraZ); __syncthreads(); if (threadIdx.x == 0) { result[0] = OpType::postProcess(sPartials[0], length, extraZ); } } } else { if (tid == 0) { unsigned int *tc = (unsigned *)reductionBuffer; tc[16384] = 0; result[0] = OpType::postProcess(sPartials[0], length, extraZ); } } } template<typename OpType> __device__ static inline void transformAll( T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, UnifiedSharedMemory *manager, Nd4jLong *xTadShapeInfo, Nd4jLong *xOffsets, Nd4jLong *yTadShapeInfo, Nd4jLong *yOffsets) { // initialize partials first T *sPartials = (T *) manager->getSharedReductionBuffer(); T startingVal = OpType::startingValue(dx); sPartials[threadIdx.x] = startingVal; T *tempX = sPartials + blockDim.x; const int maxBlock = blockDim.x; __shared__ T extraZ[OpType::extraParamsLen > 0 ? OpType::extraParamsLen : 1]; __shared__ int xTadLength; __shared__ int yTadLength; __shared__ int xTads; __shared__ int yTads; __shared__ Nd4jLong *xShape; __shared__ Nd4jLong *xStride; __shared__ int xRank; __shared__ Nd4jLong *yShape; __shared__ Nd4jLong *yStride; __shared__ int yRank; //reading initial data if (threadIdx.x == 0) { xTadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength); yTadLength = shape::tadLength(yShapeInfo, dimension, dimensionLength); xTads = shape::length(xShapeInfo) / xTadLength; yTads = shape::length(yShapeInfo) / yTadLength; xShape = shape::shapeOf(xTadShapeInfo); xStride = shape::stride(xTadShapeInfo); xRank = shape::rank(xTadShapeInfo); yShape = shape::shapeOf(yTadShapeInfo); yStride = shape::stride(yTadShapeInfo); yRank = shape::rank(yTadShapeInfo); } __syncthreads(); Nd4jLong xCoord[MAX_RANK]; Nd4jLong yCoord[MAX_RANK]; int limit = xTadLength / maxBlock; if (xTadLength % maxBlock > 0) limit++; for (int r = blockIdx.x; r < xTads; r += blockDim.x * gridDim.x) { T *x = dx + xOffsets[r]; if (threadIdx.x < xTadLength && threadIdx.x < maxBlock) { if (shape::order(xTadShapeInfo) == 'c') { shape::ind2subC(xRank, xShape, threadIdx.x, xCoord); } else { shape::ind2sub(xRank, xShape, threadIdx.x, xCoord); } auto xO = shape::getOffset(0, xShape, xStride, xCoord, xRank); tempX[threadIdx.x] = x[xO]; } for (int g = 0; g < yTads; g++) { T *y = dy + yOffsets[g]; int ri = (r * yTads) + g; sPartials[threadIdx.x] = startingVal; if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) { extraZ[threadIdx.x] = (T) startingVal; } __syncthreads(); // we might have data too large for single cache block, rendering cache useless though :( for (int t = 0; t < limit; t++) { // we reset tempX IF we have >1 tiles if (t >= 1 || (limit > 1 && g > 0)) if (threadIdx.x + (t * maxBlock) < xTadLength) { if (shape::order(xTadShapeInfo) == 'c') { shape::ind2subC(xRank, xShape, threadIdx.x + (t * maxBlock), xCoord); } else { shape::ind2sub(xRank, xShape, threadIdx.x + (t * maxBlock), xCoord); } Nd4jLong xO = shape::getOffset(0, xShape, xStride, xCoord, xRank); tempX[threadIdx.x] = x[xO]; // tempX[threadIdx.x] = x[threadIdx.x + (t * maxBlock)]; } for (int f = threadIdx.x + (t * maxBlock); f < xTadLength && f < threadIdx.x + ((t + 1) * maxBlock); f += blockDim.x * gridDim.x) { if (shape::order(yTadShapeInfo) == 'c') { shape::ind2subC(yRank, yShape, f, yCoord); } else { shape::ind2sub(yRank, yShape, f, yCoord); } Nd4jLong yO = shape::getOffset(0, yShape, yStride, yCoord, yRank); sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], OpType::opAtomic(tempX[threadIdx.x], y[yO], extraZ), extraZ); } // we MUST step through this block altogether __syncthreads(); } T **sPartialsRef = (T **) &sPartials; aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, xTadLength), extraZ); __syncthreads(); if (threadIdx.x == 0) { result[ri] = OpType::postProcess(sPartials[threadIdx.x],xTadLength, extraZ); } __syncthreads(); } } } /** Perform a reduction @param n the number of elements @param xOffset the starting offset @param dx the data to perform the reduction on @param incx the increment on which to perform the reduction @param extraParams extra parameters used for calculations @param result where to store the result of the reduction */ template<typename OpType> __device__ static inline void transform( T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, UnifiedSharedMemory *manager, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { /** * Gpu information for the problem */ int tid = threadIdx.x + blockIdx.x * blockDim.x; __shared__ int resultScalar; __shared__ int xElementWiseStride; __shared__ int yElementWiseStride; //shared memory space for storing intermediate results //SharedMemory <T> val; T *sPartials = (T *) manager->getSharedReductionBuffer(); //val.getPointer(); T init = OpType::startingValue(dx); sPartials[threadIdx.x] = init; __shared__ T extraZ[OpType::extraParamsLen > 0 ? OpType::extraParamsLen : 1]; //length for the tad __shared__ Nd4jLong resultLength; __shared__ int tadLength; __shared__ int yLength; __shared__ int tadElementWiseStride; __shared__ int yTadElementWiseStride; T startingVal = OpType::startingValue(dx); T reduction = OpType::startingValue(dx); if (threadIdx.x == 0) { if (resultShapeInfo != nullptr) resultLength = shape::length(resultShapeInfo); else resultLength = 1; if (dimensionLength == 1) { if (dimension == nullptr || dimension[0] == MAX_DIMENSION) resultScalar = 1; else resultScalar = 0; } else resultScalar = 0; if (resultLength == 1) resultScalar = 1; auto xStride = shape::stride(xShapeInfo); char xOrder = shape::order(xShapeInfo); tadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength); tadElementWiseStride = shape::elementWiseStride(tadOnlyShapeInfo); yLength = shape::length(yShapeInfo); if (yTadOnlyShapeInfo != nullptr) yTadElementWiseStride = shape::elementWiseStride(yTadOnlyShapeInfo); } __syncthreads(); // code branch for TAD vs full array if (tadLength == yLength) { Nd4jLong xCoord[MAX_RANK]; Nd4jLong yCoord[MAX_RANK]; auto yShape = shape::shapeOf(yShapeInfo); auto yStride = shape::stride(yShapeInfo); auto xShape = shape::shapeOf(tadOnlyShapeInfo); auto xStride = shape::stride(tadOnlyShapeInfo); int yRank = shape::rank(yShapeInfo); int xRank = shape::rank(tadOnlyShapeInfo); for(int i = blockIdx.x; i < resultLength; i+= gridDim.x) { int xOffsetForTad = tadOffsets[i]; if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) { extraZ[threadIdx.x] = (T) startingVal; } __syncthreads(); for(int j = threadIdx.x; j < tadLength; j += blockDim.x) { shape::ind2subC(xRank,xShape, j, xCoord); shape::ind2subC(yRank,yShape, j, yCoord); Nd4jLong xOffset = shape::getOffset(xOffsetForTad, xShape, xStride, xCoord, xRank); Nd4jLong yOffset = shape::getOffset(0, yShape, yStride, yCoord, yRank); sPartials[threadIdx.x] = j < blockDim.x ? OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ) : OpType::update(sPartials[threadIdx.x], OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ), extraZ); } __syncthreads(); T **sPartialsRef = (T **) &sPartials; aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tadLength), extraZ); __syncthreads(); if (threadIdx.x == 0) result[i] = OpType::postProcess(sPartials[threadIdx.x],tadLength, extraZ); __syncthreads(); } } else if (!resultScalar) { if(tadElementWiseStride >= 1 && yTadElementWiseStride) { for(int i = blockIdx.x; i < resultLength; i+= gridDim.x) { int xOffsetForTad = tadOffsets[i]; int yOffsetForTad = yTadOffsets[i]; if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) { extraZ[threadIdx.x] = (T) startingVal; } __syncthreads(); if (threadIdx.x < tadLength) sPartials[threadIdx.x] = OpType::op(dx[xOffsetForTad + tadElementWiseStride * threadIdx.x],dy[yOffsetForTad + yTadElementWiseStride * threadIdx.x], extraZ); for(int j = threadIdx.x + blockDim.x; j < tadLength; j += blockDim.x) { sPartials[threadIdx.x] = OpType::update(sPartials[threadIdx.x], OpType::op(dx[xOffsetForTad + tadElementWiseStride * j],dy[yOffsetForTad + yTadElementWiseStride * j], extraZ), extraZ); } __syncthreads(); T **sPartialsRef = (T **) &sPartials; aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tadLength), extraZ); __syncthreads(); if (threadIdx.x == 0) result[i] = OpType::postProcess(sPartials[threadIdx.x],tadLength, extraZ); __syncthreads(); } } else { /* // DO NOT REMOVE THIS COMMENTED BLOCK PLEASE for (int r = blockIdx.x; r < tad->numTads; r += gridDim.x) { if (threadIdx.x == 0) tad->createOffsetForBlock(r); __syncthreads(); int tadOffsetForBlock = tad->tadOffsetForBlock; T *xVal = dx + tadOffsetForBlock; sPartials[threadIdx.x] = this->startingValue(xVal); for(int i = threadIdx.x; i < tad->tadLength; i+= blockDim.x) { int xOffsetForTad = shape::tadOffset(i, xShapeInfo, dimension, dimensionLength, nullptr); int yOffsetForTad = shape::tadOffset(i, yShapeInfo, dimension, dimensionLength, nullptr); sPartials[threadIdx.x] = this->update(sPartials[threadIdx.x],dx[tadOffsetForBlock + i * tad->tadElementWiseStride], extraParams); } __syncthreads(); // aggregate. do NOT reduce for elements > tadLength T **sPartialsRef = (T **) &sPartials; aggregatePartials(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tad->tadLength), extraParams); __syncthreads(); if (threadIdx.x == 0) result[r] = this->postProcess(sPartials[threadIdx.x], tad->tadLength, extraParams); } */ Nd4jLong xCoord[MAX_RANK]; Nd4jLong yCoord[MAX_RANK]; auto yShape = shape::shapeOf(yTadOnlyShapeInfo); auto yStride = shape::stride(yTadOnlyShapeInfo); auto xShape = shape::shapeOf(tadOnlyShapeInfo); auto xStride = shape::stride(tadOnlyShapeInfo); int yRank = shape::rank(yTadOnlyShapeInfo); int xRank = shape::rank(tadOnlyShapeInfo); for(int i = blockIdx.x; i < resultLength; i+= gridDim.x) { auto xOffsetForTad = tadOffsets[i]; auto yOffsetForTad = yTadOffsets[i]; if (OpType::extraParamsLen > 0 && threadIdx.x < OpType::extraParamsLen) { extraZ[threadIdx.x] = (T) startingVal; } __syncthreads(); for(int j = threadIdx.x; j < tadLength; j += blockDim.x) { shape::ind2subC(xRank,xShape, j, xCoord); shape::ind2subC(yRank,yShape, j, yCoord); auto xOffset = shape::getOffset(xOffsetForTad, xShape, xStride, xCoord, xRank); auto yOffset = shape::getOffset(yOffsetForTad, yShape, yStride, yCoord, yRank); sPartials[threadIdx.x] = j < blockDim.x ? OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ) : OpType::update(sPartials[threadIdx.x], OpType::opAtomic(dx[xOffset],dy[yOffset], extraZ), extraZ); } __syncthreads(); T **sPartialsRef = (T **) &sPartials; aggregatePartials<OpType>(sPartialsRef, threadIdx.x, nd4j::math::nd4j_min<int>(blockDim.x, tadLength), extraZ); __syncthreads(); if (threadIdx.x == 0) result[i] = OpType::postProcess(sPartials[threadIdx.x],tadLength, extraZ); __syncthreads(); } } } } #endif #ifdef __CUDACC__ __device__ static inline void exec( const int opNum, T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, UnifiedSharedMemory *manager, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { DISPATCH_BY_OPNUM(transform, PARAMS(dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, manager, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets), REDUCE3_OPS); } __device__ static inline void execAllCuda( const int opNum, T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, UnifiedSharedMemory *manager, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { DISPATCH_BY_OPNUM(transformAll, PARAMS(dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, manager, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets), REDUCE3_OPS); } __device__ static inline void execScalarCuda( const int opNum, T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int * allocationPointer, T *reductionBuffer, UnifiedSharedMemory *manager, Nd4jLong *tadOnlyShapeInfo) { DISPATCH_BY_OPNUM(execScalarCuda, PARAMS(dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, allocationPointer, reductionBuffer, manager, tadOnlyShapeInfo), REDUCE3_OPS); } #endif #ifdef __CUDACC__ __host__ #endif static T execScalar( const int opNum, T *x, Nd4jLong *xShapeInfo, T *extraParamsVals, T *y, Nd4jLong *yShapeInfo) { RETURNING_DISPATCH_BY_OPNUM(execScalar, PARAMS(x, xShapeInfo, extraParamsVals, y, yShapeInfo), REDUCE3_OPS); } static void exec( const int opNum, T *x, Nd4jLong *xShapeInfo, T *extraParamsVals, T *y, Nd4jLong *yShapeInfo, T *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength) { DISPATCH_BY_OPNUM(exec, PARAMS(x, xShapeInfo, extraParamsVals, y, yShapeInfo, result, resultShapeInfoBuffer, dimension, dimensionLength), REDUCE3_OPS); } static void exec( const int opNum, T *x, Nd4jLong *xShapeInfo, T *extraParamsVals, T *y, Nd4jLong *yShapeInfo, T *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { DISPATCH_BY_OPNUM(exec, PARAMS(x, xShapeInfo, extraParamsVals, y, yShapeInfo, result, resultShapeInfoBuffer, dimension, dimensionLength, tadShapeInfo, tadOffsets), REDUCE3_OPS); } static void execAll( const int opNum, T *x, Nd4jLong *xShapeInfo, T *extraParamsVals, T *y, Nd4jLong *yShapeInfo, T *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *xTadShapeInfo, Nd4jLong *xOffsets, Nd4jLong *yTadShapeInfo, Nd4jLong *yOffsets) { DISPATCH_BY_OPNUM(execAll, PARAMS(x, xShapeInfo, extraParamsVals, y, yShapeInfo, result, resultShapeInfoBuffer, dimension, dimensionLength, xTadShapeInfo, xOffsets, yTadShapeInfo, yOffsets), REDUCE3_OPS); } template<typename OpType> #ifdef __CUDACC__ __host__ #endif static T execScalar( T *x, Nd4jLong *xShapeInfo, T *extraParams, T *y, Nd4jLong *yShapeInfo) { T startingVal = OpType::startingValue(x); Nd4jLong length = shape::length(xShapeInfo); Nd4jLong xElementWiseStride = shape::elementWiseStride(xShapeInfo); Nd4jLong yElementWiseStride = shape::elementWiseStride(yShapeInfo); T extraParamsVals[3] = {(T) 0.0, (T) 0.0, (T) 0.0}; // it's possible case for EqualsWithEps op if (extraParams != nullptr) { extraParamsVals[2] = extraParams[0]; } char xOrder = shape::order(xShapeInfo); char yOrder = shape::order(yShapeInfo); if(xOrder == yOrder && (xElementWiseStride >=1 && yElementWiseStride >= 1) && shape::strideDescendingCAscendingF(xShapeInfo) && shape::strideDescendingCAscendingF(yShapeInfo)) { if (xElementWiseStride == 1 && yElementWiseStride == 1) { // TODO:: proper reduction required here for(int i = 0; i < length; i++) { startingVal = OpType::update(startingVal, OpType::op(x[i],y[i], extraParamsVals), extraParamsVals); } return OpType::postProcess(startingVal, length, extraParamsVals); } else { // TODO:: proper reduction required here for(Nd4jLong i = 0; i < length; i++) { startingVal = OpType::update(startingVal, OpType::op(x[i * xElementWiseStride],y[i * yElementWiseStride], extraParamsVals), extraParamsVals); } return OpType::postProcess(startingVal, length, extraParamsVals); } } else { Nd4jLong xCoords[MAX_RANK]; Nd4jLong yCoords[MAX_RANK]; int xRank = shape::rank(xShapeInfo); int yRank = shape::rank(yShapeInfo); Nd4jLong *xShape = shape::shapeOf(xShapeInfo); Nd4jLong *xStride = shape::stride(xShapeInfo); Nd4jLong *yShape = shape::shapeOf(yShapeInfo); Nd4jLong *yStride = shape::stride(yShapeInfo); for(unsigned int i = 0 ;i < length; i++) { shape::ind2subC(xRank, xShape, i, xCoords); shape::ind2subC(yRank, yShape, i, yCoords); Nd4jLong offset = shape::getOffset(0, xShape, xStride, xCoords, xRank); Nd4jLong yOffset = shape::getOffset(0, yShape, yStride, yCoords, yRank); startingVal = OpType::update(startingVal, OpType::op(x[offset], y[yOffset], extraParamsVals), extraParamsVals); } } return OpType::postProcess(startingVal, length, extraParamsVals);; } template<typename OpType> static void execAll( T *x, Nd4jLong *xShapeInfo, T *extraParams, T *y, Nd4jLong *yShapeInfo, T *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *xTadShapeInfo, Nd4jLong *xOffsets, Nd4jLong *yTadShapeInfo, Nd4jLong *yOffsets) { auto xTadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength); auto yTadLength = shape::tadLength(yShapeInfo, dimension, dimensionLength); auto xTads = shape::length(xShapeInfo) / xTadLength; auto yTads = shape::length(yShapeInfo) / yTadLength; auto xShape = shape::shapeOf(xTadShapeInfo); auto xStride = shape::stride(xTadShapeInfo); int xRank = shape::rank(xTadShapeInfo); auto yShape = shape::shapeOf(yTadShapeInfo); auto yStride = shape::stride(yTadShapeInfo); int yRank = shape::rank(yTadShapeInfo); Nd4jLong xCoord[MAX_RANK]; Nd4jLong yCoord[MAX_RANK]; T startingVal = OpType::startingValue(x); #pragma omp parallel for proc_bind(AFFINITY) default(shared) private(xCoord, yCoord) for (Nd4jLong r = 0; r < xTads; r++) { Nd4jLong xOffset = xOffsets[r]; T *lX = x + xOffset; for (Nd4jLong g = 0; g < yTads; g++) { auto yOffset = yOffsets[g]; T *lY = y + yOffset; auto ri = (r * yTads) + g; T *localExtraParams = nullptr; if (OpType::extraParamsLen > 0) localExtraParams = new T[OpType::extraParamsLen]; for (int extraParamsIdx = 0; extraParamsIdx < OpType::extraParamsLen; extraParamsIdx++) { localExtraParams[extraParamsIdx] = startingVal; } for (int f = 0; f < xTadLength; f++) { if (shape::order(yTadShapeInfo) == 'c') { shape::ind2subC(yRank, yShape, f, yCoord); } else { shape::ind2sub(yRank, yShape, f, yCoord); } if (shape::order(xTadShapeInfo) == 'c') { shape::ind2subC(xRank, xShape, f, xCoord); } else { shape::ind2sub(xRank, xShape, f, xCoord); } Nd4jLong xO = shape::getOffset(0, xShape, xStride, xCoord, xRank); Nd4jLong yO = shape::getOffset(0, yShape, yStride, yCoord, yRank); result[ri] = OpType::update(result[ri], OpType::op(lX[xO], lY[yO], localExtraParams), localExtraParams); } result[ri] = OpType::postProcess(result[ri], xTadLength, localExtraParams); if (localExtraParams != nullptr) delete[] localExtraParams; } } } template<typename OpType> static void exec( T *x, Nd4jLong *xShapeInfo, T *extraParams, T *y, Nd4jLong *yShapeInfo, T *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { /* nd4j_printf("Xp: [%p]; Yp: [%p]; Zp: [%p];\n", (void *) x, (void *) y, (void *) result); nd4j_printf("XSp: [%p]; YSp: [%p]; ZSp: [%p];\n", (void *) xShapeInfo, (void *) yShapeInfo, (void *) resultShapeInfoBuffer); nd4j_printf("Ep: [%p]; Dp: [%p]\n", (void *) extraParams, (void *) dimension); nd4j_printf("TSp: [%p]; TOp: [%p]\n", (void *) tadShapeInfo, (void *) tadOffsets); nd4j_printf("X[0]: %f\n", x[0]); nd4j_printf("Y[0]: %f\n", y[0]); nd4j_printf("Z[0]: %f\n", result[0]); nd4j_printf("XS[0]: %i\n", xShapeInfo[0]); nd4j_printf("YS[0]: %i\n", yShapeInfo[0]); nd4j_printf("ZS[0]: %i\n", resultShapeInfoBuffer[0]); nd4j_printf("E[0]: %f\n", extraParams[0]); nd4j_printf("D[0]: %i\n", dimension[0]); nd4j_printf("TS[0]: %i\n", tadShapeInfo[0]); nd4j_printf("TO[0]: %lld\n", tadOffsets[0]); nd4j_printf("dimLength: %i\n", dimensionLength); */ T startingVal = OpType::startingValue(x); auto tadLength = shape::tadLength(xShapeInfo, dimension, dimensionLength); auto tads = shape::length(xShapeInfo) / tadLength; auto *xShape = shape::shapeOf(tadShapeInfo); auto *xStride = shape::stride(tadShapeInfo); int xRank = shape::rank(tadShapeInfo); auto *yShape = shape::shapeOf(yShapeInfo); auto *yStride = shape::stride(yShapeInfo); int yRank = shape::rank(yShapeInfo); //shape::printShapeInfoLinear(xShapeInfo); //shape::printShapeInfoLinear(yShapeInfo); //shape::printShapeInfoLinear(resultShapeInfoBuffer); //shape::printShapeInfoLinear(tadShapeInfo); Nd4jLong xCoord[MAX_RANK]; Nd4jLong yCoord[MAX_RANK]; //#pragma omp parallel for proc_bind(AFFINITY) default(shared) for (Nd4jLong r = 0; r < tads; r++) { Nd4jLong offset = tadOffsets[r]; T *localExtraParams = nullptr; if (OpType::extraParamsLen > 0) localExtraParams = new T[OpType::extraParamsLen]; for (int extraParamsIdx = 0; extraParamsIdx < OpType::extraParamsLen; extraParamsIdx++) { localExtraParams[extraParamsIdx] = startingVal; } for (Nd4jLong f = 0; f < tadLength; f++) { if (shape::order(tadShapeInfo) == 'c') { shape::ind2subC(xRank, xShape, f, xCoord); shape::ind2subC(yRank, yShape, f, yCoord); } else { shape::ind2sub(xRank, xShape, f, xCoord); shape::ind2sub(yRank, yShape, f, yCoord); } Nd4jLong xOffset = shape::getOffset(offset, xShape, xStride, xCoord, xRank); Nd4jLong yOffset = shape::getOffset(0, yShape, yStride, yCoord, yRank); result[r] = OpType::update(result[r], OpType::op(x[xOffset], y[yOffset], localExtraParams), localExtraParams); } result[r] = OpType::postProcess(result[r], tadLength, localExtraParams); if (localExtraParams != nullptr) delete[] localExtraParams; } } template<typename OpType> static void exec( T *x, Nd4jLong *xShapeInfo, T *extraParams, T *y, Nd4jLong *yShapeInfo, T *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength) { /* nd4j_printf("Xp: [%p]; Yp: [%p]; Zp: [%p];\n", (void *) x, (void *) y, (void *) result); nd4j_printf("XSp: [%p]; YSp: [%p]; ZSp: [%p];\n", (void *) xShapeInfo, (void *) yShapeInfo, (void *) resultShapeInfoBuffer); nd4j_printf("Ep: [%p]; Dp: [%p]\n", (void *) extraParams, (void *) dimension); nd4j_printf("X[0]: %f\n", x[0]); nd4j_printf("Y[0]: %f\n", y[0]); nd4j_printf("Z[0]: %f\n", result[0]); nd4j_printf("XS[0]: %i\n", xShapeInfo[0]); nd4j_printf("YS[0]: %i\n", yShapeInfo[0]); nd4j_printf("ZS[0]: %i\n", resultShapeInfoBuffer[0]); nd4j_printf("E[0]: %f\n", extraParams[0]); nd4j_printf("D[0]: %i\n", dimension[0]); nd4j_printf("dimLength: %i\n", dimensionLength); */ T extraParamsVals[3] = {(T) 0.0, (T) 0.0, (T) 0.0}; if(shape::isScalar(resultShapeInfoBuffer)) { result[0] = execScalar<OpType>( x, xShapeInfo, extraParamsVals, y, yShapeInfo); return; } char xOrder = shape::order(xShapeInfo); char yOrder = shape::order(yShapeInfo); if(xOrder != yOrder) { Nd4jLong shapeIter[MAX_RANK]; Nd4jLong coord[MAX_RANK]; int dim; Nd4jLong xStridesIter[MAX_RANK]; Nd4jLong yStridesIter[MAX_RANK]; auto xShape = shape::shapeOf(xShapeInfo); auto xStride = shape::stride(xShapeInfo); auto yStride = shape::stride(yShapeInfo); int rank = shape::rank(xShapeInfo); if(PrepareTwoRawArrayIter<T>(rank, xShape, x, xStride, y, yStride, &rank, shapeIter, &x, xStridesIter, &y, yStridesIter) >= 0) { Nd4jLong resultLength = shape::length(resultShapeInfoBuffer); Nd4jLong tadLength = shape::tadLength(xShapeInfo,dimension,dimensionLength); ND4J_RAW_ITER_START(dim, rank, coord, shapeIter); { Nd4jLong xOffset = shape::getOffset(0,xShape,xStride,coord,rank); auto reductionIndex = xOffset / resultLength; result[reductionIndex] = OpType::update(result[reductionIndex], OpType::op(x[0],y[0], extraParamsVals), extraParamsVals); } ND4J_RAW_ITER_TWO_NEXT(dim, rank, coord, shapeIter, x, xStridesIter, y, yStridesIter); //#pragma omp parallel for proc_bind(AFFINITY) default(shared) for(Nd4jLong i = 0; i < resultLength ;i++) { result[i] = OpType::postProcess(result[i],tadLength, extraParamsVals); } } else { printf("Unable to prepare array\n"); } } else { T startingVal = OpType::startingValue(x); Nd4jLong resultLength = shape::length(resultShapeInfoBuffer); shape::TAD xTad(xShapeInfo, dimension, dimensionLength); xTad.createTadOnlyShapeInfo(); xTad.createOffsets(); shape::TAD yTad(yShapeInfo, dimension, dimensionLength); yTad.createTadOnlyShapeInfo(); yTad.createOffsets(); /** * The element wise stride belong longs to a reduction index. * When used out of order, we can get rid of the data * dependencies and rely on using the max dimension * specified for stride instead. * Say we take the sum(0,1) along long arr * we can use arr.stride(1) as a representation * along long which to iterate. */ int largerElementWiseStride; int smallerElementWiseStride; auto xElementWiseStride = shape::elementWiseStride(xTad.tadOnlyShapeInfo); auto yElementWiseStride = shape::elementWiseStride(yTad.tadOnlyShapeInfo); int tadLength; Nd4jLong xModLength; Nd4jLong yModLength; Nd4jLong *iterationTadInfo; bool xTadBigger; if(shape::length(xShapeInfo) > shape::length(yShapeInfo)) { tadLength = shape::length(xTad.tadOnlyShapeInfo); iterationTadInfo = xTad.tadOnlyShapeInfo; largerElementWiseStride = shape::elementWiseStride(xShapeInfo); smallerElementWiseStride = shape::elementWiseStride(yShapeInfo); xModLength = 1; yModLength = tadLength; xTadBigger = true; } else { tadLength = shape::length(yTad.tadOnlyShapeInfo); iterationTadInfo = yTad.tadOnlyShapeInfo; largerElementWiseStride = shape::elementWiseStride(yShapeInfo); smallerElementWiseStride = shape::elementWiseStride(xShapeInfo); xModLength = tadLength; yModLength = 1; xTadBigger = false; } if (largerElementWiseStride >= 1 && smallerElementWiseStride >= 1 && xElementWiseStride >= 1 && yElementWiseStride >= 1) { if(shape::length(xShapeInfo) == shape::length(yShapeInfo)) { //#pragma omp parallel for proc_bind(AFFINITY) default(shared) for (Nd4jLong i = 0; i < resultLength; i++) { T *localExtraParams = nullptr; if (OpType::extraParamsLen > 0) localExtraParams = new T[OpType::extraParamsLen]; for (int extraParamsIdx = 0; extraParamsIdx < OpType::extraParamsLen; extraParamsIdx++) { localExtraParams[extraParamsIdx] = startingVal; } Nd4jLong offset = xTad.tadOffsets[i]; Nd4jLong yOffset = yTad.tadOffsets[i]; result[i] = OpType::op(x[offset], y[yOffset], localExtraParams); for (int j = 1; j < tadLength; j++) { int xIdx = (offset + xElementWiseStride * j); int yIdx = (yOffset + yElementWiseStride * j); result[i] = OpType::update(result[i], OpType::op(x[xIdx], y[yIdx], localExtraParams), localExtraParams); } result[i] = OpType::postProcess(result[i], tadLength, localExtraParams); if (localExtraParams != nullptr) delete[] localExtraParams; } } else { int tadsPerThread = resultLength / TAD_THRESHOLD; int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread); num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads()); //#pragma omp parallel for schedule(guided) num_threads(num_threads) if (num_threads > 1) proc_bind(AFFINITY) default(shared) for (int i = 0; i < resultLength; i++) { Nd4jLong xOffset = xTadBigger ? xTad.tadOffsets[i] : 0; Nd4jLong yOffset = !xTadBigger ? yTad.tadOffsets[i] : 0; auto xShape = xTadBigger ? xTad.tadShape : shape::shapeOf(xShapeInfo); auto yShape = !xTadBigger ? yTad.tadShape : shape::shapeOf(yShapeInfo); auto xStride = xTadBigger ? xTad.tadStride : shape::stride(xShapeInfo); auto yStride = !xTadBigger ? yTad.tadStride : shape::stride(yShapeInfo); int xRank = xTadBigger ? shape::rank(xTad.tadOnlyShapeInfo) : shape::rank(xShapeInfo); int yRank = !xTadBigger ? shape::rank(yTad.tadOnlyShapeInfo) : shape::rank(yShapeInfo); Nd4jLong coord[MAX_RANK]; Nd4jLong yCoord[MAX_RANK]; T start = 0.0; for (int j = 0; j < tadLength; j++) { if(xTadBigger) { shape::ind2subC(shape::rank(xTad.tadOnlyShapeInfo), xTad.tadStride, j, coord); shape::ind2subC(shape::rank(yShapeInfo), shape::shapeOf(yShapeInfo), j, yCoord); } else { shape::ind2subC(shape::rank(xShapeInfo), shape::shapeOf(xShapeInfo), j, coord); shape::ind2subC(shape::rank(yTad.tadOnlyShapeInfo), yTad.tadShape, j, yCoord); } int xOffset2 = shape::getOffset(xOffset,xShape,xStride,coord,xRank); int yOffset2 = shape::getOffset(yOffset,yShape,yStride,yCoord,yRank); start = OpType::update(start, OpType::op(x[xOffset2], y[yOffset2],extraParams), extraParamsVals); } result[i] = OpType::postProcess(start, shape::length(iterationTadInfo), extraParamsVals); } } } else { shape::TAD xTad(xShapeInfo, dimension, dimensionLength); xTad.createTadOnlyShapeInfo(); xTad.createOffsets(); shape::TAD yTad(yShapeInfo, dimension, dimensionLength); yTad.createTadOnlyShapeInfo(); yTad.createOffsets(); int tadsPerThread = resultLength / TAD_THRESHOLD; int num_threads = nd4j::math::nd4j_max<int>(1, tadsPerThread); num_threads = nd4j::math::nd4j_min<int>(num_threads, omp_get_max_threads()); Nd4jLong coord[MAX_RANK]; //#pragma omp parallel for schedule(guided) num_threads(num_threads) if (num_threads > 1) proc_bind(AFFINITY) default(shared) private(coord) for (int i = 0; i < resultLength; i++) { Nd4jLong xOffset = xTad.tadOffsets[i]; Nd4jLong yOffset = yTad.tadOffsets[i]; T start = OpType::startingValue(x + xOffset); for (int j = 0; j < tadLength; j++) { shape::ind2subC(shape::rank(iterationTadInfo), shape::shapeOf(iterationTadInfo), j, coord); Nd4jLong xOffset2 = shape::getOffset(xOffset,shape::shapeOf(xTad.tadOnlyShapeInfo),shape::stride(xTad.tadOnlyShapeInfo),coord,shape::rank(xTad.tadOnlyShapeInfo)); Nd4jLong yOffset2 = shape::getOffset(yOffset,shape::shapeOf(yTad.tadOnlyShapeInfo),shape::stride(yTad.tadOnlyShapeInfo),coord,shape::rank(yTad.tadOnlyShapeInfo)); start = OpType::update(start, OpType::op(x[xOffset2], y[yOffset2],extraParamsVals), extraParamsVals); } result[i] = OpType::postProcess(start, shape::length(iterationTadInfo), extraParamsVals); } } } } }; } } #ifdef __CUDACC__ /** * The driver api * @param opNum the number * @param n the length of the reduce * @param dx the input data * @param xShapeInfo the shape information * @param dy the pair wise reduce * @param yShapeInfo the shape information for y * @param extraParams the extra parameters in the operation * @param result where to store the result * @param resultShapeInfo the shape information * @param gpuInformation the gpu information * @param dimension the dimension to reduce along long * @param dimensionLength the dimension length * @param postProcessOrNot whether to post */ template <typename T> __device__ void reduce3Generic( const int opNum, T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { __shared__ UnifiedSharedMemory *manager; if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; manager = new(shmem) UnifiedSharedMemory((int *) shmem); manager->init(sizeof(UnifiedSharedMemory), 0, sizeof(functions::reduce3::Reduce3<T>), sizeof(shape::TAD), shape::rank(xShapeInfo)); } __syncthreads(); functions::reduce3::Reduce3<T>::exec( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, manager, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } template <typename T> __device__ void reduce3AllGeneric( const int opNum, T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { __shared__ UnifiedSharedMemory *manager; if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; manager = new(shmem) UnifiedSharedMemory((int *) shmem); manager->init(sizeof(UnifiedSharedMemory), 0, sizeof(functions::reduce3::Reduce3<T>), sizeof(shape::TAD), shape::rank(xShapeInfo)); } __syncthreads(); functions::reduce3::Reduce3<T>::execAllCuda( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, manager, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } template <typename T> __device__ void reduce3ScalarGeneric( int opNum, T *dx, Nd4jLong *xShapeInfo, T *dy, Nd4jLong *yShapeInfo, T *extraParams, T *result, Nd4jLong *resultShapeInfo, int *allocationPointer, T *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { __shared__ UnifiedSharedMemory *manager; if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; manager = new(shmem) UnifiedSharedMemory((int *) shmem); manager->init(sizeof(UnifiedSharedMemory), 0, sizeof(functions::reduce3::Reduce3<T>), sizeof(shape::TAD), shape::rank(xShapeInfo)); } __syncthreads(); functions::reduce3::Reduce3<T>::execScalarCuda( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, allocationPointer, reductionBuffer, manager, tadOnlyShapeInfo); } /** * The driver api * @param opNum the number * @param n the length of the reduce * @param dx the input data * @param xShapeInfo the shape information * @param dy the pair wise reduce * @param yShapeInfo the shape information for y * @param extraParams the extra parameters in the operation * @param result where to store the result * @param resultShapeInfo the shape information * @param dimension the dimension to reduce along long * @param dimensionLength the dimension length * @param postProcessOrNot whether to post [ */ extern "C" __global__ void reduce3Double( int opNum, double *dx, Nd4jLong *xShapeInfo, double *dy, Nd4jLong *yShapeInfo, double *extraParams, double *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3Generic<double>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } extern "C" __global__ void reduce3AllDouble( int opNum, double *dx, Nd4jLong *xShapeInfo, double *dy, Nd4jLong *yShapeInfo, double *extraParams, double *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3AllGeneric<double>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } /** * The driver api * @param opNum the number * @param n the length of the reduce * @param dx the input data * @param xShapeInfo the shape information * @param dy the pair wise reduce * @param yShapeInfo the shape information for y * @param extraParams the extra parameters in the operation * @param result where to store the result * @param resultShapeInfo the shape information * @param gpuInformation the gpu information * @param dimension the dimension to reduce along long * @param dimensionLength the dimension length * @param postProcessOrNot whether to post [ */ extern "C" __global__ void reduce3Float( int opNum, float *dx, Nd4jLong *xShapeInfo, float *dy, Nd4jLong *yShapeInfo, float *extraParams, float *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3Generic<float>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } extern "C" __global__ void reduce3AllFloat( int opNum, float *dx, Nd4jLong *xShapeInfo, float *dy, Nd4jLong *yShapeInfo, float *extraParams, float *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3AllGeneric<float>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } extern "C" __global__ void reduce3Half( int opNum, float16 *dx, Nd4jLong *xShapeInfo, float16 *dy, Nd4jLong *yShapeInfo, float16 *extraParams, float16 *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3Generic<float16>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } extern "C" __global__ void reduce3AllHalf( int opNum, float16 *dx, Nd4jLong *xShapeInfo, float16 *dy, Nd4jLong *yShapeInfo, float16 *extraParams, float16 *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3AllGeneric<float16>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, dimension, dimensionLength, postProcessOrNot, allocationPointer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } extern "C" __global__ void reduce3ScalarFloat( int opNum, float *dx, Nd4jLong *xShapeInfo, float *dy, Nd4jLong *yShapeInfo, float *extraParams, float *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, float *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3ScalarGeneric<float>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, allocationPointer, reductionBuffer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } extern "C" __global__ void reduce3ScalarHalf( int opNum, float16 *dx, Nd4jLong *xShapeInfo, float16 *dy, Nd4jLong *yShapeInfo, float16 *extraParams, float16 *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, float16 *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3ScalarGeneric<float16>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, allocationPointer, reductionBuffer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } extern "C" __global__ void reduce3ScalarDouble( int opNum, double *dx, Nd4jLong *xShapeInfo, double *dy, Nd4jLong *yShapeInfo, double *extraParams, double *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, int postProcessOrNot, int *allocationPointer, double *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets, Nd4jLong *yTadOnlyShapeInfo, Nd4jLong *yTadOffsets) { reduce3ScalarGeneric<double>( opNum, dx, xShapeInfo, dy, yShapeInfo, extraParams, result, resultShapeInfo, allocationPointer, reductionBuffer, tadOnlyShapeInfo, tadOffsets, yTadOnlyShapeInfo, yTadOffsets); } #endif #endif /* REDUCE3_H_ */
region_metrics.h
/* Copyright (c) 2013, Kai Klindworth All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef REGION_METRICS_H #define REGION_METRICS_H #include <utility> #include "sliding_entropy.h" #include <segmentation/intervals.h> #include "costmap_creators.h" #include "costmap_utils.h" #include <segmentation/region_descriptor.h> template<int bins> class region_info_thread { public: fast_array2d<unsigned int, bins, bins> counter_joint; fast_array<unsigned int, bins> counter_array; }; template<typename T, int bins, typename counter, typename joint_counter, typename entropy_type> std::tuple<T, T, T> entropies_calculator(joint_counter& counter_joint, counter& counter_array, const entropy_type& entropy_table, const cv::Mat& base_region, const cv::Mat& match_region) { using entropy_style = costmap_creators::entropy::soft_entropy<T>; using namespace costmap_creators::entropy; entropy_style::calculate_joint_histogramm(counter_joint, base_region.data, match_region.data, base_region.total()); T joint_entropy; if(base_region.total()*entropy_style::kernel_size() > bins*bins) joint_entropy = entropy_style::calculate_joint_entropy(counter_joint, entropy_table, bins); else joint_entropy = entropy_style::calculate_joint_entropy_sparse(counter_joint, entropy_table, bins, base_region.total(), base_region.data, match_region.data); entropy_style::calculate_histogramm(counter_array, base_region.data, base_region.total()); T base_entropy = entropy_style::calculate_entropy(counter_array, entropy_table, bins); entropy_style::calculate_histogramm(counter_array, match_region.data, match_region.total()); T match_entropy = entropy_style::calculate_entropy(counter_array, entropy_table, bins); return std::make_tuple(joint_entropy, base_entropy, match_entropy); } template<typename cost_calc, int quantizer> class region_info_disparity { private: std::vector<float> entropy_table; cost_calc calculator; cv::Mat m_base, m_match; public: using entropy_style = costmap_creators::entropy::soft_entropy<float>; static const int bins = 256/quantizer; typedef region_info_thread<bins+entropy_style::additional_bins()> thread_type; region_info_disparity(const cv::Mat& base, const cv::Mat& match, int size) : m_base(base), m_match(match) { entropy_style::fill_entropytable(entropy_table, size*entropy_style::counter_factor()); } static float normalization_value() { return cost_calc::upper_bound(); } float operator()(thread_type& thread, int d, const std::vector<region_interval>& region) { cv::Mat base_region = region_as_mat(m_base, region, 0); cv::Mat match_region = region_as_mat(m_match, region, d); assert(base_region.total() == match_region.total()); auto result = entropies_calculator<float, bins>(thread.counter_joint, thread.counter_array, entropy_table, base_region, match_region); return cost_calc::calculate(std::get<0>(result), std::get<1>(result), std::get<2>(result)); } }; template<typename cost_type> void region_disparity_internal(std::vector<region_interval>& actual_region, cost_type& cost_agg, typename cost_type::thread_type& thread, disparity_region& cregion, const cv::Mat&, const cv::Mat& match, int dispMin, int dispMax) { int length = size_of_region(actual_region); //cregion.confidence = cv::Mat(dispMax-dispMin+1, 1, CV_32FC1, cv::Scalar(0)); cregion.disparity_costs = cv::Mat(dispMax-dispMin+1, 1, CV_32FC1, cv::Scalar(cost_agg.normalization_value())); float minCost = std::numeric_limits<float>::max(); short minD = cregion.base_disparity; for(int d = dispMin; d <= dispMax; ++d) { std::vector<region_interval> filtered = filtered_region(match.size[1], actual_region, d); int filtered_length = size_of_region(filtered); if((float)filtered_length/(float)length > 0.6f && filtered_length > 10) //0.4 { float cost = cost_agg(thread, d, filtered); assert(d-dispMin >= 0 && d-dispMin < cregion.disparity_costs.size[0]); cregion.disparity_costs(d-dispMin) = cost; if(minCost > cost) { minD = d; minCost = cost; } } } cregion.disparity = minD; } //for IT metrics (region wise) template<typename cost_type> void calculate_region_disparity_regionwise(single_stereo_task& task, const cv::Mat& base, const cv::Mat& match, std::vector<disparity_region>& regions, int delta) { int dilate_step = 2;//FIXME int dilate_max = 4; const std::size_t regions_count = regions.size(); auto it = std::max_element(regions.begin(), regions.end(), [](const disparity_region& lhs, const disparity_region& rhs) { return lhs.m_size < rhs.m_size; }); cost_type cost_agg(base, match, it->size() * 3); typename cost_type::thread_type cost_thread; stat_t cstat; #pragma omp parallel for default(none) shared(task, regions, base, match, delta, cost_agg, dilate_step, dilate_max) private(cost_thread, cstat) for(std::size_t i = 0; i < regions_count; ++i) { disparity_range drange = task_subrange(task, regions[i].base_disparity, delta); regions[i].disparity_offset = drange.start(); for(int dilate = 0; dilate <= dilate_max; dilate += dilate_step) { std::vector<region_interval> actual_pixel_idx = dilated_region(regions[i], dilate, base); region_disparity_internal(actual_pixel_idx, cost_agg, cost_thread, regions[i], base, match, drange.start(), drange.end()); //dilateLR stuff generate_stats(regions[i], cstat); if ( !(cstat.confidence_range == 0 || cstat.confidence_range > 2 || cstat.confidence_variance > 0.2) ) break; } } } #endif // REGION_METRICS_H
lu.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - LU This benchmark is an OpenMP C version of the NPB LU code. The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Information on OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Authors: S. Weeratunga V. Venkatakrishnan E. Barszcz M. Yarrow OpenMP C version: S. Satoh 3.0 structure translation: M. Popov --------------------------------------------------------------------*/ #include "../common/npb-C.h" #include <nautilus/nautilus.h> #include <nautilus/shell.h> #include "../math/nas_math.h" /* global variables */ #include "applu.h" #if defined(_OPENMP) /* for thread synchronization */ static boolean flag[ISIZ1/2*2+1]; #endif /* _OPENMP */ /* function declarations */ static void blts (int nx, int ny, int nz, int k, double omega, double v[ISIZ1][ISIZ2/2*2+1][ISIZ3/2*2+1][5], double ldz[ISIZ1][ISIZ2][5][5], double ldy[ISIZ1][ISIZ2][5][5], double ldx[ISIZ1][ISIZ2][5][5], double d[ISIZ1][ISIZ2][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0 ); static void buts(int nx, int ny, int nz, int k, double omega, double v[ISIZ1][ISIZ2/2*2+1][ISIZ3/2*2+1][5], double tv[ISIZ1][ISIZ2][5], double d[ISIZ1][ISIZ2][5][5], double udx[ISIZ1][ISIZ2][5][5], double udy[ISIZ1][ISIZ2][5][5], double udz[ISIZ1][ISIZ2][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0 ); static void domain(void); static void erhs(void); static void error(void); static void exact( int i, int j, int k, double u000ijk[5] ); static void jacld(int k); static void jacu(int k); static void l2norm (int nx0, int ny0, int nz0, int ist, int iend, int jst, int jend, double v[ISIZ1][ISIZ2/2*2+1][ISIZ3/2*2+1][5], double sum[5]); static void pintgr(void); static void read_input(void); static void rhs(void); static void setbv(void); static void setcoeff(void); static void setiv(void); static void ssor(void); static void verify(double xcr[5], double xce[5], double xci, char *class, boolean *verified); /*-------------------------------------------------------------------- program applu --------------------------------------------------------------------*/ static int program_LU(char *_buf, void* _priv); static struct shell_cmd_impl nas_lu_impl = { .cmd = "nas-lu", .help_str = "NAS parallel benchmark LU", .handler = program_LU, }; nk_register_shell_cmd(nas_lu_impl); int program_LU_profile(char *_, void *__){ #ifdef NAUT_CONFIG_PROFILE nk_instrument_clear(); nk_instrument_start(); #endif program_LU(_,__); #ifdef NAUT_CONFIG_PROFILE nk_instrument_end(); nk_instrument_query(); #endif return 0; } int program_LU(char * _buf, void *_priv) { /*-------------------------------------------------------------------- c c driver for the performance evaluation of the solver for c five coupled parabolic/elliptic partial differential equations. c --------------------------------------------------------------------*/ char class; boolean verified; double mflops; int nthreads = 1; /*-------------------------------------------------------------------- c read input data --------------------------------------------------------------------*/ read_input(); /*-------------------------------------------------------------------- c set up domain sizes --------------------------------------------------------------------*/ domain(); /*-------------------------------------------------------------------- c set up coefficients --------------------------------------------------------------------*/ setcoeff(); /*-------------------------------------------------------------------- c set the boundary values for dependent variables --------------------------------------------------------------------*/ setbv(); /*-------------------------------------------------------------------- c set the initial values for dependent variables --------------------------------------------------------------------*/ setiv(); /*-------------------------------------------------------------------- c compute the forcing term based on prescribed exact solution --------------------------------------------------------------------*/ erhs(); #pragma omp parallel { #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /*-------------------------------------------------------------------- c perform the SSOR iterations --------------------------------------------------------------------*/ ssor(); /*-------------------------------------------------------------------- c compute the solution error --------------------------------------------------------------------*/ error(); /*-------------------------------------------------------------------- c compute the surface integral --------------------------------------------------------------------*/ pintgr(); /*-------------------------------------------------------------------- c verification test --------------------------------------------------------------------*/ verify ( rsdnm, errnm, frc, &class, &verified ); mflops = (double)itmax*(1984.77*(double)nx0 *(double)ny0 *(double)nz0 -10923.3*pow2((double)( nx0+ny0+nz0 )/3.0) +27770.9* (double)( nx0+ny0+nz0 )/3.0 -144010.0) / (maxtime*1000000.0); c_print_results("LU", class, nx0, ny0, nz0, itmax, nthreads, maxtime, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, "(none)"); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void blts (int nx, int ny, int nz, int k, double omega, /*-------------------------------------------------------------------- c To improve cache performance, second two dimensions padded by 1 c for even number sizes only. Only needed in v. --------------------------------------------------------------------*/ double v[ISIZ1][ISIZ2/2*2+1][ISIZ3/2*2+1][5], double ldz[ISIZ1][ISIZ2][5][5], double ldy[ISIZ1][ISIZ2][5][5], double ldx[ISIZ1][ISIZ2][5][5], double d[ISIZ1][ISIZ2][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0 ) { /*-------------------------------------------------------------------- c c compute the regular-sparse, block lower triangular solution: c c v <-- ( L-inv ) * v c --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, m; double tmp, tmp1; double tmat[5][5]; #pragma omp for nowait schedule(static) for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { for (m = 0; m < 5; m++) { v[i][j][k][m] = v[i][j][k][m] - omega * ( ldz[i][j][m][0] * v[i][j][k-1][0] + ldz[i][j][m][1] * v[i][j][k-1][1] + ldz[i][j][m][2] * v[i][j][k-1][2] + ldz[i][j][m][3] * v[i][j][k-1][3] + ldz[i][j][m][4] * v[i][j][k-1][4] ); } } } #pragma omp for nowait schedule(static) for (i = ist; i <= iend; i++) { #if defined(_OPENMP) if (i != ist) { while (flag[i-1] == 0) { #pragma omp flush(flag) ; } } if (i != iend) { while (flag[i] == 1) { #pragma omp flush(flag) ; } } #endif /* _OPENMP */ for (j = jst; j <= jend; j++) { for (m = 0; m < 5; m++) { v[i][j][k][m] = v[i][j][k][m] - omega * ( ldy[i][j][m][0] * v[i][j-1][k][0] + ldx[i][j][m][0] * v[i-1][j][k][0] + ldy[i][j][m][1] * v[i][j-1][k][1] + ldx[i][j][m][1] * v[i-1][j][k][1] + ldy[i][j][m][2] * v[i][j-1][k][2] + ldx[i][j][m][2] * v[i-1][j][k][2] + ldy[i][j][m][3] * v[i][j-1][k][3] + ldx[i][j][m][3] * v[i-1][j][k][3] + ldy[i][j][m][4] * v[i][j-1][k][4] + ldx[i][j][m][4] * v[i-1][j][k][4] ); } /*-------------------------------------------------------------------- c diagonal block inversion c c forward elimination --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { tmat[m][0] = d[i][j][m][0]; tmat[m][1] = d[i][j][m][1]; tmat[m][2] = d[i][j][m][2]; tmat[m][3] = d[i][j][m][3]; tmat[m][4] = d[i][j][m][4]; } tmp1 = 1.0 / tmat[0][0]; tmp = tmp1 * tmat[1][0]; tmat[1][1] = tmat[1][1] - tmp * tmat[0][1]; tmat[1][2] = tmat[1][2] - tmp * tmat[0][2]; tmat[1][3] = tmat[1][3] - tmp * tmat[0][3]; tmat[1][4] = tmat[1][4] - tmp * tmat[0][4]; v[i][j][k][1] = v[i][j][k][1] - v[i][j][k][0] * tmp; tmp = tmp1 * tmat[2][0]; tmat[2][1] = tmat[2][1] - tmp * tmat[0][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[0][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[0][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[0][4]; v[i][j][k][2] = v[i][j][k][2] - v[i][j][k][0] * tmp; tmp = tmp1 * tmat[3][0]; tmat[3][1] = tmat[3][1] - tmp * tmat[0][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[0][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[0][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[0][4]; v[i][j][k][3] = v[i][j][k][3] - v[i][j][k][0] * tmp; tmp = tmp1 * tmat[4][0]; tmat[4][1] = tmat[4][1] - tmp * tmat[0][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[0][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[0][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[0][4]; v[i][j][k][4] = v[i][j][k][4] - v[i][j][k][0] * tmp; tmp1 = 1.0 / tmat[ 1][1]; tmp = tmp1 * tmat[ 2][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[1][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[1][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[1][4]; v[i][j][k][2] = v[i][j][k][2] - v[i][j][k][1] * tmp; tmp = tmp1 * tmat[3][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[1][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[1][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[1][4]; v[i][j][k][3] = v[i][j][k][3] - v[i][j][k][1] * tmp; tmp = tmp1 * tmat[4][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[1][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[1][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[1][4]; v[i][j][k][4] = v[i][j][k][4] - v[i][j][k][1] * tmp; tmp1 = 1.0 / tmat[2][2]; tmp = tmp1 * tmat[3][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[2][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[2][4]; v[i][j][k][3] = v[i][j][k][3] - v[i][j][k][2] * tmp; tmp = tmp1 * tmat[4][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[2][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[2][4]; v[i][j][k][4] = v[i][j][k][4] - v[i][j][k][2] * tmp; tmp1 = 1.0 / tmat[3][3]; tmp = tmp1 * tmat[4][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[3][4]; v[i][j][k][4] = v[i][j][k][4] - v[i][j][k][3] * tmp; /*-------------------------------------------------------------------- c back substitution --------------------------------------------------------------------*/ v[i][j][k][4] = v[i][j][k][4] / tmat[4][4]; v[i][j][k][3] = v[i][j][k][3] - tmat[3][4] * v[i][j][k][4]; v[i][j][k][3] = v[i][j][k][3] / tmat[3][3]; v[i][j][k][2] = v[i][j][k][2] - tmat[2][3] * v[i][j][k][3] - tmat[2][4] * v[i][j][k][4]; v[i][j][k][2] = v[i][j][k][2] / tmat[2][2]; v[i][j][k][1] = v[i][j][k][1] - tmat[1][2] * v[i][j][k][2] - tmat[1][3] * v[i][j][k][3] - tmat[1][4] * v[i][j][k][4]; v[i][j][k][1] = v[i][j][k][1] / tmat[1][1]; v[i][j][k][0] = v[i][j][k][0] - tmat[0][1] * v[i][j][k][1] - tmat[0][2] * v[i][j][k][2] - tmat[0][3] * v[i][j][k][3] - tmat[0][4] * v[i][j][k][4]; v[i][j][k][0] = v[i][j][k][0] / tmat[0][0]; } #if defined(_OPENMP) if (i != ist) flag[i-1] = 0; if (i != iend) flag[i] = 1; #pragma omp flush(flag) #endif /* _OPENMP */ } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void buts(int nx, int ny, int nz, int k, double omega, /*-------------------------------------------------------------------- c To improve cache performance, second two dimensions padded by 1 c for even number sizes only. Only needed in v. --------------------------------------------------------------------*/ double v[ISIZ1][ISIZ2/2*2+1][ISIZ3/2*2+1][5], double tv[ISIZ1][ISIZ2][5], double d[ISIZ1][ISIZ2][5][5], double udx[ISIZ1][ISIZ2][5][5], double udy[ISIZ1][ISIZ2][5][5], double udz[ISIZ1][ISIZ2][5][5], int ist, int iend, int jst, int jend, int nx0, int ny0 ) { /*-------------------------------------------------------------------- c c compute the regular-sparse, block upper triangular solution: c c v <-- ( U-inv ) * v c --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, m; double tmp, tmp1; double tmat[5][5]; #pragma omp for nowait schedule(static) for (i = iend; i >= ist; i--) { for (j = jend; j >= jst; j--) { for (m = 0; m < 5; m++) { tv[i][j][m] = omega * ( udz[i][j][m][0] * v[i][j][k+1][0] + udz[i][j][m][1] * v[i][j][k+1][1] + udz[i][j][m][2] * v[i][j][k+1][2] + udz[i][j][m][3] * v[i][j][k+1][3] + udz[i][j][m][4] * v[i][j][k+1][4] ); } } } #pragma omp for nowait schedule(static) for (i = iend; i >= ist; i--) { #if defined(_OPENMP) if (i != iend) { while (flag[i+1] == 0) { #pragma omp flush(flag) ; } } if (i != ist) { while (flag[i] == 1) { #pragma omp flush(flag) ; } } #endif /* _OPENMP */ for (j = jend; j >= jst; j--) { for (m = 0; m < 5; m++) { tv[i][j][m] = tv[i][j][m] + omega * ( udy[i][j][m][0] * v[i][j+1][k][0] + udx[i][j][m][0] * v[i+1][j][k][0] + udy[i][j][m][1] * v[i][j+1][k][1] + udx[i][j][m][1] * v[i+1][j][k][1] + udy[i][j][m][2] * v[i][j+1][k][2] + udx[i][j][m][2] * v[i+1][j][k][2] + udy[i][j][m][3] * v[i][j+1][k][3] + udx[i][j][m][3] * v[i+1][j][k][3] + udy[i][j][m][4] * v[i][j+1][k][4] + udx[i][j][m][4] * v[i+1][j][k][4] ); } /*-------------------------------------------------------------------- c diagonal block inversion --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { tmat[m][0] = d[i][j][m][0]; tmat[m][1] = d[i][j][m][1]; tmat[m][2] = d[i][j][m][2]; tmat[m][3] = d[i][j][m][3]; tmat[m][4] = d[i][j][m][4]; } tmp1 = 1.0 / tmat[0][0]; tmp = tmp1 * tmat[1][0]; tmat[1][1] = tmat[1][1] - tmp * tmat[0][1]; tmat[1][2] = tmat[1][2] - tmp * tmat[0][2]; tmat[1][3] = tmat[1][3] - tmp * tmat[0][3]; tmat[1][4] = tmat[1][4] - tmp * tmat[0][4]; tv[i][j][1] = tv[i][j][1] - tv[i][j][0] * tmp; tmp = tmp1 * tmat[2][0]; tmat[2][1] = tmat[2][1] - tmp * tmat[0][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[0][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[0][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[0][4]; tv[i][j][2] = tv[i][j][2] - tv[i][j][0] * tmp; tmp = tmp1 * tmat[3][0]; tmat[3][1] = tmat[3][1] - tmp * tmat[0][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[0][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[0][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[0][4]; tv[i][j][3] = tv[i][j][3] - tv[i][j][0] * tmp; tmp = tmp1 * tmat[4][0]; tmat[4][1] = tmat[4][1] - tmp * tmat[0][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[0][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[0][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[0][4]; tv[i][j][4] = tv[i][j][4] - tv[i][j][0] * tmp; tmp1 = 1.0 / tmat[1][1]; tmp = tmp1 * tmat[2][1]; tmat[2][2] = tmat[2][2] - tmp * tmat[1][2]; tmat[2][3] = tmat[2][3] - tmp * tmat[1][3]; tmat[2][4] = tmat[2][4] - tmp * tmat[1][4]; tv[i][j][2] = tv[i][j][2] - tv[i][j][1] * tmp; tmp = tmp1 * tmat[3][1]; tmat[3][2] = tmat[3][2] - tmp * tmat[1][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[1][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[1][4]; tv[i][j][3] = tv[i][j][3] - tv[i][j][1] * tmp; tmp = tmp1 * tmat[4][1]; tmat[4][2] = tmat[4][2] - tmp * tmat[1][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[1][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[1][4]; tv[i][j][4] = tv[i][j][4] - tv[i][j][1] * tmp; tmp1 = 1.0 / tmat[2][2]; tmp = tmp1 * tmat[3][2]; tmat[3][3] = tmat[3][3] - tmp * tmat[2][3]; tmat[3][4] = tmat[3][4] - tmp * tmat[2][4]; tv[i][j][3] = tv[i][j][3] - tv[i][j][2] * tmp; tmp = tmp1 * tmat[4][2]; tmat[4][3] = tmat[4][3] - tmp * tmat[2][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[2][4]; tv[i][j][4] = tv[i][j][4] - tv[i][j][2] * tmp; tmp1 = 1.0 / tmat[3][3]; tmp = tmp1 * tmat[4][3]; tmat[4][4] = tmat[4][4] - tmp * tmat[3][4]; tv[i][j][4] = tv[i][j][4] - tv[i][j][3] * tmp; /*-------------------------------------------------------------------- c back substitution --------------------------------------------------------------------*/ tv[i][j][4] = tv[i][j][4] / tmat[4][4]; tv[i][j][3] = tv[i][j][3] - tmat[3][4] * tv[i][j][4]; tv[i][j][3] = tv[i][j][3] / tmat[3][3]; tv[i][j][2] = tv[i][j][2] - tmat[2][3] * tv[i][j][3] - tmat[2][4] * tv[i][j][4]; tv[i][j][2] = tv[i][j][2] / tmat[2][2]; tv[i][j][1] = tv[i][j][1] - tmat[1][2] * tv[i][j][2] - tmat[1][3] * tv[i][j][3] - tmat[1][4] * tv[i][j][4]; tv[i][j][1] = tv[i][j][1] / tmat[1][1]; tv[i][j][0] = tv[i][j][0] - tmat[0][1] * tv[i][j][1] - tmat[0][2] * tv[i][j][2] - tmat[0][3] * tv[i][j][3] - tmat[0][4] * tv[i][j][4]; tv[i][j][0] = tv[i][j][0] / tmat[0][0]; v[i][j][k][0] = v[i][j][k][0] - tv[i][j][0]; v[i][j][k][1] = v[i][j][k][1] - tv[i][j][1]; v[i][j][k][2] = v[i][j][k][2] - tv[i][j][2]; v[i][j][k][3] = v[i][j][k][3] - tv[i][j][3]; v[i][j][k][4] = v[i][j][k][4] - tv[i][j][4]; } #if defined(_OPENMP) if (i != iend) flag[i+1] = 0; if (i != ist) flag[i] = 1; #pragma omp flush(flag) #endif /* _OPENMP */ } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void domain(void) { /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ nx = nx0; ny = ny0; nz = nz0; /*-------------------------------------------------------------------- c check the sub-domain size --------------------------------------------------------------------*/ if ( nx < 4 || ny < 4 || nz < 4 ) { printf(" SUBDOMAIN SIZE IS TOO SMALL - \n" " ADJUST PROBLEM SIZE OR NUMBER OF PROCESSORS\n" " SO THAT NX, NY AND NZ ARE GREATER THAN OR EQUAL\n" " TO 4 THEY ARE CURRENTLY%3d%3d%3d\n", nx, ny, nz); exit(1); } if ( nx > ISIZ1 || ny > ISIZ2 || nz > ISIZ3 ) { printf(" SUBDOMAIN SIZE IS TOO LARGE - \n" " ADJUST PROBLEM SIZE OR NUMBER OF PROCESSORS\n" " SO THAT NX, NY AND NZ ARE LESS THAN OR EQUAL TO \n" " ISIZ1, ISIZ2 AND ISIZ3 RESPECTIVELY. THEY ARE\n" " CURRENTLY%4d%4d%4d\n", nx, ny, nz); exit(1); } /*-------------------------------------------------------------------- c set up the start and end in i and j extents for all processors --------------------------------------------------------------------*/ ist = 1; iend = nx - 2; jst = 1; jend = ny - 2; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void erhs(void) { #pragma omp parallel { /*-------------------------------------------------------------------- c c compute the right hand side based on exact solution c --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k, m; int iglob, jglob; int L1, L2; int ist1, iend1; int jst1, jend1; double dsspm; double xi, eta, zeta; double q; double u21, u31, u41; double tmp; double u21i, u31i, u41i, u51i; double u21j, u31j, u41j, u51j; double u21k, u31k, u41k, u51k; double u21im1, u31im1, u41im1, u51im1; double u21jm1, u31jm1, u41jm1, u51jm1; double u21km1, u31km1, u41km1, u51km1; dsspm = dssp; #pragma omp for for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { for (k = 0; k < nz; k++) { for (m = 0; m < 5; m++) { frct[i][j][k][m] = 0.0; } } } } #pragma omp for for (i = 0; i < nx; i++) { iglob = i; xi = ( (double)(iglob) ) / ( nx0 - 1 ); for (j = 0; j < ny; j++) { jglob = j; eta = ( (double)(jglob) ) / ( ny0 - 1 ); for (k = 0; k < nz; k++) { zeta = ( (double)(k) ) / ( nz - 1 ); for (m = 0; m < 5; m++) { rsd[i][j][k][m] = ce[m][0] + ce[m][1] * xi + ce[m][2] * eta + ce[m][3] * zeta + ce[m][4] * xi * xi + ce[m][5] * eta * eta + ce[m][6] * zeta * zeta + ce[m][7] * xi * xi * xi + ce[m][8] * eta * eta * eta + ce[m][9] * zeta * zeta * zeta + ce[m][10] * xi * xi * xi * xi + ce[m][11] * eta * eta * eta * eta + ce[m][12] * zeta * zeta * zeta * zeta; } } } } /*-------------------------------------------------------------------- c xi-direction flux differences --------------------------------------------------------------------*/ L1 = 0; L2 = nx-1; #pragma omp for for (i = L1; i <= L2; i++) { for (j = jst; j <= jend; j++) { for (k = 1; k < nz - 1; k++) { flux[i][j][k][0] = rsd[i][j][k][1]; u21 = rsd[i][j][k][1] / rsd[i][j][k][0]; q = 0.50 * ( rsd[i][j][k][1] * rsd[i][j][k][1] + rsd[i][j][k][2] * rsd[i][j][k][2] + rsd[i][j][k][3] * rsd[i][j][k][3] ) / rsd[i][j][k][0]; flux[i][j][k][1] = rsd[i][j][k][1] * u21 + C2 * ( rsd[i][j][k][4] - q ); flux[i][j][k][2] = rsd[i][j][k][2] * u21; flux[i][j][k][3] = rsd[i][j][k][3] * u21; flux[i][j][k][4] = ( C1 * rsd[i][j][k][4] - C2 * q ) * u21; } } } #pragma omp for for (j = jst; j <= jend; j++) { for (k = 1; k <= nz - 2; k++) { for (i = ist; i <= iend; i++) { for (m = 0; m < 5; m++) { frct[i][j][k][m] = frct[i][j][k][m] - tx2 * ( flux[i+1][j][k][m] - flux[i-1][j][k][m] ); } } for (i = ist; i <= L2; i++) { tmp = 1.0 / rsd[i][j][k][0]; u21i = tmp * rsd[i][j][k][1]; u31i = tmp * rsd[i][j][k][2]; u41i = tmp * rsd[i][j][k][3]; u51i = tmp * rsd[i][j][k][4]; tmp = 1.0 / rsd[i-1][j][k][0]; u21im1 = tmp * rsd[i-1][j][k][1]; u31im1 = tmp * rsd[i-1][j][k][2]; u41im1 = tmp * rsd[i-1][j][k][3]; u51im1 = tmp * rsd[i-1][j][k][4]; flux[i][j][k][1] = (4.0/3.0) * tx3 * ( u21i - u21im1 ); flux[i][j][k][2] = tx3 * ( u31i - u31im1 ); flux[i][j][k][3] = tx3 * ( u41i - u41im1 ); flux[i][j][k][4] = 0.50 * ( 1.0 - C1*C5 ) * tx3 * ( ( u21i * u21i + u31i * u31i + u41i * u41i ) - ( u21im1*u21im1 + u31im1*u31im1 + u41im1*u41im1 ) ) + (1.0/6.0) * tx3 * ( u21i*u21i - u21im1*u21im1 ) + C1 * C5 * tx3 * ( u51i - u51im1 ); } for (i = ist; i <= iend; i++) { frct[i][j][k][0] = frct[i][j][k][0] + dx1 * tx1 * ( rsd[i-1][j][k][0] - 2.0 * rsd[i][j][k][0] + rsd[i+1][j][k][0] ); frct[i][j][k][1] = frct[i][j][k][1] + tx3 * C3 * C4 * ( flux[i+1][j][k][1] - flux[i][j][k][1] ) + dx2 * tx1 * ( rsd[i-1][j][k][1] - 2.0 * rsd[i][j][k][1] + rsd[i+1][j][k][1] ); frct[i][j][k][2] = frct[i][j][k][2] + tx3 * C3 * C4 * ( flux[i+1][j][k][2] - flux[i][j][k][2] ) + dx3 * tx1 * ( rsd[i-1][j][k][2] - 2.0 * rsd[i][j][k][2] + rsd[i+1][j][k][2] ); frct[i][j][k][3] = frct[i][j][k][3] + tx3 * C3 * C4 * ( flux[i+1][j][k][3] - flux[i][j][k][3] ) + dx4 * tx1 * ( rsd[i-1][j][k][3] - 2.0 * rsd[i][j][k][3] + rsd[i+1][j][k][3] ); frct[i][j][k][4] = frct[i][j][k][4] + tx3 * C3 * C4 * ( flux[i+1][j][k][4] - flux[i][j][k][4] ) + dx5 * tx1 * ( rsd[i-1][j][k][4] - 2.0 * rsd[i][j][k][4] + rsd[i+1][j][k][4] ); } /*-------------------------------------------------------------------- c Fourth-order dissipation --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { frct[1][j][k][m] = frct[1][j][k][m] - dsspm * ( + 5.0 * rsd[1][j][k][m] - 4.0 * rsd[2][j][k][m] + rsd[3][j][k][m] ); frct[2][j][k][m] = frct[2][j][k][m] - dsspm * ( - 4.0 * rsd[1][j][k][m] + 6.0 * rsd[2][j][k][m] - 4.0 * rsd[3][j][k][m] + rsd[4][j][k][m] ); } ist1 = 3; iend1 = nx - 4; for (i = ist1; i <=iend1; i++) { for (m = 0; m < 5; m++) { frct[i][j][k][m] = frct[i][j][k][m] - dsspm * ( rsd[i-2][j][k][m] - 4.0 * rsd[i-1][j][k][m] + 6.0 * rsd[i][j][k][m] - 4.0 * rsd[i+1][j][k][m] + rsd[i+2][j][k][m] ); } } for (m = 0; m < 5; m++) { frct[nx-3][j][k][m] = frct[nx-3][j][k][m] - dsspm * ( rsd[nx-5][j][k][m] - 4.0 * rsd[nx-4][j][k][m] + 6.0 * rsd[nx-3][j][k][m] - 4.0 * rsd[nx-2][j][k][m] ); frct[nx-2][j][k][m] = frct[nx-2][j][k][m] - dsspm * ( rsd[nx-4][j][k][m] - 4.0 * rsd[nx-3][j][k][m] + 5.0 * rsd[nx-2][j][k][m] ); } } } /*-------------------------------------------------------------------- c eta-direction flux differences --------------------------------------------------------------------*/ L1 = 0; L2 = ny-1; #pragma omp for for (i = ist; i <= iend; i++) { for (j = L1; j <= L2; j++) { for (k = 1; k <= nz - 2; k++) { flux[i][j][k][0] = rsd[i][j][k][2]; u31 = rsd[i][j][k][2] / rsd[i][j][k][0]; q = 0.50 * ( rsd[i][j][k][1] * rsd[i][j][k][1] + rsd[i][j][k][2] * rsd[i][j][k][2] + rsd[i][j][k][3] * rsd[i][j][k][3] ) / rsd[i][j][k][0]; flux[i][j][k][1] = rsd[i][j][k][1] * u31; flux[i][j][k][2] = rsd[i][j][k][2] * u31 + C2 * ( rsd[i][j][k][4] - q ); flux[i][j][k][3] = rsd[i][j][k][3] * u31; flux[i][j][k][4] = ( C1 * rsd[i][j][k][4] - C2 * q ) * u31; } } } #pragma omp for for (i = ist; i <= iend; i++) { for (k = 1; k <= nz - 2; k++) { for (j = jst; j <= jend; j++) { for (m = 0; m < 5; m++) { frct[i][j][k][m] = frct[i][j][k][m] - ty2 * ( flux[i][j+1][k][m] - flux[i][j-1][k][m] ); } } for (j = jst; j <= L2; j++) { tmp = 1.0 / rsd[i][j][k][0]; u21j = tmp * rsd[i][j][k][1]; u31j = tmp * rsd[i][j][k][2]; u41j = tmp * rsd[i][j][k][3]; u51j = tmp * rsd[i][j][k][4]; tmp = 1.0 / rsd[i][j-1][k][0]; u21jm1 = tmp * rsd[i][j-1][k][1]; u31jm1 = tmp * rsd[i][j-1][k][2]; u41jm1 = tmp * rsd[i][j-1][k][3]; u51jm1 = tmp * rsd[i][j-1][k][4]; flux[i][j][k][1] = ty3 * ( u21j - u21jm1 ); flux[i][j][k][2] = (4.0/3.0) * ty3 * ( u31j - u31jm1 ); flux[i][j][k][3] = ty3 * ( u41j - u41jm1 ); flux[i][j][k][4] = 0.50 * ( 1.0 - C1*C5 ) * ty3 * ( ( u21j *u21j + u31j *u31j + u41j *u41j ) - ( u21jm1*u21jm1 + u31jm1*u31jm1 + u41jm1*u41jm1 ) ) + (1.0/6.0) * ty3 * ( u31j*u31j - u31jm1*u31jm1 ) + C1 * C5 * ty3 * ( u51j - u51jm1 ); } for (j = jst; j <= jend; j++) { frct[i][j][k][0] = frct[i][j][k][0] + dy1 * ty1 * ( rsd[i][j-1][k][0] - 2.0 * rsd[i][j][k][0] + rsd[i][j+1][k][0] ); frct[i][j][k][1] = frct[i][j][k][1] + ty3 * C3 * C4 * ( flux[i][j+1][k][1] - flux[i][j][k][1] ) + dy2 * ty1 * ( rsd[i][j-1][k][1] - 2.0 * rsd[i][j][k][1] + rsd[i][j+1][k][1] ); frct[i][j][k][2] = frct[i][j][k][2] + ty3 * C3 * C4 * ( flux[i][j+1][k][2] - flux[i][j][k][2] ) + dy3 * ty1 * ( rsd[i][j-1][k][2] - 2.0 * rsd[i][j][k][2] + rsd[i][j+1][k][2] ); frct[i][j][k][3] = frct[i][j][k][3] + ty3 * C3 * C4 * ( flux[i][j+1][k][3] - flux[i][j][k][3] ) + dy4 * ty1 * ( rsd[i][j-1][k][3] - 2.0 * rsd[i][j][k][3] + rsd[i][j+1][k][3] ); frct[i][j][k][4] = frct[i][j][k][4] + ty3 * C3 * C4 * ( flux[i][j+1][k][4] - flux[i][j][k][4] ) + dy5 * ty1 * ( rsd[i][j-1][k][4] - 2.0 * rsd[i][j][k][4] + rsd[i][j+1][k][4] ); } /*-------------------------------------------------------------------- c fourth-order dissipation --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { frct[i][1][k][m] = frct[i][1][k][m] - dsspm * ( + 5.0 * rsd[i][1][k][m] - 4.0 * rsd[i][2][k][m] + rsd[i][3][k][m] ); frct[i][2][k][m] = frct[i][2][k][m] - dsspm * ( - 4.0 * rsd[i][1][k][m] + 6.0 * rsd[i][2][k][m] - 4.0 * rsd[i][3][k][m] + rsd[i][4][k][m] ); } jst1 = 3; jend1 = ny - 4; for (j = jst1; j <= jend1; j++) { for (m = 0; m < 5; m++) { frct[i][j][k][m] = frct[i][j][k][m] - dsspm * ( rsd[i][j-2][k][m] - 4.0 * rsd[i][j-1][k][m] + 6.0 * rsd[i][j][k][m] - 4.0 * rsd[i][j+1][k][m] + rsd[i][j+2][k][m] ); } } for (m = 0; m < 5; m++) { frct[i][ny-3][k][m] = frct[i][ny-3][k][m] - dsspm * ( rsd[i][ny-5][k][m] - 4.0 * rsd[i][ny-4][k][m] + 6.0 * rsd[i][ny-3][k][m] - 4.0 * rsd[i][ny-2][k][m] ); frct[i][ny-2][k][m] = frct[i][ny-2][k][m] - dsspm * ( rsd[i][ny-4][k][m] - 4.0 * rsd[i][ny-3][k][m] + 5.0 * rsd[i][ny-2][k][m] ); } } } /*-------------------------------------------------------------------- c zeta-direction flux differences --------------------------------------------------------------------*/ #pragma omp for for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { for (k = 0; k <= nz-1; k++) { flux[i][j][k][0] = rsd[i][j][k][3]; u41 = rsd[i][j][k][3] / rsd[i][j][k][0]; q = 0.50 * ( rsd[i][j][k][1] * rsd[i][j][k][1] + rsd[i][j][k][2] * rsd[i][j][k][2] + rsd[i][j][k][3] * rsd[i][j][k][3] ) / rsd[i][j][k][0]; flux[i][j][k][1] = rsd[i][j][k][1] * u41; flux[i][j][k][2] = rsd[i][j][k][2] * u41; flux[i][j][k][3] = rsd[i][j][k][3] * u41 + C2 * ( rsd[i][j][k][4] - q ); flux[i][j][k][4] = ( C1 * rsd[i][j][k][4] - C2 * q ) * u41; } for (k = 1; k <= nz - 2; k++) { for (m = 0; m < 5; m++) { frct[i][j][k][m] = frct[i][j][k][m] - tz2 * ( flux[i][j][k+1][m] - flux[i][j][k-1][m] ); } } for (k = 1; k <= nz-1; k++) { tmp = 1.0 / rsd[i][j][k][0]; u21k = tmp * rsd[i][j][k][1]; u31k = tmp * rsd[i][j][k][2]; u41k = tmp * rsd[i][j][k][3]; u51k = tmp * rsd[i][j][k][4]; tmp = 1.0 / rsd[i][j][k-1][0]; u21km1 = tmp * rsd[i][j][k-1][1]; u31km1 = tmp * rsd[i][j][k-1][2]; u41km1 = tmp * rsd[i][j][k-1][3]; u51km1 = tmp * rsd[i][j][k-1][4]; flux[i][j][k][1] = tz3 * ( u21k - u21km1 ); flux[i][j][k][2] = tz3 * ( u31k - u31km1 ); flux[i][j][k][3] = (4.0/3.0) * tz3 * ( u41k - u41km1 ); flux[i][j][k][4] = 0.50 * ( 1.0 - C1*C5 ) * tz3 * ( ( u21k *u21k + u31k *u31k + u41k *u41k ) - ( u21km1*u21km1 + u31km1*u31km1 + u41km1*u41km1 ) ) + (1.0/6.0) * tz3 * ( u41k*u41k - u41km1*u41km1 ) + C1 * C5 * tz3 * ( u51k - u51km1 ); } for (k = 1; k <= nz - 2; k++) { frct[i][j][k][0] = frct[i][j][k][0] + dz1 * tz1 * ( rsd[i][j][k+1][0] - 2.0 * rsd[i][j][k][0] + rsd[i][j][k-1][0] ); frct[i][j][k][1] = frct[i][j][k][1] + tz3 * C3 * C4 * ( flux[i][j][k+1][1] - flux[i][j][k][1] ) + dz2 * tz1 * ( rsd[i][j][k+1][1] - 2.0 * rsd[i][j][k][1] + rsd[i][j][k-1][1] ); frct[i][j][k][2] = frct[i][j][k][2] + tz3 * C3 * C4 * ( flux[i][j][k+1][2] - flux[i][j][k][2] ) + dz3 * tz1 * ( rsd[i][j][k+1][2] - 2.0 * rsd[i][j][k][2] + rsd[i][j][k-1][2] ); frct[i][j][k][3] = frct[i][j][k][3] + tz3 * C3 * C4 * ( flux[i][j][k+1][3] - flux[i][j][k][3] ) + dz4 * tz1 * ( rsd[i][j][k+1][3] - 2.0 * rsd[i][j][k][3] + rsd[i][j][k-1][3] ); frct[i][j][k][4] = frct[i][j][k][4] + tz3 * C3 * C4 * ( flux[i][j][k+1][4] - flux[i][j][k][4] ) + dz5 * tz1 * ( rsd[i][j][k+1][4] - 2.0 * rsd[i][j][k][4] + rsd[i][j][k-1][4] ); } /*-------------------------------------------------------------------- c fourth-order dissipation --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { frct[i][j][1][m] = frct[i][j][1][m] - dsspm * ( + 5.0 * rsd[i][j][1][m] - 4.0 * rsd[i][j][2][m] + rsd[i][j][3][m] ); frct[i][j][2][m] = frct[i][j][2][m] - dsspm * (- 4.0 * rsd[i][j][1][m] + 6.0 * rsd[i][j][2][m] - 4.0 * rsd[i][j][3][m] + rsd[i][j][4][m] ); } for (k = 3; k <= nz - 4; k++) { for (m = 0; m < 5; m++) { frct[i][j][k][m] = frct[i][j][k][m] - dsspm * ( rsd[i][j][k-2][m] - 4.0 * rsd[i][j][k-1][m] + 6.0 * rsd[i][j][k][m] - 4.0 * rsd[i][j][k+1][m] + rsd[i][j][k+2][m] ); } } for (m = 0; m < 5; m++) { frct[i][j][nz-3][m] = frct[i][j][nz-3][m] - dsspm * ( rsd[i][j][nz-5][m] - 4.0 * rsd[i][j][nz-4][m] + 6.0 * rsd[i][j][nz-3][m] - 4.0 * rsd[i][j][nz-2][m] ); frct[i][j][nz-2][m] = frct[i][j][nz-2][m] - dsspm * ( rsd[i][j][nz-4][m] - 4.0 * rsd[i][j][nz-3][m] + 5.0 * rsd[i][j][nz-2][m] ); } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void error(void) { /*-------------------------------------------------------------------- c c compute the solution error c --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k, m; int iglob, jglob; double tmp; double u000ijk[5]; for (m = 0; m < 5; m++) { errnm[m] = 0.0; } for (i = ist; i <= iend; i++) { iglob = i; for (j = jst; j <= jend; j++) { jglob = j; for (k = 1; k <= nz-2; k++) { exact( iglob, jglob, k, u000ijk ); for (m = 0; m < 5; m++) { tmp = ( u000ijk[m] - u[i][j][k][m] ); errnm[m] = errnm[m] + tmp *tmp; } } } } for (m = 0; m < 5; m++) { errnm[m] = sqrt ( errnm[m] / ( (nx0-2)*(ny0-2)*(nz0-2) ) ); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact( int i, int j, int k, double u000ijk[5] ) { /*-------------------------------------------------------------------- c c compute the exact solution at (i,j,k) c --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int m; double xi, eta, zeta; xi = ((double)i) / (nx0 - 1); eta = ((double)j) / (ny0 - 1); zeta = ((double)k) / (nz - 1); for (m = 0; m < 5; m++) { u000ijk[m] = ce[m][0] + ce[m][1] * xi + ce[m][2] * eta + ce[m][3] * zeta + ce[m][4] * xi * xi + ce[m][5] * eta * eta + ce[m][6] * zeta * zeta + ce[m][7] * xi * xi * xi + ce[m][8] * eta * eta * eta + ce[m][9] * zeta * zeta * zeta + ce[m][10] * xi * xi * xi * xi + ce[m][11] * eta * eta * eta * eta + ce[m][12] * zeta * zeta * zeta * zeta; } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void jacld(int k) { /*-------------------------------------------------------------------- c compute the lower triangular part of the jacobian matrix --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j; double r43; double c1345; double c34; double tmp1, tmp2, tmp3; r43 = ( 4.0 / 3.0 ); c1345 = C1 * C3 * C4 * C5; c34 = C3 * C4; #pragma omp for nowait schedule(static) for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { /*-------------------------------------------------------------------- c form the block daigonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i][j][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; d[i][j][0][0] = 1.0 + dt * 2.0 * ( tx1 * dx1 + ty1 * dy1 + tz1 * dz1 ); d[i][j][0][1] = 0.0; d[i][j][0][2] = 0.0; d[i][j][0][3] = 0.0; d[i][j][0][4] = 0.0; d[i][j][1][0] = dt * 2.0 * ( tx1 * ( - r43 * c34 * tmp2 * u[i][j][k][1] ) + ty1 * ( - c34 * tmp2 * u[i][j][k][1] ) + tz1 * ( - c34 * tmp2 * u[i][j][k][1] ) ); d[i][j][1][1] = 1.0 + dt * 2.0 * ( tx1 * r43 * c34 * tmp1 + ty1 * c34 * tmp1 + tz1 * c34 * tmp1 ) + dt * 2.0 * ( tx1 * dx2 + ty1 * dy2 + tz1 * dz2 ); d[i][j][1][2] = 0.0; d[i][j][1][3] = 0.0; d[i][j][1][4] = 0.0; d[i][j][2][0] = dt * 2.0 * ( tx1 * ( - c34 * tmp2 * u[i][j][k][2] ) + ty1 * ( - r43 * c34 * tmp2 * u[i][j][k][2] ) + tz1 * ( - c34 * tmp2 * u[i][j][k][2] ) ); d[i][j][2][1] = 0.0; d[i][j][2][2] = 1.0 + dt * 2.0 * ( tx1 * c34 * tmp1 + ty1 * r43 * c34 * tmp1 + tz1 * c34 * tmp1 ) + dt * 2.0 * ( tx1 * dx3 + ty1 * dy3 + tz1 * dz3 ); d[i][j][2][3] = 0.0; d[i][j][2][4] = 0.0; d[i][j][3][0] = dt * 2.0 * ( tx1 * ( - c34 * tmp2 * u[i][j][k][3] ) + ty1 * ( - c34 * tmp2 * u[i][j][k][3] ) + tz1 * ( - r43 * c34 * tmp2 * u[i][j][k][3] ) ); d[i][j][3][1] = 0.0; d[i][j][3][2] = 0.0; d[i][j][3][3] = 1.0 + dt * 2.0 * ( tx1 * c34 * tmp1 + ty1 * c34 * tmp1 + tz1 * r43 * c34 * tmp1 ) + dt * 2.0 * ( tx1 * dx4 + ty1 * dy4 + tz1 * dz4 ); d[i][j][3][4] = 0.0; d[i][j][4][0] = dt * 2.0 * ( tx1 * ( - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][1]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][2]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][3]) ) - ( c1345 ) * tmp2 * u[i][j][k][4] ) + ty1 * ( - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][1]) ) - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][2]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][3]) ) - ( c1345 ) * tmp2 * u[i][j][k][4] ) + tz1 * ( - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][1]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][2]) ) - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][3]) ) - ( c1345 ) * tmp2 * u[i][j][k][4] ) ); d[i][j][4][1] = dt * 2.0 * ( tx1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j][k][1] + ty1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][1] + tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][1] ); d[i][j][4][2] = dt * 2.0 * ( tx1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][2] + ty1 * ( r43*c34 -c1345 ) * tmp2 * u[i][j][k][2] + tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][2] ); d[i][j][4][3] = dt * 2.0 * ( tx1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][3] + ty1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][3] + tz1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j][k][3] ); d[i][j][4][4] = 1.0 + dt * 2.0 * ( tx1 * c1345 * tmp1 + ty1 * c1345 * tmp1 + tz1 * c1345 * tmp1 ) + dt * 2.0 * ( tx1 * dx5 + ty1 * dy5 + tz1 * dz5 ); /*-------------------------------------------------------------------- c form the first block sub-diagonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i][j][k-1][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; a[i][j][0][0] = - dt * tz1 * dz1; a[i][j][0][1] = 0.0; a[i][j][0][2] = 0.0; a[i][j][0][3] = - dt * tz2; a[i][j][0][4] = 0.0; a[i][j][1][0] = - dt * tz2 * ( - ( u[i][j][k-1][1]*u[i][j][k-1][3] ) * tmp2 ) - dt * tz1 * ( - c34 * tmp2 * u[i][j][k-1][1] ); a[i][j][1][1] = - dt * tz2 * ( u[i][j][k-1][3] * tmp1 ) - dt * tz1 * c34 * tmp1 - dt * tz1 * dz2 ; a[i][j][1][2] = 0.0; a[i][j][1][3] = - dt * tz2 * ( u[i][j][k-1][1] * tmp1 ); a[i][j][1][4] = 0.0; a[i][j][2][0] = - dt * tz2 * ( - ( u[i][j][k-1][2]*u[i][j][k-1][3] ) * tmp2 ) - dt * tz1 * ( - c34 * tmp2 * u[i][j][k-1][2] ); a[i][j][2][1] = 0.0; a[i][j][2][2] = - dt * tz2 * ( u[i][j][k-1][3] * tmp1 ) - dt * tz1 * ( c34 * tmp1 ) - dt * tz1 * dz3; a[i][j][2][3] = - dt * tz2 * ( u[i][j][k-1][2] * tmp1 ); a[i][j][2][4] = 0.0; a[i][j][3][0] = - dt * tz2 * ( - ( u[i][j][k-1][3] * tmp1 ) *( u[i][j][k-1][3] * tmp1 ) + 0.50 * C2 * ( ( u[i][j][k-1][1] * u[i][j][k-1][1] + u[i][j][k-1][2] * u[i][j][k-1][2] + u[i][j][k-1][3] * u[i][j][k-1][3] ) * tmp2 ) ) - dt * tz1 * ( - r43 * c34 * tmp2 * u[i][j][k-1][3] ); a[i][j][3][1] = - dt * tz2 * ( - C2 * ( u[i][j][k-1][1] * tmp1 ) ); a[i][j][3][2] = - dt * tz2 * ( - C2 * ( u[i][j][k-1][2] * tmp1 ) ); a[i][j][3][3] = - dt * tz2 * ( 2.0 - C2 ) * ( u[i][j][k-1][3] * tmp1 ) - dt * tz1 * ( r43 * c34 * tmp1 ) - dt * tz1 * dz4; a[i][j][3][4] = - dt * tz2 * C2; a[i][j][4][0] = - dt * tz2 * ( ( C2 * ( u[i][j][k-1][1] * u[i][j][k-1][1] + u[i][j][k-1][2] * u[i][j][k-1][2] + u[i][j][k-1][3] * u[i][j][k-1][3] ) * tmp2 - C1 * ( u[i][j][k-1][4] * tmp1 ) ) * ( u[i][j][k-1][3] * tmp1 ) ) - dt * tz1 * ( - ( c34 - c1345 ) * tmp3 * (u[i][j][k-1][1]*u[i][j][k-1][1]) - ( c34 - c1345 ) * tmp3 * (u[i][j][k-1][2]*u[i][j][k-1][2]) - ( r43*c34 - c1345 )* tmp3 * (u[i][j][k-1][3]*u[i][j][k-1][3]) - c1345 * tmp2 * u[i][j][k-1][4] ); a[i][j][4][1] = - dt * tz2 * ( - C2 * ( u[i][j][k-1][1]*u[i][j][k-1][3] ) * tmp2 ) - dt * tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k-1][1]; a[i][j][4][2] = - dt * tz2 * ( - C2 * ( u[i][j][k-1][2]*u[i][j][k-1][3] ) * tmp2 ) - dt * tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k-1][2]; a[i][j][4][3] = - dt * tz2 * ( C1 * ( u[i][j][k-1][4] * tmp1 ) - 0.50 * C2 * ( ( u[i][j][k-1][1]*u[i][j][k-1][1] + u[i][j][k-1][2]*u[i][j][k-1][2] + 3.0*u[i][j][k-1][3]*u[i][j][k-1][3] ) * tmp2 ) ) - dt * tz1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j][k-1][3]; a[i][j][4][4] = - dt * tz2 * ( C1 * ( u[i][j][k-1][3] * tmp1 ) ) - dt * tz1 * c1345 * tmp1 - dt * tz1 * dz5; /*-------------------------------------------------------------------- c form the second block sub-diagonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i][j-1][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; b[i][j][0][0] = - dt * ty1 * dy1; b[i][j][0][1] = 0.0; b[i][j][0][2] = - dt * ty2; b[i][j][0][3] = 0.0; b[i][j][0][4] = 0.0; b[i][j][1][0] = - dt * ty2 * ( - ( u[i][j-1][k][1]*u[i][j-1][k][2] ) * tmp2 ) - dt * ty1 * ( - c34 * tmp2 * u[i][j-1][k][1] ); b[i][j][1][1] = - dt * ty2 * ( u[i][j-1][k][2] * tmp1 ) - dt * ty1 * ( c34 * tmp1 ) - dt * ty1 * dy2; b[i][j][1][2] = - dt * ty2 * ( u[i][j-1][k][1] * tmp1 ); b[i][j][1][3] = 0.0; b[i][j][1][4] = 0.0; b[i][j][2][0] = - dt * ty2 * ( - ( u[i][j-1][k][2] * tmp1 ) *( u[i][j-1][k][2] * tmp1 ) + 0.50 * C2 * ( ( u[i][j-1][k][1] * u[i][j-1][k][1] + u[i][j-1][k][2] * u[i][j-1][k][2] + u[i][j-1][k][3] * u[i][j-1][k][3] ) * tmp2 ) ) - dt * ty1 * ( - r43 * c34 * tmp2 * u[i][j-1][k][2] ); b[i][j][2][1] = - dt * ty2 * ( - C2 * ( u[i][j-1][k][1] * tmp1 ) ); b[i][j][2][2] = - dt * ty2 * ( ( 2.0 - C2 ) * ( u[i][j-1][k][2] * tmp1 ) ) - dt * ty1 * ( r43 * c34 * tmp1 ) - dt * ty1 * dy3; b[i][j][2][3] = - dt * ty2 * ( - C2 * ( u[i][j-1][k][3] * tmp1 ) ); b[i][j][2][4] = - dt * ty2 * C2; b[i][j][3][0] = - dt * ty2 * ( - ( u[i][j-1][k][2]*u[i][j-1][k][3] ) * tmp2 ) - dt * ty1 * ( - c34 * tmp2 * u[i][j-1][k][3] ); b[i][j][3][1] = 0.0; b[i][j][3][2] = - dt * ty2 * ( u[i][j-1][k][3] * tmp1 ); b[i][j][3][3] = - dt * ty2 * ( u[i][j-1][k][2] * tmp1 ) - dt * ty1 * ( c34 * tmp1 ) - dt * ty1 * dy4; b[i][j][3][4] = 0.0; b[i][j][4][0] = - dt * ty2 * ( ( C2 * ( u[i][j-1][k][1] * u[i][j-1][k][1] + u[i][j-1][k][2] * u[i][j-1][k][2] + u[i][j-1][k][3] * u[i][j-1][k][3] ) * tmp2 - C1 * ( u[i][j-1][k][4] * tmp1 ) ) * ( u[i][j-1][k][2] * tmp1 ) ) - dt * ty1 * ( - ( c34 - c1345 )*tmp3*(pow2(u[i][j-1][k][1])) - ( r43*c34 - c1345 )*tmp3*(pow2(u[i][j-1][k][2])) - ( c34 - c1345 )*tmp3*(pow2(u[i][j-1][k][3])) - c1345*tmp2*u[i][j-1][k][4] ); b[i][j][4][1] = - dt * ty2 * ( - C2 * ( u[i][j-1][k][1]*u[i][j-1][k][2] ) * tmp2 ) - dt * ty1 * ( c34 - c1345 ) * tmp2 * u[i][j-1][k][1]; b[i][j][4][2] = - dt * ty2 * ( C1 * ( u[i][j-1][k][4] * tmp1 ) - 0.50 * C2 * ( ( u[i][j-1][k][1]*u[i][j-1][k][1] + 3.0 * u[i][j-1][k][2]*u[i][j-1][k][2] + u[i][j-1][k][3]*u[i][j-1][k][3] ) * tmp2 ) ) - dt * ty1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j-1][k][2]; b[i][j][4][3] = - dt * ty2 * ( - C2 * ( u[i][j-1][k][2]*u[i][j-1][k][3] ) * tmp2 ) - dt * ty1 * ( c34 - c1345 ) * tmp2 * u[i][j-1][k][3]; b[i][j][4][4] = - dt * ty2 * ( C1 * ( u[i][j-1][k][2] * tmp1 ) ) - dt * ty1 * c1345 * tmp1 - dt * ty1 * dy5; /*-------------------------------------------------------------------- c form the third block sub-diagonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i-1][j][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; c[i][j][0][0] = - dt * tx1 * dx1; c[i][j][0][1] = - dt * tx2; c[i][j][0][2] = 0.0; c[i][j][0][3] = 0.0; c[i][j][0][4] = 0.0; c[i][j][1][0] = - dt * tx2 * ( - ( u[i-1][j][k][1] * tmp1 ) *( u[i-1][j][k][1] * tmp1 ) + C2 * 0.50 * ( u[i-1][j][k][1] * u[i-1][j][k][1] + u[i-1][j][k][2] * u[i-1][j][k][2] + u[i-1][j][k][3] * u[i-1][j][k][3] ) * tmp2 ) - dt * tx1 * ( - r43 * c34 * tmp2 * u[i-1][j][k][1] ); c[i][j][1][1] = - dt * tx2 * ( ( 2.0 - C2 ) * ( u[i-1][j][k][1] * tmp1 ) ) - dt * tx1 * ( r43 * c34 * tmp1 ) - dt * tx1 * dx2; c[i][j][1][2] = - dt * tx2 * ( - C2 * ( u[i-1][j][k][2] * tmp1 ) ); c[i][j][1][3] = - dt * tx2 * ( - C2 * ( u[i-1][j][k][3] * tmp1 ) ); c[i][j][1][4] = - dt * tx2 * C2; c[i][j][2][0] = - dt * tx2 * ( - ( u[i-1][j][k][1] * u[i-1][j][k][2] ) * tmp2 ) - dt * tx1 * ( - c34 * tmp2 * u[i-1][j][k][2] ); c[i][j][2][1] = - dt * tx2 * ( u[i-1][j][k][2] * tmp1 ); c[i][j][2][2] = - dt * tx2 * ( u[i-1][j][k][1] * tmp1 ) - dt * tx1 * ( c34 * tmp1 ) - dt * tx1 * dx3; c[i][j][2][3] = 0.0; c[i][j][2][4] = 0.0; c[i][j][3][0] = - dt * tx2 * ( - ( u[i-1][j][k][1]*u[i-1][j][k][3] ) * tmp2 ) - dt * tx1 * ( - c34 * tmp2 * u[i-1][j][k][3] ); c[i][j][3][1] = - dt * tx2 * ( u[i-1][j][k][3] * tmp1 ); c[i][j][3][2] = 0.0; c[i][j][3][3] = - dt * tx2 * ( u[i-1][j][k][1] * tmp1 ) - dt * tx1 * ( c34 * tmp1 ) - dt * tx1 * dx4; c[i][j][3][4] = 0.0; c[i][j][4][0] = - dt * tx2 * ( ( C2 * ( u[i-1][j][k][1] * u[i-1][j][k][1] + u[i-1][j][k][2] * u[i-1][j][k][2] + u[i-1][j][k][3] * u[i-1][j][k][3] ) * tmp2 - C1 * ( u[i-1][j][k][4] * tmp1 ) ) * ( u[i-1][j][k][1] * tmp1 ) ) - dt * tx1 * ( - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i-1][j][k][1]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i-1][j][k][2]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i-1][j][k][3]) ) - c1345 * tmp2 * u[i-1][j][k][4] ); c[i][j][4][1] = - dt * tx2 * ( C1 * ( u[i-1][j][k][4] * tmp1 ) - 0.50 * C2 * ( ( 3.0*u[i-1][j][k][1]*u[i-1][j][k][1] + u[i-1][j][k][2]*u[i-1][j][k][2] + u[i-1][j][k][3]*u[i-1][j][k][3] ) * tmp2 ) ) - dt * tx1 * ( r43*c34 - c1345 ) * tmp2 * u[i-1][j][k][1]; c[i][j][4][2] = - dt * tx2 * ( - C2 * ( u[i-1][j][k][2]*u[i-1][j][k][1] ) * tmp2 ) - dt * tx1 * ( c34 - c1345 ) * tmp2 * u[i-1][j][k][2]; c[i][j][4][3] = - dt * tx2 * ( - C2 * ( u[i-1][j][k][3]*u[i-1][j][k][1] ) * tmp2 ) - dt * tx1 * ( c34 - c1345 ) * tmp2 * u[i-1][j][k][3]; c[i][j][4][4] = - dt * tx2 * ( C1 * ( u[i-1][j][k][1] * tmp1 ) ) - dt * tx1 * c1345 * tmp1 - dt * tx1 * dx5; } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void jacu(int k) { /*-------------------------------------------------------------------- c compute the upper triangular part of the jacobian matrix --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j; double r43; double c1345; double c34; double tmp1, tmp2, tmp3; r43 = ( 4.0 / 3.0 ); c1345 = C1 * C3 * C4 * C5; c34 = C3 * C4; #pragma omp for nowait schedule(static) #if defined(_OPENMP) for (i = iend; i >= ist; i--) { for (j = jend; j >= jst; j--) { #else for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { #endif /*-------------------------------------------------------------------- c form the block daigonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i][j][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; d[i][j][0][0] = 1.0 + dt * 2.0 * ( tx1 * dx1 + ty1 * dy1 + tz1 * dz1 ); d[i][j][0][1] = 0.0; d[i][j][0][2] = 0.0; d[i][j][0][3] = 0.0; d[i][j][0][4] = 0.0; d[i][j][1][0] = dt * 2.0 * ( tx1 * ( - r43 * c34 * tmp2 * u[i][j][k][1] ) + ty1 * ( - c34 * tmp2 * u[i][j][k][1] ) + tz1 * ( - c34 * tmp2 * u[i][j][k][1] ) ); d[i][j][1][1] = 1.0 + dt * 2.0 * ( tx1 * r43 * c34 * tmp1 + ty1 * c34 * tmp1 + tz1 * c34 * tmp1 ) + dt * 2.0 * ( tx1 * dx2 + ty1 * dy2 + tz1 * dz2 ); d[i][j][1][2] = 0.0; d[i][j][1][3] = 0.0; d[i][j][1][4] = 0.0; d[i][j][2][0] = dt * 2.0 * ( tx1 * ( - c34 * tmp2 * u[i][j][k][2] ) + ty1 * ( - r43 * c34 * tmp2 * u[i][j][k][2] ) + tz1 * ( - c34 * tmp2 * u[i][j][k][2] ) ); d[i][j][2][1] = 0.0; d[i][j][2][2] = 1.0 + dt * 2.0 * ( tx1 * c34 * tmp1 + ty1 * r43 * c34 * tmp1 + tz1 * c34 * tmp1 ) + dt * 2.0 * ( tx1 * dx3 + ty1 * dy3 + tz1 * dz3 ); d[i][j][2][3] = 0.0; d[i][j][2][4] = 0.0; d[i][j][3][0] = dt * 2.0 * ( tx1 * ( - c34 * tmp2 * u[i][j][k][3] ) + ty1 * ( - c34 * tmp2 * u[i][j][k][3] ) + tz1 * ( - r43 * c34 * tmp2 * u[i][j][k][3] ) ); d[i][j][3][1] = 0.0; d[i][j][3][2] = 0.0; d[i][j][3][3] = 1.0 + dt * 2.0 * ( tx1 * c34 * tmp1 + ty1 * c34 * tmp1 + tz1 * r43 * c34 * tmp1 ) + dt * 2.0 * ( tx1 * dx4 + ty1 * dy4 + tz1 * dz4 ); d[i][j][3][4] = 0.0; d[i][j][4][0] = dt * 2.0 * ( tx1 * ( - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][1]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][2]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][3]) ) - ( c1345 ) * tmp2 * u[i][j][k][4] ) + ty1 * ( - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][1]) ) - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][2]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][3]) ) - ( c1345 ) * tmp2 * u[i][j][k][4] ) + tz1 * ( - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][1]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][2]) ) - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k][3]) ) - ( c1345 ) * tmp2 * u[i][j][k][4] ) ); d[i][j][4][1] = dt * 2.0 * ( tx1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j][k][1] + ty1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][1] + tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][1] ); d[i][j][4][2] = dt * 2.0 * ( tx1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][2] + ty1 * ( r43*c34 -c1345 ) * tmp2 * u[i][j][k][2] + tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][2] ); d[i][j][4][3] = dt * 2.0 * ( tx1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][3] + ty1 * ( c34 - c1345 ) * tmp2 * u[i][j][k][3] + tz1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j][k][3] ); d[i][j][4][4] = 1.0 + dt * 2.0 * ( tx1 * c1345 * tmp1 + ty1 * c1345 * tmp1 + tz1 * c1345 * tmp1 ) + dt * 2.0 * ( tx1 * dx5 + ty1 * dy5 + tz1 * dz5 ); /*-------------------------------------------------------------------- c form the first block sub-diagonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i+1][j][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; a[i][j][0][0] = - dt * tx1 * dx1; a[i][j][0][1] = dt * tx2; a[i][j][0][2] = 0.0; a[i][j][0][3] = 0.0; a[i][j][0][4] = 0.0; a[i][j][1][0] = dt * tx2 * ( - ( u[i+1][j][k][1] * tmp1 ) *( u[i+1][j][k][1] * tmp1 ) + C2 * 0.50 * ( u[i+1][j][k][1] * u[i+1][j][k][1] + u[i+1][j][k][2] * u[i+1][j][k][2] + u[i+1][j][k][3] * u[i+1][j][k][3] ) * tmp2 ) - dt * tx1 * ( - r43 * c34 * tmp2 * u[i+1][j][k][1] ); a[i][j][1][1] = dt * tx2 * ( ( 2.0 - C2 ) * ( u[i+1][j][k][1] * tmp1 ) ) - dt * tx1 * ( r43 * c34 * tmp1 ) - dt * tx1 * dx2; a[i][j][1][2] = dt * tx2 * ( - C2 * ( u[i+1][j][k][2] * tmp1 ) ); a[i][j][1][3] = dt * tx2 * ( - C2 * ( u[i+1][j][k][3] * tmp1 ) ); a[i][j][1][4] = dt * tx2 * C2 ; a[i][j][2][0] = dt * tx2 * ( - ( u[i+1][j][k][1] * u[i+1][j][k][2] ) * tmp2 ) - dt * tx1 * ( - c34 * tmp2 * u[i+1][j][k][2] ); a[i][j][2][1] = dt * tx2 * ( u[i+1][j][k][2] * tmp1 ); a[i][j][2][2] = dt * tx2 * ( u[i+1][j][k][1] * tmp1 ) - dt * tx1 * ( c34 * tmp1 ) - dt * tx1 * dx3; a[i][j][2][3] = 0.0; a[i][j][2][4] = 0.0; a[i][j][3][0] = dt * tx2 * ( - ( u[i+1][j][k][1]*u[i+1][j][k][3] ) * tmp2 ) - dt * tx1 * ( - c34 * tmp2 * u[i+1][j][k][3] ); a[i][j][3][1] = dt * tx2 * ( u[i+1][j][k][3] * tmp1 ); a[i][j][3][2] = 0.0; a[i][j][3][3] = dt * tx2 * ( u[i+1][j][k][1] * tmp1 ) - dt * tx1 * ( c34 * tmp1 ) - dt * tx1 * dx4; a[i][j][3][4] = 0.0; a[i][j][4][0] = dt * tx2 * ( ( C2 * ( u[i+1][j][k][1] * u[i+1][j][k][1] + u[i+1][j][k][2] * u[i+1][j][k][2] + u[i+1][j][k][3] * u[i+1][j][k][3] ) * tmp2 - C1 * ( u[i+1][j][k][4] * tmp1 ) ) * ( u[i+1][j][k][1] * tmp1 ) ) - dt * tx1 * ( - ( r43*c34 - c1345 ) * tmp3 * ( pow2(u[i+1][j][k][1]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i+1][j][k][2]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i+1][j][k][3]) ) - c1345 * tmp2 * u[i+1][j][k][4] ); a[i][j][4][1] = dt * tx2 * ( C1 * ( u[i+1][j][k][4] * tmp1 ) - 0.50 * C2 * ( ( 3.0*u[i+1][j][k][1]*u[i+1][j][k][1] + u[i+1][j][k][2]*u[i+1][j][k][2] + u[i+1][j][k][3]*u[i+1][j][k][3] ) * tmp2 ) ) - dt * tx1 * ( r43*c34 - c1345 ) * tmp2 * u[i+1][j][k][1]; a[i][j][4][2] = dt * tx2 * ( - C2 * ( u[i+1][j][k][2]*u[i+1][j][k][1] ) * tmp2 ) - dt * tx1 * ( c34 - c1345 ) * tmp2 * u[i+1][j][k][2]; a[i][j][4][3] = dt * tx2 * ( - C2 * ( u[i+1][j][k][3]*u[i+1][j][k][1] ) * tmp2 ) - dt * tx1 * ( c34 - c1345 ) * tmp2 * u[i+1][j][k][3]; a[i][j][4][4] = dt * tx2 * ( C1 * ( u[i+1][j][k][1] * tmp1 ) ) - dt * tx1 * c1345 * tmp1 - dt * tx1 * dx5; /*-------------------------------------------------------------------- c form the second block sub-diagonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i][j+1][k][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; b[i][j][0][0] = - dt * ty1 * dy1; b[i][j][0][1] = 0.0; b[i][j][0][2] = dt * ty2; b[i][j][0][3] = 0.0; b[i][j][0][4] = 0.0; b[i][j][1][0] = dt * ty2 * ( - ( u[i][j+1][k][1]*u[i][j+1][k][2] ) * tmp2 ) - dt * ty1 * ( - c34 * tmp2 * u[i][j+1][k][1] ); b[i][j][1][1] = dt * ty2 * ( u[i][j+1][k][2] * tmp1 ) - dt * ty1 * ( c34 * tmp1 ) - dt * ty1 * dy2; b[i][j][1][2] = dt * ty2 * ( u[i][j+1][k][1] * tmp1 ); b[i][j][1][3] = 0.0; b[i][j][1][4] = 0.0; b[i][j][2][0] = dt * ty2 * ( - ( u[i][j+1][k][2] * tmp1 ) *( u[i][j+1][k][2] * tmp1 ) + 0.50 * C2 * ( ( u[i][j+1][k][1] * u[i][j+1][k][1] + u[i][j+1][k][2] * u[i][j+1][k][2] + u[i][j+1][k][3] * u[i][j+1][k][3] ) * tmp2 ) ) - dt * ty1 * ( - r43 * c34 * tmp2 * u[i][j+1][k][2] ); b[i][j][2][1] = dt * ty2 * ( - C2 * ( u[i][j+1][k][1] * tmp1 ) ); b[i][j][2][2] = dt * ty2 * ( ( 2.0 - C2 ) * ( u[i][j+1][k][2] * tmp1 ) ) - dt * ty1 * ( r43 * c34 * tmp1 ) - dt * ty1 * dy3; b[i][j][2][3] = dt * ty2 * ( - C2 * ( u[i][j+1][k][3] * tmp1 ) ); b[i][j][2][4] = dt * ty2 * C2; b[i][j][3][0] = dt * ty2 * ( - ( u[i][j+1][k][2]*u[i][j+1][k][3] ) * tmp2 ) - dt * ty1 * ( - c34 * tmp2 * u[i][j+1][k][3] ); b[i][j][3][1] = 0.0; b[i][j][3][2] = dt * ty2 * ( u[i][j+1][k][3] * tmp1 ); b[i][j][3][3] = dt * ty2 * ( u[i][j+1][k][2] * tmp1 ) - dt * ty1 * ( c34 * tmp1 ) - dt * ty1 * dy4; b[i][j][3][4] = 0.0; b[i][j][4][0] = dt * ty2 * ( ( C2 * ( u[i][j+1][k][1] * u[i][j+1][k][1] + u[i][j+1][k][2] * u[i][j+1][k][2] + u[i][j+1][k][3] * u[i][j+1][k][3] ) * tmp2 - C1 * ( u[i][j+1][k][4] * tmp1 ) ) * ( u[i][j+1][k][2] * tmp1 ) ) - dt * ty1 * ( - ( c34 - c1345 )*tmp3*( pow2(u[i][j+1][k][1]) ) - ( r43*c34 - c1345 )*tmp3*( pow2(u[i][j+1][k][2]) ) - ( c34 - c1345 )*tmp3*( pow2(u[i][j+1][k][3]) ) - c1345*tmp2*u[i][j+1][k][4] ); b[i][j][4][1] = dt * ty2 * ( - C2 * ( u[i][j+1][k][1]*u[i][j+1][k][2] ) * tmp2 ) - dt * ty1 * ( c34 - c1345 ) * tmp2 * u[i][j+1][k][1]; b[i][j][4][2] = dt * ty2 * ( C1 * ( u[i][j+1][k][4] * tmp1 ) - 0.50 * C2 * ( ( u[i][j+1][k][1]*u[i][j+1][k][1] + 3.0 * u[i][j+1][k][2]*u[i][j+1][k][2] + u[i][j+1][k][3]*u[i][j+1][k][3] ) * tmp2 ) ) - dt * ty1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j+1][k][2]; b[i][j][4][3] = dt * ty2 * ( - C2 * ( u[i][j+1][k][2]*u[i][j+1][k][3] ) * tmp2 ) - dt * ty1 * ( c34 - c1345 ) * tmp2 * u[i][j+1][k][3]; b[i][j][4][4] = dt * ty2 * ( C1 * ( u[i][j+1][k][2] * tmp1 ) ) - dt * ty1 * c1345 * tmp1 - dt * ty1 * dy5; /*-------------------------------------------------------------------- c form the third block sub-diagonal --------------------------------------------------------------------*/ tmp1 = 1.0 / u[i][j][k+1][0]; tmp2 = tmp1 * tmp1; tmp3 = tmp1 * tmp2; c[i][j][0][0] = - dt * tz1 * dz1; c[i][j][0][1] = 0.0; c[i][j][0][2] = 0.0; c[i][j][0][3] = dt * tz2; c[i][j][0][4] = 0.0; c[i][j][1][0] = dt * tz2 * ( - ( u[i][j][k+1][1]*u[i][j][k+1][3] ) * tmp2 ) - dt * tz1 * ( - c34 * tmp2 * u[i][j][k+1][1] ); c[i][j][1][1] = dt * tz2 * ( u[i][j][k+1][3] * tmp1 ) - dt * tz1 * c34 * tmp1 - dt * tz1 * dz2 ; c[i][j][1][2] = 0.0; c[i][j][1][3] = dt * tz2 * ( u[i][j][k+1][1] * tmp1 ); c[i][j][1][4] = 0.0; c[i][j][2][0] = dt * tz2 * ( - ( u[i][j][k+1][2]*u[i][j][k+1][3] ) * tmp2 ) - dt * tz1 * ( - c34 * tmp2 * u[i][j][k+1][2] ); c[i][j][2][1] = 0.0; c[i][j][2][2] = dt * tz2 * ( u[i][j][k+1][3] * tmp1 ) - dt * tz1 * ( c34 * tmp1 ) - dt * tz1 * dz3; c[i][j][2][3] = dt * tz2 * ( u[i][j][k+1][2] * tmp1 ); c[i][j][2][4] = 0.0; c[i][j][3][0] = dt * tz2 * ( - ( u[i][j][k+1][3] * tmp1 ) *( u[i][j][k+1][3] * tmp1 ) + 0.50 * C2 * ( ( u[i][j][k+1][1] * u[i][j][k+1][1] + u[i][j][k+1][2] * u[i][j][k+1][2] + u[i][j][k+1][3] * u[i][j][k+1][3] ) * tmp2 ) ) - dt * tz1 * ( - r43 * c34 * tmp2 * u[i][j][k+1][3] ); c[i][j][3][1] = dt * tz2 * ( - C2 * ( u[i][j][k+1][1] * tmp1 ) ); c[i][j][3][2] = dt * tz2 * ( - C2 * ( u[i][j][k+1][2] * tmp1 ) ); c[i][j][3][3] = dt * tz2 * ( 2.0 - C2 ) * ( u[i][j][k+1][3] * tmp1 ) - dt * tz1 * ( r43 * c34 * tmp1 ) - dt * tz1 * dz4; c[i][j][3][4] = dt * tz2 * C2; c[i][j][4][0] = dt * tz2 * ( ( C2 * ( u[i][j][k+1][1] * u[i][j][k+1][1] + u[i][j][k+1][2] * u[i][j][k+1][2] + u[i][j][k+1][3] * u[i][j][k+1][3] ) * tmp2 - C1 * ( u[i][j][k+1][4] * tmp1 ) ) * ( u[i][j][k+1][3] * tmp1 ) ) - dt * tz1 * ( - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k+1][1]) ) - ( c34 - c1345 ) * tmp3 * ( pow2(u[i][j][k+1][2]) ) - ( r43*c34 - c1345 )* tmp3 * ( pow2(u[i][j][k+1][3]) ) - c1345 * tmp2 * u[i][j][k+1][4] ); c[i][j][4][1] = dt * tz2 * ( - C2 * ( u[i][j][k+1][1]*u[i][j][k+1][3] ) * tmp2 ) - dt * tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k+1][1]; c[i][j][4][2] = dt * tz2 * ( - C2 * ( u[i][j][k+1][2]*u[i][j][k+1][3] ) * tmp2 ) - dt * tz1 * ( c34 - c1345 ) * tmp2 * u[i][j][k+1][2]; c[i][j][4][3] = dt * tz2 * ( C1 * ( u[i][j][k+1][4] * tmp1 ) - 0.50 * C2 * ( ( u[i][j][k+1][1]*u[i][j][k+1][1] + u[i][j][k+1][2]*u[i][j][k+1][2] + 3.0*u[i][j][k+1][3]*u[i][j][k+1][3] ) * tmp2 ) ) - dt * tz1 * ( r43*c34 - c1345 ) * tmp2 * u[i][j][k+1][3]; c[i][j][4][4] = dt * tz2 * ( C1 * ( u[i][j][k+1][3] * tmp1 ) ) - dt * tz1 * c1345 * tmp1 - dt * tz1 * dz5; } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void l2norm (int nx0, int ny0, int nz0, int ist, int iend, int jst, int jend, /*-------------------------------------------------------------------- c To improve cache performance, second two dimensions padded by 1 c for even number sizes only. Only needed in v. --------------------------------------------------------------------*/ double v[ISIZ1][ISIZ2/2*2+1][ISIZ3/2*2+1][5], double sum[5]) { #pragma omp parallel { /*-------------------------------------------------------------------- c to compute the l2-norm of vector v. --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k, m; double sum0=0.0, sum1=0.0, sum2=0.0, sum3=0.0, sum4=0.0; #pragma omp single for (m = 0; m < 5; m++) { sum[m] = 0.0; } #pragma omp for nowait for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { for (k = 1; k <= nz0-2; k++) { sum0 = sum0 + v[i][j][k][0] * v[i][j][k][0]; sum1 = sum1 + v[i][j][k][1] * v[i][j][k][1]; sum2 = sum2 + v[i][j][k][2] * v[i][j][k][2]; sum3 = sum3 + v[i][j][k][3] * v[i][j][k][3]; sum4 = sum4 + v[i][j][k][4] * v[i][j][k][4]; } } } #pragma omp critical(lu) { sum[0] += sum0; sum[1] += sum1; sum[2] += sum2; sum[3] += sum3; sum[4] += sum4; } #pragma omp barrier #pragma omp single for (m = 0; m < 5; m++) { sum[m] = sqrt ( sum[m] / ( (nx0-2)*(ny0-2)*(nz0-2) ) ); } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void pintgr(void) { /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k; int ibeg, ifin, ifin1; int jbeg, jfin, jfin1; int iglob, iglob1, iglob2; int jglob, jglob1, jglob2; double phi1[ISIZ2+2][ISIZ3+2]; /* phi1(0:isiz2+1,0:isiz3+1) */ double phi2[ISIZ2+2][ISIZ3+2]; /* phi2(0:isiz2+1,0:isiz3+1) */ double frc1, frc2, frc3; /*-------------------------------------------------------------------- c set up the sub-domains for integeration in each processor --------------------------------------------------------------------*/ ibeg = nx; ifin = 0; iglob1 = -1; iglob2 = nx-1; if (iglob1 >= ii1 && iglob2 < ii2+nx) ibeg = 0; if (iglob1 >= ii1-nx && iglob2 <= ii2) ifin = nx; if (ii1 >= iglob1 && ii1 <= iglob2) ibeg = ii1; if (ii2 >= iglob1 && ii2 <= iglob2) ifin = ii2; jbeg = ny; jfin = -1; jglob1 = 0; jglob2 = ny-1; if (jglob1 >= ji1 && jglob2 < ji2+ny) jbeg = 0; if (jglob1 > ji1-ny && jglob2 <= ji2) jfin = ny; if (ji1 >= jglob1 && ji1 <= jglob2) jbeg = ji1; if (ji2 >= jglob1 && ji2 <= jglob2) jfin = ji2; ifin1 = ifin; jfin1 = jfin; if (ifin1 == ii2) ifin1 = ifin -1; if (jfin1 == ji2) jfin1 = jfin -1; /*-------------------------------------------------------------------- c initialize --------------------------------------------------------------------*/ for (i = 0; i <= ISIZ2+1; i++) { for (k = 0; k <= ISIZ3+1; k++) { phi1[i][k] = 0.0; phi2[i][k] = 0.0; } } for (i = ibeg; i <= ifin; i++) { iglob = i; for (j = jbeg; j <= jfin; j++) { jglob = j; k = ki1; phi1[i][j] = C2*( u[i][j][k][4] - 0.50 * ( pow2(u[i][j][k][1]) + pow2(u[i][j][k][2]) + pow2(u[i][j][k][3]) ) / u[i][j][k][0] ); k = ki2; phi2[i][j] = C2*( u[i][j][k][4] - 0.50 * ( pow2(u[i][j][k][1]) + pow2(u[i][j][k][2]) + pow2(u[i][j][k][3]) ) / u[i][j][k][0] ); } } frc1 = 0.0; for (i = ibeg; i <= ifin1; i++) { for (j = jbeg; j <= jfin1; j++) { frc1 = frc1 + ( phi1[i][j] + phi1[i+1][j] + phi1[i][j+1] + phi1[i+1][j+1] + phi2[i][j] + phi2[i+1][j] + phi2[i][j+1] + phi2[i+1][j+1] ); } } frc1 = dxi * deta * frc1; /*-------------------------------------------------------------------- c initialize --------------------------------------------------------------------*/ for (i = 0; i <= ISIZ2+1; i++) { for (k = 0; k <= ISIZ3+1; k++) { phi1[i][k] = 0.0; phi2[i][k] = 0.0; } } jglob = jbeg; if (jglob == ji1) { for (i = ibeg; i <= ifin; i++) { iglob = i; for (k = ki1; k <= ki2; k++) { phi1[i][k] = C2*( u[i][jbeg][k][4] - 0.50 * ( pow2(u[i][jbeg][k][1]) + pow2(u[i][jbeg][k][2]) + pow2(u[i][jbeg][k][3]) ) / u[i][jbeg][k][0] ); } } } jglob = jfin; if (jglob == ji2) { for (i = ibeg; i <= ifin; i++) { iglob = i; for (k = ki1; k <= ki2; k++) { phi2[i][k] = C2*( u[i][jfin][k][4] - 0.50 * ( pow2(u[i][jfin][k][1]) + pow2(u[i][jfin][k][2]) + pow2(u[i][jfin][k][3]) ) / u[i][jfin][k][0] ); } } } frc2 = 0.0; for (i = ibeg; i <= ifin1; i++) { for (k = ki1; k <= ki2-1; k++) { frc2 = frc2 + ( phi1[i][k] + phi1[i+1][k] + phi1[i][k+1] + phi1[i+1][k+1] + phi2[i][k] + phi2[i+1][k] + phi2[i][k+1] + phi2[i+1][k+1] ); } } frc2 = dxi * dzeta * frc2; /*-------------------------------------------------------------------- c initialize --------------------------------------------------------------------*/ for (i = 0; i <= ISIZ2+1; i++) { for (k = 0; k <= ISIZ3+1; k++) { phi1[i][k] = 0.0; phi2[i][k] = 0.0; } } iglob = ibeg; if (iglob == ii1) { for (j = jbeg; j <= jfin; j++) { jglob = j; for (k = ki1; k <= ki2; k++) { phi1[j][k] = C2*( u[ibeg][j][k][4] - 0.50 * ( pow2(u[ibeg][j][k][1]) + pow2(u[ibeg][j][k][2]) + pow2(u[ibeg][j][k][3]) ) / u[ibeg][j][k][0] ); } } } iglob = ifin; if (iglob == ii2) { for (j = jbeg; j <= jfin; j++) { jglob = j; for (k = ki1; k <= ki2; k++) { phi2[j][k] = C2*( u[ifin][j][k][4] - 0.50 * ( pow2(u[ifin][j][k][1]) + pow2(u[ifin][j][k][2]) + pow2(u[ifin][j][k][3]) ) / u[ifin][j][k][0] ); } } } frc3 = 0.0; for (j = jbeg; j <= jfin1; j++) { for (k = ki1; k <= ki2-1; k++) { frc3 = frc3 + ( phi1[j][k] + phi1[j+1][k] + phi1[j][k+1] + phi1[j+1][k+1] + phi2[j][k] + phi2[j+1][k] + phi2[j][k+1] + phi2[j+1][k+1] ); } } frc3 = deta * dzeta * frc3; frc = 0.25 * ( frc1 + frc2 + frc3 ); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void read_input(void) { // FILE *fp; /*-------------------------------------------------------------------- c if input file does not exist, it uses defaults c ipr = 1 for detailed progress output c inorm = how often the norm is printed (once every inorm iterations) c itmax = number of pseudo time steps c dt = time step c omega 1 over-relaxation factor for SSOR c tolrsd = steady state residual tolerance levels c nx, ny, nz = number of grid points in x, y, z directions --------------------------------------------------------------------*/ printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - LU Benchmark\n\n"); /* fp = fopen("inputlu.data", "r"); */ /* if (fp != NULL) { */ /* printf(" Reading from input file inputlu.data\n"); */ /* while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); */ /* fscanf(fp, "%d%d", &ipr, &inorm); */ /* while(fgetc(fp) != '\n'); */ /* while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); */ /* fscanf(fp, "%d", &itmax); */ /* while(fgetc(fp) != '\n'); */ /* while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); */ /* fscanf(fp, "%lf", &dt); */ /* while(fgetc(fp) != '\n'); */ /* while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); */ /* fscanf(fp, "%lf", &omega); */ /* while(fgetc(fp) != '\n'); */ /* while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); */ /* fscanf(fp, "%lf%lf%lf%lf%lf", */ /* &tolrsd[0], &tolrsd[1], &tolrsd[2], &tolrsd[3], &tolrsd[4]); */ /* while(fgetc(fp) != '\n'); */ /* while(fgetc(fp) != '\n'); while(fgetc(fp) != '\n'); */ /* fscanf(fp, "%d%d%d", &nx0, &ny0, &nz0); */ /* while(fgetc(fp) != '\n'); */ /* fclose(fp); */ /* } else { */ ipr = IPR_DEFAULT; inorm = INORM_DEFAULT; itmax = ITMAX_DEFAULT; dt = DT_DEFAULT; omega = OMEGA_DEFAULT; tolrsd[0] = TOLRSD1_DEF; tolrsd[1] = TOLRSD2_DEF; tolrsd[2] = TOLRSD3_DEF; tolrsd[3] = TOLRSD4_DEF; tolrsd[4] = TOLRSD5_DEF; nx0 = ISIZ1; ny0 = ISIZ2; nz0 = ISIZ3; // } /*-------------------------------------------------------------------- c check problem size --------------------------------------------------------------------*/ if ( nx0 < 4 || ny0 < 4 || nz0 < 4 ) { printf(" PROBLEM SIZE IS TOO SMALL - \n" " SET EACH OF NX, NY AND NZ AT LEAST EQUAL TO 5\n"); exit(1); } if ( nx0 > ISIZ1 || ny0 > ISIZ2 || nz0 > ISIZ3 ) { printf(" PROBLEM SIZE IS TOO LARGE - \n" " NX, NY AND NZ SHOULD BE EQUAL TO \n" " ISIZ1, ISIZ2 AND ISIZ3 RESPECTIVELY\n"); exit(1); } printf(" Size: %3dx%3dx%3d\n", nx0, ny0, nz0); printf(" Iterations: %3d\n", itmax); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void rhs(void) { #pragma omp parallel { /*-------------------------------------------------------------------- c compute the right hand sides --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k, m; int L1, L2; int ist1, iend1; int jst1, jend1; double q; double u21, u31, u41; double tmp; double u21i, u31i, u41i, u51i; double u21j, u31j, u41j, u51j; double u21k, u31k, u41k, u51k; double u21im1, u31im1, u41im1, u51im1; double u21jm1, u31jm1, u41jm1, u51jm1; double u21km1, u31km1, u41km1, u51km1; #pragma omp for for (i = 0; i <= nx-1; i++) { for (j = 0; j <= ny-1; j++) { for (k = 0; k <= nz-1; k++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = - frct[i][j][k][m]; } } } } /*-------------------------------------------------------------------- c xi-direction flux differences --------------------------------------------------------------------*/ L1 = 0; L2 = nx-1; #pragma omp for for (i = L1; i <= L2; i++) { for (j = jst; j <= jend; j++) { for (k = 1; k <= nz - 2; k++) { flux[i][j][k][0] = u[i][j][k][1]; u21 = u[i][j][k][1] / u[i][j][k][0]; q = 0.50 * ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) / u[i][j][k][0]; flux[i][j][k][1] = u[i][j][k][1] * u21 + C2 * ( u[i][j][k][4] - q ); flux[i][j][k][2] = u[i][j][k][2] * u21; flux[i][j][k][3] = u[i][j][k][3] * u21; flux[i][j][k][4] = ( C1 * u[i][j][k][4] - C2 * q ) * u21; } } } #pragma omp for for (j = jst; j <= jend; j++) { for (k = 1; k <= nz - 2; k++) { for (i = ist; i <= iend; i++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = rsd[i][j][k][m] - tx2 * ( flux[i+1][j][k][m] - flux[i-1][j][k][m] ); } } L2 = nx-1; for (i = ist; i <= L2; i++) { tmp = 1.0 / u[i][j][k][0]; u21i = tmp * u[i][j][k][1]; u31i = tmp * u[i][j][k][2]; u41i = tmp * u[i][j][k][3]; u51i = tmp * u[i][j][k][4]; tmp = 1.0 / u[i-1][j][k][0]; u21im1 = tmp * u[i-1][j][k][1]; u31im1 = tmp * u[i-1][j][k][2]; u41im1 = tmp * u[i-1][j][k][3]; u51im1 = tmp * u[i-1][j][k][4]; flux[i][j][k][1] = (4.0/3.0) * tx3 * (u21i-u21im1); flux[i][j][k][2] = tx3 * ( u31i - u31im1 ); flux[i][j][k][3] = tx3 * ( u41i - u41im1 ); flux[i][j][k][4] = 0.50 * ( 1.0 - C1*C5 ) * tx3 * ( ( pow2(u21i) + pow2(u31i) + pow2(u41i) ) - ( pow2(u21im1) + pow2(u31im1) + pow2(u41im1) ) ) + (1.0/6.0) * tx3 * ( pow2(u21i) - pow2(u21im1) ) + C1 * C5 * tx3 * ( u51i - u51im1 ); } for (i = ist; i <= iend; i++) { rsd[i][j][k][0] = rsd[i][j][k][0] + dx1 * tx1 * ( u[i-1][j][k][0] - 2.0 * u[i][j][k][0] + u[i+1][j][k][0] ); rsd[i][j][k][1] = rsd[i][j][k][1] + tx3 * C3 * C4 * ( flux[i+1][j][k][1] - flux[i][j][k][1] ) + dx2 * tx1 * ( u[i-1][j][k][1] - 2.0 * u[i][j][k][1] + u[i+1][j][k][1] ); rsd[i][j][k][2] = rsd[i][j][k][2] + tx3 * C3 * C4 * ( flux[i+1][j][k][2] - flux[i][j][k][2] ) + dx3 * tx1 * ( u[i-1][j][k][2] - 2.0 * u[i][j][k][2] + u[i+1][j][k][2] ); rsd[i][j][k][3] = rsd[i][j][k][3] + tx3 * C3 * C4 * ( flux[i+1][j][k][3] - flux[i][j][k][3] ) + dx4 * tx1 * ( u[i-1][j][k][3] - 2.0 * u[i][j][k][3] + u[i+1][j][k][3] ); rsd[i][j][k][4] = rsd[i][j][k][4] + tx3 * C3 * C4 * ( flux[i+1][j][k][4] - flux[i][j][k][4] ) + dx5 * tx1 * ( u[i-1][j][k][4] - 2.0 * u[i][j][k][4] + u[i+1][j][k][4] ); } /*-------------------------------------------------------------------- c Fourth-order dissipation --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { rsd[1][j][k][m] = rsd[1][j][k][m] - dssp * ( + 5.0 * u[1][j][k][m] - 4.0 * u[2][j][k][m] + u[3][j][k][m] ); rsd[2][j][k][m] = rsd[2][j][k][m] - dssp * ( - 4.0 * u[1][j][k][m] + 6.0 * u[2][j][k][m] - 4.0 * u[3][j][k][m] + u[4][j][k][m] ); } ist1 = 3; iend1 = nx - 4; for (i = ist1; i <= iend1; i++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = rsd[i][j][k][m] - dssp * ( u[i-2][j][k][m] - 4.0 * u[i-1][j][k][m] + 6.0 * u[i][j][k][m] - 4.0 * u[i+1][j][k][m] + u[i+2][j][k][m] ); } } for (m = 0; m < 5; m++) { rsd[nx-3][j][k][m] = rsd[nx-3][j][k][m] - dssp * ( u[nx-5][j][k][m] - 4.0 * u[nx-4][j][k][m] + 6.0 * u[nx-3][j][k][m] - 4.0 * u[nx-2][j][k][m] ); rsd[nx-2][j][k][m] = rsd[nx-2][j][k][m] - dssp * ( u[nx-4][j][k][m] - 4.0 * u[nx-3][j][k][m] + 5.0 * u[nx-2][j][k][m] ); } } } /*-------------------------------------------------------------------- c eta-direction flux differences --------------------------------------------------------------------*/ L1 = 0; L2 = ny-1; #pragma omp for for (i = ist; i <= iend; i++) { for (j = L1; j <= L2; j++) { for (k = 1; k <= nz - 2; k++) { flux[i][j][k][0] = u[i][j][k][2]; u31 = u[i][j][k][2] / u[i][j][k][0]; q = 0.50 * ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) / u[i][j][k][0]; flux[i][j][k][1] = u[i][j][k][1] * u31; flux[i][j][k][2] = u[i][j][k][2] * u31 + C2 * (u[i][j][k][4]-q); flux[i][j][k][3] = u[i][j][k][3] * u31; flux[i][j][k][4] = ( C1 * u[i][j][k][4] - C2 * q ) * u31; } } } #pragma omp for for (i = ist; i <= iend; i++) { for (k = 1; k <= nz - 2; k++) { for (j = jst; j <= jend; j++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = rsd[i][j][k][m] - ty2 * ( flux[i][j+1][k][m] - flux[i][j-1][k][m] ); } } L2 = ny-1; for (j = jst; j <= L2; j++) { tmp = 1.0 / u[i][j][k][0]; u21j = tmp * u[i][j][k][1]; u31j = tmp * u[i][j][k][2]; u41j = tmp * u[i][j][k][3]; u51j = tmp * u[i][j][k][4]; tmp = 1.0 / u[i][j-1][k][0]; u21jm1 = tmp * u[i][j-1][k][1]; u31jm1 = tmp * u[i][j-1][k][2]; u41jm1 = tmp * u[i][j-1][k][3]; u51jm1 = tmp * u[i][j-1][k][4]; flux[i][j][k][1] = ty3 * ( u21j - u21jm1 ); flux[i][j][k][2] = (4.0/3.0) * ty3 * (u31j-u31jm1); flux[i][j][k][3] = ty3 * ( u41j - u41jm1 ); flux[i][j][k][4] = 0.50 * ( 1.0 - C1*C5 ) * ty3 * ( ( pow2(u21j) + pow2(u31j) + pow2(u41j) ) - ( pow2(u21jm1) + pow2(u31jm1) + pow2(u41jm1) ) ) + (1.0/6.0) * ty3 * ( pow2(u31j) - pow2(u31jm1) ) + C1 * C5 * ty3 * ( u51j - u51jm1 ); } for (j = jst; j <= jend; j++) { rsd[i][j][k][0] = rsd[i][j][k][0] + dy1 * ty1 * ( u[i][j-1][k][0] - 2.0 * u[i][j][k][0] + u[i][j+1][k][0] ); rsd[i][j][k][1] = rsd[i][j][k][1] + ty3 * C3 * C4 * ( flux[i][j+1][k][1] - flux[i][j][k][1] ) + dy2 * ty1 * ( u[i][j-1][k][1] - 2.0 * u[i][j][k][1] + u[i][j+1][k][1] ); rsd[i][j][k][2] = rsd[i][j][k][2] + ty3 * C3 * C4 * ( flux[i][j+1][k][2] - flux[i][j][k][2] ) + dy3 * ty1 * ( u[i][j-1][k][2] - 2.0 * u[i][j][k][2] + u[i][j+1][k][2] ); rsd[i][j][k][3] = rsd[i][j][k][3] + ty3 * C3 * C4 * ( flux[i][j+1][k][3] - flux[i][j][k][3] ) + dy4 * ty1 * ( u[i][j-1][k][3] - 2.0 * u[i][j][k][3] + u[i][j+1][k][3] ); rsd[i][j][k][4] = rsd[i][j][k][4] + ty3 * C3 * C4 * ( flux[i][j+1][k][4] - flux[i][j][k][4] ) + dy5 * ty1 * ( u[i][j-1][k][4] - 2.0 * u[i][j][k][4] + u[i][j+1][k][4] ); } /*-------------------------------------------------------------------- c fourth-order dissipation --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { rsd[i][1][k][m] = rsd[i][1][k][m] - dssp * ( + 5.0 * u[i][1][k][m] - 4.0 * u[i][2][k][m] + u[i][3][k][m] ); rsd[i][2][k][m] = rsd[i][2][k][m] - dssp * ( - 4.0 * u[i][1][k][m] + 6.0 * u[i][2][k][m] - 4.0 * u[i][3][k][m] + u[i][4][k][m] ); } jst1 = 3; jend1 = ny - 4; for (j = jst1; j <= jend1; j++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = rsd[i][j][k][m] - dssp * ( u[i][j-2][k][m] - 4.0 * u[i][j-1][k][m] + 6.0 * u[i][j][k][m] - 4.0 * u[i][j+1][k][m] + u[i][j+2][k][m] ); } } for (m = 0; m < 5; m++) { rsd[i][ny-3][k][m] = rsd[i][ny-3][k][m] - dssp * ( u[i][ny-5][k][m] - 4.0 * u[i][ny-4][k][m] + 6.0 * u[i][ny-3][k][m] - 4.0 * u[i][ny-2][k][m] ); rsd[i][ny-2][k][m] = rsd[i][ny-2][k][m] - dssp * ( u[i][ny-4][k][m] - 4.0 * u[i][ny-3][k][m] + 5.0 * u[i][ny-2][k][m] ); } } } /*-------------------------------------------------------------------- c zeta-direction flux differences --------------------------------------------------------------------*/ #pragma omp for for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { for (k = 0; k <= nz-1; k++) { flux[i][j][k][0] = u[i][j][k][3]; u41 = u[i][j][k][3] / u[i][j][k][0]; q = 0.50 * ( u[i][j][k][1] * u[i][j][k][1] + u[i][j][k][2] * u[i][j][k][2] + u[i][j][k][3] * u[i][j][k][3] ) / u[i][j][k][0]; flux[i][j][k][1] = u[i][j][k][1] * u41; flux[i][j][k][2] = u[i][j][k][2] * u41; flux[i][j][k][3] = u[i][j][k][3] * u41 + C2 * (u[i][j][k][4]-q); flux[i][j][k][4] = ( C1 * u[i][j][k][4] - C2 * q ) * u41; } for (k = 1; k <= nz - 2; k++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = rsd[i][j][k][m] - tz2 * ( flux[i][j][k+1][m] - flux[i][j][k-1][m] ); } } for (k = 1; k <= nz-1; k++) { tmp = 1.0 / u[i][j][k][0]; u21k = tmp * u[i][j][k][1]; u31k = tmp * u[i][j][k][2]; u41k = tmp * u[i][j][k][3]; u51k = tmp * u[i][j][k][4]; tmp = 1.0 / u[i][j][k-1][0]; u21km1 = tmp * u[i][j][k-1][1]; u31km1 = tmp * u[i][j][k-1][2]; u41km1 = tmp * u[i][j][k-1][3]; u51km1 = tmp * u[i][j][k-1][4]; flux[i][j][k][1] = tz3 * ( u21k - u21km1 ); flux[i][j][k][2] = tz3 * ( u31k - u31km1 ); flux[i][j][k][3] = (4.0/3.0) * tz3 * (u41k-u41km1); flux[i][j][k][4] = 0.50 * ( 1.0 - C1*C5 ) * tz3 * ( ( pow2(u21k) + pow2(u31k) + pow2(u41k) ) - ( pow2(u21km1) + pow2(u31km1) + pow2(u41km1) ) ) + (1.0/6.0) * tz3 * ( pow2(u41k) - pow2(u41km1) ) + C1 * C5 * tz3 * ( u51k - u51km1 ); } for (k = 1; k <= nz - 2; k++) { rsd[i][j][k][0] = rsd[i][j][k][0] + dz1 * tz1 * ( u[i][j][k-1][0] - 2.0 * u[i][j][k][0] + u[i][j][k+1][0] ); rsd[i][j][k][1] = rsd[i][j][k][1] + tz3 * C3 * C4 * ( flux[i][j][k+1][1] - flux[i][j][k][1] ) + dz2 * tz1 * ( u[i][j][k-1][1] - 2.0 * u[i][j][k][1] + u[i][j][k+1][1] ); rsd[i][j][k][2] = rsd[i][j][k][2] + tz3 * C3 * C4 * ( flux[i][j][k+1][2] - flux[i][j][k][2] ) + dz3 * tz1 * ( u[i][j][k-1][2] - 2.0 * u[i][j][k][2] + u[i][j][k+1][2] ); rsd[i][j][k][3] = rsd[i][j][k][3] + tz3 * C3 * C4 * ( flux[i][j][k+1][3] - flux[i][j][k][3] ) + dz4 * tz1 * ( u[i][j][k-1][3] - 2.0 * u[i][j][k][3] + u[i][j][k+1][3] ); rsd[i][j][k][4] = rsd[i][j][k][4] + tz3 * C3 * C4 * ( flux[i][j][k+1][4] - flux[i][j][k][4] ) + dz5 * tz1 * ( u[i][j][k-1][4] - 2.0 * u[i][j][k][4] + u[i][j][k+1][4] ); } /*-------------------------------------------------------------------- c fourth-order dissipation --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { rsd[i][j][1][m] = rsd[i][j][1][m] - dssp * ( + 5.0 * u[i][j][1][m] - 4.0 * u[i][j][2][m] + u[i][j][3][m] ); rsd[i][j][2][m] = rsd[i][j][2][m] - dssp * ( - 4.0 * u[i][j][1][m] + 6.0 * u[i][j][2][m] - 4.0 * u[i][j][3][m] + u[i][j][4][m] ); } for (k = 3; k <= nz - 4; k++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = rsd[i][j][k][m] - dssp * ( u[i][j][k-2][m] - 4.0 * u[i][j][k-1][m] + 6.0 * u[i][j][k][m] - 4.0 * u[i][j][k+1][m] + u[i][j][k+2][m] ); } } for (m = 0; m < 5; m++) { rsd[i][j][nz-3][m] = rsd[i][j][nz-3][m] - dssp * ( u[i][j][nz-5][m] - 4.0 * u[i][j][nz-4][m] + 6.0 * u[i][j][nz-3][m] - 4.0 * u[i][j][nz-2][m] ); rsd[i][j][nz-2][m] = rsd[i][j][nz-2][m] - dssp * ( u[i][j][nz-4][m] - 4.0 * u[i][j][nz-3][m] + 5.0 * u[i][j][nz-2][m] ); } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void setbv(void) { #pragma omp parallel { /*-------------------------------------------------------------------- c set the boundary values of dependent variables --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k; int iglob, jglob; /*-------------------------------------------------------------------- c set the dependent variable values along the top and bottom faces --------------------------------------------------------------------*/ #pragma omp for for (i = 0; i < nx; i++) { iglob = i; for (j = 0; j < ny; j++) { jglob = j; exact( iglob, jglob, 0, &u[i][j][0][0] ); exact( iglob, jglob, nz-1, &u[i][j][nz-1][0] ); } } /*-------------------------------------------------------------------- c set the dependent variable values along north and south faces --------------------------------------------------------------------*/ #pragma omp for for (i = 0; i < nx; i++) { iglob = i; for (k = 0; k < nz; k++) { exact( iglob, 0, k, &u[i][0][k][0] ); } } #pragma omp for for (i = 0; i < nx; i++) { iglob = i; for (k = 0; k < nz; k++) { exact( iglob, ny0-1, k, &u[i][ny-1][k][0] ); } } /*-------------------------------------------------------------------- c set the dependent variable values along east and west faces --------------------------------------------------------------------*/ #pragma omp for for (j = 0; j < ny; j++) { jglob = j; for (k = 0; k < nz; k++) { exact( 0, jglob, k, &u[0][j][k][0] ); } } #pragma omp for for (j = 0; j < ny; j++) { jglob = j; for (k = 0; k < nz; k++) { exact( nx0-1, jglob, k, &u[nx-1][j][k][0] ); } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void setcoeff(void) { /*-------------------------------------------------------------------- c set up coefficients --------------------------------------------------------------------*/ dxi = 1.0 / ( nx0 - 1 ); deta = 1.0 / ( ny0 - 1 ); dzeta = 1.0 / ( nz0 - 1 ); tx1 = 1.0 / ( dxi * dxi ); tx2 = 1.0 / ( 2.0 * dxi ); tx3 = 1.0 / dxi; ty1 = 1.0 / ( deta * deta ); ty2 = 1.0 / ( 2.0 * deta ); ty3 = 1.0 / deta; tz1 = 1.0 / ( dzeta * dzeta ); tz2 = 1.0 / ( 2.0 * dzeta ); tz3 = 1.0 / dzeta; ii1 = 1; ii2 = nx0 - 2; ji1 = 1; ji2 = ny0 - 3; ki1 = 2; ki2 = nz0 - 2; /*-------------------------------------------------------------------- c diffusion coefficients --------------------------------------------------------------------*/ dx1 = 0.75; dx2 = dx1; dx3 = dx1; dx4 = dx1; dx5 = dx1; dy1 = 0.75; dy2 = dy1; dy3 = dy1; dy4 = dy1; dy5 = dy1; dz1 = 1.00; dz2 = dz1; dz3 = dz1; dz4 = dz1; dz5 = dz1; /*-------------------------------------------------------------------- c fourth difference dissipation --------------------------------------------------------------------*/ dssp = ( max (dx1, max(dy1, dz1) ) ) / 4.0; /*-------------------------------------------------------------------- c coefficients of the exact solution to the first pde --------------------------------------------------------------------*/ ce[0][0] = 2.0; ce[0][1] = 0.0; ce[0][2] = 0.0; ce[0][3] = 4.0; ce[0][4] = 5.0; ce[0][5] = 3.0; ce[0][6] = 5.0e-01; ce[0][7] = 2.0e-02; ce[0][8] = 1.0e-02; ce[0][9] = 3.0e-02; ce[0][10] = 5.0e-01; ce[0][11] = 4.0e-01; ce[0][12] = 3.0e-01; /*-------------------------------------------------------------------- c coefficients of the exact solution to the second pde --------------------------------------------------------------------*/ ce[1][0] = 1.0; ce[1][1] = 0.0; ce[1][2] = 0.0; ce[1][3] = 0.0; ce[1][4] = 1.0; ce[1][5] = 2.0; ce[1][6] = 3.0; ce[1][7] = 1.0e-02; ce[1][8] = 3.0e-02; ce[1][9] = 2.0e-02; ce[1][10] = 4.0e-01; ce[1][11] = 3.0e-01; ce[1][12] = 5.0e-01; /*-------------------------------------------------------------------- c coefficients of the exact solution to the third pde --------------------------------------------------------------------*/ ce[2][0] = 2.0; ce[2][1] = 2.0; ce[2][2] = 0.0; ce[2][3] = 0.0; ce[2][4] = 0.0; ce[2][5] = 2.0; ce[2][6] = 3.0; ce[2][7] = 4.0e-02; ce[2][8] = 3.0e-02; ce[2][9] = 5.0e-02; ce[2][10] = 3.0e-01; ce[2][11] = 5.0e-01; ce[2][12] = 4.0e-01; /*-------------------------------------------------------------------- c coefficients of the exact solution to the fourth pde --------------------------------------------------------------------*/ ce[3][0] = 2.0; ce[3][1] = 2.0; ce[3][2] = 0.0; ce[3][3] = 0.0; ce[3][4] = 0.0; ce[3][5] = 2.0; ce[3][6] = 3.0; ce[3][7] = 3.0e-02; ce[3][8] = 5.0e-02; ce[3][9] = 4.0e-02; ce[3][10] = 2.0e-01; ce[3][11] = 1.0e-01; ce[3][12] = 3.0e-01; /*-------------------------------------------------------------------- c coefficients of the exact solution to the fifth pde --------------------------------------------------------------------*/ ce[4][0] = 5.0; ce[4][1] = 4.0; ce[4][2] = 3.0; ce[4][3] = 2.0; ce[4][4] = 1.0e-01; ce[4][5] = 4.0e-01; ce[4][6] = 3.0e-01; ce[4][7] = 5.0e-02; ce[4][8] = 4.0e-02; ce[4][9] = 3.0e-02; ce[4][10] = 1.0e-01; ce[4][11] = 3.0e-01; ce[4][12] = 2.0e-01; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void setiv(void) { #pragma omp parallel { /*-------------------------------------------------------------------- c c set the initial values of independent variables based on tri-linear c interpolation of boundary values in the computational space. c --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k, m; int iglob, jglob; double xi, eta, zeta; double pxi, peta, pzeta; double ue_1jk[5],ue_nx0jk[5],ue_i1k[5], ue_iny0k[5],ue_ij1[5],ue_ijnz[5]; #pragma omp for for (j = 0; j < ny; j++) { jglob = j; for (k = 1; k < nz - 1; k++) { zeta = ((double)k) / (nz-1); if (jglob != 0 && jglob != ny0-1) { eta = ( (double) (jglob) ) / (ny0-1); for (i = 0; i < nx; i++) { iglob = i; if(iglob != 0 && iglob != nx0-1) { xi = ( (double) (iglob) ) / (nx0-1); exact (0,jglob,k,ue_1jk); exact (nx0-1,jglob,k,ue_nx0jk); exact (iglob,0,k,ue_i1k); exact (iglob,ny0-1,k,ue_iny0k); exact (iglob,jglob,0,ue_ij1); exact (iglob,jglob,nz-1,ue_ijnz); for (m = 0; m < 5; m++) { pxi = ( 1.0 - xi ) * ue_1jk[m] + xi * ue_nx0jk[m]; peta = ( 1.0 - eta ) * ue_i1k[m] + eta * ue_iny0k[m]; pzeta = ( 1.0 - zeta ) * ue_ij1[m] + zeta * ue_ijnz[m]; u[i][j][k][m] = pxi + peta + pzeta - pxi * peta - peta * pzeta - pzeta * pxi + pxi * peta * pzeta; } } } } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void ssor(void) { /*-------------------------------------------------------------------- c to perform pseudo-time stepping SSOR iterations c for five nonlinear pde s. --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c local variables --------------------------------------------------------------------*/ int i, j, k, m; int istep; double tmp; double delunm[5], tv[ISIZ1][ISIZ2][5]; /*-------------------------------------------------------------------- c begin pseudo-time stepping iterations --------------------------------------------------------------------*/ tmp = 1.0 / ( omega * ( 2.0 - omega ) ) ; /*-------------------------------------------------------------------- c initialize a,b,c,d to zero (guarantees that page tables have been c formed, if applicable on given architecture, before timestepping). --------------------------------------------------------------------*/ #pragma omp parallel private(i,j,k,m) { #pragma omp for for (i = 0; i < ISIZ1; i++) { for (j = 0; j < ISIZ2; j++) { for (k = 0; k < 5; k++) { for (m = 0; m < 5; m++) { a[i][j][k][m] = 0.0; b[i][j][k][m] = 0.0; c[i][j][k][m] = 0.0; d[i][j][k][m] = 0.0; } } } } } /*-------------------------------------------------------------------- c compute the steady-state residuals --------------------------------------------------------------------*/ rhs(); /*-------------------------------------------------------------------- c compute the L2 norms of newton iteration residuals --------------------------------------------------------------------*/ l2norm( nx0, ny0, nz0, ist, iend, jst, jend, rsd, rsdnm ); timer_clear(1); timer_start(1); /*-------------------------------------------------------------------- c the timestep loop --------------------------------------------------------------------*/ for (istep = 1; istep <= itmax; istep++) { if (istep%20 == 0 || istep == itmax || istep == 1) { #pragma omp master printf(" Time step %4d\n", istep); } #pragma omp parallel private(istep,i,j,k,m) { /*-------------------------------------------------------------------- c perform SSOR iteration --------------------------------------------------------------------*/ #pragma omp for for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { for (k = 1; k <= nz - 2; k++) { for (m = 0; m < 5; m++) { rsd[i][j][k][m] = dt * rsd[i][j][k][m]; } } } } for (k = 1; k <= nz - 2; k++) { /*-------------------------------------------------------------------- c form the lower triangular part of the jacobian matrix --------------------------------------------------------------------*/ jacld(k); /*-------------------------------------------------------------------- c perform the lower triangular solution --------------------------------------------------------------------*/ blts(nx, ny, nz, k, omega, rsd, a, b, c, d, ist, iend, jst, jend, nx0, ny0 ); } #pragma omp barrier for (k = nz - 2; k >= 1; k--) { /*-------------------------------------------------------------------- c form the strictly upper triangular part of the jacobian matrix --------------------------------------------------------------------*/ jacu(k); /*-------------------------------------------------------------------- c perform the upper triangular solution --------------------------------------------------------------------*/ buts(nx, ny, nz, k, omega, rsd, tv, d, a, b, c, ist, iend, jst, jend, nx0, ny0 ); } #pragma omp barrier /*-------------------------------------------------------------------- c update the variables --------------------------------------------------------------------*/ #pragma omp for for (i = ist; i <= iend; i++) { for (j = jst; j <= jend; j++) { for (k = 1; k <= nz-2; k++) { for (m = 0; m < 5; m++) { u[i][j][k][m] = u[i][j][k][m] + tmp * rsd[i][j][k][m]; } } } } } /* end parallel */ /*-------------------------------------------------------------------- c compute the max-norms of newton iteration corrections --------------------------------------------------------------------*/ if ( istep % inorm == 0 ) { l2norm( nx0, ny0, nz0, ist, iend, jst, jend, rsd, delunm ); } /*-------------------------------------------------------------------- c compute the steady-state residuals --------------------------------------------------------------------*/ rhs(); /*-------------------------------------------------------------------- c compute the max-norms of newton iteration residuals --------------------------------------------------------------------*/ if ( ( istep % inorm == 0 ) || ( istep == itmax ) ) { l2norm( nx0, ny0, nz0, ist, iend, jst, jend, rsd, rsdnm ); } /*-------------------------------------------------------------------- c check the newton-iteration residuals against the tolerance levels --------------------------------------------------------------------*/ if ( ( rsdnm[0] < tolrsd[0] ) && ( rsdnm[1] < tolrsd[1] ) && ( rsdnm[2] < tolrsd[2] ) && ( rsdnm[3] < tolrsd[3] ) && ( rsdnm[4] < tolrsd[4] ) ) { exit(1); } } timer_stop(1); maxtime= timer_read(1); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void verify(double xcr[5], double xce[5], double xci, char *class, boolean *verified) { /*-------------------------------------------------------------------- c verification routine --------------------------------------------------------------------*/ double xcrref[5],xceref[5],xciref, xcrdif[5],xcedif[5],xcidif, epsilon, dtref; int m; /*-------------------------------------------------------------------- c tolerance level --------------------------------------------------------------------*/ epsilon = 1.0e-08; *class = 'U'; *verified = TRUE; for (m = 0; m < 5; m++) { xcrref[m] = 1.0; xceref[m] = 1.0; } xciref = 1.0; if ( nx0 == 12 && ny0 == 12 && nz0 == 12 && itmax == 50) { *class = 'S'; dtref = 5.0e-1; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual, for the (12X12X12) grid, c after 50 time steps, with DT = 5.0d-01 --------------------------------------------------------------------*/ xcrref[0] = 1.6196343210976702e-02; xcrref[1] = 2.1976745164821318e-03; xcrref[2] = 1.5179927653399185e-03; xcrref[3] = 1.5029584435994323e-03; xcrref[4] = 3.4264073155896461e-02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error, for the (12X12X12) grid, c after 50 time steps, with DT = 5.0d-01 --------------------------------------------------------------------*/ xceref[0] = 6.4223319957960924e-04; xceref[1] = 8.4144342047347926e-05; xceref[2] = 5.8588269616485186e-05; xceref[3] = 5.8474222595157350e-05; xceref[4] = 1.3103347914111294e-03; /*-------------------------------------------------------------------- c Reference value of surface integral, for the (12X12X12) grid, c after 50 time steps, with DT = 5.0d-01 --------------------------------------------------------------------*/ xciref = 7.8418928865937083; } else if ( nx0 == 33 && ny0 == 33 && nz0 == 33 && itmax == 300) { *class = 'W'; /* SPEC95fp size */ dtref = 1.5e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual, for the (33x33x33) grid, c after 300 time steps, with DT = 1.5d-3 --------------------------------------------------------------------*/ xcrref[0] = 0.1236511638192e+02; xcrref[1] = 0.1317228477799e+01; xcrref[2] = 0.2550120713095e+01; xcrref[3] = 0.2326187750252e+01; xcrref[4] = 0.2826799444189e+02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error, for the (33X33X33) grid, --------------------------------------------------------------------*/ xceref[0] = 0.4867877144216; xceref[1] = 0.5064652880982e-01; xceref[2] = 0.9281818101960e-01; xceref[3] = 0.8570126542733e-01; xceref[4] = 0.1084277417792e+01; /*-------------------------------------------------------------------- c Reference value of surface integral, for the (33X33X33) grid, c after 300 time steps, with DT = 1.5d-3 --------------------------------------------------------------------*/ xciref = 0.1161399311023e+02; } else if ( nx0 == 64 && ny0 == 64 && nz0 == 64 && itmax == 250) { *class = 'A'; dtref = 2.0e+0; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual, for the (64X64X64) grid, c after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xcrref[0] = 7.7902107606689367e+02; xcrref[1] = 6.3402765259692870e+01; xcrref[2] = 1.9499249727292479e+02; xcrref[3] = 1.7845301160418537e+02; xcrref[4] = 1.8384760349464247e+03; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error, for the (64X64X64) grid, c after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xceref[0] = 2.9964085685471943e+01; xceref[1] = 2.8194576365003349; xceref[2] = 7.3473412698774742; xceref[3] = 6.7139225687777051; xceref[4] = 7.0715315688392578e+01; /*-------------------------------------------------------------------- c Reference value of surface integral, for the (64X64X64) grid, c after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xciref = 2.6030925604886277e+01; } else if ( nx0 == 102 && ny0 == 102 && nz0 == 102 && itmax == 250) { *class = 'B'; dtref = 2.0e+0; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual, for the (102X102X102) grid, c after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xcrref[0] = 3.5532672969982736e+03; xcrref[1] = 2.6214750795310692e+02; xcrref[2] = 8.8333721850952190e+02; xcrref[3] = 7.7812774739425265e+02; xcrref[4] = 7.3087969592545314e+03; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error, for the (102X102X102) c grid, after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xceref[0] = 1.1401176380212709e+02; xceref[1] = 8.1098963655421574; xceref[2] = 2.8480597317698308e+01; xceref[3] = 2.5905394567832939e+01; xceref[4] = 2.6054907504857413e+02; /*-------------------------------------------------------------------- c Reference value of surface integral, for the (102X102X102) grid, c after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xciref = 4.7887162703308227e+01; } else if ( nx0 == 162 && ny0 == 162 && nz0 == 162 && itmax == 250) { *class = 'C'; dtref = 2.0e+0; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual, for the (162X162X162) grid, c after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xcrref[0] = 1.03766980323537846e+04; xcrref[1] = 8.92212458801008552e+02; xcrref[2] = 2.56238814582660871e+03; xcrref[3] = 2.19194343857831427e+03; xcrref[4] = 1.78078057261061185e+04; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error, for the (162X162X162) c grid, after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xceref[0] = 2.15986399716949279e+02; xceref[1] = 1.55789559239863600e+01; xceref[2] = 5.41318863077207766e+01; xceref[3] = 4.82262643154045421e+01; xceref[4] = 4.55902910043250358e+02; /*-------------------------------------------------------------------- c Reference value of surface integral, for the (162X162X162) grid, c after 250 time steps, with DT = 2.0d+0.0 --------------------------------------------------------------------*/ xciref = 6.66404553572181300e+01; } else { *verified = FALSE; } /*-------------------------------------------------------------------- c verification test for residuals if gridsize is either 12X12X12 or c 64X64X64 or 102X102X102 or 162X162X162 --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Compute the difference of solution values and the known reference values. --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { xcrdif[m] = fabs((xcr[m]-xcrref[m])/xcrref[m]); xcedif[m] = fabs((xce[m]-xceref[m])/xceref[m]); } xcidif = fabs((xci - xciref)/xciref); /*-------------------------------------------------------------------- c Output the comparison of computed results to known cases. --------------------------------------------------------------------*/ if (*class != 'U') { printf("\n Verification being performed for class %1c\n", *class); printf(" Accuracy setting for epsilon = %20.13e\n", epsilon); if (fabs(dt-dtref) > epsilon) { *verified = FALSE; *class = 'U'; printf(" DT does not match the reference value of %15.8e\n", dtref); } } else { printf(" Unknown class\n"); } if (*class != 'U') { printf(" Comparison of RMS-norms of residual\n"); } else { printf(" RMS-norms of residual\n"); } for (m = 0; m < 5; m++) { if (*class == 'U') { printf(" %2d %20.13e\n", m, xcr[m]); } else if (xcrdif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d %20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); } else { printf(" %2d %20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); } } if (*class != 'U') { printf(" Comparison of RMS-norms of solution error\n"); } else { printf(" RMS-norms of solution error\n"); } for (m = 0; m < 5; m++) { if (*class == 'U') { printf(" %2d %20.13e\n", m, xce[m]); } else if (xcedif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d %20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); } else { printf(" %2d %20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); } } if (*class != 'U') { printf(" Comparison of surface integral\n"); } else { printf(" Surface integral\n"); } if (*class == 'U') { printf(" %20.13e\n", xci); } else if (xcidif > epsilon) { *verified = FALSE; printf(" FAILURE: %20.13e%20.13e%20.13e\n", xci, xciref, xcidif); } else { printf(" %20.13e%20.13e%20.13e\n", xci, xciref, xcidif); } if (*class == 'U') { printf(" No reference values provided\n"); printf(" No verification performed\n"); } else if (*verified) { printf(" Verification Successful\n"); } else { printf(" Verification failed\n"); } }
GB_binop__bxnor_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__bxnor_uint32 // A.*B function (eWiseMult): GB_AemultB__bxnor_uint32 // A*D function (colscale): GB_AxD__bxnor_uint32 // D*A function (rowscale): GB_DxB__bxnor_uint32 // C+=B function (dense accum): GB_Cdense_accumB__bxnor_uint32 // C+=b function (dense accum): GB_Cdense_accumb__bxnor_uint32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bxnor_uint32 // C=scalar+B GB_bind1st__bxnor_uint32 // C=scalar+B' GB_bind1st_tran__bxnor_uint32 // C=A+scalar GB_bind2nd__bxnor_uint32 // C=A'+scalar GB_bind2nd_tran__bxnor_uint32 // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = ~((aij) ^ (bij)) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ 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) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // 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) \ 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)) ; // 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_BXNOR || GxB_NO_UINT32 || GxB_NO_BXNOR_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__bxnor_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__bxnor_uint32 ( 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__bxnor_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__bxnor_uint32 ( 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 uint32_t *GB_RESTRICT Cx = (uint32_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__bxnor_uint32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_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__bxnor_uint32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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__bxnor_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 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__bxnor_uint32 ( 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 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 < anz ; p++) { if (!GBB (Bb, p)) continue ; uint32_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__bxnor_uint32 ( 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 ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = 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) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = ~((x) ^ (aij)) ; \ } GrB_Info GB_bind1st_tran__bxnor_uint32 ( 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 \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = ~((aij) ^ (y)) ; \ } GrB_Info GB_bind2nd_tran__bxnor_uint32 ( 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 uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
hamcluster_1.h
// // Created by Vasiliy Ershov on 25/09/16. // #ifndef PROJECT_HAMCLUSTER_1_H #define PROJECT_HAMCLUSTER_1_H #include <common/adt/concurrent_dsu.hpp> #include <common/pipeline/config_singl.hpp> #include "HSeq.hpp" #include "kmer_data.hpp" #include "utils/logger/logger.hpp" #include "valid_hkmer_generator.hpp" namespace hammer { using HRun = HomopolymerRun; class TOneErrorClustering { private: const KMerData& data_; dsu::ConcurrentDSU clusters_; bool TryMergeClusters(const HKMer& source, const size_t source_idx, const HKMer& fixed) { auto fixed_idx = data_.checking_seq_idx(fixed); if (fixed_idx == (-1ULL)) { return false; } if (data_[fixed_idx].count > 0) { clusters_.unite(source_idx, fixed_idx); auto rSource = !source; auto rFixed = !fixed; clusters_.unite(data_.seq_idx(rSource), data_.seq_idx(rFixed)); return true; } else { return false; } } void TryCorrection(const KMerStat& source_stat, size_t source_idx) { const auto& source = source_stat.kmer; auto fixed = source; for (uint k = 0; k < K; ++k) { for (uint i = (uint)std::max(source[k].len - 1, 1); i <= (uint)(source[k].len + 1); ++i) { if (i == source[k].len) { continue; } fixed[k].len = i & 0x3F; TryMergeClusters(source, source_idx, fixed); } fixed[k].len = source[k].len; } } public: TOneErrorClustering(const KMerData& data, const uint num_threads = 16) : data_(data), clusters_(data.size()) { (void)num_threads; // stupid compiler #pragma omp parallel for num_threads(num_threads) for (size_t idx = 0; idx < data_.size(); ++idx) { if (data_[idx].count > 0) { TryCorrection(data_[idx], idx); } } } void FillClasses(std::vector<std::vector<size_t> >& clusters) { clusters_.get_sets(clusters); } }; } // namespace hammer #endif // PROJECT_HAMCLUSTER_1_H
task_types.c
// RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s // REQUIRES: ompt #include "callback.h" #include <omp.h> #include <math.h> __attribute__ ((noinline)) // workaround for bug in icc void print_task_type(int id) { #pragma omp critical { int task_type; char buffer[2048]; ompt_get_task_info(0, &task_type, NULL, NULL, NULL, NULL); format_task_type(task_type, buffer); printf("%" PRIu64 ": id=%d task_type=%s=%d\n", ompt_get_thread_data()->value, id, buffer, task_type); } }; int main() { //initial task print_task_type(0); int x; //implicit task #pragma omp parallel num_threads(1) { print_task_type(1); x++; } #pragma omp parallel num_threads(2) #pragma omp master { //explicit task #pragma omp task { print_task_type(2); x++; } //explicit task with undeferred #pragma omp task if(0) { print_task_type(3); x++; } //explicit task with untied #pragma omp task untied { print_task_type(4); x++; } //explicit task with final #pragma omp task final(1) { print_task_type(5); x++; //nested explicit task with final and undeferred #pragma omp task { print_task_type(6); x++; } } //Mergeable task test deactivated for now //explicit task with mergeable /* #pragma omp task mergeable if((int)sin(0)) { print_task_type(7); x++; } */ //TODO: merged task } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create' // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_task_create: parent_task_id=0, parent_task_frame.exit=[[NULL]], parent_task_frame.reenter=[[NULL]], new_task_id={{[0-9]+}}, codeptr_ra=[[NULL]], task_type=ompt_task_initial=1, has_dependences=no // CHECK-NOT: 0: parallel_data initially not null // CHECK: {{^}}[[MASTER_ID]]: id=0 task_type=ompt_task_initial=1 // CHECK: {{^}}[[MASTER_ID]]: id=1 task_type=ompt_task_implicit|ompt_task_undeferred=134217730 // CHECK-DAG: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit=4, has_dependences=no // CHECK-DAG: {{^[0-9]+}}: id=2 task_type=ompt_task_explicit=4 // CHECK-DAG: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred=134217732, has_dependences=no // CHECK-DAG: {{^[0-9]+}}: id=3 task_type=ompt_task_explicit|ompt_task_undeferred=134217732 // CHECK-DAG: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_untied=268435460, has_dependences=no // CHECK-DAG: {{^[0-9]+}}: id=4 task_type=ompt_task_explicit|ompt_task_untied=268435460 // CHECK-DAG: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_final=536870916, has_dependences=no // CHECK-DAG: {{^[0-9]+}}: id=5 task_type=ompt_task_explicit|ompt_task_final=536870916 // CHECK-DAG: {{^[0-9]+}}: ompt_event_task_create: parent_task_id={{[0-9]+}}, parent_task_frame.exit={{0x[0-f]+}}, parent_task_frame.reenter={{0x[0-f]+}}, new_task_id={{[0-9]+}}, codeptr_ra={{0x[0-f]+}}, task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_final=671088644, has_dependences=no // CHECK-DAG: {{^[0-9]+}}: id=6 task_type=ompt_task_explicit|ompt_task_undeferred|ompt_task_final=671088644 return 0; }
omp_parallel_sections_private.c
<ompts:test> <ompts:testdescription>Test which checks the omp parallel sections private directive.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp parallel sections private</ompts:directive> <ompts:dependences>omp critical</ompts:dependences> <ompts:testcode> #include <stdio.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_parallel_sections_private</ompts:testcode:functionname>(FILE * logFile){ <ompts:orphan:vars> int sum; int sum0; int i; </ompts:orphan:vars> int known_sum; sum = 7; sum0=0; <ompts:orphan> #pragma omp parallel sections private(<ompts:check>sum0,</ompts:check> i) { #pragma omp section { <ompts:check> sum0=0; </ompts:check> for (i=1;i<400;i++) sum0=sum0+i; #pragma omp critical { sum= sum+sum0; } /*end of critical */ } #pragma omp section { <ompts:check> sum0=0; </ompts:check> for(i=400;i<700;i++) sum0=sum0+i; #pragma omp critical { sum= sum+sum0; } /*end of critical */ } #pragma omp section { <ompts:check> sum0=0; </ompts:check> for(i=700;i<1000;i++) sum0=sum0+i; #pragma omp critical { sum= sum+sum0; } /*end of critical */ } } /*end of paralell sections*/ </ompts:orphan> known_sum=(999*1000)/2+7; return (known_sum==sum); } /* end of check_section_private*/ </ompts:testcode> </ompts:test>
loopct_r8.c
/* * Input: ntabs nchannels padded_size * Output: ntabs ntimes -nchannels ; ntimes < padded_size * * We process a finished tab directly, so no need to build up the full ntabs array */ void deinterleave(const char *page, char *transposed, const int ntabs, const int nchannels, const int ntimes, const int padded_size) { int tab; for (tab = 0; tab < ntabs; tab++) { int channel; #pragma omp parallel for for (channel = 0; channel < nchannels; channel+=6) { const char *channelA = &page[(tab*nchannels + channel + 0)*padded_size]; const char *channelB = &page[(tab*nchannels + channel + 1)*padded_size]; const char *channelC = &page[(tab*nchannels + channel + 2)*padded_size]; const char *channelD = &page[(tab*nchannels + channel + 3)*padded_size]; const char *channelE = &page[(tab*nchannels + channel + 4)*padded_size]; const char *channelF = &page[(tab*nchannels + channel + 5)*padded_size]; const char *channelG = &page[(tab*nchannels + channel + 6)*padded_size]; const char *channelH = &page[(tab*nchannels + channel + 7)*padded_size]; int time; for (time = 0; time < ntimes; time++) { // reverse freq order to comply with header transposed[time*nchannels+nchannels-(channel+0)-1] = channelA[time]; transposed[time*nchannels+nchannels-(channel+1)-1] = channelB[time]; transposed[time*nchannels+nchannels-(channel+2)-1] = channelC[time]; transposed[time*nchannels+nchannels-(channel+3)-1] = channelD[time]; transposed[time*nchannels+nchannels-(channel+4)-1] = channelE[time]; transposed[time*nchannels+nchannels-(channel+5)-1] = channelF[time]; transposed[time*nchannels+nchannels-(channel+6)-1] = channelG[time]; transposed[time*nchannels+nchannels-(channel+7)-1] = channelH[time]; } } } }
thread_ws_scale.c
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ /* * See COPYRIGHT in top-level directory. */ #define _GNU_SOURCE #include <stdio.h> #include <omp.h> #include <sched.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <getopt.h> #include "zmtest_abslock.h" #define TEST_NITER (1<<22) #define WARMUP_ITER 128 #define CACHELINE_SZ 64 char *cache_lines; unsigned array_len = 10; zm_abslock_t lock; #if defined (ZM_BIND_MANUAL) void bind_compact(){ int tid = omp_get_thread_num(); /* Compute the target core */ int tgt_core = tid; cpu_set_t set; CPU_ZERO(&set); CPU_SET(tgt_core, &set); if (pthread_setaffinity_np(pthread_self(), sizeof(set), &set) < 0) { perror("pthread_setaffinity_np"); } } #else #define bind_compact() #endif static void test_thruput() { memset(cache_lines, 0, CACHELINE_SZ * array_len); unsigned nthreads = omp_get_max_threads(); zm_abslock_init(&lock); int cur_nthreads; /* Throughput = lock acquisitions per second */ printf("nthreads,thruput,lat\n"); for(cur_nthreads=1; cur_nthreads <= nthreads; cur_nthreads+= ((cur_nthreads==1) ? 1 : 2)) { double start_time, stop_time; #pragma omp parallel num_threads(cur_nthreads) { bind_compact(); int tid = omp_get_thread_num(); assert(tid >= 0); unsigned private_seed = (unsigned) tid; /* Warmup */ for(int iter=0; iter < WARMUP_ITER; iter++) { zm_abslock_acquire(&lock); /* Computation */ for(int i = 0; i < array_len; i++) { unsigned read_index = rand_r(&private_seed) % array_len; unsigned write_index = rand_r(&private_seed) % array_len; cache_lines[write_index] += cache_lines[read_index] + 1; } zm_abslock_release(&lock); } #pragma omp barrier #pragma omp single { start_time = omp_get_wtime(); } #pragma omp for schedule(static) for(int iter = 0; iter < TEST_NITER; iter++) { zm_abslock_acquire(&lock); /* Computation */ for(int i = 0; i < array_len; i++) { unsigned read_index = rand_r(&private_seed) % array_len; unsigned write_index = rand_r(&private_seed) % array_len; cache_lines[write_index] += cache_lines[read_index] + 1; } zm_abslock_release(&lock); } } stop_time = omp_get_wtime(); double elapsed_time = stop_time - start_time; double thruput = (double)TEST_NITER/elapsed_time; double latency = elapsed_time*1e9/TEST_NITER; // latency in nanoseconds printf("%d,%.2lf,%.2lf\n", cur_nthreads, thruput, latency); } } void usage() { printf("usage: ./<binary name> [-s <size of shared array>]\n"); } int main(int argc, char **argv) { int c; while((c = getopt(argc, argv, "s:")) != -1) { switch (c) { case 's': array_len = atoi(optarg); break; default: usage(); } } posix_memalign((void**)&cache_lines, 64, CACHELINE_SZ * array_len); test_thruput(); return 0; }
qcomp.c
// vim: noai:ts=4:sw=4 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <assert.h> #include <signal.h> #include <xmmintrin.h> #include <time.h> #ifndef __unix__ #include <sys/time.h> #endif #include <omp.h> #include "mkl.h" #include "model.h" const char *charset = "abcdefghijklmnopqrstuvwxyz0123456789 .-%_:/\\$"; int char_index[256]; // some ancient compiler does not support C11, so we have to supply this function ourselves void *aligned_alloc(size_t alignment, size_t size) { void *ptr = NULL; posix_memalign(&ptr, alignment, size); return ptr; } // The LSTM struct implementing Kera's LSTM typedef struct lstm_t { float *kernel; // concat of Kera's kernel and recurrent kernel float *bias; float **c, **h; float **z, **t; float **cbuf, **hbuf; // c and h buffer for beam search int n_in, n_hid, max_batch; // # of (input, hidden) units, and max batch size } lstm_t; // A softmax layer with linear input typedef struct softmax_t { float *W, *bias; float **out; int n_in, n_out, max_batch; } softmax_t; // The NN model typedef struct model_t { float **in; // The input lstm_t lstm_1, lstm_2; // The two layer LSTM softmax_t softmax; // THe output softmas layer (w/ linear unit) float dropout; // The fraction of dropout int n_in, n_hid, max_batch; } model_t; // Struct for completion distance typedef struct dist_t { int *seq; float *dist, *dist_new; int pos, len, extend; } dist_t; // Struct for omnicompletion typedef struct qcomp_t { int **cand, **result, **buf; float *cand_score, *result_score, **new_score; int *rank, *next_char; dist_t *dist, *dist_buf; int max_batch, max_len; } qcomp_t; // The Trie typedef struct list_t { struct list_t *next, *prev; struct list_t *child, *parent; struct list_t **top; // pointers to 16 most frequent strings in subtries int key, val; double weight; } list_t; /*********** time utils **********/ #define NS_PER_SEC 1000000000 int64_t wall_clock_ns() { #ifdef __unix__ struct timespec tspec; int r = clock_gettime(CLOCK_MONOTONIC, &tspec); assert(r==0); return tspec.tv_sec*NS_PER_SEC + tspec.tv_nsec; #else struct timeval tv; int r = gettimeofday( &tv, NULL ); assert(r==0); return tv.tv_sec*NS_PER_SEC + tv.tv_usec*1000; #endif } double wall_time_diff(int64_t ed, int64_t st) { return (double)(ed-st)/(double)NS_PER_SEC; } /************* BLAS utils *************/ void mysgemm(int m, int n, int k, float alpha, const float *restrict A, const float *restrict B, float beta, float *restrict C) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, alpha, A, k, B, k, beta, C, n); } void mysaxpy(int n, float a, const float *restrict x , float *restrict y) { cblas_saxpy(n, a, x, 1, y, 1); } void myszero(int n, float *x) { memset(x, 0, n*sizeof(*x)); } void myscopy(int n, const float *restrict x, float *restrict y) { memcpy(y, x, n*sizeof(*x)); } void myclip(int n, float *x) { x = __builtin_assume_aligned(x, 8*sizeof(float)); const __m128 mzero = _mm_set1_ps(0); const __m128 mone = _mm_set1_ps(1); for(int i=0; i<n; i+=8, x+=8){ __m128 a = _mm_load_ps(x); __m128 b = _mm_load_ps(x+4); a = _mm_max_ps(a, mzero); b = _mm_max_ps(b, mzero); a = _mm_min_ps(a, mone); b = _mm_min_ps(b, mone); _mm_store_ps(x, a); _mm_store_ps(x+4, b); } } // allocate 2D matrix with aligned bytes float **smat2d_init(int m, int n) { float **a = calloc(m, sizeof(*a)); *a = aligned_alloc(8*sizeof(float), m*n* sizeof(**a)); for(int i=1; i<m; i++) a[i] = a[0] + i*n; return a; } // allocating integer 2d matrix int **imat2d_init(int m, int n) { int **a = calloc(m, sizeof(*a)); *a = calloc(m*n, sizeof(**a)); for(int i=1; i<m; i++) a[i] = a[0]+n*i; return a; } /************* lstm_t ***********/ lstm_t lstm_init(int max_batch, int n_in, int n_hid) { lstm_t self = { .kernel = aligned_alloc(8*sizeof(float), 4*n_hid*(n_in+n_hid) * sizeof(float)), .bias = aligned_alloc(8*sizeof(float), 4*n_hid * sizeof(float)), .c = smat2d_init(max_batch, n_hid), .h = smat2d_init(max_batch, n_hid), .z = smat2d_init(max_batch, 4*n_hid), .t = smat2d_init(max_batch, n_in+n_hid), .cbuf = smat2d_init(max_batch, n_hid), .hbuf = smat2d_init(max_batch, n_hid), .n_in = n_in, .n_hid = n_hid, .max_batch = max_batch, }; return self; } // loading LSTM weights from model.h // Note that we swapped z2 and z3 in the keras impl void lstm_load(lstm_t self, const float *kernel, const float *rec_kernel, const float *bias) { int line = self.n_in + self.n_hid; for(int ii=0; ii<4*self.n_hid; ii++){ int i = ii; // swap z2 and z3 if(ii >= 3*self.n_hid) i -= self.n_hid; else if(ii >= 2*self.n_hid) i += self.n_hid; for(int j=0; j<self.n_in; j++) self.kernel[ii*line+j] = kernel[j*4*self.n_hid+i]; for(int j=0; j<self.n_hid; j++) self.kernel[ii*line+self.n_in+j] = rec_kernel[j*4*self.n_hid+i]; } myscopy(2*self.n_hid, bias, self.bias); // swap z2 and z3 myscopy(self.n_hid, bias+2*self.n_hid, self.bias+3*self.n_hid); myscopy(self.n_hid, bias+3*self.n_hid, self.bias+2*self.n_hid); } // The forward pass for LSTM // Note that the input (in) is scaled by in_alpha void lstm_forward(lstm_t self, int batch, float **in, float in_alpha) { // Applying linear ops to the input (in) #pragma omp parallel for schedule(dynamic) for(int i=0; i<batch; i++){ myszero(self.n_in, self.t[i]); mysaxpy(self.n_in, in_alpha, in[i], self.t[i]); myscopy(self.n_hid, self.h[i], self.t[i]+self.n_in); } mysgemm(batch, 4*self.n_hid, self.n_in+self.n_hid, 1, *self.t, self.kernel, 0, *self.z); // Adding bias to input, then do hard-sigmoid #pragma omp parallel for schedule(dynamic) for(int i=0; i<batch; i++){ float *z = self.z[i]; mysaxpy(4*self.n_hid, 1., self.bias, z); for(int j=0; j<3*self.n_hid; j++) z[j] = 0.2*z[j] + 0.5; myclip(3*self.n_hid, z); } // Eval next c and h #pragma omp parallel for schedule(dynamic) for(int i=0; i<batch; i++){ float *c = self.c[i], *h = self.h[i]; float *z0 = self.z[i] + self.n_hid*0, *z1 = self.z[i] + self.n_hid*1; float *z2 = self.z[i] + self.n_hid*2, *z3 = self.z[i] + self.n_hid*3; for(int j=0; j<self.n_hid; j++){ c[j] = z1[j]*c[j] + z0[j]*tanh(z3[j]); h[j] = z2[j]*tanh(c[j]); } } } // Backup current c and h to buffer void lstm_backup(lstm_t self) { myscopy(self.max_batch*self.n_hid, *self.c, *self.cbuf); myscopy(self.max_batch*self.n_hid, *self.h, *self.hbuf); } // Recover c and h from buffer void lstm_recover(lstm_t self, int src, int dst) { myscopy(self.n_hid, self.cbuf[src], self.c[dst]); myscopy(self.n_hid, self.hbuf[src], self.h[dst]); } // Reset all c and h to zero void lstm_reset(lstm_t self) { memset(*self.c, 0, self.max_batch*self.n_hid*sizeof(**self.c)); memset(*self.h, 0, self.max_batch*self.n_hid*sizeof(**self.h)); } /************* softmax_t **********/ softmax_t softmax_init(int max_batch, int n_in, int n_out) { softmax_t self = { .W = aligned_alloc(8*sizeof(float), n_in*n_out * sizeof(float)), .bias = calloc(4*sizeof(float), n_out * sizeof(float)), .out = smat2d_init(max_batch, n_out), .n_in = n_in, .n_out = n_out, .max_batch = max_batch, }; return self; } // Loading the linear weights of softmax layer void softmax_load(softmax_t self, const float *kernel, const float *bias) { for(int i=0; i<self.n_out; i++) for(int j=0; j<self.n_in; j++) self.W[i*self.n_in+j] = kernel[j*self.n_out+i]; myscopy(self.n_out, bias, self.bias); } // The forward pass of softmax void softmax_forward(softmax_t self, int batch, float **in, float in_alpha) { mysgemm(batch, self.n_out, self.n_in, in_alpha, *in, self.W, 0, *self.out); #pragma omp parallel for schedule(dynamic) for(int i=0; i<batch; i++){ float *out = self.out[i]; mysaxpy(self.n_out, 1, self.bias, out); // stable log-sum-exp float max = out[0]; for(int j=1; j<self.n_out; j++) if(max<out[j]) max = out[j]; float sum_exp = 0; for(int j=0; j<self.n_out; j++) sum_exp += exp(out[j]-max); float log_sum_exp = log(sum_exp); for(int j=0; j<self.n_out; j++) out[j] -= log_sum_exp+max; } } /************* model_t **********/ model_t model_init(int max_batch, int n_in, int n_hid) { model_t self = { .in = smat2d_init(max_batch, n_in), .lstm_1 = lstm_init(max_batch, n_in, n_hid), .lstm_2 = lstm_init(max_batch, n_hid, n_hid), .softmax = softmax_init(max_batch, n_hid, n_in), .dropout = 1, .n_in = n_in, .n_hid = n_hid, .max_batch = max_batch, }; return self; } // Loading all the weights for the model void model_load(model_t self) { lstm_load(self.lstm_1, LSTM_1_KERNEL, LSTM_1_RECURRENT_KERNEL, LSTM_1_BIAS); lstm_load(self.lstm_2, LSTM_2_KERNEL, LSTM_2_RECURRENT_KERNEL, LSTM_2_BIAS); softmax_load(self.softmax, DENSE_1_KERNEL, DENSE_1_BIAS); } // The forward pass for the model void model_forward(model_t self, int batch, int *x) { // setup the onehot encodings for inputs memset(*self.in, 0, self.max_batch*self.n_in*sizeof(float)); for(int i=0; i<batch; i++) self.in[i][x[i]] = 1; lstm_forward(self.lstm_1, batch, self.in, 1); lstm_forward(self.lstm_2, batch, self.lstm_1.h, 1/self.dropout); softmax_forward(self.softmax, batch, self.lstm_2.h, 1/self.dropout); } // Reset the recurrent units of the model void model_reset(model_t self) { lstm_reset(self.lstm_1); lstm_reset(self.lstm_2); } /************* dist_t **********/ dist_t dist_init(int max_len) { dist_t self = { .seq = calloc(max_len+1, sizeof(int)), .dist = calloc(max_len+1, sizeof(float)), .dist_new = calloc(max_len+1, sizeof(float)), .pos = 0, .len = 0, .extend = 0, }; return self; } // Setup the first column for the distance matrix dist_t dist_build(dist_t self, int *a) { int len = 0; for(; a[len]; len++) ; self.pos = 1; self.len = len; for(int j=0; j<=len; j++){ self.dist[j] = j; self.seq[j] = a[j]; } return self; } // Hard-coded index (charset + PAD/END) for space symbol #define SPACE_SYMBOL (2+26+10) // Bump the distance matrix by one column (DP-ish) // and store the result in dist_new dist_t dist_bump(dist_t self, int next_b) { self.extend = 1; self.dist_new[0] = self.pos; for(int j=1; j<=self.len; j++){ // white space or end int is_last = self.seq[j] == SPACE_SYMBOL || self.seq[j] == 0; int is_same = (next_b == self.seq[j-1]); float add = self.dist[j] + !is_last; float sub = self.dist[j-1] + !is_same; float del = self.dist_new[j-1] + 1; float cost = add; if(cost > sub) cost = sub; if(cost > del) cost = del; self.dist_new[j] = cost; } return self; } // Commit dist_new to dist dist_t dist_commit(dist_t self) { myscopy(self.len+1, self.dist_new, self.dist); self.pos++; return self; } // Copying (branching) the distance matirx void dist_copy(dist_t *src, dist_t *dst) { for(int i=0; i<=src->len; i++){ dst->seq[i] = src->seq[i]; dst->dist[i] = src->dist[i]; dst->dist_new[i] = src->dist_new[i]; } dst->len = src->len; dst->pos = src->pos; dst->extend = src->extend; } // The difference between dist_new and dist float dist_diff(dist_t self) { return self.dist_new[self.len] - self.dist[self.len]; } /************* qcomp_t ***********/ qcomp_t qcomp_init(int max_batch, int max_len) { int voc_size = strlen(charset)+2; qcomp_t self = { .cand = imat2d_init(max_batch, max_len), .result = imat2d_init(max_batch, max_len), .buf = imat2d_init(max_batch, max_len), .cand_score = calloc(max_batch, sizeof(float)), .result_score = calloc(max_batch, sizeof(float)), .new_score = smat2d_init(max_batch, voc_size), .rank = calloc(max_batch*voc_size, sizeof(int)), .next_char = calloc(max_batch, sizeof(int)), .dist = calloc(max_batch, sizeof(dist_t)), .dist_buf = calloc(max_batch, sizeof(dist_t)), .max_batch = max_batch, .max_len = max_len, }; for(int i=0; i<strlen(charset); i++) char_index[(unsigned)charset[i]] = i+2; // after PAD and END for(int i=0; i<max_batch; i++){ self.dist[i] = dist_init(max_len); self.dist_buf[i] = dist_init(max_len); } return self; } // Encode string to zero-terminating index sequence void qcomp_encode(qcomp_t self, const char *str, int *seq, int transparent) { int i; if (transparent) for(i=0; i<strlen(str); i++) seq[i] = ((unsigned char)str[i]) + 2; else for(i=0; i<strlen(str); i++) seq[i] = char_index[(unsigned)str[i]]; seq[i] = 0; } // Decode index sequence to string void qcomp_decode(qcomp_t self, const int *seq, char *str, int transparent) { int i=0; if (transparent) for(i=0; seq[i]>1 && i < 60; i++) str[i] = seq[i] - 2; else for(i=0; seq[i]>1 && i < 60; i++) str[i] = charset[seq[i]-2]; str[i] = '\0'; } // Comparator for two index by SCORE[index] float *SCORE; int argcmp(const void *x, const void *y) { int ix = *((int*)x), iy = *((int*)y); float fx = SCORE[ix], fy = SCORE[iy]; if(fx<fy) return 1; else if (fx>fy) return -1; else return 0; } // Argsort, returning index matrix sorted by score[index] void argsort(float *score, int *rank, int n) { for(int i=0; i<n; i++) rank[i] = i; SCORE=score; qsort(rank, n, sizeof(*rank), argcmp); } // Safely copying zero-terminating index sequence void seq_copy(int *src, int *dst, int max) { for(int i=0; src[i] && i<max; i++) dst[i] = src[i]; } // Boltzman sampling with temperature (scaling) int boltzman_sampling(int n, const float *log_softmax, float temp) { float *prob = calloc(n, sizeof(float)); for(int i=0; i<n; i++) prob[i] = log_softmax[i] / temp; float sum_exp = 0; for(int i=0; i<n; i++) sum_exp += exp(prob[i]); float log_sum_exp = log(sum_exp); for(int i=0; i<n; i++) prob[i] = exp(prob[i]-log_sum_exp); float t = ((float)random())/(RAND_MAX); int itval; float acc = prob[0]; for(itval=1; itval<n; acc += prob[itval++]) if(acc > t) break; free(prob); return itval-1; } // Stochastic search void qcomp_stocsearch(qcomp_t self, model_t model, int *prefix) { int voc_size = model.n_in; for(int j=0; j<self.max_batch; j++){ model_reset(model); int i; for(i=0; prefix[i]; i++){ self.result[j][i] = self.next_char[0] = prefix[i]; model_forward(model, 1, self.next_char); } float score = 0; for(; self.next_char[0]>1 && i < self.max_len; i++){ int sample = boltzman_sampling(voc_size, model.softmax.out[0], 1); self.result[j][i] = self.next_char[0] = sample; score += model.softmax.out[0][sample]; model_forward(model, 1, self.next_char); } self.result_score[j] = score; } } // Beam search // inspired by https://gist.github.com/udibr/67be473cf053d8c38730 int qcomp_beamsearch(qcomp_t self, model_t model, int *prefix) { int n_cand = 1, n_result = 0; int voc_size = model.n_in; seq_copy(prefix, self.cand[0], self.max_len); self.cand_score[0] = 0; model_reset(model); int pos=0; for(int i=0; prefix[i]; i++, pos++){ self.cand[0][i] = self.next_char[0] = prefix[i]; model_forward(model, 1, self.next_char); } for(; n_cand && pos < self.max_len; pos++){ for(int i=0; i<n_cand; i++){ for(int j=0; j<voc_size; j++) self.new_score[i][j] = self.cand_score[i] + model.softmax.out[i][j]; } argsort(*self.new_score, self.rank, voc_size*n_cand); n_cand = self.max_batch - n_result; for(int i=0; i<n_cand; i++) seq_copy(self.cand[i], self.buf[i], self.max_len); lstm_backup(model.lstm_1); lstm_backup(model.lstm_2); int n_zombie = 0; for(int r=0; r<n_cand; r++){ int idx = self.rank[r]; int i = idx / voc_size, j = idx % voc_size; if (j <= 1) { self.result_score[n_result] = (*self.new_score)[idx]; seq_copy(self.buf[i], self.result[n_result], self.max_len); self.result[n_result][pos] = j; n_result++; n_zombie++; continue; } int dst = r - n_zombie; seq_copy(self.buf[i], self.cand[dst], self.max_len); lstm_recover(model.lstm_1, i, dst); lstm_recover(model.lstm_2, i, dst); self.cand[dst][pos] = self.next_char[dst] = j; self.cand_score[dst] = (*self.new_score)[idx]; } n_cand -= n_zombie; model_forward(model, n_cand, self.next_char); } return n_result; } // Omni search int qcomp_omnisearch(qcomp_t self, model_t model, int *prefix) { int n_cand = 1, n_result = 0; int voc_size = model.n_in; double forward_time = 0; seq_copy(prefix, self.cand[0], self.max_len); self.cand_score[0] = 0; self.dist[0] = dist_build(self.dist[0], prefix); model_reset(model); int pos=0; for(int i=0; prefix[i] && i<2; i++, pos++){ self.cand[0][i] = self.next_char[0] = prefix[i]; model_forward(model, 1, self.next_char); self.dist[0] = dist_bump(self.dist[0], prefix[i]); self.dist[0] = dist_commit(self.dist[0]); } self.cand_score[0] = -4*self.dist[0].dist[self.dist[0].len]; for(; n_cand && pos < self.max_len; pos++){ #pragma omp parallel for schedule(dynamic) for(int i=0; i<n_cand; i++){ for(int j=0; j<voc_size; j++){ self.dist[i] = dist_bump(self.dist[i], j); self.new_score[i][j] = self.cand_score[i] + model.softmax.out[i][j] * self.dist[i].extend; self.new_score[i][j] -= 4*dist_diff(self.dist[i]); } } argsort(*self.new_score, self.rank, voc_size*n_cand); n_cand = self.max_batch - n_result; for(int i=0; i<n_cand; i++) seq_copy(self.cand[i], self.buf[i], self.max_len); lstm_backup(model.lstm_1); lstm_backup(model.lstm_2); for(int i=0; i<n_cand; i++) dist_copy(self.dist+i, self.dist_buf+i); int n_zombie = 0; for(int r=0; r<n_cand; r++){ int idx = self.rank[r]; int i = idx / voc_size, j = idx % voc_size; if (j <= 1) { self.result_score[n_result] = (*self.new_score)[idx]; seq_copy(self.buf[i], self.result[n_result], self.max_len); self.result[n_result][pos] = j; n_result++; n_zombie++; continue; } int dst = r - n_zombie; seq_copy(self.buf[i], self.cand[dst], self.max_len); lstm_recover(model.lstm_1, i, dst); lstm_recover(model.lstm_2, i, dst); dist_copy(self.dist_buf+i, self.dist+dst); self.cand[dst][pos] = self.next_char[dst] = j; self.cand_score[dst] = (*self.new_score)[idx]; self.dist[dst] = dist_bump(self.dist[dst], j); self.dist[dst] = dist_commit(self.dist[dst]); } n_cand -= n_zombie; int64_t time_st = wall_clock_ns(); model_forward(model, n_cand, self.next_char); int64_t time_ed = wall_clock_ns(); forward_time += wall_time_diff(time_ed, time_st); } fprintf(stderr, "forward time %f\n", forward_time); return n_result; } const int END=1; enum{VERTICAL, HORIZONTAL}; /************* trie_t *************/ list_t* trie_init(const char *fname) { char *buf = malloc(2048+20); FILE *fin = fopen(fname, "r"); list_t *root = calloc(1, sizeof(list_t)); int trie_size = 1; while(fgets(buf, 2048, fin) != NULL){ // Handling oversize sequence, strip end-lines, // and appending END symbol int len = strlen(buf); if(len>60) len = 60, buf[len] = '\0'; if(buf[len-1] == '\n') buf[--len] = '\0'; buf[len++] = END; buf[len] = '\0'; // Setup weights int count = 0; int pos = 0; // Counting # of tabs for (int i = 0; i < len; ++i) { if(buf[i] == '\t') { pos = i; count++; } } // If we find two tabs, after the second tab it is the weight // Otherwise the weight is 1 float weight = 1.0f; if (count == 2) { buf[pos] = END; weight = atof(buf+pos+1); } buf[pos+1] = '\0'; // Going down the Trie list_t *p = root; int link; char *s = buf; for(; *s; s++){ for(; p->next != NULL && p->key != *s; p = p->next) ; if(p->key != *s){ link = HORIZONTAL; break; } p->val++; p->weight += weight; if(p->child == NULL){ link = VERTICAL; s++; break; } p = p->child; } // Create nodes if not matched for(; *s; s++){ list_t *old = p; p = calloc(1, sizeof(list_t)); trie_size++; p->key = *s; p->val = 1; p->weight = weight; if(link==VERTICAL) old->child = p, p->parent = old; else old->next = p, p->prev = old; link = VERTICAL; } } fprintf(stderr, "trie size = %d\n", trie_size); free(buf); return root; } int min(int a, int b) { if(a<b) return a; else return b; } list_t *MERGE_BUF[16]; // Merging the most frequent pointers (the **top) void trie_merge_top(list_t *a, list_t *b) { int size_a = min(16, a->val); int size_b = min(16, b->val); int i=0, k=0; for(int j=0; i<size_a && j<size_b && k<size_a; k++){ list_t *pa = a->top[i], *pb = b->top[j]; if(!pa || (pb && pa->weight < pb->weight)) MERGE_BUF[k] = pb, j++; else MERGE_BUF[k] = pa, i++; } for(; k<size_a; i++, k++) MERGE_BUF[k] = a->top[i]; for(int i=0; i<size_a; i++){ a->top[i] = MERGE_BUF[i]; } } // Build the top list by recursively calling merge void trie_build(list_t *root) { int top_size = min(16, root->val); root->top = calloc(top_size, sizeof(*root->top)); // leave node if(root->key == END){ root->top[0] = root; } if (root->child) { trie_build(root->child); for(list_t *p=root->child; p; p = p->next){ trie_merge_top(root, p); } } if(root->next) trie_build(root->next); } // Lookup s in the trie, // returning trie node if found and null otherwise list_t *trie_lookup(list_t *root, char *s) { list_t *p = root; while(*s){ for(; p && p->key != *s; p = p->next) ; if(!p) break; s++; if(!*s) break; p = p->child; } return p; } // Trie search int qcomp_triesearch(qcomp_t qcomp, list_t *root, int *seq) { char prefix[258], r[258], buf[258]; #ifdef TRANSPARENT_TRIE qcomp_decode(qcomp, seq, prefix, 1); #else qcomp_decode(qcomp, seq, prefix, 0); #endif list_t *q = trie_lookup(root, prefix); if(!q){ for(int i=0; i<qcomp.max_batch; i++) qcomp.result[i][0] = qcomp.result_score[i] = 0; return 0; } for(int i=0; i<qcomp.max_batch; i++){ if(i>=q->val || !q->top[i]){ qcomp.result_score[i] = 0; qcomp.result[i][0] = 0; continue; } qcomp.result_score[i] = log(q->top[i]->weight)-log(q->weight); int len=0; for(list_t *p = q->top[i]; p != q; ){ r[len++] = p->key; while(!p->parent) p = p->prev; p = p->parent; } for(int j=0, k=len-1, t; j<k; j++, k--) t = r[j], r[j] = r[k], r[k] = t; r[len-1] = 0; memset(buf, 0, 256); strcat(buf, prefix); strcat(buf, r); #ifdef TRANSPARENT_TRIE qcomp_encode(qcomp, buf, qcomp.result[i], 1); #else qcomp_encode(qcomp, buf, qcomp.result[i], 0); #endif } return q->val; } enum{STOCSEARCH, BEAMSEARCH, OMNISEARCH, TRIESEARCH, TRIELOOKUP}; /*****************************/ int main(int argc, char **argv) { srand((unsigned)0); omp_set_num_threads(8); int n_beam = 16, max_len = 60; int voc_size = LSTM_1_KERNEL_SHAPE_0; model_t model = model_init(n_beam, voc_size, 256); model_load(model); qcomp_t qcomp = qcomp_init(n_beam, max_len); char *prefix = malloc(2048), prev[62] = {0}; char str[62]; int seq[62], rank[16]; const char *prog_name = argv[0]; const char *base_name = prog_name+strlen(prog_name)-1; for(; base_name!=prog_name && isalnum(*base_name); base_name--) ; base_name += 1; int mode = 0; int transparent = 0; // Different program names would invoke different functionalities if(strcmp(base_name, "stocsearch") == 0) mode = STOCSEARCH; else if(strcmp(base_name, "beamsearch") == 0) mode = BEAMSEARCH; else if(strcmp(base_name, "omnisearch") == 0) mode = OMNISEARCH; else if(strcmp(base_name, "triesearch") == 0) { mode = TRIESEARCH; #ifdef TRANSPARENT_TRIE transparent = 1; #endif } else if(strcmp(base_name, "trielookup") == 0) { mode = TRIELOOKUP; #ifdef TRANSPARENT_TRIE transparent = 1; #endif } else fprintf(stderr, "ERROR CMD\n"), exit(1); fprintf(stderr, "%s mode %d\n", base_name, mode); list_t *root = NULL; if(mode == TRIESEARCH || mode == TRIELOOKUP){ root = trie_init(argv[1]); trie_build(root); } int to_end = 0; if(argc >= 3 && strcmp(argv[2], "1") == 0) to_end = 1; signal(SIGPIPE, SIG_IGN); fprintf(stderr, "ready\n"); while(NULL != fgets(prefix, 2000, stdin)){ int len = strlen(prefix); if(len>60) len = 60, prefix[len] = '\0'; if(prefix[len-1] == '\n') prefix[len-1] = '\0'; qcomp_encode(qcomp, prefix, seq, transparent); int64_t st = wall_clock_ns(); // if(strcmp(prefix, prev) == 0 && mode != TRIELOOKUP) // fprintf(stderr, "repeat\n"); if(mode==STOCSEARCH) qcomp_stocsearch(qcomp, model, seq); else if(mode==BEAMSEARCH) qcomp_beamsearch(qcomp, model, seq); else if(mode==OMNISEARCH) qcomp_omnisearch(qcomp, model, seq); else if(mode==TRIESEARCH) { int count = qcomp_triesearch(qcomp, root, seq); // also count and print to stderr fprintf(stderr, "%d\n", count); fflush(stderr); } else if(mode==TRIELOOKUP){ int len = strlen(prefix); if(to_end) prefix[len++] = END; prefix[len] = '\0'; list_t *p = trie_lookup(root, prefix); if(!p) printf("0\n"); else printf("%d %f\n", p->val, p->weight); fflush(stdout); continue; } argsort(qcomp.result_score, rank, n_beam); for(int jj=0; jj<n_beam; jj++){ int j = rank[jj]; qcomp_decode(qcomp, qcomp.result[j], str, transparent); printf("%f:\t%s\n", qcomp.result_score[j], str); } fflush(stdout); strcpy(prev, prefix); } fprintf(stderr, "exit\n"); return 0; }
c-tree.h
/* Definitions for C parsing and type checking. Copyright (C) 1987, 1993, 1994, 1995, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef GCC_C_TREE_H #define GCC_C_TREE_H #include "c-common.h" #include "toplev.h" #include "diagnostic.h" /* struct lang_identifier is private to c-decl.c, but langhooks.c needs to know how big it is. This is sanity-checked in c-decl.c. */ #define C_SIZEOF_STRUCT_LANG_IDENTIFIER \ (sizeof (struct c_common_identifier) + 3 * sizeof (void *)) /* Language-specific declaration information. */ struct lang_decl GTY(()) { char dummy; }; /* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is read-only. */ #define C_TYPE_FIELDS_READONLY(TYPE) TREE_LANG_FLAG_1 (TYPE) /* In a RECORD_TYPE or UNION_TYPE, nonzero if any component is volatile. */ #define C_TYPE_FIELDS_VOLATILE(TYPE) TREE_LANG_FLAG_2 (TYPE) /* In a RECORD_TYPE or UNION_TYPE or ENUMERAL_TYPE nonzero if the definition of the type has already started. */ #define C_TYPE_BEING_DEFINED(TYPE) TYPE_LANG_FLAG_0 (TYPE) /* In an incomplete RECORD_TYPE or UNION_TYPE, a list of variable declarations whose type would be completed by completing that type. */ #define C_TYPE_INCOMPLETE_VARS(TYPE) TYPE_VFIELD (TYPE) /* In an IDENTIFIER_NODE, nonzero if this identifier is actually a keyword. C_RID_CODE (node) is then the RID_* value of the keyword, and C_RID_YYCODE is the token number wanted by Yacc. */ #define C_IS_RESERVED_WORD(ID) TREE_LANG_FLAG_0 (ID) struct lang_type GTY(()) { /* In a RECORD_TYPE, a sorted array of the fields of the type. */ struct sorted_fields_type * GTY ((reorder ("resort_sorted_fields"))) s; /* In an ENUMERAL_TYPE, the min and max values. */ tree enum_min; tree enum_max; /* In a RECORD_TYPE, information specific to Objective-C, such as a list of adopted protocols or a pointer to a corresponding @interface. See objc/objc-act.h for details. */ tree objc_info; }; /* Record whether a type or decl was written with nonconstant size. Note that TYPE_SIZE may have simplified to a constant. */ #define C_TYPE_VARIABLE_SIZE(TYPE) TYPE_LANG_FLAG_1 (TYPE) #define C_DECL_VARIABLE_SIZE(TYPE) DECL_LANG_FLAG_0 (TYPE) /* Record whether a typedef for type `int' was actually `signed int'. */ #define C_TYPEDEF_EXPLICITLY_SIGNED(EXP) DECL_LANG_FLAG_1 (EXP) /* For a FUNCTION_DECL, nonzero if it was defined without an explicit return type. */ #define C_FUNCTION_IMPLICIT_INT(EXP) DECL_LANG_FLAG_1 (EXP) /* For a FUNCTION_DECL, nonzero if it was an implicit declaration. */ #define C_DECL_IMPLICIT(EXP) DECL_LANG_FLAG_2 (EXP) /* For FUNCTION_DECLs, evaluates true if the decl is built-in but has been declared. */ #define C_DECL_DECLARED_BUILTIN(EXP) \ DECL_LANG_FLAG_3 (FUNCTION_DECL_CHECK (EXP)) /* For FUNCTION_DECLs, evaluates true if the decl is built-in, has a built-in prototype and does not have a non-built-in prototype. */ #define C_DECL_BUILTIN_PROTOTYPE(EXP) \ DECL_LANG_FLAG_6 (FUNCTION_DECL_CHECK (EXP)) /* Record whether a decl was declared register. This is strictly a front-end flag, whereas DECL_REGISTER is used for code generation; they may differ for structures with volatile fields. */ #define C_DECL_REGISTER(EXP) DECL_LANG_FLAG_4 (EXP) /* Record whether a decl was used in an expression anywhere except an unevaluated operand of sizeof / typeof / alignof. This is only used for functions declared static but not defined, though outside sizeof and typeof it is set for other function decls as well. */ #define C_DECL_USED(EXP) DECL_LANG_FLAG_5 (FUNCTION_DECL_CHECK (EXP)) /* Record whether a label was defined in a statement expression which has finished and so can no longer be jumped to. */ #define C_DECL_UNJUMPABLE_STMT_EXPR(EXP) \ DECL_LANG_FLAG_6 (LABEL_DECL_CHECK (EXP)) /* Record whether a label was the subject of a goto from outside the current level of statement expression nesting and so cannot be defined right now. */ #define C_DECL_UNDEFINABLE_STMT_EXPR(EXP) \ DECL_LANG_FLAG_7 (LABEL_DECL_CHECK (EXP)) /* Record whether a label was defined in the scope of an identifier with variably modified type which has finished and so can no longer be jumped to. */ #define C_DECL_UNJUMPABLE_VM(EXP) \ DECL_LANG_FLAG_3 (LABEL_DECL_CHECK (EXP)) /* Record whether a label was the subject of a goto from outside the current level of scopes of identifiers with variably modified type and so cannot be defined right now. */ #define C_DECL_UNDEFINABLE_VM(EXP) \ DECL_LANG_FLAG_5 (LABEL_DECL_CHECK (EXP)) /* Record whether a variable has been declared threadprivate by #pragma omp threadprivate. */ #define C_DECL_THREADPRIVATE_P(DECL) DECL_LANG_FLAG_3 (VAR_DECL_CHECK (DECL)) /* Nonzero for a decl which either doesn't exist or isn't a prototype. N.B. Could be simplified if all built-in decls had complete prototypes (but this is presently difficult because some of them need FILE*). */ #define C_DECL_ISNT_PROTOTYPE(EXP) \ (EXP == 0 \ || (TYPE_ARG_TYPES (TREE_TYPE (EXP)) == 0 \ && !DECL_BUILT_IN (EXP))) /* For FUNCTION_TYPE, a hidden list of types of arguments. The same as TYPE_ARG_TYPES for functions with prototypes, but created for functions without prototypes. */ #define TYPE_ACTUAL_ARG_TYPES(NODE) TYPE_LANG_SLOT_1 (NODE) /* Record parser information about an expression that is irrelevant for code generation alongside a tree representing its value. */ struct c_expr { /* The value of the expression. */ tree value; /* Record the original binary operator of an expression, which may have been changed by fold, STRING_CST for unparenthesized string constants, or ERROR_MARK for other expressions (including parenthesized expressions). */ enum tree_code original_code; }; /* A kind of type specifier. Note that this information is currently only used to distinguish tag definitions, tag references and typeof uses. */ enum c_typespec_kind { /* A reserved keyword type specifier. */ ctsk_resword, /* A reference to a tag, previously declared, such as "struct foo". This includes where the previous declaration was as a different kind of tag, in which case this is only valid if shadowing that tag in an inner scope. */ ctsk_tagref, /* A reference to a tag, not previously declared in a visible scope. */ ctsk_tagfirstref, /* A definition of a tag such as "struct foo { int a; }". */ ctsk_tagdef, /* A typedef name. */ ctsk_typedef, /* An ObjC-specific kind of type specifier. */ ctsk_objc, /* A typeof specifier. */ ctsk_typeof }; /* A type specifier: this structure is created in the parser and passed to declspecs_add_type only. */ struct c_typespec { /* What kind of type specifier this is. */ enum c_typespec_kind kind; /* The specifier itself. */ tree spec; }; /* A storage class specifier. */ enum c_storage_class { csc_none, csc_auto, csc_extern, csc_register, csc_static, csc_typedef }; /* A type specifier keyword "void", "_Bool", "char", "int", "float", "double", or none of these. */ enum c_typespec_keyword { cts_none, cts_void, cts_bool, cts_char, cts_int, cts_float, cts_double, cts_dfloat32, cts_dfloat64, cts_dfloat128 }; /* A sequence of declaration specifiers in C. */ struct c_declspecs { /* The type specified, if a single type specifier such as a struct, union or enum specifier, typedef name or typeof specifies the whole type, or NULL_TREE if none or a keyword such as "void" or "char" is used. Does not include qualifiers. */ tree type; /* The attributes from a typedef decl. */ tree decl_attr; /* When parsing, the attributes. Outside the parser, this will be NULL; attributes (possibly from multiple lists) will be passed separately. */ tree attrs; /* Any type specifier keyword used such as "int", not reflecting modifiers such as "short", or cts_none if none. */ enum c_typespec_keyword typespec_word; /* The storage class specifier, or csc_none if none. */ enum c_storage_class storage_class; /* Whether any declaration specifiers have been seen at all. */ BOOL_BITFIELD declspecs_seen_p : 1; /* Whether a type specifier has been seen. */ BOOL_BITFIELD type_seen_p : 1; /* Whether something other than a storage class specifier or attribute has been seen. This is used to warn for the obsolescent usage of storage class specifiers other than at the start of the list. (Doing this properly would require function specifiers to be handled separately from storage class specifiers.) */ BOOL_BITFIELD non_sc_seen_p : 1; /* Whether the type is specified by a typedef or typeof name. */ BOOL_BITFIELD typedef_p : 1; /* Whether a struct, union or enum type either had its content defined by a type specifier in the list or was the first visible declaration of its tag. */ BOOL_BITFIELD tag_defined_p : 1; /* Whether the type is explicitly "signed" or specified by a typedef whose type is explicitly "signed". */ BOOL_BITFIELD explicit_signed_p : 1; /* Whether the specifiers include a deprecated typedef. */ BOOL_BITFIELD deprecated_p : 1; /* APPLE LOCAL begin "unavailable" attribute (radar 2809697) */ /* Whether the specifiers include a unavailable typedef. */ BOOL_BITFIELD unavailable_p : 1; /* APPLE LOCAL end "unavailable" attribute (radar 2809697) */ /* APPLE LOCAL begin private extern */ /* Whether the specifiers include __private_extern. */ BOOL_BITFIELD private_extern_p : 1; /* APPLE LOCAL end private extern */ /* APPLE LOCAL CW asm blocks */ BOOL_BITFIELD iasm_asm_specbit : 1; /* Whether the type defaulted to "int" because there were no type specifiers. */ BOOL_BITFIELD default_int_p; /* Whether "long" was specified. */ BOOL_BITFIELD long_p : 1; /* Whether "long" was specified more than once. */ BOOL_BITFIELD long_long_p : 1; /* Whether "short" was specified. */ BOOL_BITFIELD short_p : 1; /* Whether "signed" was specified. */ BOOL_BITFIELD signed_p : 1; /* Whether "unsigned" was specified. */ BOOL_BITFIELD unsigned_p : 1; /* Whether "complex" was specified. */ BOOL_BITFIELD complex_p : 1; /* Whether "inline" was specified. */ BOOL_BITFIELD inline_p : 1; /* Whether "__thread" was specified. */ BOOL_BITFIELD thread_p : 1; /* Whether "const" was specified. */ BOOL_BITFIELD const_p : 1; /* Whether "volatile" was specified. */ BOOL_BITFIELD volatile_p : 1; /* Whether "restrict" was specified. */ BOOL_BITFIELD restrict_p : 1; }; /* The various kinds of declarators in C. */ enum c_declarator_kind { /* An identifier. */ cdk_id, /* A function. */ cdk_function, /* An array. */ cdk_array, /* A pointer. */ cdk_pointer, /* Parenthesized declarator with nested attributes. */ cdk_attrs }; /* Information about the parameters in a function declarator. */ struct c_arg_info { /* A list of parameter decls. */ tree parms; /* A list of structure, union and enum tags defined. */ tree tags; /* A list of argument types to go in the FUNCTION_TYPE. */ tree types; /* A list of non-parameter decls (notably enumeration constants) defined with the parameters. */ tree others; /* A list of VLA sizes from the parameters. In a function definition, these are used to ensure that side-effects in sizes of arrays converted to pointers (such as a parameter int i[n++]) take place; otherwise, they are ignored. */ tree pending_sizes; /* True when these arguments had [*]. */ BOOL_BITFIELD had_vla_unspec : 1; }; /* A declarator. */ struct c_declarator { /* The kind of declarator. */ enum c_declarator_kind kind; /* Except for cdk_id, the contained declarator. For cdk_id, NULL. */ struct c_declarator *declarator; location_t id_loc; /* Currently only set for cdk_id. */ union { /* For identifiers, an IDENTIFIER_NODE or NULL_TREE if an abstract declarator. */ tree id; /* For functions. */ struct c_arg_info *arg_info; /* For arrays. */ struct { /* The array dimension, or NULL for [] and [*]. */ tree dimen; /* The qualifiers inside []. */ int quals; /* The attributes (currently ignored) inside []. */ tree attrs; /* Whether [static] was used. */ BOOL_BITFIELD static_p : 1; /* Whether [*] was used. */ BOOL_BITFIELD vla_unspec_p : 1; } array; /* For pointers, the qualifiers on the pointer type. */ int pointer_quals; /* For attributes. */ tree attrs; } u; }; /* A type name. */ struct c_type_name { /* The declaration specifiers. */ struct c_declspecs *specs; /* The declarator. */ struct c_declarator *declarator; }; /* A parameter. */ struct c_parm { /* The declaration specifiers, minus any prefix attributes. */ struct c_declspecs *specs; /* The attributes. */ tree attrs; /* The declarator. */ struct c_declarator *declarator; }; /* Save and restore the variables in this file and elsewhere that keep track of the progress of compilation of the current function. Used for nested functions. */ struct language_function GTY(()) { struct c_language_function base; tree x_break_label; tree x_cont_label; struct c_switch * GTY((skip)) x_switch_stack; struct c_arg_info * GTY((skip)) arg_info; int returns_value; int returns_null; int returns_abnormally; int warn_about_return_type; /* APPLE LOCAL begin mainline 4.3 2006-10-31 4134307 */ /* APPLE LOCAL end mainline 4.3 2006-10-31 4134307 */ }; /* Save lists of labels used or defined in particular contexts. Allocated on the parser obstack. */ struct c_label_list { /* The label at the head of the list. */ tree label; /* The rest of the list. */ struct c_label_list *next; }; /* Statement expression context. */ struct c_label_context_se { /* The labels defined at this level of nesting. */ struct c_label_list *labels_def; /* The labels used at this level of nesting. */ struct c_label_list *labels_used; /* The next outermost context. */ struct c_label_context_se *next; }; /* Context of variably modified declarations. */ struct c_label_context_vm { /* The labels defined at this level of nesting. */ struct c_label_list *labels_def; /* The labels used at this level of nesting. */ struct c_label_list *labels_used; /* The scope of this context. Multiple contexts may be at the same numbered scope, since each variably modified declaration starts a new context. */ unsigned scope; /* The next outermost context. */ struct c_label_context_vm *next; }; /* in c-parser.c */ extern void c_parse_init (void); /* in c-aux-info.c */ extern void gen_aux_info_record (tree, int, int, int); /* in c-decl.c */ extern struct obstack parser_obstack; extern tree c_break_label; extern tree c_cont_label; extern int global_bindings_p (void); extern void push_scope (void); extern tree pop_scope (void); extern void insert_block (tree); extern void c_expand_body (tree); extern void c_init_decl_processing (void); extern void c_dup_lang_specific_decl (tree); extern void c_print_identifier (FILE *, tree, int); extern int quals_from_declspecs (const struct c_declspecs *); extern struct c_declarator *build_array_declarator (tree, struct c_declspecs *, bool, bool); extern tree build_enumerator (tree, tree); extern tree check_for_loop_decls (void); extern void mark_forward_parm_decls (void); extern void declare_parm_level (void); extern void undeclared_variable (tree, location_t); extern tree declare_label (tree); extern tree define_label (location_t, tree); extern void c_maybe_initialize_eh (void); extern void finish_decl (tree, tree, tree); extern tree finish_enum (tree, tree, tree); extern void finish_function (void); extern tree finish_struct (tree, tree, tree); extern struct c_arg_info *get_parm_info (bool); extern tree grokfield (struct c_declarator *, struct c_declspecs *, tree); extern tree groktypename (struct c_type_name *); extern tree grokparm (const struct c_parm *); extern tree implicitly_declare (tree); extern void keep_next_level (void); extern void pending_xref_error (void); extern void c_push_function_context (struct function *); extern void c_pop_function_context (struct function *); extern void push_parm_decl (const struct c_parm *); extern struct c_declarator *set_array_declarator_inner (struct c_declarator *, struct c_declarator *, bool); extern tree builtin_function (const char *, tree, int, enum built_in_class, const char *, tree); extern void shadow_tag (const struct c_declspecs *); extern void shadow_tag_warned (const struct c_declspecs *, int); extern tree start_enum (tree); extern int start_function (struct c_declspecs *, struct c_declarator *, tree); extern tree start_decl (struct c_declarator *, struct c_declspecs *, bool, tree); extern tree start_struct (enum tree_code, tree); extern void store_parm_decls (void); extern void store_parm_decls_from (struct c_arg_info *); extern tree xref_tag (enum tree_code, tree); extern struct c_typespec parser_xref_tag (enum tree_code, tree); extern int c_expand_decl (tree); extern struct c_parm *build_c_parm (struct c_declspecs *, tree, struct c_declarator *); extern struct c_declarator *build_attrs_declarator (tree, struct c_declarator *); extern struct c_declarator *build_function_declarator (struct c_arg_info *, struct c_declarator *); extern struct c_declarator *build_id_declarator (tree); extern struct c_declarator *make_pointer_declarator (struct c_declspecs *, struct c_declarator *); extern struct c_declspecs *build_null_declspecs (void); extern struct c_declspecs *declspecs_add_qual (struct c_declspecs *, tree); extern struct c_declspecs *declspecs_add_type (struct c_declspecs *, struct c_typespec); extern struct c_declspecs *declspecs_add_scspec (struct c_declspecs *, tree); extern struct c_declspecs *declspecs_add_attrs (struct c_declspecs *, tree); extern struct c_declspecs *finish_declspecs (struct c_declspecs *); /* in c-objc-common.c */ extern int c_disregard_inline_limits (tree); extern int c_cannot_inline_tree_fn (tree *); extern bool c_objc_common_init (void); extern bool c_missing_noreturn_ok_p (tree); extern tree c_objc_common_truthvalue_conversion (tree expr); extern bool c_warn_unused_global_decl (tree); extern void c_initialize_diagnostics (diagnostic_context *); extern bool c_vla_unspec_p (tree x, tree fn); #define c_build_type_variant(TYPE, CONST_P, VOLATILE_P) \ c_build_qualified_type ((TYPE), \ ((CONST_P) ? TYPE_QUAL_CONST : 0) | \ ((VOLATILE_P) ? TYPE_QUAL_VOLATILE : 0)) /* in c-typeck.c */ extern int in_alignof; extern int in_sizeof; extern int in_typeof; extern struct c_switch *c_switch_stack; extern struct c_label_context_se *label_context_stack_se; extern struct c_label_context_vm *label_context_stack_vm; extern tree require_complete_type (tree); extern int same_translation_unit_p (tree, tree); extern int comptypes (tree, tree); extern bool c_vla_type_p (tree); extern bool c_mark_addressable (tree); extern void c_incomplete_type_error (tree, tree); extern tree c_type_promotes_to (tree); extern struct c_expr default_function_array_conversion (struct c_expr); extern tree composite_type (tree, tree); extern tree build_component_ref (tree, tree); extern tree build_array_ref (tree, tree); extern tree build_external_ref (tree, int, location_t); extern void pop_maybe_used (bool); extern struct c_expr c_expr_sizeof_expr (struct c_expr); extern struct c_expr c_expr_sizeof_type (struct c_type_name *); extern struct c_expr parser_build_unary_op (enum tree_code, struct c_expr); extern struct c_expr parser_build_binary_op (enum tree_code, struct c_expr, struct c_expr); extern tree build_conditional_expr (tree, tree, tree); extern tree build_compound_expr (tree, tree); extern tree c_cast_expr (struct c_type_name *, tree); extern tree build_c_cast (tree, tree); extern void store_init_value (tree, tree); extern void error_init (const char *); extern void pedwarn_init (const char *); extern void maybe_warn_string_init (tree, struct c_expr); extern void start_init (tree, tree, int); extern void finish_init (void); extern void really_start_incremental_init (tree); extern void push_init_level (int); extern struct c_expr pop_init_level (int); extern void set_init_index (tree, tree); extern void set_init_label (tree); extern void process_init_element (struct c_expr); extern tree build_compound_literal (tree, tree); extern tree c_start_case (tree); extern void c_finish_case (tree); extern tree build_asm_expr (tree, tree, tree, tree, bool); extern tree build_asm_stmt (tree, tree); extern tree c_convert_parm_for_inlining (tree, tree, tree, int); extern int c_types_compatible_p (tree, tree); extern tree c_begin_compound_stmt (bool); extern tree c_end_compound_stmt (tree, bool); extern void c_finish_if_stmt (location_t, tree, tree, tree, bool); /* APPLE LOCAL begin for-fsf-4_4 3274130 5295549 */ \ extern void c_finish_loop (location_t, tree, tree, tree, tree, tree, tree, bool); /* APPLE LOCAL end for-fsf-4_4 3274130 5295549 */ \ extern tree c_begin_stmt_expr (void); extern tree c_finish_stmt_expr (tree); extern tree c_process_expr_stmt (tree); extern tree c_finish_expr_stmt (tree); extern tree c_finish_return (tree); extern tree c_finish_bc_stmt (tree *, bool); extern tree c_finish_goto_label (tree); extern tree c_finish_goto_ptr (tree); extern void c_begin_vm_scope (unsigned int); extern void c_end_vm_scope (unsigned int); extern tree c_expr_to_decl (tree, bool *, bool *, bool *); extern tree c_begin_omp_parallel (void); extern tree c_finish_omp_parallel (tree, tree); extern tree c_finish_omp_clauses (tree); /* APPLE LOCAL begin CW asm blocks */ extern tree get_structure_offset (tree, tree); extern tree lookup_struct_or_union_tag (tree); /* APPLE LOCAL end CW asm blocks */ /* Set to 0 at beginning of a function definition, set to 1 if a return statement that specifies a return value is seen. */ extern int current_function_returns_value; /* Set to 0 at beginning of a function definition, set to 1 if a return statement with no argument is seen. */ extern int current_function_returns_null; /* Set to 0 at beginning of a function definition, set to 1 if a call to a noreturn function is seen. */ extern int current_function_returns_abnormally; /* Nonzero means we are reading code that came from a system header file. */ extern int system_header_p; /* True means global_bindings_p should return false even if the scope stack says we are in file scope. */ extern bool c_override_global_bindings_to_false; /* True means we've initialized exception handling. */ extern bool c_eh_initialized_p; /* In c-decl.c */ extern void c_finish_incomplete_decl (tree); extern void c_write_global_declarations (void); /* APPLE LOCAL radar 5741070 */ extern tree c_return_interface_record_type (tree); /* In order for the format checking to accept the C frontend diagnostic framework extensions, you must include this file before toplev.h, not after. */ #if GCC_VERSION >= 4001 #define ATTRIBUTE_GCC_CDIAG(m, n) __attribute__ ((__format__ (GCC_DIAG_STYLE, m ,n))) ATTRIBUTE_NONNULL(m) #else #define ATTRIBUTE_GCC_CDIAG(m, n) ATTRIBUTE_NONNULL(m) #endif extern void pedwarn_c90 (const char *, ...) ATTRIBUTE_GCC_CDIAG(1,2); extern void pedwarn_c99 (const char *, ...) ATTRIBUTE_GCC_CDIAG(1,2); #endif /* ! GCC_C_TREE_H */
engine.c
/********************************************************************[libaroma]* * Copyright (C) 2011-2015 Ahmad Amarullah (http://amarullz.com/) * * 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. *______________________________________________________________________________ * * Filename : engine.c * Description : engine header * * + This is part of libaroma, an embedded ui toolkit. * + 27/02/15 - Author(s): Ahmad Amarullah * */ #ifndef __libaroma_engine_c__ #define __libaroma_engine_c__ #ifdef __ARM_HAVE_NEON #include <arm_neon.h> /* include arm_neon.h */ #define LIBAROMA_CONFIG_ENGINE_ALPHA \ "neon/alpha_neon.c" #define LIBAROMA_CONFIG_ENGINE_BLT \ "neon/blt_neon.c" #define LIBAROMA_CONFIG_ENGINE_COLOR \ "neon/color_neon.c" #define LIBAROMA_CONFIG_ENGINE_DITHER \ "neon/dither_neon.c" #endif /* __ARM_HAVE_NEON */ /* * Variable : libaroma_dither_tresshold_r * Type : const * Descriptions: dither tresshold for red channel */ static const byte libaroma_dither_tresshold_r[64] = { 1, 7, 3, 5, 0, 8, 2, 6, 7, 1, 5, 3, 8, 0, 6, 2, 3, 5, 0, 8, 2, 6, 1, 7, 5, 3, 8, 0, 6, 2, 7, 1, 0, 8, 2, 6, 1, 7, 3, 5, 8, 0, 6, 2, 7, 1, 5, 3, 2, 6, 1, 7, 3, 5, 0, 8, 6, 2, 7, 1, 5, 3, 8, 0 }; /* * Variable : libaroma_dither_tresshold_g * Type : const * Descriptions: dither tresshold for green channel */ static const byte libaroma_dither_tresshold_g[64] = { 1, 3, 2, 2, 3, 1, 2, 2, 2, 2, 0, 4, 2, 2, 4, 0, 3, 1, 2, 2, 1, 3, 2, 2, 2, 2, 4, 0, 2, 2, 0, 4, 1, 3, 2, 2, 3, 1, 2, 2, 2, 2, 0, 4, 2, 2, 4, 0, 3, 1, 2, 2, 1, 3, 2, 2, 2, 2, 4, 0, 2, 2, 0, 4 }; /* * Variable : libaroma_dither_tresshold_b * Type : const * Descriptions: dither tresshold for blue channel */ static const byte libaroma_dither_tresshold_b[64] = { 5, 3, 8, 0, 6, 2, 7, 1, 3, 5, 0, 8, 2, 6, 1, 7, 8, 0, 6, 2, 7, 1, 5, 3, 0, 8, 2, 6, 1, 7, 3, 5, 6, 2, 7, 1, 5, 3, 8, 0, 2, 6, 1, 7, 3, 5, 0, 8, 7, 1, 5, 3, 8, 0, 6, 2, 1, 7, 3, 5, 0, 8, 2, 6 }; word libaroma_rgb_from_string(const char * c) { if (c[0] != '#') { return 0; } char out[9] = {'0', 'x'}; int i; if (strlen(c) == 7) { for (i = 1; i < 7; i++) { out[i + 1] = c[i]; } } else if (strlen(c) == 4) { for (i = 0; i < 3; i++) { out[(i * 2) + 2] = c[i + 1]; out[(i * 2) + 3] = c[i + 1]; } } else { return 0; } out[8] = 0; return libaroma_rgb_to16(strtoul(out, NULL, 0)); } /* 16bit color channel */ byte libaroma_color_r(word rgb) { return ((byte) (((((word)(rgb)) & 0xF800)) >> 8)); } byte libaroma_color_g(word rgb) { return ((byte) (((((word)(rgb)) & 0x07E0)) >> 3)); } byte libaroma_color_b(word rgb) { return ((byte) (((((word)(rgb)) & 0x001F)) << 3)); } /* hi color shifted */ byte libaroma_color_hi_r(byte v){ return (v | (v >> 5)); } byte libaroma_color_hi_g(byte v){ return (v | (v >> 6)); } /* calculate color luminance */ byte libaroma_color_luminance(word rgb){ return (byte) MIN(0xff,MAX(0, (( libaroma_color_r(rgb)*306+ libaroma_color_g(rgb)*602+ libaroma_color_b(rgb)*116 )>>10) )); } /* is dark color */ byte libaroma_color_isdark(word rgb){ if (libaroma_color_luminance(rgb)>128){ return 0; } return 1; } /* 32bit color channel */ byte libaroma_color_r32(dword rgb) { return (byte) ((rgb >> 16) & 0xff); } byte libaroma_color_g32(dword rgb) { return (byte) ((rgb >> 8) & 0xff); } byte libaroma_color_b32(dword rgb) { return (byte) (rgb & 0xff); } byte libaroma_color_a32(dword rgb) { return (byte) ((rgb >> 24) & 0xff); } /* 16bit closest color channel */ byte libaroma_color_close_r(byte c) { /* red & blue */ return (((byte) c) >> 3 << 3); } byte libaroma_color_close_g(byte c) { return (((byte) c) >> 2 << 2); } /* hi color left */ byte libaroma_color_left(byte r, byte g, byte b) { return ( (((r - libaroma_color_close_r(r)) & 7) << 5) | (((g - libaroma_color_close_g(g)) & 3) << 3) | ((b - libaroma_color_close_b(b)) & 7) ); } /* merge hi color & main color */ dword libaroma_color_merge(word color, byte hicolor) { return libaroma_rgba( libaroma_color_r(color) + (hicolor >> 5), libaroma_color_g(color) + ((hicolor >> 3) & 3), libaroma_color_b(color) + (hicolor & 7), 0xff ); } byte libaroma_color_merge_r(word color, byte hicolor) { return ((byte) (((((word)(color)) & 0xF800)) >> 8)) + (hicolor >> 5); } byte libaroma_color_merge_g(word color, byte hicolor) { return ((byte) (((((word)(color)) & 0x07E0)) >> 3)) + ((hicolor >> 3) & 3); } byte libaroma_color_merge_b(word color, byte hicolor) { return ((byte) (((((word)(color)) & 0x001F)) << 3)) + (hicolor & 7); } /* 16bit rgb */ word libaroma_rgb(byte r, byte g, byte b) { return ((word)((r >> 3) << 11)|((g >> 2) << 5) | (b >> 3)); } /* 32bit rgba */ dword libaroma_rgba(byte r, byte g, byte b, byte a) { return (dword) ( ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff) | ((a & 0xff) << 24) ); } /* 32bit rgb */ dword libaroma_rgb32(byte r, byte g, byte b) { return libaroma_rgba(r, g, b, 0xff); } /* Convert 32bit color to 16bit color */ word libaroma_rgb_to16(dword rgb) { return libaroma_rgb( libaroma_color_r32(rgb), libaroma_color_g32(rgb), libaroma_color_b32(rgb)); } /* Convert 16bit color to 32bit color */ dword libaroma_rgb_to32(word rgb) { #ifdef LIBAROMA_CONFIG_USE_HICOLOR_BIT return libaroma_rgb32( libaroma_color_hi_r(libaroma_color_r(rgb)), libaroma_color_hi_g(libaroma_color_g(rgb)), libaroma_color_hi_b(libaroma_color_b(rgb)) ); #else return libaroma_rgb32( libaroma_color_r(rgb), libaroma_color_g(rgb), libaroma_color_b(rgb) ); #endif } /* Convert 16bit color to RGBA */ dword libaroma_rgb_to_rgba(word rgb, byte alpha) { #ifdef LIBAROMA_CONFIG_USE_HICOLOR_BIT return libaroma_rgba( libaroma_color_hi_r(libaroma_color_r(rgb)), libaroma_color_hi_g(libaroma_color_g(rgb)), libaroma_color_hi_b(libaroma_color_b(rgb)), alpha ); #else return libaroma_rgba( libaroma_color_r(rgb), libaroma_color_g(rgb), libaroma_color_b(rgb), alpha ); #endif } #ifdef LIBAROMA_CONFIG_ENGINE_COLOR #include LIBAROMA_CONFIG_ENGINE_COLOR #endif #ifndef __engine_have_libaroma_color_set void libaroma_color_set(wordp dst, word color, int n) { #ifdef libaroma_memset16 libaroma_memset16(dst,color,n); #else int i; for (i = 0; i < n; i++) { dst[i] = color; } #endif } #endif #ifndef __engine_have_libaroma_color_set32 void libaroma_color_set32(dwordp dst, dword color, int n) { #ifdef libaroma_memcpy32 libaroma_memcpy32(dst,color,n); #else int i; for (i = 0; i < n; i++) { dst[i] = color; } #endif } #endif #ifndef __engine_have_libaroma_color_copy32 void libaroma_color_copy32(dwordp dst, wordp src, int n, bytep rgb_pos) { int i; for (i = 0; i < n; i++) { word cl = src[i]; #ifdef LIBAROMA_CONFIG_USE_HICOLOR_BIT dst[i] = ( ((libaroma_color_hi_r(libaroma_color_r(cl)) & 0xff) << rgb_pos[0]) | ((libaroma_color_hi_g(libaroma_color_g(cl)) & 0xff) << rgb_pos[1]) | ((libaroma_color_hi_b(libaroma_color_b(cl)) & 0xff) << rgb_pos[2]) ); #else dst[i] = ( ((libaroma_color_r(cl) & 0xff) << rgb_pos[0]) | ((libaroma_color_g(cl) & 0xff) << rgb_pos[1]) | ((libaroma_color_b(cl) & 0xff) << rgb_pos[2]) ); #endif } } #endif #ifndef __engine_have_libaroma_color_copy16 void libaroma_color_copy16(wordp dst, dwordp src, int n, bytep rgb_pos) { int i; for (i = 0; i < n; i++) { dword cl = src[i]; dst[i] = libaroma_rgb( (byte) ((cl >> rgb_pos[0]) & 0xff), (byte) ((cl >> rgb_pos[1]) & 0xff), (byte) ((cl >> rgb_pos[2]) & 0xff) ); } } #endif #ifdef LIBAROMA_CONFIG_ENGINE_BLT #include LIBAROMA_CONFIG_ENGINE_BLT #endif #ifndef __engine_have_libaroma_btl16 void libaroma_btl16(int n, wordp dst, const dwordp src) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_rgb_to16(src[i]); } } #endif #ifndef __engine_have_libaroma_btl32 void libaroma_btl32(int n, dwordp dst, const wordp src) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_rgb_to32(src[i]); } } #endif byte libaroma_dither_table_pos(int x, int y) { return ((y & 7) << 3) + (x & 7); } byte libaroma_dither_r(byte p) { return libaroma_dither_tresshold_r[p]; } byte libaroma_dither_g(byte p) { return libaroma_dither_tresshold_g[p]; } byte libaroma_dither_b(byte p) { return libaroma_dither_tresshold_b[p]; } word libaroma_dither_rgb(int x, int y, byte sr, byte sg, byte sb) { byte dither_xy = ((y & 7) << 3) + (x & 7); byte r = libaroma_color_close_r(MIN(sr + libaroma_dither_tresshold_r[dither_xy], 0xff)); byte g = libaroma_color_close_g(MIN(sg + libaroma_dither_tresshold_g[dither_xy], 0xff)); byte b = libaroma_color_close_b(MIN(sb + libaroma_dither_tresshold_b[dither_xy], 0xff)); return libaroma_rgb(r, g, b); } word libaroma_dither_mono_rgb(int x, int y, byte sr, byte sg, byte sb) { byte dither_xy = libaroma_dither_tresshold_g[((y & 7) << 3) + (x & 7)]; byte dither_xyrb = dither_xy * 2; byte r = libaroma_color_close_r(MIN(sr + dither_xyrb, 0xff)); byte g = libaroma_color_close_g(MIN(sg + dither_xy, 0xff)); byte b = libaroma_color_close_b(MIN(sb + dither_xyrb, 0xff)); return libaroma_rgb(r, g, b); } word libaroma_dither_mono(int x, int y, dword col) { return libaroma_dither_mono_rgb(x, y, libaroma_color_r32(col), libaroma_color_g32(col), libaroma_color_b32(col)); } word libaroma_dither(int x, int y, dword col) { return libaroma_dither_rgb(x, y, libaroma_color_r32(col), libaroma_color_g32(col), libaroma_color_b32(col)); } #ifdef LIBAROMA_CONFIG_ENGINE_DITHER #include LIBAROMA_CONFIG_ENGINE_DITHER #endif #ifndef __engine_have_libaroma_dither_line void libaroma_dither_line(int y, int w, wordp dst, const dwordp src) { int i; for (i = 0; i < w; i++) { dst[i] = libaroma_dither(i, y, src[i]); } } #endif #ifndef __engine_have_libaroma_dither_line_const void libaroma_dither_line_const(int y, int w, wordp dst, dword src) { int i; for (i = 0; i < w; i++) { dst[i] = libaroma_dither(i, y, src); } } #endif word libaroma_alpha(word dcl, word scl, byte l) { if (scl == dcl) { return scl; } else if (l == 0) { return dcl; } else if (l == 0xff) { return scl; } word na = l; word fa = 256 - na; return (word) ( (((libaroma_color_r(dcl) * fa) + (libaroma_color_r(scl) * na)) >> 11 << 11) | (((libaroma_color_g(dcl) * fa) + (libaroma_color_g(scl) * na)) >> 10 << 5) | (((libaroma_color_b(dcl) * fa) + (libaroma_color_b(scl) * na)) >> 11) ); } dword libaroma_alpha32(word dcl, word scl, byte l) { if (scl == dcl) { return libaroma_rgb_to32(scl); } else if (l == 0) { return libaroma_rgb_to32(dcl); } else if (l == 0xff) { return libaroma_rgb_to32(scl); } word na = l; word fa = 256 - na; return (dword) ( (((libaroma_color_r(dcl) * fa) + (libaroma_color_r(scl) * na)) >> 8 << 16) | (((libaroma_color_g(dcl) * fa) + (libaroma_color_g(scl) * na)) >> 8 << 8) | (((libaroma_color_b(dcl) * fa) + (libaroma_color_b(scl) * na)) >> 8) | (0xff << 24) ); } word libaroma_alpha_multi(word dcl, word scl, byte lr, byte lg, byte lb) { if (scl == dcl) { return scl; } else if (lr + lg + lb == 0) { return dcl; } else if (lr + lg + lb == 765) { return scl; } word rr = 256 - lr; word rg = 256 - lg; word rb = 256 - lb; return (word) ( (((libaroma_color_r(dcl) * rr) + (libaroma_color_r(scl) * lr)) >> 11 << 11) | (((libaroma_color_g(dcl) * rg) + (libaroma_color_g(scl) * lg)) >> 10 << 5) | (((libaroma_color_b(dcl) * rb) + (libaroma_color_b(scl) * lb)) >> 11) ); } word libaroma_alphab(word scl, byte l) { if (l == 0) { return 0; } else if (l == 255) { return scl; } word na = l; return (word) ( ((libaroma_color_r(scl) * na) >> 11 << 11) | ((libaroma_color_g(scl) * na) >> 10 << 5) | ((libaroma_color_b(scl) * na) >> 11) ); } #ifdef LIBAROMA_CONFIG_ENGINE_ALPHA #include LIBAROMA_CONFIG_ENGINE_ALPHA #endif #ifndef __engine_have_libaroma_alpha_black void libaroma_alpha_black(int n, wordp dst, wordp top, byte alpha) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_alphab(top[i], alpha); } } #endif #ifndef __engine_have_libaroma_alpha_const void libaroma_alpha_const(int n, wordp dst, wordp bottom, wordp top, byte alpha) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_alpha(bottom[i], top[i], alpha); } } #endif #ifndef __engine_have_libaroma_alpha_const_line void libaroma_alpha_const_line(int _Y, int n, wordp dst, wordp bottom, wordp top, byte alpha) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_dither(i, _Y, libaroma_alpha32(bottom[i], top[i], alpha)); } } #endif #ifndef __engine_have_libaroma_alpha_px void libaroma_alpha_px(int n, wordp dst, wordp bottom, wordp top, bytep alpha) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_alpha(bottom[i], top[i], alpha[i]); } } #endif #ifndef __engine_have_libaroma_alpha_px_line void libaroma_alpha_px_line(int _Y, int n, wordp dst, wordp bottom, wordp top, bytep alpha) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_dither(i, _Y, libaroma_alpha32(bottom[i], top[i], alpha[i])); } } #endif #ifndef __engine_have_libaroma_alpha_rgba_fill void libaroma_alpha_rgba_fill(int n, wordp dst, wordp bottom, word top, byte alpha) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_alpha(bottom[i], top, alpha); } } #endif #ifndef __engine_have_libaroma_alpha_mono void libaroma_alpha_mono(int n, wordp dst, wordp bottom, word top, bytep alpha) { int i; for (i = 0; i < n; i++) { dst[i] = libaroma_alpha(bottom[i], top, alpha[i]); } } #endif #ifndef __engine_have_libaroma_alpha_multi_line void libaroma_alpha_multi_line(int n, wordp dst, wordp bottom, word top, bytep alphargb) { int i; for (i = 0; i < n; i++) { int j = i * 3; dst[i] = libaroma_alpha_multi(bottom[i], top, alphargb[j], alphargb[j + 1], alphargb[j + 2]); } } #endif void libaroma_blt_align16(wordp dst, wordp src, int w, int h, int dst_stride, int src_stride) { int i; int w2 = w<<1; int ds = w2 + dst_stride; int ss = w2 + src_stride; bytep d = (bytep) dst; bytep s = (bytep) src; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i = 0; i < h; i++) { memcpy( d+ds*i, s+ss*i, w2 ); } } void libaroma_blt_align32_to16(wordp dst, dwordp src, int w, int h, int dst_stride, int src_stride) { int i; int dline = w+(dst_stride>>1); int sline = w+(src_stride>>2); #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i = 0; i < h; i++) { libaroma_dither_line( i, w, dst+dline*i, src+sline*i ); } } void libaroma_blt_align16_to32(dwordp dst, wordp src, int w, int h, int dst_stride, int src_stride) { int i; int dline = w+(dst_stride>>2); int sline = w+(src_stride>>1); #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i = 0; i < h; i++) { libaroma_btl32( w,dst+dline*i,src+sline*i ); } } void libaroma_blt_align32(dwordp dst, dwordp src, int w, int h, int dst_stride, int src_stride) { int i; int w4 = w<<2; int ds = w4 + dst_stride; int ss = w4 + src_stride; bytep d = (bytep) dst; bytep s = (bytep) src; #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i = 0; i < h; i++) { memcpy( d+ds*i, s+ss*i, w4 ); } } void libaroma_blt_align_to32_pos(dwordp dst, wordp src, int w, int h, int dst_stride, int src_stride, bytep rgb_pos) { int i; int dline = w+(dst_stride>>2); int sline = w+(src_stride>>1); #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i = 0; i < h; i++) { libaroma_color_copy32( dst+dline*i, src+sline*i, w, rgb_pos ); } } void libaroma_blt_align_to16_pos(wordp dst, dwordp src, int w, int h, int dst_stride, int src_stride, bytep rgb_pos) { int i; int dline = w+(dst_stride>>1); int sline = w+(src_stride>>2); #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel for #endif for (i = 0; i < h; i++) { libaroma_color_copy16( dst+dline*i, src+sline*i, w, rgb_pos ); } } #endif /* __libaroma_engine_c__ */
bins_dynamic_objects.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Nelson Lafontaine // Carlos A. Roig #if !defined(KRATOS_BINS_DYNAMIC_OBJECTS_CONTAINER_H_INCLUDED) #define KRATOS_BINS_DYNAMIC_OBJECTS_CONTAINER_H_INCLUDED // System includes #include <string> #include <iostream> #include <cmath> #include <algorithm> #include <array> // Project includes #include "tree.h" #include "cell.h" #ifdef _OPENMP #include <omp.h> #endif namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ template<class TConfigure> class BinsObjectDynamic { public: ///@name Type Definitions ///@{ enum { Dimension = TConfigure::Dimension }; typedef TConfigure Configure; typedef typename TConfigure::PointType PointType; typedef typename TConfigure::PointerType PointerType; typedef typename TConfigure::ContainerType ContainerType; typedef typename TConfigure::IteratorType IteratorType; typedef typename TConfigure::ResultContainerType ResultContainerType; typedef typename TConfigure::ResultIteratorType ResultIteratorType; typedef typename TConfigure::DistanceIteratorType DistanceIteratorType; typedef TreeNode<Dimension, PointType, PointerType, IteratorType, typename TConfigure::DistanceIteratorType> TreeNodeType; typedef typename TreeNodeType::CoordinateType CoordinateType; // double typedef typename TreeNodeType::SizeType SizeType; // std::size_t typedef typename TreeNodeType::IndexType IndexType; // std::size_t typedef Tvector<CoordinateType,Dimension> CoordinateArray; typedef Tvector<SizeType,Dimension> SizeArray; typedef Tvector<IndexType,Dimension> IndexArray; ///Contact Pair typedef typename TConfigure::ContainerContactType ContainerContactType; typedef typename TConfigure::IteratorContactType IteratorContactType; ///typedef TreeNodeType LeafType; typedef typename TreeNodeType::IteratorIteratorType IteratorIteratorType; typedef typename TreeNodeType::SearchStructureType SearchStructureType; // Global Container typedef Cell<Configure> CellType; typedef std::vector<CellType> CellContainerType; typedef typename CellContainerType::iterator CellContainerIterator; /// Pointer definition of BinsObjectDynamic KRATOS_CLASS_POINTER_DEFINITION(BinsObjectDynamic); ///@} ///@name Life Cycle ///@{ /// Default constructor. BinsObjectDynamic() {} /// Constructor de bins a bounding box /** * @brief Constructs a new BinsObjectDynamic * * Construct a new BinsObjectDynamic using a list of objects and an automatically calculate cell size. * * @param ObjectsBegin Iterator to the first object of the bins * @param ObjectsEnd Iterator to the last object of the bins */ BinsObjectDynamic (IteratorType const& ObjectsBegin, IteratorType const& ObjectsEnd) : mObjectsBegin(ObjectsBegin), mObjectsEnd(ObjectsEnd) { mObjectsSize = SearchUtils::PointerDistance(mObjectsBegin,mObjectsEnd); CalculateBoundingBox(); // Calculate mMinPoint, mMaxPoint CalculateCellSize(mObjectsSize); // Calculate number of Cells AllocateContainer(); // Allocate cell list GenerateBins(); // Fill Cells with objects } /** * @brief Constructs a new BinsObjectDynamic * * Constructs a new BinsObjectDynamic using a list of objects and an user provided cell size. * * @param ObjectsBegin Iterator to the first object of the bins * @param ObjectsEnd Iterator to the last object of the bins * @param CellSize Size of the cells (equal for every dimension) */ BinsObjectDynamic (IteratorType const& ObjectsBegin, IteratorType const& ObjectsEnd, CoordinateType CellSize) : mObjectsBegin(ObjectsBegin), mObjectsEnd(ObjectsEnd) { mObjectsSize = SearchUtils::PointerDistance(mObjectsBegin,mObjectsEnd); CalculateBoundingBox(); // Calculate mMinPoint, mMaxPoint AssignCellSize(CellSize); // Calculate number of Cells AllocateContainer(); // Allocate cell list GenerateBins(); // Fill Cells with objects } /** * @brief Constructs a new BinsObjectDynamic * * Constructs a new BinsObjectDynamic using a given bounding box and a user provided cell size. * * @param MinPoint Min point of the boundingbox containing the bins * @param MaxPoint Max point of the boundingbox containing the bins * @param CellSize Size of the cells (equal for very dimension) */ BinsObjectDynamic (const PointType& MinPoint, const PointType& MaxPoint, CoordinateType CellSize) : mObjectsSize(0), mObjectsBegin(0), mObjectsEnd(0) { for(SizeType i = 0; i < Dimension; i++) { mMinPoint[i] = MinPoint[i]; mMaxPoint[i] = MaxPoint[i]; } AssignCellSize(CellSize); // Calculate number of Cells AllocateContainer(); // Allocate cell list } /** * @brief Constructs a new BinsObjectDynamic object * * Constructs a new BinsObjectDynamic using a given bounding box and a provided aproximation of the number * of objects that will be added to the bins. * * @param MinPoint Min point of the boundingbox containing the bins * @param MaxPoint Max point of the boundingbox containing the bins * @param NumPoints Expected number of elements in the bins */ BinsObjectDynamic (const PointType& MinPoint, const PointType& MaxPoint, SizeType NumPoints) : mObjectsSize(0), mObjectsBegin(0), mObjectsEnd(0) { for(SizeType i = 0; i < Dimension; i++) { mMinPoint[i] = MinPoint[i]; mMaxPoint[i] = MaxPoint[i]; } CalculateCellSize(NumPoints); // Calculate number of Cells AllocateContainer(); // Allocate cell list } /// Destructor. virtual ~BinsObjectDynamic() {} /// Single search API /** * [SearchObjects description] * @param ThisObject [description] * @param Result [description] * @return [description] */ SizeType SearchObjects(PointerType& ThisObject, ResultContainerType& Result) { PointType Low, High; SearchStructureType Box; TConfigure::CalculateBoundingBox(ThisObject, Low, High); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInBoxLocal(ThisObject, Result, Box ); return Result.size(); } /** * [SearchObjects description] * @param ThisObject [description] * @param Result [description] * @param MaxNumberOfResults [description] * @return [description] */ SizeType SearchObjects(PointerType& ThisObject, ResultIteratorType& Result, const SizeType& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; SizeType NumberOfResults = 0; TConfigure::CalculateBoundingBox(ThisObject, Low, High); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInBoxLocal(ThisObject, Result, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } /** * [SearchObjectsInCell description] * @param ThisPoint [description] * @param Result [description] * @return [description] */ SizeType SearchObjectsInCell(const PointType& ThisPoint, ResultIteratorType Result) { /// Missing API for 'SearchObjectsInCell' without 'MaxNumberOfResults' KRATOS_ERROR << "Missing implementation of SearchObjectsInCell(PointerType, ResultIteratorType)" << std::endl; } /** * [SearchObjectsInCell description] * @param ThisPoint [description] * @param Result [description] * @param MaxNumberOfResults [description] * @return [description] */ SizeType SearchObjectsInCell(const PointType& ThisPoint, ResultIteratorType Result, const SizeType& MaxNumberOfResults) { IndexType icell = CalculateIndex(ThisPoint); if(mCells[icell].Size() < MaxNumberOfResults) { for(IteratorType i_object = mCells[icell].Begin() ; i_object != mCells[icell].End(); i_object++, Result++) { *Result = *i_object; } return mCells[icell].Size(); } else { return -1; } } /** * [SearchObjectsExclusive description] * @param ThisObject [description] * @param Result [description] * @param MaxNumberOfResults [description] * @return [description] */ SizeType SearchObjectsExclusive(PointerType& ThisObject, ResultIteratorType& Result) { PointType Low, High; SearchStructureType Box; TConfigure::CalculateBoundingBox(ThisObject, Low, High); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchObjectLocalExclusive(ThisObject, Result, Box ); return Result.size(); } /** * [SearchObjectsExclusive description] * @param ThisObject [description] * @param Result [description] * @param MaxNumberOfResults [description] * @return [description] */ SizeType SearchObjectsExclusive(PointerType& ThisObject, ResultIteratorType& Result, const SizeType& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; SizeType NumberOfResults = 0; TConfigure::CalculateBoundingBox(ThisObject, Low, High); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchObjectLocalExclusive(ThisObject, Result, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } /** * [SearchObjectsInRadius description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @return [description] */ SizeType SearchObjectsInRadius(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results) { /// Missing API for 'SearchObjectsInRadius' without 'MaxNumberOfResults' KRATOS_ERROR << "Missing implementation of SearchObjectsInRadius(PointerType, const double, ResultIteratorType)" << std::endl; } /** * [SearchObjectsInRadius description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @param MaxNumberOfResults [description] * @return [description] */ SizeType SearchObjectsInRadius(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results, const SizeType& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; SizeType NumberOfResults = 0; TConfigure::CalculateBoundingBox(ThisObject, Low, High, Radius); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInRadius(ThisObject, Radius, Results, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } /** * [SearchObjectsInRadius description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @param ResultDistances [description] * @return [description] */ SizeType SearchObjectsInRadius(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results, DistanceIteratorType ResultDistances) { /// Missing API for 'SearchObjectsInRadius' without 'MaxNumberOfResults' KRATOS_ERROR << "Missing implementation of SearchObjectsInRadius(PointerType, const double, ResultIteratorType, DistanceIteratorType)" << std::endl; } /** * [SearchObjectsInRadius description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @param ResultDistances [description] * @param MaxNumberOfResults [description] * @return [description] */ SizeType SearchObjectsInRadius(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results, DistanceIteratorType ResultDistances, const SizeType& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; SizeType NumberOfResults = 0; TConfigure::CalculateBoundingBox(ThisObject, Low, High, Radius); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInRadius(ThisObject, Radius, Results, ResultDistances, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } /** * [SearchObjectsInRadiusExclusive description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @param MaxNumberOfResults [description] * @return [description] */ virtual SizeType SearchObjectsInRadiusExclusive(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results) { /// Missing API for 'SearchObjectsInRadiusExclusive' without 'MaxNumberOfResults' KRATOS_ERROR << "Missing implementation of SearchObjectsInRadiusExclusive(PointerType, const double, ResultIteratorType)" << std::endl; } /** * [SearchObjectsInRadiusExclusive description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @param MaxNumberOfResults [description] * @return [description] */ virtual SizeType SearchObjectsInRadiusExclusive(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results, const SizeType& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; SizeType NumberOfResults = 0; TConfigure::CalculateBoundingBox(ThisObject, Low, High, Radius); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInRadiusExclusive(ThisObject, Radius, Results, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } /** * [SearchObjectsInRadiusExclusive description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @param ResultDistances [description] * @return [description] */ virtual SizeType SearchObjectsInRadiusExclusive(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results, DistanceIteratorType ResultDistances) { /// Missing API for 'SearchObjectsInRadiusExclusive' without 'MaxNumberOfResults' KRATOS_ERROR << "Missing implementation of SearchObjectsInRadiusExclusive(PointerType, const double, ResultIteratorType, DistanceIteratorType)" << std::endl; } /** * [SearchObjectsInRadiusExclusive description] * @param ThisObject [description] * @param Radius [description] * @param Results [description] * @param ResultDistances [description] * @param MaxNumberOfResults [description] * @return [description] */ virtual SizeType SearchObjectsInRadiusExclusive(PointerType& ThisObject, const double& Radius, ResultIteratorType& Results, DistanceIteratorType ResultDistances, const SizeType& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; SizeType NumberOfResults = 0; TConfigure::CalculateBoundingBox(ThisObject, Low, High, Radius); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInRadiusExclusive(ThisObject, Radius, Results, ResultDistances, NumberOfResults, MaxNumberOfResults, Box ); return NumberOfResults; } /// Batch search API (needs to be extended with the missing functions) /** * [SearchObjectsInRadius description] * @param ThisObjects [description] * @param NumberOfObjects [description] * @param Radius [description] * @param Results [description] * @param NumberOfResults [description] * @param MaxNumberOfResults [description] */ void SearchObjectsInRadius(IteratorType const& ThisObjects, SizeType const& NumberOfObjects, std::vector<double>& Radius, std::vector<std::vector<PointerType> >& Results, std::vector<SizeType>& NumberOfResults, SizeType const& MaxNumberOfResults) { struct tls_type { PointType Low; PointType High; SearchStructureType Box; }; IndexPartition<std::size_t>(NumberOfObjects).for_each(tls_type(), [&](std::size_t i, tls_type& rTLS){ ResultIteratorType ResultsPointer = Results[i].begin(); NumberOfResults[i] = 0; TConfigure::CalculateBoundingBox(ThisObjects[i], rTLS.Low, rTLS.High, Radius[i]); rTLS.Box.Set( CalculateCell(rTLS.Low), CalculateCell(rTLS.High), mN ); SearchInRadius(ThisObjects[i], Radius[i], ResultsPointer, NumberOfResults[i], MaxNumberOfResults, rTLS.Box ); }); } /** * [SearchObjectsInRadius description] * @param ThisObjects [description] * @param NumberOfObjects [description] * @param Radius [description] * @param Results [description] * @param ResultsDistances [description] * @param NumberOfResults [description] * @param MaxNumberOfResults [description] */ void SearchObjectsInRadius(IteratorType const& ThisObjects, SizeType const& NumberOfObjects, std::vector<double>& Radius, std::vector<std::vector<PointerType> >& Results, std::vector<std::vector<double> >& ResultsDistances, std::vector<SizeType>& NumberOfResults, SizeType const& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; #pragma omp parallel for private(Low,High,Box) for(int i = 0; i < static_cast<int>(NumberOfObjects); i++) { ResultIteratorType ResultsPointer = Results[i].begin(); DistanceIteratorType ResultsDistancesPointer = ResultsDistances[i].begin(); NumberOfResults[i] = 0; TConfigure::CalculateBoundingBox(ThisObjects[i], Low, High, Radius[i]); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInRadius(ThisObjects[i], Radius[i], ResultsPointer, ResultsDistancesPointer, NumberOfResults[i], MaxNumberOfResults, Box ); } } /** * [SearchObjectsInRadiusExclusive description] * @param ThisObjects [description] * @param NumberOfObjects [description] * @param Radius [description] * @param Results [description] * @param NumberOfResults [description] * @param MaxNumberOfResults [description] */ virtual void SearchObjectsInRadiusExclusive(IteratorType const& ThisObjects, SizeType const& NumberOfObjects, std::vector<double>& Radius, std::vector<std::vector<PointerType> >& Results, std::vector<SizeType>& NumberOfResults, SizeType const& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; #pragma omp parallel for private(Low,High,Box) for(int i = 0; i < static_cast<int>(NumberOfObjects); i++) { ResultIteratorType ResultsPointer = Results[i].begin(); NumberOfResults[i] = 0; TConfigure::CalculateBoundingBox(ThisObjects[i], Low, High, Radius[i]); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInRadiusExclusive(ThisObjects[i], Radius[i], ResultsPointer, NumberOfResults[i], MaxNumberOfResults, Box ); } } /** * [SearchObjectsInRadiusExclusive description] * @param ThisObjects [description] * @param NumberOfObjects [description] * @param Radius [description] * @param Results [description] * @param ResultsDistances [description] * @param NumberOfResults [description] * @param MaxNumberOfResults [description] */ virtual void SearchObjectsInRadiusExclusive(IteratorType const& ThisObjects, SizeType const& NumberOfObjects, std::vector<double>& Radius, std::vector<std::vector<PointerType> >& Results, std::vector<std::vector<double> >& ResultsDistances, std::vector<SizeType>& NumberOfResults, SizeType const& MaxNumberOfResults) { PointType Low, High; SearchStructureType Box; #pragma omp parallel for private(Low,High,Box) for(int i = 0; i < static_cast<int>(NumberOfObjects); i++) { ResultIteratorType ResultsPointer = Results[i].begin(); DistanceIteratorType ResultsDistancesPointer = ResultsDistances[i].begin(); NumberOfResults[i] = 0; TConfigure::CalculateBoundingBox(ThisObjects[i], Low, High, Radius[i]); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); SearchInRadiusExclusive(ThisObjects[i], Radius[i], ResultsPointer, ResultsDistancesPointer, NumberOfResults[i], MaxNumberOfResults, Box ); } } /// Contact search API /** * [SearchContact description] * NOTE[Charlie]: Why this function does not return the number of results like the others? * @param Result [description] */ void SearchContact(ContainerContactType& Result) { for (CellContainerIterator icell = mCells.begin() ; icell!= mCells.end(); icell++) { icell->SearchContact(Result); } } /** * [SearchContact description] * @param Result [description] * @param MaxNumberOfResults [description] * @return [description] */ SizeType SearchContact(IteratorContactType& Result, const SizeType& MaxNumberOfResults ) { SizeType NumberOfResults = 0; for (CellContainerIterator icell = mCells.begin() ; icell!= mCells.end(); icell++) { icell->SearchContact(Result, NumberOfResults, MaxNumberOfResults); } return NumberOfResults; } /// Add/Remove /** * [AddObject description] * @param ThisObject [description] */ virtual void AddObject(const PointerType& ThisObject) { PointType Low, High; SearchStructureType Box; TConfigure::CalculateBoundingBox(ThisObject, Low, High); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); FillObject(Box,ThisObject); mObjectsSize++; } /** * [RemoveObject description] * @param ThisObject [description] */ void RemoveObject(const PointerType& ThisObject) { PointType Low, High; SearchStructureType Box; TConfigure::CalculateBoundingBox(ThisObject, Low, High); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); RemoveObjectLocal(Box,ThisObject); mObjectsSize--; } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** Calculates the IndexArray (x[,y[,z]]) of the provided object. * Calculates the IndexArray (x[,y[,z]]) of the provided object. * The provided object must provide its coordinates through the [] operator. * @param ThisObject Input Object * @return Cell coordinates of 'ThisObject' in the bins */ template<class GenericCoordType> IndexArray CalculateCell(const GenericCoordType& ThisObject) { IndexArray IndexCell; for(SizeType i = 0 ; i < Dimension ; i++) { IndexCell[i] = CalculatePosition(ThisObject[i],i); } return IndexCell; } /** Calculates the Index of the provided object. * Calculates the Index of the provided object. * The provided object must provide its coordinates through the [] operator. * @param ThisObject Input Object * @return Cell index of 'ThisObject' in the bins */ template<class GenericCoordType> IndexType CalculateIndex(const GenericCoordType& ThisObject) { IndexType Index = 0; for(SizeType iDim = Dimension-1 ; iDim > 0 ; iDim--) { Index += CalculatePosition(ThisObject[iDim],iDim); Index *= mN[iDim-1]; } Index += CalculatePosition(ThisObject[0],0); return Index; } /** * [CalculatePosition description] * @param ThisCoord [description] * @param ThisDimension [description] * @return [description] */ virtual IndexType CalculatePosition(CoordinateType const& ThisCoord, const SizeType& ThisDimension) { CoordinateType d_index = (ThisCoord - mMinPoint[ThisDimension]) * mInvCellSize[ThisDimension]; IndexType index = static_cast<IndexType>( (d_index < 0.00) ? 0.00 : d_index ); return (index > mN[ThisDimension]-1) ? mN[ThisDimension]-1 : index; } ///@} ///@name Access ///@{ /** * @brief Get the Cell Container object * * @return CellContainerType& The Cell Container object */ CellContainerType& GetCellContainer() { return mCells; } /** * @brief Get the Divisions object * * @return SizeArray& Array containing the number of Cells in each dimension */ SizeArray& GetDivisions() { return mN; } /** * @brief Get the Cell Size object * * @return CoordinateArray& Array containing the size of the Cell in each dimension */ CoordinateArray& GetCellSize() { return mCellSize; } /** * @brief Get the Min Point object * * @return PointType& Min point of the bins */ PointType& GetMinPoint() { return mMinPoint; } /** * @brief Get the Max Point object * * @return PointType& Max point of the bins */ PointType& GetMaxPoint() { return mMaxPoint; } ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const { return "BinsObjectDynamic" ; } /** Print information about this object. * Print information about this object. * @param rOStream [description] */ virtual void PrintInfo(std::ostream& rOStream) const { rOStream << Info(); } /** Print object's data. * Print object's data. * @param rOStream [description] * @param Perfix [description] */ virtual void PrintData(std::ostream& rOStream, std::string const& Perfix = std::string()) const { rOStream << " BinsSize: "; for(SizeType i = 0 ; i < Dimension ; i++) { rOStream << "[" << mN[i] << "]"; } rOStream << std::endl; rOStream << " CellSize: "; for(SizeType i = 0 ; i < Dimension ; i++) { rOStream << "[" << mCellSize[i] << "]"; } rOStream << std::endl; SizeType nn = 0; for(SizeType i = 0 ; i < mCells.size(); i++) { nn += mCells[i].Size(); } rOStream << "NumPointers: " << nn << std::endl; } /** Print Size of Container * Print Size of Container * @param rout [description] */ void PrintSize(std::ostream& rout) { rout << " BinsSize: "; for(SizeType i = 0 ; i < Dimension ; i++) { rout << "[" << mN[i] << "]"; } rout << std::endl; } /** Print Limits Points of the Container * Print Limits Points of the Container * @param rout [description] */ void PrintBox(std::ostream& rout) { rout << " BinsBox: Min ["; mMinPoint.Print(rout); rout << "]; Max ["; mMaxPoint.Print(rout); rout << "]; Size ["; mCellSize.Print(rout); rout << "]" << std::endl; } protected: ///@} ///@name Friends ///@{ ///@} ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ /// It computes each object's boundinx box and uses it to find the max and min points virtual void CalculateBoundingBox() { PointType Low, High; TConfigure::CalculateBoundingBox(*mObjectsBegin,mMinPoint,mMaxPoint); #ifdef _OPENMP SizeType number_of_threads = omp_get_max_threads(); #else SizeType number_of_threads = 1; #endif std::vector<SizeType> node_partition; CreatePartition(number_of_threads, mObjectsSize, node_partition); std::vector<PointType> Max(number_of_threads); std::vector<PointType> Min(number_of_threads); for(SizeType k=0; k<number_of_threads; k++ ) { Max[k] = mMaxPoint; Min[k] = mMinPoint; } IteratorType i_begin = mObjectsBegin; IteratorType i_end = mObjectsEnd; for (IteratorType i_object = i_begin ; i_object != i_end ; i_object++ ) { TConfigure::CalculateBoundingBox(*i_object, Low, High); for(SizeType i = 0 ; i < Dimension ; i++) { mMaxPoint[i] = (mMaxPoint[i] < High[i]) ? High[i] : mMaxPoint[i]; mMinPoint[i] = (mMinPoint[i] > Low[i]) ? Low[i] : mMinPoint[i]; } } auto Epsilon = PointType{mMaxPoint - mMinPoint}; for(SizeType i = 0 ; i < Dimension ; i++) { mMaxPoint[i] += Epsilon[i] * 0.01; mMinPoint[i] -= Epsilon[i] * 0.01; } } /** * @brief Calculates the cell size of the bins. * * Calculates the cell size of the bins using an average aproximation of the objects in the bins. * * @param ApproximatedSize Aproximate number of objects that will be stored in the bins */ void CalculateCellSize(std::size_t ApproximatedSize) { std::size_t average_number_of_cells = static_cast<std::size_t>(std::pow(static_cast<double>(ApproximatedSize), 1.00 / Dimension)); std::array<double, 3> lengths; double average_length = 0.00; for (int i = 0; i < Dimension; i++) { lengths[i] = mMaxPoint[i] - mMinPoint[i]; average_length += lengths[i]; } average_length *= 1.00 / 3.00; if (average_length < std::numeric_limits<double>::epsilon()) { for(int i = 0; i < Dimension; i++) { mN[i] = 1; } return; } for (int i = 0; i < Dimension; i++) { mN[i] = static_cast<std::size_t>(lengths[i] / average_length * (double)average_number_of_cells) + 1; if (mN[i] > 1) { mCellSize[i] = lengths[i] / mN[i]; } else { mCellSize[i] = average_length; } mInvCellSize[i] = 1.00 / mCellSize[i]; } } /** * @brief Assigns the cell size of the bins using the provided CellSize. * * Assigns the cell size of the bins using the provided CellSize. * * @param CellSize Desired size of the cells. */ void AssignCellSize(CoordinateType CellSize) { for(SizeType i = 0 ; i < Dimension ; i++) { mCellSize[i] = CellSize; mInvCellSize[i] = 1.00 / mCellSize[i]; mN[i] = static_cast<SizeType>( (mMaxPoint[i]-mMinPoint[i]) / mCellSize[i]) + 1; } } virtual void GenerateBins() { PointType Low, High; SearchStructureType Box; /// Fill container with objects for(IteratorType i_object = mObjectsBegin ; i_object != mObjectsEnd ; i_object++) { TConfigure::CalculateBoundingBox(*i_object, Low, High); Box.Set( CalculateCell(Low), CalculateCell(High), mN ); FillObject(Box, *i_object); } } // **** THREAD SAFE // Dimension = 1 void SearchInBoxLocal(PointerType& ThisObject, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0]) if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjects(ThisObject, Result, NumberOfResults, MaxNumberOfResults); } // Dimension = 2 void SearchInBoxLocal(PointerType& ThisObject, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjects(ThisObject, Result, NumberOfResults, MaxNumberOfResults); } } } // Dimension = 3 void SearchInBoxLocal(PointerType& ThisObject, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2] += mCellSize[2], MaxCell[2] += mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) { mCells[I].SearchObjects(ThisObject, Result, NumberOfResults, MaxNumberOfResults); } } } } } // **** THREAD SAFE // Dimension = 1 void SearchInBoxLocal(PointerType& ThisObject, ResultContainerType& Result, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjects(ThisObject, Result); } } // Dimension = 2 void SearchInBoxLocal(PointerType& ThisObject, ResultContainerType& Result, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjects(ThisObject, Result); } } } // Dimension = 3 void SearchInBoxLocal(PointerType& ThisObject, ResultContainerType& Result, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) { mCells[I].SearchObjects(ThisObject, Result); } } } } } // **** THREAD SAFE // Dimension = 1 void SearchObjectLocalExclusive(PointerType& ThisObject, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0]) if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjectsExclusive(ThisObject, Result, NumberOfResults, MaxNumberOfResults); } // Dimension = 2 void SearchObjectLocalExclusive(PointerType& ThisObject, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjectsExclusive(ThisObject, Result, NumberOfResults, MaxNumberOfResults); } } } // Dimension = 3 void SearchObjectLocalExclusive(PointerType& ThisObject, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2] += mCellSize[2], MaxCell[2] += mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) { mCells[I].SearchObjectsExclusive(ThisObject, Result, NumberOfResults, MaxNumberOfResults); } } } } } // **** THREAD SAFE // Dimension = 1 void SearchObjectLocalExclusive(PointerType& ThisObject, ResultContainerType& Result, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block ) if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjectsExclusive(ThisObject, Result); } // Dimension = 2 void SearchObjectLocalExclusive(PointerType& ThisObject, ResultContainerType& Result, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) mCells[I].SearchObjectsExclusive(ThisObject, Result); } } } // Dimension = 3 void SearchObjectLocalExclusive(PointerType& ThisObject, ResultContainerType& Result, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block ) { MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell)) { mCells[I].SearchObjectsExclusive(ThisObject, Result); } } } } } // **** THREAD SAFE // Dimension = 1 void SearchInRadius(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0]) if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRaius(ThisObject, Radius, Result, NumberOfResults, MaxNumberOfResults); } // Dimension = 2 void SearchInRadius(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRaius(ThisObject, Radius, Result, NumberOfResults, MaxNumberOfResults); } } } // Dimension = 3 void SearchInRadius(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2] += mCellSize[2], MaxCell[2] += mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) { mCells[I].SearchObjectsInRadius(ThisObject, Radius, Result, NumberOfResults, MaxNumberOfResults); } } } } } // **** THREAD SAFE // Dimension = 1 void SearchInRadius(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, DistanceIteratorType ResultDistances, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0]) if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRaius(ThisObject, Radius, Result, ResultDistances, NumberOfResults, MaxNumberOfResults); } // Dimension = 2 void SearchInRadius(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, DistanceIteratorType ResultDistances, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRaius(ThisObject, Radius, Result, ResultDistances, NumberOfResults, MaxNumberOfResults); } } } // Dimension = 3 void SearchInRadius(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, DistanceIteratorType ResultDistances, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2] += mCellSize[2], MaxCell[2] += mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) { mCells[I].SearchObjectsInRadius(ThisObject, Radius, Result, ResultDistances, NumberOfResults, MaxNumberOfResults); } } } } } // **** THREAD SAFE // Dimension = 1 virtual void SearchInRadiusExclusive(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0]) if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRadiusExclusive(ThisObject, Radius, Result, NumberOfResults, MaxNumberOfResults); } // Dimension = 2 virtual void SearchInRadiusExclusive(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRadiusExclusive(ThisObject, Radius, Result, NumberOfResults, MaxNumberOfResults); } } } // Dimension = 3 virtual void SearchInRadiusExclusive(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2] += mCellSize[2], MaxCell[2] += mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) { mCells[I].SearchObjectsInRadiusExclusive(ThisObject, Radius, Result, NumberOfResults, MaxNumberOfResults); } } } } } // **** THREAD SAFE // Dimension = 1 virtual void SearchInRadiusExclusive(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, DistanceIteratorType ResultDistances, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0]) if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRadiusExclusive(ThisObject, Radius, Result, ResultDistances, NumberOfResults, MaxNumberOfResults); } // Dimension = 2 virtual void SearchInRadiusExclusive(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, DistanceIteratorType ResultDistances, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) mCells[I].SearchObjectsInRadiusExclusive(ThisObject, Radius, Result, ResultDistances, NumberOfResults, MaxNumberOfResults); } } } // Dimension = 3 virtual void SearchInRadiusExclusive(PointerType& ThisObject, CoordinateType const& Radius, ResultIteratorType& Result, DistanceIteratorType ResultDistances, SizeType& NumberOfResults, const SizeType& MaxNumberOfResults, SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box ) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2] += mCellSize[2], MaxCell[2] += mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1] += mCellSize[1], MaxCell[1] += mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0] += mCellSize[0], MaxCell[0] += mCellSize[0] ) { if(TConfigure::IntersectionBox(ThisObject, MinCell, MaxCell, Radius)) { mCells[I].SearchObjectsInRadiusExclusive(ThisObject, Radius, Result, ResultDistances, NumberOfResults, MaxNumberOfResults); } } } } } // Dimension = 1 void FillObject( SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box, const PointerType& i_object) { PointType MinCell, MaxCell; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0]+=mCellSize[0], MaxCell[0]+=mCellSize[0] ) { if(TConfigure::IntersectionBox(i_object, MinCell, MaxCell)) mCells[I].Add(i_object); } } // Dimension = 2 void FillObject( SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box, const PointerType& i_object) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1]+=mCellSize[1], MaxCell[1]+=mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0]+=mCellSize[0], MaxCell[0]+=mCellSize[0] ) { if(TConfigure::IntersectionBox(i_object,MinCell,MaxCell)) mCells[I].Add(i_object); } } } // Dimension = 3 virtual void FillObject( SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box, const PointerType& i_object) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2]+=mCellSize[2], MaxCell[2]+=mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1]+=mCellSize[1], MaxCell[1]+=mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0]+=mCellSize[0], MaxCell[0]+=mCellSize[0] ) { if(TConfigure::IntersectionBox(i_object,MinCell,MaxCell)) mCells[I].Add(i_object); } } } } // Dimension = 1 void RemoveObjectLocal( SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,1>& Box, const PointerType& i_object) { PointType MinCell, MaxCell; MinCell[0] = static_cast<CoordinateType>(Box.Axis[0].Min) * mCellSize[0] + mMinPoint[0]; // MaxCell[0] = MinCell[0] + mCellSize[0]; for(IndexType I = Box.Axis[0].Begin() ; I <= Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0]+=mCellSize[0], MaxCell[0]+=mCellSize[0] ) { if(TConfigure::IntersectionBox(i_object, MinCell, MaxCell)) mCells[I].Remove(i_object); } } // Dimension = 2 void RemoveObjectLocal( SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,2>& Box, const PointerType& i_object) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 2; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = Box.Axis[1].Begin() ; II <= Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1]+=mCellSize[1], MaxCell[1]+=mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0]+=mCellSize[0], MaxCell[0]+=mCellSize[0] ) { if(TConfigure::IntersectionBox(i_object,MinCell,MaxCell)) mCells[I].Remove(i_object); } } } // Dimension = 3 void RemoveObjectLocal( SearchStructure<IndexType,SizeType,CoordinateType,IteratorType,IteratorIteratorType,3>& Box, const PointerType& i_object) { PointType MinCell, MaxCell; PointType MinBox, MaxBox; for(SizeType i = 0; i < 3; i++) { MinBox[i] = static_cast<CoordinateType>(Box.Axis[i].Min) * mCellSize[i] + mMinPoint[i]; // MaxBox[i] = MinBox[i] + mCellSize[i]; } MinCell[2] = MinBox[2]; MaxCell[2] = MaxBox[2]; for(IndexType III = Box.Axis[2].Begin() ; III <= Box.Axis[2].End() ; III += Box.Axis[2].Block, MinCell[2]+=mCellSize[2], MaxCell[2]+=mCellSize[2] ) { MinCell[1] = MinBox[1]; MaxCell[1] = MaxBox[1]; for(IndexType II = III + Box.Axis[1].Begin() ; II <= III + Box.Axis[1].End() ; II += Box.Axis[1].Block, MinCell[1]+=mCellSize[1], MaxCell[1]+=mCellSize[1] ) { MinCell[0] = MinBox[0]; MaxCell[0] = MaxBox[0]; for(IndexType I = II + Box.Axis[0].Begin() ; I <= II + Box.Axis[0].End() ; I += Box.Axis[0].Block, MinCell[0]+=mCellSize[0], MaxCell[0]+=mCellSize[0] ) { if(TConfigure::IntersectionBox(i_object,MinCell,MaxCell)) mCells[I].Remove(i_object); } } } } void AllocateContainer() { SizeType Size = mN[0]; for(SizeType i = 1 ; i < Dimension ; i++) Size *= mN[i]; mCells.resize(Size); } inline void CreatePartition(SizeType number_of_threads, const SizeType number_of_rows, std::vector<SizeType>& partitions) { partitions.resize(number_of_threads+1); SizeType partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for(SizeType i = 1; i<number_of_threads; i++) partitions[i] = partitions[i-1] + partition_size ; } ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ PointType mMinPoint; PointType mMaxPoint; SizeType mObjectsSize; IteratorType mObjectsBegin; IteratorType mObjectsEnd; CoordinateArray mCellSize; CoordinateArray mInvCellSize; SizeArray mN; CellContainerType mCells; ///The bin private: ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} public: /// Assignment operator. BinsObjectDynamic<TConfigure> & operator=(const BinsObjectDynamic<TConfigure> & rOther) { mMinPoint = rOther.mMinPoint; mMaxPoint = rOther.mMaxPoint; mObjectsBegin = rOther.mObjectsBegin; mObjectsEnd = rOther.mObjectsEnd; mObjectsSize = rOther.mObjectsSize; mCellSize = rOther.mCellSize; mInvCellSize = rOther.mInvCellSize; mN = rOther.mN; mCells = rOther.mCells; return *this; } /// Copy constructor. BinsObjectDynamic(const BinsObjectDynamic& rOther) { *this = rOther; } /// Copy constructor. template<class T> BinsObjectDynamic(const BinsObjectDynamic<T>& rOther) { *this = rOther; } }; // Class BinsObjectDynamic ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function template<class TConfigure> inline std::istream& operator >> (std::istream& rIStream, BinsObjectDynamic<TConfigure>& rThis) { return rIStream; } /// output stream function template<class TConfigure> inline std::ostream& operator << (std::ostream& rOStream, const BinsObjectDynamic<TConfigure> & rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_FILENAME_H_INCLUDED defined
omp_directive.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> /** * 记录openmp制导指令用法 * parallel, for, sections, single, master, threadprivate * * 具体介绍可以参考 http://blog.zhangjikai.com/tags/OpenMP/ */ void omp_parallel() { #pragma omp parallel { printf("The parallel region is executed by thread %d\n", omp_get_thread_num()); if ( omp_get_thread_num() == 2 ) { printf(" Thread %d does things differently\n", omp_get_thread_num()); } } } void omp_for() { int n = 9, i; #pragma omp parallel for shared(n) private(i) for(i = 0; i < n; i++) { printf("Thread %d executes loop iteration %d\n", omp_get_thread_num(),i); } } /** * 使用#pragma omp sections 和 #pragma omp section, 来使不同的线程执行不同的任务 * 如果线程数量大于section数量, 那么多余的线程会处于空闲状态(idle) * 如果线程数量少于section数量, 那么一个线程会执行多个section代码 */ void funcA() { printf("In funcA: this section is executed by thread %d\n", omp_get_thread_num()); } void funcB() { printf("In funcB: this section is executed by thread %d\n", omp_get_thread_num()); } void omp_sections() { #pragma omp parallel sections { #pragma omp section { (void)funcA(); } #pragma omp section { (void)funcB(); } } } void omp_single() { #pragma omp parallel { // 只有一个线程会执行这段代码, 其他线程会等待该线程执行完毕 #pragma omp single { printf("Single construct executed by thread %d\n\n", omp_get_thread_num()); } // A barrier is automatically inserted here printf("thread %d is running\n", omp_get_thread_num()); } } void omp_master() { #pragma omp parallel { // 只有主线程执行, 不会自动插入barrier, 需要手动同步 #pragma omp master { printf("master construct executed by thread %d\n\n", omp_get_thread_num()); } #pragma omp barrier printf("thread %d is running\n", omp_get_thread_num()); } } int counter = 10; #pragma omp threadprivate(counter) void omp_threadprivate() { printf("counter is %d\n", counter); #pragma omp parallel copyin(counter) { counter = omp_get_thread_num() + counter + 1; printf("thread %d : counter is %d\n", omp_get_thread_num(), counter); } printf("counter is %d\n", counter); } int main() { // omp_parallel(); // omp_for(); // omp_sections(); // omp_single(); // omp_master(); omp_threadprivate(); }
single.c
#include<stdio.h> #include<omp.h> int main(){ int id; #pragma omp parallel { #pragma omp single { id = omp_get_thread_num(); printf("Single block thread %d.\n", id); } id = omp_get_thread_num(); printf("Parallel block thread %d.\n", id); } }
rose_c99loop.c
/* Contributed by Jeff Keasler Liao, 10/22/2009 */ #include "omp.h" int main(int argc,char *argv[]) { double a[20UL][20UL]; for (int i = 0; i <= 18; i += 1) { #pragma omp parallel for for (int j = 0; j <= 19; j += 1) { a[i][j] += a[i + 1][j]; } } return 0; } // with shadow i and j void foo(int i,int j) { double a[20][20]; for (int i = 0; i <= 18; i += 1) { #pragma omp parallel for for (int j = 0; j <= 19; j += 1) { a[i][j] += a[i + 1][j]; } } }
ndvi.c
#include<stdio.h> #include "gdal.h" #include<omp.h> #include "cpl_string.h" #define NODATA -28768 /* -1 Fill/No Data Not Processed 0 Good Data Use with confidence 1 Marginal data Useful, but look at other QA information 2 Snow/Ice Target covered with snow/ice 3 Cloudy Target not visible, covered with cloud */ void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--Serial code----\n"); printf( "-----------------------------------------\n"); printf( "./ndvi inNDVI inNDVI_QA\n"); printf( "\toutNDVI\n"); printf( "-----------------------------------------\n"); printf( "inNDVI\t\tModis MOD13Q1 NDVI 250m\n"); printf( "inNDVI_QA\t\tModis MOD13Q1 NDVI Reliability\n"); printf( "outNDVI\tQA corrected NDVI output [-]\n"); return; } int main( int argc, char *argv[] ) { if( argc < 4 ) { usage(); return 1; } char *inB2 = argv[1]; //NDVI char *inB3 = argv[2]; //NDVI_QA char *ndviF = argv[3]; GDALAllRegister(); GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//NDVI GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//NDVI_QA if(hD2==NULL||hD3==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } GDALDriverH hDr2 = GDALGetDatasetDriver(hD2); char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); GDALDatasetH hDOut = GDALCreateCopy(hDr2,ndviF,hD2,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); GDALSetRasterNoDataValue(hBOut, NODATA); GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//NDVI GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//NDVI_QA int nX = GDALGetRasterBandXSize(hB2); int nY = GDALGetRasterBandYSize(hB2); int N = nX*nY; float *l2 = (float *) malloc(sizeof(float)*N); float *l3 = (float *) malloc(sizeof(float)*N); float *lOut = (float *) malloc(sizeof(float)*N); int rowcol; int err=GDALRasterIO(hB2,GF_Read,0,0,nX,nY,l2,nX,nY,GDT_Float32,0,0); err=GDALRasterIO(hB3,GF_Read,0,0,nX,nY,l3,nX,nY,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private (rowcol) shared (N, l2, l3, lOut) for(rowcol=0;rowcol<N;rowcol++){ if( l3[rowcol] == 0||l3[rowcol] == 1) lOut[rowcol] = l2[rowcol]; else if(l2[rowcol] == -3000) lOut[rowcol] = NODATA; else lOut[rowcol] = NODATA; } #pragma omp barrier err=GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,lOut,nX,nY,GDT_Float32,0,0); err=err+1; if( l2 != NULL ) free( l2 ); if( l3 != NULL ) free( l3 ); GDALClose(hD2); GDALClose(hD3); GDALClose(hDOut); return(EXIT_SUCCESS); }
GB_unop__bnot_uint16_uint16.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__bnot_uint16_uint16) // op(A') function: GB (_unop_tran__bnot_uint16_uint16) // C type: uint16_t // A type: uint16_t // cast: uint16_t cij = aij // unaryop: cij = ~(aij) #define GB_ATYPE \ uint16_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ~(x) ; // casting #define GB_CAST(z, aij) \ uint16_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint16_t z = aij ; \ Cx [pC] = ~(z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BNOT || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__bnot_uint16_uint16) ( uint16_t *Cx, // Cx and Ax may be aliased const uint16_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++) { uint16_t aij = Ax [p] ; uint16_t z = 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 ; uint16_t aij = Ax [p] ; uint16_t z = aij ; Cx [p] = ~(z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__bnot_uint16_uint16) ( 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
critical-4.c
/* { dg-do compile } */ extern void bar(int); void foo1 (void) { #pragma omp critical #pragma omp critical(foo) #pragma omp critical(bar) bar (0); } void foo2 (void) { #pragma omp critical #pragma omp critical /* { dg-warning "with the same name" } */ bar (0); } void foo3 (void) { #pragma omp critical(foo) #pragma omp critical(foo) /* { dg-warning "with the same name" } */ bar (0); }
reduce_mean.h
// // Copyright (c) 2017 XiaoMi All rights reserved. // #ifndef MACE_KERNELS_REDUCE_MEAN_H_ #define MACE_KERNELS_REDUCE_MEAN_H_ #if defined(MACE_ENABLE_NEON) && defined(__aarch64__) #include <arm_neon.h> #endif #include <algorithm> #include <memory> #include <vector> #include "mace/core/future.h" #include "mace/core/tensor.h" #ifdef MACE_ENABLE_OPENCL #include "mace/core/runtime/opencl/cl2_header.h" #endif namespace mace { namespace kernels { struct ReduceFunctorBase { ReduceFunctorBase(const std::vector<int> &axis, const bool keep_dims) : keep_dims_(keep_dims), axis_(axis) {} bool keep_dims_; bool reduce_first_axis_; const std::vector<int> axis_; std::vector<int> data_reshape_; std::vector<index_t> out_shape_; }; template <DeviceType D, typename T> struct ReduceMeanFunctor : ReduceFunctorBase{ ReduceMeanFunctor(const std::vector<int> &axis, const bool keep_dims) : ReduceFunctorBase(axis, keep_dims) {} void Simplify(const Tensor *input) { std::vector<bool> bitmap(static_cast<uint32_t>(input->dim_size()), false); if (axis_.size() == 0) { for (int i = 0; i < input->dim_size(); ++i) { bitmap[i] = true; } } else { for (unsigned int i = 0; i < axis_.size(); ++i) { const int index = axis_[i] >= 0 ? axis_[i] : axis_[i] + input->dim_size(); bitmap[index] = true; } } out_shape_.clear(); for (unsigned int i = 0; i < input->dim_size(); ++i) { if (!bitmap[i]) { out_shape_.push_back(input->dim(i)); } else if (keep_dims_) { out_shape_.push_back(1); } } data_reshape_.clear(); unsigned int dim_index = 0; for (; dim_index < input->dim_size(); ++dim_index) { if (input->dim(dim_index) != 1) break; } if (dim_index >= input->dim_size()) { reduce_first_axis_ = true; } else { reduce_first_axis_ = bitmap[dim_index]; data_reshape_.push_back(input->dim(dim_index)); ++dim_index; for (; dim_index < input->dim_size(); ++dim_index) { const int n = input->dim(dim_index); if (n == 1) { bitmap[dim_index] = bitmap[dim_index - 1]; } if (bitmap[dim_index-1] != bitmap[dim_index]) { data_reshape_.push_back(n); } else { data_reshape_.back() *= n; } } } } void Compute(const Tensor *input, Tensor *output) { Tensor::MappingGuard input_mapper(input); const T *input_ptr = input->data<T>(); Tensor::MappingGuard output_map(output); T *output_ptr = output->mutable_data<T>(); memset(output_ptr, 0, output->size() * sizeof(T)); switch (data_reshape_.size()) { case 1: if (reduce_first_axis_) { T sum = 0; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < data_reshape_[0]; ++i) { sum = sum + input_ptr[i]; } output_ptr[0] = sum / data_reshape_[0]; } else { #pragma omp parallel for for (int i = 0; i < data_reshape_[0]; ++i) { output_ptr[i] = input_ptr[i]; } } break; case 2: if (reduce_first_axis_) { #pragma omp parallel for for (int i = 0; i < data_reshape_[1]; ++i) { for (int j = 0; j < data_reshape_[0]; ++j) { output_ptr[i] += input_ptr[j * data_reshape_[1] + i]; } output_ptr[i] /= data_reshape_[0]; } } else { #pragma omp parallel for for (int i = 0; i < data_reshape_[0]; ++i) { for (int j = 0; j < data_reshape_[1]; ++j) { output_ptr[i] += input_ptr[i * data_reshape_[1] + j]; } output_ptr[i] /= data_reshape_[1]; } } break; case 3: if (reduce_first_axis_) { #pragma omp parallel for for (int i = 0; i < data_reshape_[1]; ++i) { for (int j = 0; j < data_reshape_[2]; ++j) { for (int k = 0; k < data_reshape_[0]; ++k) { output_ptr[i] += input_ptr[(k * data_reshape_[1] + i) * data_reshape_[2] + j]; } } output_ptr[i] /= (data_reshape_[0] * data_reshape_[2]); } } else { #pragma omp parallel for collapse(2) for (int i = 0; i < data_reshape_[0]; ++i) { for (int j = 0; j < data_reshape_[2]; ++j) { for (int k = 0; k < data_reshape_[1]; ++k) { output_ptr[i * data_reshape_[2] + j] += input_ptr[(i * data_reshape_[1] + k) * data_reshape_[2] + j]; } output_ptr[i * data_reshape_[2] + j] /= data_reshape_[1]; } } } break; case 4: if (reduce_first_axis_) { #pragma omp parallel for collapse(2) for (int i = 0; i < data_reshape_[1]; ++i) { for (int j = 0; j < data_reshape_[3]; ++j) { for (int k = 0; k < data_reshape_[2]; ++k) { for (int t = 0; t < data_reshape_[0]; ++t) { output_ptr[i * data_reshape_[3] + j] += input_ptr[((t * data_reshape_[1] + i) * data_reshape_[2] + k)*data_reshape_[3] + j]; } } output_ptr[i * data_reshape_[3] + j] /= (data_reshape_[0] * data_reshape_[2]); } } } else { #pragma omp parallel for collapse(2) for (int i = 0; i < data_reshape_[0]; ++i) { for (int j = 0; j < data_reshape_[2]; ++j) { for (int k = 0; k < data_reshape_[1]; ++k) { for (int t = 0; t < data_reshape_[3]; ++t) { output_ptr[i * data_reshape_[2] + j] += input_ptr[((i * data_reshape_[1] + k) * data_reshape_[2] + j)*data_reshape_[3] + t]; } } output_ptr[i * data_reshape_[2] + j] /= (data_reshape_[1] * data_reshape_[3]); } } } break; default: MACE_CHECK(false, "not implemented in mace") << "data reshape size" << data_reshape_.size() << "reduce first axis:" << reduce_first_axis_; break; } } MaceStatus operator()(const Tensor *input, Tensor *output, StatsFuture *future) { MACE_UNUSED(future); Simplify(input); output->Resize(out_shape_); Compute(input, output); return MACE_SUCCESS; } }; #ifdef MACE_ENABLE_OPENCL template <typename T> struct ReduceMeanFunctor<DeviceType::GPU, T> : ReduceFunctorBase { ReduceMeanFunctor(const std::vector<int> axis, const bool keep_dims) : ReduceFunctorBase(axis, keep_dims) {} MaceStatus operator()(const Tensor *input, Tensor *output_tensor, StatsFuture *future); cl::Kernel kernel_; uint32_t kwg_size_; std::unique_ptr<BufferBase> kernel_error_; std::vector<index_t> input_shape_; }; #endif } // namespace kernels } // namespace mace #endif // MACE_KERNELS_REDUCE_MEAN_H_
BitMap.h
#pragma once #include <unistd.h> #include <cstdlib> #include <cstdio> #include <string> #include <string_view> #include <cstdarg> #include <cassert> #include <memory> // debug #include <iostream> #include <vector> #include "PRNG.h" enum DistrName{ UNIFORM, NORMAL }; struct png_dims{ png_dims(size_t h, size_t w, size_t c, size_t bd, png_byte ct) : height{ h }, width{ w }, channels{ c }, bit_depth{ bd }, color_type(ct){} size_t height, width, channels, bit_depth; png_byte color_type; }; // utility lookup maps structure to retrieve the correct shift/value for r-g-b-a pixels struct RGBA_utils{ static constexpr uint32_t rgba[4] = {0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000}; static constexpr unsigned char shift[4] = {0, 8, 16, 24}; }; RGBA_utils rgba_utils; #define CLIP(p, inf, sup) if(p < inf) { p = inf; } else if(p > sup) { p = sup; } class BitMapRGBA; class BitMapRGB; template<typename T> class PixelMap{ public: explicit PixelMap(); PixelMap(size_t height, size_t width, size_t channels); PixelMap(png_dims&& dims); PixelMap(PixelMap<T>&& other) noexcept; PixelMap(const PixelMap<T>& other); PixelMap(const BitMapRGBA& bitmap); PixelMap(const BitMapRGB& bitmap); inline size_t getHeight() const; inline size_t getWidth() const; inline size_t getChannels() const; inline bool has_same_dims_as(const PixelMap<T>& other) const; PixelMap<T> transpose() const; PixelMap<T>& subtract(const PixelMap<T>& other); inline T& operator()(size_t i, size_t j, size_t c); inline const T& operator()(size_t i, size_t j, size_t c) const; inline T* begin(); inline T* end(); inline const T* begin() const; inline const T* end() const; inline T* rowBegin(size_t row); inline T* rowEnd(size_t row); inline const T* rowBegin(size_t row) const; inline const T* rowEnd(size_t row) const; inline T* pixBegin(size_t row, size_t col); inline T* pixEnd(size_t row, size_t col); inline const T* pixBegin(size_t row, size_t col) const; inline const T* pixEnd(size_t row, size_t col) const; PixelMap<T>& operator=(const PixelMap<T>& other); bool operator==(const PixelMap<T>& other) const; void print() const; private: size_t _height = 0; size_t _width = 0; size_t _channels = 0; std::unique_ptr<T[]> _pixel_map; }; class BitMapRGBA{ public: explicit BitMapRGBA(); BitMapRGBA(size_t height, size_t width); BitMapRGBA(size_t height, size_t width, DistrName d_name); template<typename U, typename V> BitMapRGBA(size_t height, size_t width, DistrName d_name, U param1, V param2); BitMapRGBA(const BitMapRGBA& other); BitMapRGBA(BitMapRGBA&& other) noexcept; BitMapRGBA(const PixelMap<png_byte>& pixelmap); inline size_t getHeight() const; inline size_t getWidth() const; inline unsigned char get(size_t i, size_t j, size_t c) const; template<typename rowIt> void copy_row(rowIt rowit, size_t row, size_t channels); BitMapRGBA transpose() const; BitMapRGBA& subtract_rgb(const BitMapRGBA& other); BitMapRGBA& subtract_rgba(const BitMapRGBA& other); inline uint32_t& operator()(size_t i, size_t j); inline const uint32_t& operator()(size_t i, size_t j) const; inline uint32_t* begin(); inline uint32_t* end(); inline const uint32_t* begin() const; inline const uint32_t* end() const; inline uint32_t* rowBegin(size_t row); inline uint32_t* rowEnd(size_t row); inline const uint32_t* rowBegin(size_t row) const; inline const uint32_t* rowEnd(size_t row) const; BitMapRGBA& operator=(const BitMapRGBA& other); //BitMapRGBA& operator=(const PixelMap<png_byte>& pixelmap); void print() const; void print_bitmap() const; private: size_t _height = 0; size_t _width = 0; std::unique_ptr<uint32_t[]> _data; }; class BitMapRGB{ public: explicit BitMapRGB(); BitMapRGB(size_t height, size_t width); BitMapRGB(size_t height, size_t width, DistrName d_name); template<typename U, typename V> BitMapRGB(size_t height, size_t width, DistrName d_name, U param1, V param2); BitMapRGB(const BitMapRGB& other); BitMapRGB(BitMapRGB&& other) noexcept; BitMapRGB(const PixelMap<png_byte>& pixelmap); inline size_t getHeight() const; inline size_t getWidth() const; inline unsigned char get(size_t i, size_t j, size_t c) const; template<typename rowIt> void copy_row(rowIt rowit, size_t row, size_t channels); BitMapRGB transpose() const; BitMapRGB& subtract(const BitMapRGB& other); inline uint32_t& operator()(size_t i, size_t j); inline const uint32_t& operator()(size_t i, size_t j) const; inline uint32_t* begin(); inline uint32_t* end(); inline const uint32_t* begin() const; inline const uint32_t* end() const; inline uint32_t* rowBegin(size_t row); inline uint32_t* rowEnd(size_t row); inline const uint32_t* rowBegin(size_t row) const; inline const uint32_t* rowEnd(size_t row) const; BitMapRGB& operator=(const BitMapRGB& other); //BitMapRGB& operator=(const PixelMap<png_byte>& pixelmap); //BitMapRGB& operator-=(const BitMapRGB other); void print() const; void print_bitmap() const; private: size_t _height = 0; size_t _width = 0; std::unique_ptr<uint32_t[]> _data; }; ////////////////////////////////////////////////////////////////////// // // // PIXELMAP IMPLEM // // // ////////////////////////////////////////////////////////////////////// template<typename T> PixelMap<T>::PixelMap() : _height{ 0 }, _width{ 0 }, _channels{ 0 }{} template<typename T> PixelMap<T>::PixelMap(size_t height, size_t width, size_t channels) : _height{ height }, _width{ width }, _channels{ channels }, _pixel_map{ std::make_unique<T[]>(height*width*channels) }{} template<typename T> PixelMap<T>::PixelMap(png_dims&& dims) : _height{ dims.height }, _width{ dims.width }, _channels{ dims.channels }, _pixel_map{ std::make_unique<T[]>(dims.height*dims.width*dims.channels) }{} template<typename T> PixelMap<T>::PixelMap(PixelMap<T>&& other) noexcept: _height{ other._height }, _width{ other._width }, _channels{ other._channels }, _pixel_map{ std::move(other._pixel_map) }{} template<typename T> PixelMap<T>::PixelMap(const PixelMap<T>& other){ *this = other; } template<typename T> PixelMap<T>::PixelMap(const BitMapRGBA& bitmap) : _height{ bitmap.getHeight() }, _width{ bitmap.getWidth() }, _channels{ 4 }, _pixel_map{ std::make_unique<T[]>(bitmap.getHeight()*bitmap.getWidth()*4) }{ for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ (*this)(i, j, 0) = ( bitmap(i, j) & 0xff); (*this)(i, j, 1) = ((bitmap(i, j) >> 8 )& 0xff); (*this)(i, j, 2) = ((bitmap(i, j) >> 16)& 0xff); (*this)(i, j, 3) = ((bitmap(i, j) >> 24)& 0xff); } } } template<typename T> PixelMap<T>::PixelMap(const BitMapRGB& bitmap) : _height{ bitmap.getHeight() }, _width{ bitmap.getWidth() }, _channels{ 3 }, _pixel_map{ std::make_unique<T[]>(bitmap.getHeight()*bitmap.getWidth()*3) }{ for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ (*this)(i, j, 0) = ( bitmap(i, j) & 0xff); (*this)(i, j, 1) = ((bitmap(i, j) >> 8 )& 0xff); (*this)(i, j, 2) = ((bitmap(i, j) >> 16)& 0xff); } } } template<typename T> size_t PixelMap<T>::getHeight() const{ return _height; } template<typename T> size_t PixelMap<T>::getWidth() const{ return _width; } template<typename T> size_t PixelMap<T>::getChannels() const{ return _channels; } template<typename T> T& PixelMap<T>::operator()(size_t i, size_t j, size_t c){ return _pixel_map[c+(j+i*_width)*_channels]; } template<typename T> const T& PixelMap<T>::operator()(size_t i, size_t j, size_t c) const{ return _pixel_map[c+(j+i*_width)*_channels]; } template<typename T> T* PixelMap<T>::begin() { return _pixel_map.get(); } template<typename T> T* PixelMap<T>::end() { return begin() + _width*_height*_channels; } template<typename T> const T* PixelMap<T>::begin() const { return _pixel_map.get(); } template<typename T> const T* PixelMap<T>::end() const { return begin() + _width*_height*_channels; } template<typename T> T* PixelMap<T>::rowBegin(size_t row) { return begin() + row*_width*_channels; } template<typename T> T* PixelMap<T>::rowEnd(size_t row) { return rowBegin(row) + _width*_channels; } template<typename T> const T* PixelMap<T>::rowBegin(size_t row) const { return begin() + row*_width*_channels; } template<typename T> const T* PixelMap<T>::rowEnd(size_t row) const { return rowBegin(row) + _width*_channels; } template<typename T> T* PixelMap<T>::pixBegin(size_t row, size_t col) { return rowBegin(row) + col*_channels; } template<typename T> T* PixelMap<T>::pixEnd(size_t row, size_t col) { return pixBegin(row, col) + _channels; } template<typename T> const T* PixelMap<T>::pixBegin(size_t row, size_t col) const { return rowBegin(row) + col*_channels; } template<typename T> const T* PixelMap<T>::pixEnd(size_t row, size_t col) const { return pixBegin(row, col) + _channels; } template<typename T> PixelMap<T>& PixelMap<T>::operator=(const PixelMap<T>& other){ if(_height != other.getHeight() || _width != other.getWidth() || _channels != other.getChannels()){ _height = other.getHeight(); _width = other.getWidth(); _channels = other.getChannels(); _pixel_map.reset(nullptr); _pixel_map = std::make_unique<T[]>(_height*_width*_channels); } T* it_dest = begin(); const T* it_src = other.begin(); for(; it_dest != end(); ++it_dest, ++it_src) *it_dest = *it_src; return *this; } template<typename T> bool PixelMap<T>::operator==(const PixelMap<T>& other) const{ if(has_same_dims_as(other)) return false; return std::equal(begin(), other.begin(), other.end()); } template<typename T> bool PixelMap<T>::has_same_dims_as(const PixelMap<T>& other) const{ if(_height != other.getHeight() || _width != other.getWidth() || _channels != other.getChannels()) return false; return true; } template<typename T> PixelMap<T> PixelMap<T>::transpose() const{ PixelMap<T> res(_width, _height, _channels); for(size_t y = 0; y < _height; ++y){ for(size_t x = 0; x < _width; ++x){ for(size_t c = 0; c < _channels; ++c){ res(x, y, c) = (*this)(y, x, c); } } } return res; } // if min val negative shift all values /** * normalization: * x_new = (x - min)*(max_des - min_des)/(max-min)+min_des */ template<typename T> PixelMap<T>& PixelMap<T>::subtract(const PixelMap<T>& other){ assert(has_same_dims_as(other)); std::vector<uint16_t> min_val(_channels); std::vector<uint16_t> max_val(_channels); #ifdef _OPENMP #pragma omp for simd #endif for(size_t c = 0; c < _channels; ++c) min_val[c] = 510; // 2*255 #ifdef _OPENMP #pragma omp for simd #endif for(size_t c = 0; c < _channels; ++c) max_val[c] = 0; std::vector<uint16_t> buf(_width*_height*_channels); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ for(size_t c = 0; c < _channels; ++c){ buf[c+(j+i*_width)*_channels] = (255 + (*this)(i, j, c)) - static_cast<uint32_t>(other(i, j, c)); if(buf[c+(j+i*_width)*_channels] < min_val[c]) min_val[c] = buf[c+(j+i*_width)*_channels]; else if(buf[c+(j+i*_width)*_channels] > max_val[c]) max_val[c] = buf[c+(j+i*_width)*_channels]; } } } for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ for(size_t c = 0; c < _channels; ++c){ float fact = 255/(max_val[c]-min_val[c]+1e-10f/* == 0 ? 1e-10f : max_val[c]-min_val[c]*/); (*this)(i, j, c) = static_cast<png_byte>((buf[c+(j+i*_width)*_channels] - min_val[c]) * fact); } } } return *this; } template<typename T> void PixelMap<T>::print() const{ const T* it = begin(); for(size_t y = 0; y < _height; ++y){ for(size_t x = 0; x < _width; ++x){ //const T* it = pixBegin(y, x); std::cout << "{"; for(size_t c = 0; c < _channels; ++c){ std::cout << *static_cast<const T*>(it++) << ", "; } std::cout << "}, "; } std::cout << std::endl; } std::cout << std::endl; } ////////////////////////////////////////////////////////////////////// // // // BITMAP IMPLEM (RGBA) // // // ////////////////////////////////////////////////////////////////////// BitMapRGBA::BitMapRGBA() : _height{ 0 }, _width{ 0 }{} BitMapRGBA::BitMapRGBA(size_t height, size_t width) : _height{ height }, _width{ width }, _data{ std::make_unique<uint32_t[]>(height*width) }{} /** * Constructor with default arguments that may have different types * d_name == UNIFORM -> pixel in [0, 255] * d_name == NORMAL -> n_trials = height*width*channels | probability = 0.5 */ BitMapRGBA::BitMapRGBA(size_t height, size_t width, DistrName d_name) : BitMapRGBA(height, width, d_name, ((d_name==NORMAL) ? 255 : 0), ((d_name==NORMAL) ? 0.5f : 255)){} template<typename U, typename V> BitMapRGBA::BitMapRGBA(size_t height, size_t width, DistrName d_name, U param1, V param2) : _height{ height }, _width{ width }, _data{ std::make_unique<uint32_t[]>(height*width) }{ std::unique_ptr<distribution<uint32_t>> distr; switch(d_name){ case UNIFORM:{ distr = std::make_unique<uniform_dist<uint32_t>>(param1, param2); break; } case NORMAL:{ distr = std::make_unique<normal_dist<uint32_t>>(param1, param2); break; } default:{ printf("default bitmap noise: uniform\n"); distr = std::make_unique<uniform_dist<uint32_t>>(param1, param2); break; } }; for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ _data[j+i*_width] = (((*distr)() << 0 )& 0x000000ff) | (((*distr)() << 8 )& 0x0000ff00) | (((*distr)() << 16)& 0x00ff0000) | (((*distr)() << 24)& 0xff000000); } } } BitMapRGBA::BitMapRGBA(const BitMapRGBA& other){ *this = other; } BitMapRGBA::BitMapRGBA(BitMapRGBA&& other) noexcept: _height{ other._height }, _width{ other._width }, _data{ std::move(other._data) }{} BitMapRGBA::BitMapRGBA(const PixelMap<png_byte>& pixelmap) : BitMapRGBA(pixelmap.getHeight(), pixelmap.getWidth()){ size_t channels = pixelmap.getChannels(); switch(channels){ case 1:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); *(it_bm++) = ( 0xff00) | (static_cast<uint32_t>(*pixel_pm) & 0x00ff); } } break; } case 2:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); *(it_bm++) = (static_cast<uint32_t>(*(pixel_pm+1) << 8) & 0x0000ff00) | (static_cast<uint32_t>(* pixel_pm << 0) & 0x000000ff); } } break; } case 3:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); *(it_bm++) = ( 0xff000000) | ((static_cast<uint32_t>(*(pixel_pm+2)) << 16) & 0x00ff0000) | ((static_cast<uint32_t>(*(pixel_pm+1)) << 8 ) & 0x0000ff00) | ( static_cast<uint32_t>(* pixel_pm ) & 0x000000ff); } } break; } case 4:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); *(it_bm++) = ((static_cast<uint32_t>(*(pixel_pm+3)) << 24) & 0xff000000) | ((static_cast<uint32_t>(*(pixel_pm+2)) << 16) & 0x00ff0000) | ((static_cast<uint32_t>(*(pixel_pm+1)) << 8 ) & 0x0000ff00) | ( static_cast<uint32_t>(* pixel_pm ) & 0x000000ff); } } break; } default:{ printf("Must provide (1-4) channels for Bitmap construction.\n"); abort(); } } } size_t BitMapRGBA::getHeight() const{ return _height; } size_t BitMapRGBA::getWidth() const{ return _width; } unsigned char BitMapRGBA::get(size_t i, size_t j, size_t c) const{ return (_data[j+i*_width] >> (8*c) & 0xff); } uint32_t& BitMapRGBA::operator()(size_t i, size_t j){ return _data[j+i*_width]; } const uint32_t& BitMapRGBA::operator()(size_t i, size_t j) const{ return _data[j+i*_width]; } uint32_t* BitMapRGBA::begin(){ return _data.get(); } uint32_t* BitMapRGBA::end(){ return begin() + _height*_width; } const uint32_t* BitMapRGBA::begin() const{ return _data.get(); } const uint32_t* BitMapRGBA::end() const{ return begin() + _height*_width; } uint32_t* BitMapRGBA::rowBegin(size_t row){ return begin() + row*_height*_width; } uint32_t* BitMapRGBA::rowEnd(size_t row){ return rowBegin(row) + _width; } const uint32_t* BitMapRGBA::rowBegin(size_t row) const{ return begin() + row*_height*_width; } const uint32_t* BitMapRGBA::rowEnd(size_t row) const{ return rowBegin(row) + _width; } template<typename rowIt> void BitMapRGBA::copy_row(rowIt rowit, size_t row, size_t channels){ //assert(row < _height && (*rowit)->getWidth() == _width); for(size_t j = 0; j < _width; ++j){ for(size_t c = 0; c < channels; ++c){ _data[j+row*_width] |= (*(rowit+(c+j*channels)) << rgba_utils.shift[c] & rgba_utils.rgba[c]); } } } BitMapRGBA BitMapRGBA::transpose() const{ BitMapRGBA res(_width, _height); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ res(j, i) = _data[j + i*_width]; } } return res; } /* * shift all values by min_value to avoid negative values * * normalization: * x_new = (x - min)*(max_des - min_des)/(max-min)+min_des * * each rgba max value "spreads" in uint64_t integer * max possible value: 2 * 255 = 510 = 0x01fe */ BitMapRGBA& BitMapRGBA::subtract_rgb(const BitMapRGBA& other){ uint64_t min_val = 0x000001fe01fe01fe; uint64_t max_val = 0x0; std::vector<uint64_t> buf(_width*_height, 0); for(size_t n = 0; n < _width*_height; ++n) buf[n] = 0x000000ff00ff00ff; const uint32_t *this_it = begin(); const uint32_t *other_it = other.begin(); for(size_t n = 0; n < _width*_height; ++this_it, ++other_it, ++n){ buf[n] += ((static_cast<uint64_t>(*this_it & 0xff0000)) << 16) | ((static_cast<uint64_t>(*this_it & 0xff00)) << 8) | ( static_cast<uint64_t>(*this_it & 0xff)); buf[n] -= ((static_cast<uint64_t>(*other_it & 0xff0000)) << 16) | ((static_cast<uint64_t>(*other_it & 0xff00)) << 8) | ( static_cast<uint64_t>(*other_it & 0xff)); min_val = ((buf[n] & 0x01fe00000000) < (min_val & 0x01fe00000000) ? (buf[n] & 0x01fe00000000) : (min_val & 0x01fe00000000)) | ((buf[n] & 0x01fe0000) < (min_val & 0x01fe0000) ? (buf[n] & 0x01fe0000) : (min_val & 0x01fe0000)) | ((buf[n] & 0x01fe) < (min_val & 0x01fe) ? (buf[n] & 0x01fe) : (min_val & 0x01fe)); max_val = ((buf[n] & 0x01fe00000000) > (max_val & 0x01fe00000000) ? (buf[n] & 0x01fe00000000) : (max_val & 0x01fe00000000)) | ((buf[n] & 0x01fe0000) > (max_val & 0x01fe0000) ? (buf[n] & 0x01fe0000) : (max_val & 0x01fe0000)) | ((buf[n] & 0x01fe) > (max_val & 0x01fe) ? (buf[n] & 0x01fe) : (max_val & 0x01fe)); } uint64_t max_min = max_val - min_val; // norm. factor for each col. channel (diff. can still be 0x1fe at this point) float b_fact = 255.0f / ((max_min & 0x1fe00000000) >> 32); float g_fact = 255.0f / ((max_min & 0x1fe0000) >> 16); float r_fact = 255.0f / ( max_min & 0x1fe); uint32_t *this_it_update = begin(); for(size_t n = 0; n < _width*_height; ++n, ++this_it_update){ //res = (buf[n] - min_val) * fact; buf[n] -= min_val; // shifting the bits so that they line up in proper uint32_t position. Alpha channel is copied *this_it_update = ((*this_it_update) & 0xff000000) | ((static_cast<uint32_t>(((buf[n] & 0xff00000000) >> 32) * b_fact)/* & 0xff*/) << 16) | ((static_cast<uint32_t>(((buf[n] & 0x0000ff0000) >> 16) * g_fact)/* & 0xff*/) << 8 ) | ((static_cast<uint32_t>(((buf[n] & 0x00000000ff) ) * r_fact)/* & 0xff*/) ); } return *this; } BitMapRGBA& BitMapRGBA::subtract_rgba(const BitMapRGBA& other){ uint64_t min_val = 0x01fe01fe01fe01fe; uint64_t max_val = 0x0; std::vector<uint64_t> buf(_width*_height, 0); for(size_t n = 0; n < _width*_height; ++n) buf[n] = 0x00ff00ff00ff00ff; const uint32_t *this_it = begin(); const uint32_t *other_it = other.begin(); for(size_t n = 0; n < _width*_height; ++n, ++this_it, ++other_it){ buf[n] += ((static_cast<uint64_t>(*this_it & 0xff000000)) << 24) | ((static_cast<uint64_t>(*this_it & 0xff0000)) << 16) | ((static_cast<uint64_t>(*this_it & 0xff00)) << 8) | ( static_cast<uint64_t>(*this_it & 0xff)); buf[n] -= ((static_cast<uint64_t>(*other_it & 0xff000000)) << 24) | ((static_cast<uint64_t>(*other_it & 0xff0000)) << 16) | ((static_cast<uint64_t>(*other_it & 0xff00)) << 8) | ( static_cast<uint64_t>(*other_it & 0xff)); min_val = ((buf[n] & 0x01fe000000000000) < (min_val & 0x01fe000000000000) ? (buf[n] & 0x01fe000000000000) : (min_val & 0x01fe000000000000)) | ((buf[n] & 0x01fe00000000) < (min_val & 0x01fe00000000) ? (buf[n] & 0x01fe00000000) : (min_val & 0x01fe00000000)) | ((buf[n] & 0x01fe0000) < (min_val & 0x01fe0000) ? (buf[n] & 0x01fe0000) : (min_val & 0x01fe0000)) | ((buf[n] & 0x01fe) < (min_val & 0x01fe) ? (buf[n] & 0x01fe) : (min_val & 0x01fe)); max_val = ((buf[n] & 0x01fe000000000000) > (max_val & 0x01fe000000000000) ? (buf[n] & 0x01fe000000000000) : (max_val & 0x01fe000000000000)) | ((buf[n] & 0x01fe00000000) > (max_val & 0x01fe00000000) ? (buf[n] & 0x01fe00000000) : (max_val & 0x01fe00000000)) | ((buf[n] & 0x01fe0000) > (max_val & 0x01fe0000) ? (buf[n] & 0x01fe0000) : (max_val & 0x01fe0000)) | ((buf[n] & 0x01fe) > (max_val & 0x01fe) ? (buf[n] & 0x01fe) : (max_val & 0x01fe)); } uint64_t max_min = max_val - min_val; // norm. factor for each col. channel (diff. can still be 0x1fe at this point) float a_fact = 255.0f / ((max_min & 0x1fe000000000000) >> 48); float b_fact = 255.0f / ((max_min & 0x1fe00000000) >> 32); float g_fact = 255.0f / ((max_min & 0x1fe0000) >> 16); float r_fact = 255.0f / ( max_min & 0x1fe); uint32_t *this_it_update = begin(); for(size_t n = 0; n < _width*_height; ++n, ++this_it_update){ //res = (buf[n] - min_val) * fact; buf[n] -= min_val; // shifting the bits so that they line up in proper uint32_t position *this_it_update = ((static_cast<uint32_t>(((buf[n] & 0xff0000000000) >> 48) * a_fact)/* & 0xff*/) << 24) | ((static_cast<uint32_t>(((buf[n] & 0x00ff00000000) >> 32) * b_fact)/* & 0xff*/) << 16) | ((static_cast<uint32_t>(((buf[n] & 0x000000ff0000) >> 16) * g_fact)/* & 0xff*/) << 8 ) | ((static_cast<uint32_t>(((buf[n] & 0x0000000000ff) ) * r_fact)/* & 0xff*/) ); } return *this; } BitMapRGBA& BitMapRGBA::operator=(const BitMapRGBA& other){ if(_height != other.getHeight() || _width != other.getWidth()){ _height = other.getHeight(); _width = other.getWidth(); _data.reset(nullptr); _data = std::make_unique<uint32_t[]>(_height*_width); } uint32_t* it_dest = begin(); const uint32_t* it_src = other.begin(); for(; it_dest != end(); ++it_dest, ++it_src) *it_dest = *it_src; return *this; } /* BitMapRGBA& BitMapRGBA::operator=(const PixelMap<png_byte>& pixelmap){ *this = BitMapRGBA(pixelmap); return *this; } */ void BitMapRGBA::print() const{ printf("red = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d]", (int)(_data[j+i*_width] >> 0 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 0 & 0xff)); } //printf("\n"); } printf("\n"); printf("green = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d]", (int)(_data[j+i*_width] >> 8 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 8 & 0xff)); } //printf("\n"); } printf("\n"); printf("blue = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d]", (int)(_data[j+i*_width] >> 16 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 16 & 0xff)); } //printf("\n"); } printf("\n"); printf("alpha = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d]", (int)(_data[j+i*_width] >> 24 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 24 & 0xff)); } //printf("\n"); } printf("\n"); } void BitMapRGBA::print_bitmap() const{ printf("red = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d],", (int)((_data[j+i*_width] >> 0) & 0xff)); else printf("%d,", (int)((_data[j+i*_width] >> 0) & 0xff)); } printf("\n"); } printf("\n"); printf("green = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d],", (int)((_data[j+i*_width] >> 8) & 0xff)); else printf("%d,", (int)((_data[j+i*_width] >> 8) & 0xff)); } printf("\n"); } printf("\n"); printf("blue = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d],", (int)((_data[j+i*_width] >> 16) & 0xff)); else printf("%d,", (int)((_data[j+i*_width] >> 16) & 0xff)); } printf("\n"); } printf("\n"); /* printf("alpha = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d],", (int)((_data[j+i*_width] >> 24) & 0xff)); else printf("%d,", (int)((_data[j+i*_width] >> 24) & 0xff)); } printf("\n"); } printf("\n"); */ } ////////////////////////////////////////////////////////////////////// // // // BITMAP IMPLEM (RGB) // // // ////////////////////////////////////////////////////////////////////// BitMapRGB::BitMapRGB() : _height{ 0 }, _width{ 0 }{} BitMapRGB::BitMapRGB(size_t height, size_t width) : _height{ height }, _width{ width }, _data{ std::make_unique<uint32_t[]>(height*width) }{} /** * Constructor with default arguments that may have different types * d_name == UNIFORM -> pixel in [0, 255] * d_name == NORMAL -> n_trials = height*width*channels | probability = 0.5 */ BitMapRGB::BitMapRGB(size_t height, size_t width, DistrName d_name) : BitMapRGB(height, width, d_name, ((d_name==NORMAL) ? 255 : 0), ((d_name==NORMAL) ? 0.5f : 255)){} template<typename U, typename V> BitMapRGB::BitMapRGB(size_t height, size_t width, DistrName d_name, U param1, V param2) : _height{ height }, _width{ width }, _data{ std::make_unique<uint32_t[]>(height*width) }{ std::unique_ptr<distribution<uint32_t>> distr; switch(d_name){ case UNIFORM:{ distr = std::make_unique<uniform_dist<uint32_t>>(param1, param2); break; } case NORMAL:{ distr = std::make_unique<normal_dist<uint32_t>>(param1, param2); break; } default:{ printf("default bitmap noise: uniform\n"); distr = std::make_unique<uniform_dist<uint32_t>>(param1, param2); break; } }; for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ _data[j+i*_width] = (( *distr)() & 0xff) | (((*distr)() << 8 )& 0xff00) | (((*distr)() << 16)& 0xff0000); } } } BitMapRGB::BitMapRGB(const BitMapRGB& other){ *this = other; } BitMapRGB::BitMapRGB(BitMapRGB&& other) noexcept: _height{ other._height }, _width{ other._width }, _data{ std::move(other._data) }{} BitMapRGB::BitMapRGB(const PixelMap<png_byte>& pixelmap) : BitMapRGB(pixelmap.getHeight(), pixelmap.getWidth()){ size_t channels = pixelmap.getChannels(); switch(channels){ case 1:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); // first channel *(it_bm++) = (static_cast<uint32_t>(*pixel_pm) & 0xff); } } break; } case 2:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); // first and alpha channels *(it_bm++) = (static_cast<uint32_t>(*(pixel_pm+1) << 8) & 0xff00) | (static_cast<uint32_t>(* pixel_pm ) & 0x00ff); } } break; } case 3:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); // rgb channels *(it_bm++) = ((static_cast<uint32_t>(*(pixel_pm+2)) << 16) & 0xff0000) | ((static_cast<uint32_t>(*(pixel_pm+1)) << 8 ) & 0x00ff00) | ( static_cast<uint32_t>(* pixel_pm ) & 0x0000ff); } } break; } case 4:{ uint32_t *it_bm = begin(); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ const png_byte *pixel_pm = pixelmap.pixBegin(i, j); // skip alpha channel *(it_bm++) = ((static_cast<uint32_t>(*(pixel_pm+2)) << 16) & 0xff0000) | ((static_cast<uint32_t>(*(pixel_pm+1)) << 8 ) & 0x00ff00) | ( static_cast<uint32_t>(* pixel_pm ) & 0x0000ff); } } break; } default:{ printf("Must provide (1-4) channels for Bitmap construction.\n"); abort(); } } } size_t BitMapRGB::getHeight() const{ return _height; } size_t BitMapRGB::getWidth() const{ return _width; } unsigned char BitMapRGB::get(size_t i, size_t j, size_t c) const{ return (_data[j+i*_width] >> (8*c) & 0xff); } uint32_t& BitMapRGB::operator()(size_t i, size_t j){ return _data[j+i*_width]; } const uint32_t& BitMapRGB::operator()(size_t i, size_t j) const{ return _data[j+i*_width]; } uint32_t* BitMapRGB::begin(){ return _data.get(); } uint32_t* BitMapRGB::end(){ return begin() + _height*_width; } const uint32_t* BitMapRGB::begin() const{ return _data.get(); } const uint32_t* BitMapRGB::end() const{ return begin() + _height*_width; } uint32_t* BitMapRGB::rowBegin(size_t row){ return begin() + row*_height*_width; } uint32_t* BitMapRGB::rowEnd(size_t row){ return rowBegin(row) + _width; } const uint32_t* BitMapRGB::rowBegin(size_t row) const{ return begin() + row*_height*_width; } const uint32_t* BitMapRGB::rowEnd(size_t row) const{ return rowBegin(row) + _width; } BitMapRGB& BitMapRGB::operator=(const BitMapRGB& other){ if(_height != other.getHeight() || _width != other.getWidth()){ _height = other.getHeight(); _width = other.getWidth(); _data.reset(nullptr); _data = std::make_unique<uint32_t[]>(_height*_width); } uint32_t* it_dest = begin(); const uint32_t* it_src = other.begin(); for(; it_dest != end(); ++it_dest, ++it_src) *it_dest = *it_src; return *this; } /* BitMapRGB& BitMapRGB::operator=(const PixelMap<png_byte>& pixelmap){ *this = BitMapRGB(pixelmap); return *this; } */ template<typename rowIt> void BitMapRGB::copy_row(rowIt rowit, size_t row, size_t channels){ assert(channels < 4); //assert(row < _height && (*rowit)->getWidth() == _width); for(size_t j = 0; j < _width; ++j){ for(size_t c = 0; c < 3; ++c){ _data[j+row*_width] |= (*(rowit+(c+j*channels)) << rgba_utils.shift[c] & rgba_utils.rgba[c]); } } } BitMapRGB BitMapRGB::transpose() const{ BitMapRGB res(_width, _height); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ res(j, i) = _data[j + i*_width]; } } return res; } BitMapRGB& BitMapRGB::subtract(const BitMapRGB& other){ uint64_t min_val = 0x01fe01fe01fe; uint64_t max_val = 0x0; std::vector<uint64_t> buf(_width*_height, 0); for(size_t n = 0; n < _width*_height; ++n) buf[n] = 0x00ff00ff00ff; const uint32_t *this_it = begin(); const uint32_t *other_it = other.begin(); for(size_t n = 0; n < _width*_height; ++this_it, ++other_it, ++n){ buf[n] += ((static_cast<uint64_t>(*this_it & 0xff0000)) << 16) | ((static_cast<uint64_t>(*this_it & 0xff00)) << 8) | ( static_cast<uint64_t>(*this_it & 0xff)); buf[n] -= ((static_cast<uint64_t>(*other_it & 0xff0000)) << 16) | ((static_cast<uint64_t>(*other_it & 0xff00)) << 8) | ( static_cast<uint64_t>(*other_it & 0xff)); min_val = ((buf[n] & 0x01fe00000000) < (min_val & 0x01fe00000000) ? (buf[n] & 0x01fe00000000) : (min_val & 0x01fe00000000)) | ((buf[n] & 0x01fe0000) < (min_val & 0x01fe0000) ? (buf[n] & 0x01fe0000) : (min_val & 0x01fe0000)) | ((buf[n] & 0x01fe) < (min_val & 0x01fe) ? (buf[n] & 0x01fe) : (min_val & 0x01fe)); max_val = ((buf[n] & 0x01fe00000000) > (max_val & 0x01fe00000000) ? (buf[n] & 0x01fe00000000) : (max_val & 0x01fe00000000)) | ((buf[n] & 0x01fe0000) > (max_val & 0x01fe0000) ? (buf[n] & 0x01fe0000) : (max_val & 0x01fe0000)) | ((buf[n] & 0x01fe) > (max_val & 0x01fe) ? (buf[n] & 0x01fe) : (max_val & 0x01fe)); } uint64_t max_min = max_val - min_val; // norm. factor for each col. channel (diff. can still be 0x1fe at this point) float b_fact = 255.0f / ((max_min & 0x1fe00000000) >> 32); float g_fact = 255.0f / ((max_min & 0x1fe0000) >> 16); float r_fact = 255.0f / ( max_min & 0x1fe); uint32_t *this_it_update = begin(); for(size_t n = 0; n < _width*_height; ++n, ++this_it_update){ //res = (buf[n] - min_val) * fact; buf[n] -= min_val; // shifting the bits so that they line up in proper uint32_t position. Alpha channel is copied *this_it_update = ((static_cast<uint32_t>(((buf[n] & 0xff00000000) >> 32) * b_fact)/* & 0xff*/) << 16) | ((static_cast<uint32_t>(((buf[n] & 0x0000ff0000) >> 16) * g_fact)/* & 0xff*/) << 8 ) | ((static_cast<uint32_t>(((buf[n] & 0x00000000ff) ) * r_fact)/* & 0xff*/) ); } return *this; } void BitMapRGB::print() const{ printf("red = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d]", (int)(_data[j+i*_width] >> 0 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 0 & 0xff)); } //printf("\n"); } printf("\n"); printf("green = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d]", (int)(_data[j+i*_width] >> 8 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 8 & 0xff)); } //printf("\n"); } printf("\n"); printf("blue = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d]", (int)(_data[j+i*_width] >> 16 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 16 & 0xff)); } //printf("\n"); } printf("\n"); } void BitMapRGB::print_bitmap() const{ printf("red = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d],", (int)(_data[j+i*_width] >> 0 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 0 & 0xff)); } printf("\n"); } printf("\n"); printf("green = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d],", (int)(_data[j+i*_width] >> 8 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 8 & 0xff)); } printf("\n"); } printf("\n"); printf("blue = ["); for(size_t i = 0; i < _height; ++i){ for(size_t j = 0; j < _width; ++j){ if(i == _height-1 && j == _width-1) printf("%d],", (int)(_data[j+i*_width] >> 16 & 0xff)); else printf("%d,", (int)(_data[j+i*_width] >> 16 & 0xff)); } printf("\n"); } printf("\n"); }
GB_unop__isfinite_bool_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 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__isfinite_bool_fp64) // op(A') function: GB (_unop_tran__isfinite_bool_fp64) // C type: bool // A type: double // cast: double cij = (aij) // unaryop: cij = isfinite (aij) #define GB_ATYPE \ double #define GB_CTYPE \ bool // 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 = isfinite (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] = isfinite (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISFINITE || GxB_NO_BOOL || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__isfinite_bool_fp64) ( bool *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = (aij) ; Cx [p] = isfinite (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; double z = (aij) ; Cx [p] = isfinite (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__isfinite_bool_fp64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
CostEvaluatorFull.h
/********************************************************************************************************************** This file is part of the Control Toolbox (https://adrlab.bitbucket.io/ct), copyright by ETH Zurich, Google Inc. Licensed under Apache2 license (see LICENSE file in main directory) **********************************************************************************************************************/ #pragma once #include <omp.h> #include <math.h> #include <cmath> #include <functional> #include <ct/optcon/costfunction/CostFunctionQuadratic.hpp> #include <ct/optcon/dms/dms_core/OptVectorDms.h> #include <ct/optcon/dms/dms_core/ShotContainer.h> #include <ct/optcon/nlp/DiscreteCostEvaluatorBase.h> namespace ct { namespace optcon { /** * @ingroup DMS * * @brief Performs the full cost integration over the shots * * @tparam STATE_DIM The state dimension * @tparam CONTROL_DIM The input dimension */ template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR = double> class CostEvaluatorFull : public tpl::DiscreteCostEvaluatorBase<SCALAR> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef DmsDimensions<STATE_DIM, CONTROL_DIM, SCALAR> DIMENSIONS; typedef typename DIMENSIONS::state_vector_t state_vector_t; typedef typename DIMENSIONS::control_vector_t control_vector_t; typedef typename DIMENSIONS::state_vector_array_t state_vector_array_t; typedef typename DIMENSIONS::control_vector_array_t control_vector_array_t; typedef typename DIMENSIONS::time_array_t time_array_t; CostEvaluatorFull() = delete; /** * @brief Custom constructor * * @param[in] costFct The cost function * @param[in] w The optimization vector * @param[in] controlSpliner The control spliner * @param[in] shotInt The shot number * @param[in] settings The dms settings */ CostEvaluatorFull(std::shared_ptr<ct::optcon::CostFunctionQuadratic<STATE_DIM, CONTROL_DIM, SCALAR>> costFct, std::shared_ptr<OptVectorDms<STATE_DIM, CONTROL_DIM, SCALAR>> w, std::shared_ptr<SplinerBase<control_vector_t, SCALAR>> controlSpliner, std::vector<std::shared_ptr<ShotContainer<STATE_DIM, CONTROL_DIM, SCALAR>>> shotInt, DmsSettings settings) : costFct_(costFct), w_(w), controlSpliner_(controlSpliner), shotContainers_(shotInt), settings_(settings) { } /** * @brief The destructor. */ ~CostEvaluatorFull() override = default; SCALAR eval() override { SCALAR cost = SCALAR(0.0); #pragma omp parallel for num_threads(settings_.nThreads_) for (auto shotContainer = shotContainers_.begin(); shotContainer < shotContainers_.end(); ++shotContainer) { (*shotContainer)->integrateCost(); } for (auto shotContainer : shotContainers_) cost += shotContainer->getCostIntegrated(); costFct_->setCurrentStateAndControl(w_->getOptimizedState(settings_.N_), control_vector_t::Zero()); cost += costFct_->evaluateTerminal(); return cost; } void evalGradient(size_t grad_length, Eigen::Map<Eigen::Matrix<SCALAR, Eigen::Dynamic, 1>>& grad) override { grad.setZero(); assert(shotContainers_.size() == settings_.N_); // go through all shots, integrate the state trajectories and evaluate cost accordingly // intermediate costs #pragma omp parallel for num_threads(settings_.nThreads_) for (auto shotContainer = shotContainers_.begin(); shotContainer < shotContainers_.end(); ++shotContainer) { (*shotContainer)->integrateCostSensitivities(); } for (size_t shotNr = 0; shotNr < shotContainers_.size(); ++shotNr) { switch (settings_.splineType_) { case DmsSettings::ZERO_ORDER_HOLD: { grad.segment(w_->getStateIndex(shotNr), STATE_DIM) += shotContainers_[shotNr]->getdLdSiIntegrated(); grad.segment(w_->getControlIndex(shotNr), CONTROL_DIM) += shotContainers_[shotNr]->getdLdQiIntegrated(); break; } case DmsSettings::PIECEWISE_LINEAR: { grad.segment(w_->getStateIndex(shotNr), STATE_DIM) += shotContainers_[shotNr]->getdLdSiIntegrated(); grad.segment(w_->getControlIndex(shotNr), CONTROL_DIM) += shotContainers_[shotNr]->getdLdQiIntegrated(); grad.segment(w_->getControlIndex(shotNr + 1), CONTROL_DIM) += shotContainers_[shotNr]->getdLdQip1Integrated(); break; } default: throw(std::runtime_error( " cost gradient not yet implemented for this type of interpolation. Exiting")); } // H-part. // if(settings_.objectiveType_ == DmsSettings::OPTIMIZE_GRID) // { // costFct_->setCurrentStateAndControl(shotContainers_[shotNr]->getStateIntegrated(), // controlSpliner_->evalSpline(shotContainers_[shotNr]->getIntegrationTimeFinal(), shotNr)); // grad(w_->getTimeSegmentIndex(shotNr)) = costFct_->evaluateIntermediate() + shotContainers_[shotNr]->getdLdHiIntegrated(); // } } /* gradient of terminal cost */ costFct_->setCurrentStateAndControl(w_->getOptimizedState(settings_.N_), control_vector_t::Zero()); grad.segment(w_->getStateIndex(settings_.N_), STATE_DIM) += costFct_->stateDerivativeTerminal(); // * dXdSi.back(); } private: std::shared_ptr<ct::optcon::CostFunctionQuadratic<STATE_DIM, CONTROL_DIM, SCALAR>> costFct_; std::shared_ptr<OptVectorDms<STATE_DIM, CONTROL_DIM, SCALAR>> w_; std::shared_ptr<SplinerBase<control_vector_t, SCALAR>> controlSpliner_; std::vector<std::shared_ptr<ShotContainer<STATE_DIM, CONTROL_DIM, SCALAR>>> shotContainers_; const DmsSettings settings_; }; } // namespace optcon } // namespace ct
DijkstraAlgorithm_OPENMP.c
#include <limits.h> #include <stdio.h> #include <stdbool.h> #include <omp.h> #include <time.h> #define V 9 int minDistance(int dist[], bool sptSet[]) { int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } void printSolution(int dist[]) { printf("Vertex \t\t Distance from Source\n"); for (int i = 0; i < V; i++) printf("%d \t\t %d\n", i, dist[i]); } void dijkstra(int graph[V][V], int src) { double begin, end; begin = (double) clock()/CLOCKS_PER_SEC; int dist[V]; bool sptSet[V]; for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; dist[src] = 0; #pragma omp parallel for for (int count = 0; count < V - 1; count++) { int u = minDistance(dist, sptSet); sptSet[u] = true; #pragma omp parallel for for (int v = 0; v < V; v++){ if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } } end = (double) clock()/CLOCKS_PER_SEC; printf("My serial code took %g\n", end-begin); printSolution(dist); } int main() { omp_set_num_threads(2); int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; dijkstra(graph, 0); return 0; }
getStartLists.c
#include "defs.h" double getStartLists(graph* G, edge** maxIntWtListPtr, INT_T* maxIntWtListSizePtr) { mcsim_skip_instrs_begin(); LONG_T *local_max, maxWeight; edge *maxIntWtList; LONG_T maxIntWtListSize; LONG_T *p_start, *p_end; double elapsed_time; elapsed_time = get_seconds(); #ifdef _OPENMP omp_set_num_threads(NUM_THREADS); #pragma omp parallel { #endif LONG_T i, j, n; edge* pList; LONG_T pCount, tmpListSize; int tid, nthreads; #ifdef DIAGNOSTIC double elapsed_time_part; #endif #ifdef _OPENMP tid = omp_get_thread_num(); nthreads = omp_get_num_threads(); #else tid = 0; nthreads = 1; #endif n = G->n; /* Determine the maximum edge weight */ if (tid == 0) { local_max = (LONG_T *) malloc(nthreads*sizeof(LONG_T)); } /* Allocate memory for partial edge list on each thread */ tmpListSize = 1000; pList = (edge *) malloc(tmpListSize*sizeof(edge)); pCount = 0; #ifdef _OPENMP #pragma omp barrier #endif local_max[tid] = -1; #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds(); } #endif mcsim_skip_instrs_end(); #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) { for (j=G->numEdges[i]; j<G->numEdges[i+1]; j++) { if (G->weight[j] > local_max[tid]) { #ifdef PERSISTENT mcsim_log_begin(); //mcsim_skip_instrs_begin(); #ifdef UNDOLOG LONG_T *undolog_local_max; undolog_local_max = (LONG_T *) malloc(nthreads*sizeof(LONG_T)); undolog_local_max[tid] = local_max[tid]; #endif // UNDOLOG #ifdef REDOLOG LONG_T *redolog_local_max; redolog_local_max = (LONG_T *) malloc(nthreads*sizeof(LONG_T)); redolog_local_max[tid] = G->weight[j]; #endif // REDOLOG //mcsim_skip_instrs_end(); mcsim_mem_fence(); mcsim_log_end(); mcsim_mem_fence(); #endif // PERSISTENT local_max[tid] = G->weight[j]; pCount = 0; #ifdef PERSISTENT mcsim_log_begin(); //mcsim_skip_instrs_begin(); #ifdef UNDOLOG edge *undolog_pList; undolog_pList = (edge *) malloc(tmpListSize*sizeof(edge)); undolog_pList[pCount].startVertex = pList[pCount].startVertex; undolog_pList[pCount].endVertex = pList[pCount].endVertex; undolog_pList[pCount].w = pList[pCount].w; undolog_pList[pCount].e = pList[pCount].e; #endif // UNDOLOG #ifdef REDOLOG edge *redolog_pList; redolog_pList = (edge *) malloc(tmpListSize*sizeof(edge)); redolog_pList[pCount].startVertex = i; redolog_pList[pCount].endVertex = G->endV[j]; redolog_pList[pCount].w = local_max[tid]; redolog_pList[pCount].e = j; #endif // REDOLOG //mcsim_skip_instrs_end(); mcsim_mem_fence(); mcsim_log_end(); mcsim_mem_fence(); #endif // PERSISTENT pList[pCount].startVertex = i; pList[pCount].endVertex = G->endV[j]; pList[pCount].w = local_max[tid]; pList[pCount].e = j; pCount++; // make sure undolog and redolog data structures are not discarded by compiler #ifdef PERSISTENT mcsim_skip_instrs_begin(); #ifdef UNDOLOG printf("%d\n", (int)((sizeof undolog_local_max) + (sizeof undolog_pList))); #endif // UNDOLOG #ifdef REDOLOG printf("%d\n", (int)((sizeof redolog_local_max) + (sizeof redolog_pList))); #endif // REDOLOG mcsim_skip_instrs_end(); #endif // PERSISTENT } else if (G->weight[j] == local_max[tid]) { #ifdef PERSISTENT mcsim_log_begin(); //mcsim_skip_instrs_begin(); #ifdef UNDOLOG edge *undolog_pList; undolog_pList = (edge *) malloc(tmpListSize*sizeof(edge)); undolog_pList[pCount].startVertex = pList[pCount].startVertex; undolog_pList[pCount].endVertex = pList[pCount].endVertex; undolog_pList[pCount].w = pList[pCount].w; undolog_pList[pCount].e = pList[pCount].e; #endif // UNDOLOG #ifdef REDOLOG edge *redolog_pList; redolog_pList = (edge *) malloc(tmpListSize*sizeof(edge)); redolog_pList[pCount].startVertex = i; redolog_pList[pCount].endVertex = G->endV[j]; redolog_pList[pCount].w = local_max[tid]; redolog_pList[pCount].e = j; #endif // REDOLOG //mcsim_skip_instrs_end(); mcsim_mem_fence(); mcsim_log_end(); mcsim_mem_fence(); #endif // PERSISTENT pList[pCount].startVertex = i; pList[pCount].endVertex = G->endV[j]; pList[pCount].w = local_max[tid]; pList[pCount].e = j; pCount++; // make sure undolog and redolog data structures are not discarded by compiler #ifdef PERSISTENT mcsim_skip_instrs_begin(); #ifdef UNDOLOG printf("%d\n", (int)(sizeof undolog_pList)); #endif // UNDOLOG #ifdef REDOLOG printf("%d\n", (int)(sizeof redolog_pList)); #endif // REDOLOG mcsim_skip_instrs_end(); #endif // PERSISTENT } } } #ifdef _OPENMP #pragma omp barrier #endif if (tid == 0) { #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() - elapsed_time_part; fprintf(stderr, "Max. weight computation time: %lf seconds\n", elapsed_time_part); } #endif maxWeight = local_max[0]; for (i=1; i<nthreads; i++) { if (local_max[i] > maxWeight) maxWeight = local_max[i]; } // free(local_max); } #ifdef _OPENMP #pragma omp barrier #endif if (local_max[tid] != maxWeight) { pCount = 0; } mcsim_skip_instrs_begin(); /* Merge all te partial edge lists */ if (tid == 0) { p_start = (LONG_T *) malloc(nthreads*sizeof(LONG_T)); p_end = (LONG_T *) malloc(nthreads*sizeof(LONG_T)); } #ifdef _OPENMP #pragma omp barrier #endif p_end[tid] = pCount; p_start[tid] = 0; #ifdef _OPENMP #pragma omp barrier #endif if (tid == 0) { for (i=1; i<nthreads; i++) { p_end[i] = p_end[i-1] + p_end[i]; p_start[i] = p_end[i-1]; } maxIntWtListSize = p_end[nthreads-1]; free(*maxIntWtListPtr); maxIntWtList = (edge *) malloc((maxIntWtListSize)*sizeof(edge)); } mcsim_skip_instrs_end(); #ifdef _OPENMP #pragma omp barrier #endif for (j=p_start[tid]; j<p_end[tid]; j++) { #ifdef PERSISTENT mcsim_log_begin(); //mcsim_skip_instrs_begin(); #ifdef UNDOLOG edge *undolog_maxIntWtList; undolog_maxIntWtList = (edge *) malloc((maxIntWtListSize)*sizeof(edge)); (undolog_maxIntWtList[j]).startVertex = (maxIntWtList[j]).startVertex; (undolog_maxIntWtList[j]).endVertex = (maxIntWtList[j]).endVertex; (undolog_maxIntWtList[j]).e = (maxIntWtList[j]).e; (undolog_maxIntWtList[j]).w = (maxIntWtList[j]).w; #endif // UNDOLOG #ifdef REDOLOG edge *redolog_maxIntWtList; redolog_maxIntWtList = (edge *) malloc((maxIntWtListSize)*sizeof(edge)); (redolog_maxIntWtList[j]).startVertex = pList[j-p_start[tid]].startVertex; (redolog_maxIntWtList[j]).endVertex = pList[j-p_start[tid]].endVertex; (redolog_maxIntWtList[j]).e = pList[j-p_start[tid]].e; (redolog_maxIntWtList[j]).w = pList[j-p_start[tid]].w; #endif // REDOLOG //mcsim_skip_instrs_end(); mcsim_mem_fence(); mcsim_log_end(); mcsim_mem_fence(); #endif // PERSISTENT (maxIntWtList[j]).startVertex = pList[j-p_start[tid]].startVertex; (maxIntWtList[j]).endVertex = pList[j-p_start[tid]].endVertex; (maxIntWtList[j]).e = pList[j-p_start[tid]].e; (maxIntWtList[j]).w = pList[j-p_start[tid]].w; #ifdef PERSISTENT mcsim_skip_instrs_begin(); #ifdef UNDOLOG printf("%d\n", (int)(sizeof undolog_maxIntWtList)); #endif // UNDOLOG #ifdef REDOLOG printf("%d\n", (int)(sizeof redolog_maxIntWtList)); #endif // REDOLOG mcsim_skip_instrs_end(); #endif // PERSISTENT } #ifdef _OPENMP #pragma omp barrier #endif mcsim_skip_instrs_begin(); free(pList); if (tid == 0) { free(local_max); free(p_start); free(p_end); *maxIntWtListPtr = maxIntWtList; *maxIntWtListSizePtr = maxIntWtListSize; } #ifdef _OPENMP } #endif /* Verification */ #if 0 maxIntWtList = *maxIntWtListPtr; for (int i=0; i<*maxIntWtListSizePtr; i++) { fprintf(stderr, "[%ld %ld %ld %ld] ", maxIntWtList[i].startVertex, maxIntWtList[i].endVertex, maxIntWtList[i].e, maxIntWtList[i].w); } #endif elapsed_time = get_seconds() - elapsed_time; mcsim_skip_instrs_end(); return elapsed_time; }
mpncra.c
/* $Header$ */ /* This single source file may be called as three separate executables: ncra -- netCDF record averager nces -- netCDF ensemble statistics ncrcat -- netCDF record concatenator */ /* Purpose: Compute averages or extract series of specified hyperslabs of specfied variables of multiple input netCDF files and output them to a single file. */ /* Copyright (C) 1995--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. You are permitted to link NCO with the HDF, netCDF, OPeNDAP, and UDUnits libraries and to distribute the resulting executables under the terms of the BSD, but in addition obeying the extra stipulations of the HDF, netCDF, OPeNDAP, and UDUnits licenses. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 3-Clause BSD License for more details. The original author of this software, Charlie Zender, seeks to improve it with your suggestions, contributions, bug-reports, and patches. Please contact the NCO project at http://nco.sf.net or write to Charlie Zender Department of Earth System Science University of California, Irvine Irvine, CA 92697-3100 */ /* Usage: ncra -n 3,4,1 -p ${HOME}/nco/data h0001.nc ~/foo.nc ncra -n 3,4,1 -p ${HOME}/nco/data -l ${HOME} h0001.nc ~/foo.nc ncra -n 3,4,1 -p /ZENDER/tmp -l ${HOME}/nco/data h0001.nc ~/foo.nc scp ~/nco/src/nco/ncra.c esmf.ess.uci.edu:nco/src/nco nces in.nc in.nc ~/foo.nc nces -n 3,4,1 -p ${HOME}/nco/data h0001.nc ~/foo.nc nces -n 3,4,1 -p ${HOME}/nco/data -l ${HOME} h0001.nc ~/foo.nc nces -n 3,4,1 -p /ZENDER/tmp -l ${HOME} h0001.nc ~/foo.nc */ #ifdef HAVE_CONFIG_H # include <config.h> /* Autotools tokens */ #endif /* !HAVE_CONFIG_H */ /* Standard C headers */ #include <assert.h> /* assert() debugging macro */ #include <math.h> /* sin cos cos sin 3.14159 */ #include <stdio.h> /* stderr, FILE, NULL, etc. */ #include <stdlib.h> /* abs, getopt, malloc, strtol */ #include <string.h> /* strcmp() */ #include <sys/stat.h> /* stat() */ #include <time.h> /* machine time */ #include <unistd.h> /* POSIX stuff */ #ifndef HAVE_GETOPT_LONG # include "nco_getopt.h" #else /* HAVE_GETOPT_LONG */ # ifdef HAVE_GETOPT_H # include <getopt.h> # endif /* !HAVE_GETOPT_H */ #endif /* HAVE_GETOPT_LONG */ /* Internationalization i18n, Linux Journal 200211 p. 57--59 */ #ifdef I18N #include <libintl.h> /* Internationalization i18n */ #include <locale.h> /* Locale setlocale() */ #define _(sng) gettext (sng) #define gettext_noop(sng) (sng) #define N_(sng) gettext_noop(sng) #endif /* I18N */ #ifndef _LIBINTL_H # define gettext(foo) foo #endif /* _LIBINTL_H */ /* 3rd party vendors */ #include <netcdf.h> /* netCDF definitions and C library */ #ifdef ENABLE_MPI #include <mpi.h> /* MPI definitions */ #include "nco_mpi.h" /* MPI utilities */ #endif /* !ENABLE_MPI */ /* Personal headers */ /* #define MAIN_PROGRAM_FILE MUST precede #include libnco.h */ #define MAIN_PROGRAM_FILE #include "libnco.h" /* netCDF Operator (NCO) library */ #ifdef ENABLE_MPI void checkpointMpi(int prc_rnk, int stage){ int msg[]={0,0}; int rcd; /* [rcd] Return code */ FILE * const fp_stderr=stderr; /* [fl] stderr filehandle CEWI */ if(prc_rnk == rnk_mgr){ msg[0]=stage; msg[1]=stage; } /* endif */ (void)fprintf(fp_stderr,"%d checkpointing at stage %d\n",prc_rnk,stage); /* make everyone continue from this point. */ rcd=MPI_Bcast(msg,2,MPI_INT,rnk_mgr,MPI_COMM_WORLD); if(prc_rnk != rnk_mgr) { /* basic sanity check */ assert(msg[0] == stage); assert(msg[1] == stage); } /* end if */ } /* end checkpointMpi() */ #endif /* !ENABLE_MPI */ int main(int argc,char **argv) { char **fl_lst_abb=NULL; /* Option n */ char **fl_lst_in; char **gaa_arg=NULL; /* [sng] Global attribute arguments */ char **var_lst_in=NULL_CEWI; char *cmd_ln; char *cnk_arg[NC_MAX_DIMS]; char *cnk_map_sng=NULL_CEWI; /* [sng] Chunking map */ char *cnk_plc_sng=NULL_CEWI; /* [sng] Chunking policy */ char *fl_in=NULL; char *fl_out=NULL; /* Option o */ char *fl_out_tmp=NULL_CEWI; char *fl_pth=NULL; /* Option p */ char *fl_pth_lcl=NULL; /* Option l */ char *lmt_arg[NC_MAX_DIMS]; char *nco_op_typ_sng=NULL_CEWI; /* [sng] Operation type Option y */ char *nco_pck_plc_sng=NULL_CEWI; /* [sng] Packing policy Option P */ char *opt_crr=NULL; /* [sng] String representation of current long-option name */ char *optarg_lcl=NULL; /* [sng] Local copy of system optarg */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ const char * const CVS_Id="$Id$"; const char * const CVS_Revision="$Revision$"; const char * const opt_sht_lst="34567ACcD:d:FHhL:l:n:Oo:p:P:rRSt:v:xY:y:-:"; dmn_sct **dim; dmn_sct **dmn_out; extern char *optarg; extern int optind; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped shared in parallel clause */ FILE * const fp_stderr=stderr; /* [fl] stderr filehandle CEWI */ int *in_id_arr; int abb_arg_nbr=0; int cnk_map=nco_cnk_map_nil; /* [enm] Chunking map */ int cnk_nbr=0; /* [nbr] Number of chunk sizes */ int cnk_plc=nco_cnk_plc_nil; /* [enm] Chunking policy */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_idx; int fl_nbr=0; int fl_in_fmt; /* [enm] Input file format */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int gaa_nbr=0; /* [nbr] Number of global attributes to add */ int idx=int_CEWI; int in_id; int lmt_nbr=0; /* Option d. NB: lmt_nbr gets incremented */ int log_lvl=0; /* [enm] netCDF library debugging verbosity [0..5] */ int md_open; /* [enm] Mode flag for nc_open() call */ int nbr_dmn_fl; int nbr_dmn_xtr; int nbr_var_fix; /* nbr_var_fix gets incremented */ int nbr_var_fl; int nbr_var_prc; /* nbr_var_prc gets incremented */ int xtr_nbr=0; /* xtr_nbr won't otherwise be set for -c with no -v */ int nco_op_typ=nco_op_avg; /* [enm] Default operation is averaging */ int nco_pck_plc=nco_pck_plc_nil; /* [enm] Default packing is none */ int opt; int out_id; int rcd=NC_NOERR; /* [rcd] Return code */ int rec_dmn_id=NCO_REC_DMN_UNDEFINED; int thr_idx; /* [idx] Index of current thread */ int thr_nbr=int_CEWI; /* [nbr] Thread number Option t */ int var_lst_in_nbr=0; lmt_sct **lmt=NULL_CEWI; lmt_sct *lmt_rec=NULL_CEWI; lmt_all_sct **lmt_all_lst; /* List of *lmt_all structures */ lmt_all_sct *lmt_all_rec=NULL_CEWI; /* Pointer to record limit structure in above list */ long idx_rec; /* [idx] Index of current record in current input file */ long rec_usd_cml=0L; /* [idx] Index of current record in output file (0 is first, ...) */ nco_bool CNV_ARM; cnv_sct *cnv; /* [sct] Convention structure */ nco_bool EXCLUDE_INPUT_LIST=False; /* Option c */ nco_bool EXTRACT_ALL_COORDINATES=False; /* Option c */ nco_bool EXTRACT_ASSOCIATED_COORDINATES=True; /* Option C */ nco_bool FL_RTR_RMT_LCN; nco_bool FL_LST_IN_APPEND=True; /* Option H */ nco_bool FL_LST_IN_FROM_STDIN=False; /* [flg] fl_lst_in comes from stdin */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=False; /* Option O */ nco_bool FORTRAN_IDX_CNV=False; /* Option F */ nco_bool HISTORY_APPEND=True; /* Option h */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool LAST_RECORD=False; nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=False; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=False; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=True; /* [flg] Write output to temporary file */ nco_bool flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ nco_int base_time_srt=nco_int_CEWI; nco_int base_time_crr=nco_int_CEWI; nm_id_sct *dmn_lst; nm_id_sct *xtr_lst=NULL; /* xtr_lst may be alloc()'d from NULL with -c option */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ size_t cnk_csh_byt=NCO_CNK_CSH_BYT_DFL; /* [B] Chunk cache size */ size_t cnk_min_byt=NCO_CNK_SZ_MIN_BYT_DFL; /* [B] Minimize size of variable to chunk */ size_t cnk_sz_byt=0UL; /* [B] Chunk size in bytes */ size_t cnk_sz_scl=0UL; /* [nbr] Chunk size scalar */ size_t hdr_pad=0UL; /* [B] Pad at end of header section */ var_sct **var; var_sct **var_fix; var_sct **var_fix_out; var_sct **var_out=NULL_CEWI; var_sct **var_prc; var_sct **var_prc_out; #ifdef ENABLE_MPI /* Declare all MPI-specific variables here */ MPI_Status mpi_stt; /* [enm] Status check to decode msg_tag_typ */ nco_bool TKN_WRT_FREE=True; /* [flg] Write-access to output file is available */ int fl_nm_lng; /* [nbr] Output file name length */ int msg_bfr[msg_bfr_lng]; /* [bfr] Buffer containing var, idx, tkn_wrt_rsp */ int jdx=0; /* [idx] MPI index for local variables */ int lcl_idx_lst[60]; /* [arr] Array containing indices of variables processed at each Worker */ int lcl_nbr_var=0; /* [nbr] Count of variables processes at each Worker */ int msg_tag_typ; /* [enm] MPI message tag type */ int prc_rnk; /* [idx] Process rank */ int prc_nbr=0; /* [nbr] Number of MPI processes */ int tkn_wrt_rnk=0; /* [idx] Rank of process holding write token */ int tkn_wrt_rsp; /* [enm] Response to request for write token */ int var_wrt_nbr=0; /* [nbr] Variables written to output file until now */ int rnk_wrk; /* [idx] Worker rank */ int wrk_id_bfr[wrk_id_bfr_lng]; /* [bfr] Buffer for rnk_wrk */ #endif /* !ENABLE_MPI */ static struct option opt_lng[]={ /* Structure ordered by short option key if possible */ /* Long options with no argument, no short option counterpart */ {"clean",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"mmr_cln",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"dirty",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"mmr_drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"ram_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"create_ram",no_argument,0,0}, /* [flg] Create file in RAM */ {"open_ram",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) in RAM */ {"diskless_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"share_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"create_share",no_argument,0,0}, /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ {"open_share",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ {"unbuffered_io",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"uio",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"wrt_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"write_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"no_tmp_fl",no_argument,0,0}, /* [flg] Do not write output to temporary file */ {"version",no_argument,0,0}, {"vrs",no_argument,0,0}, /* Long options with argument, no short option counterpart */ {"bfr_sz_hnt",required_argument,0,0}, /* [B] Buffer size hint */ {"buffer_size_hint",required_argument,0,0}, /* [B] Buffer size hint */ {"cnk_byt",required_argument,0,0}, /* [B] Chunk size in bytes */ {"chunk_byte",required_argument,0,0}, /* [B] Chunk size in bytes */ {"cnk_dmn",required_argument,0,0}, /* [nbr] Chunk size */ {"chunk_dimension",required_argument,0,0}, /* [nbr] Chunk size */ {"cnk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"chunk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"cnk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"chunk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"cnk_plc",required_argument,0,0}, /* [nbr] Chunking policy */ {"chunk_policy",required_argument,0,0}, /* [nbr] Chunking policy */ {"cnk_scl",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"chunk_scalar",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"fl_fmt",required_argument,0,0}, {"file_format",required_argument,0,0}, {"gaa",required_argument,0,0}, /* [sng] Global attribute add */ {"glb_att_add",required_argument,0,0}, /* [sng] Global attribute add */ {"hdr_pad",required_argument,0,0}, {"header_pad",required_argument,0,0}, {"log_lvl",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_level",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_lvl",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_level",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ /* Long options with short counterparts */ {"3",no_argument,0,'3'}, {"4",no_argument,0,'4'}, {"netcdf4",no_argument,0,'4'}, {"5",no_argument,0,'5'}, {"64bit_data",no_argument,0,'5'}, {"cdf5",no_argument,0,'5'}, {"pnetcdf",no_argument,0,'5'}, {"64bit_offset",no_argument,0,'6'}, {"7",no_argument,0,'7'}, {"append",no_argument,0,'A'}, {"coords",no_argument,0,'c'}, {"crd",no_argument,0,'c'}, {"xtr_ass_var",no_argument,0,'c'}, {"xcl_ass_var",no_argument,0,'C'}, {"no_coords",no_argument,0,'C'}, {"no_crd",no_argument,0,'C'}, {"dbg_lvl",required_argument,0,'D'}, {"debug",required_argument,0,'D'}, {"nco_dbg_lvl",required_argument,0,'D'}, {"dimension",required_argument,0,'d'}, {"dmn",required_argument,0,'d'}, {"fortran",no_argument,0,'F'}, {"ftn",no_argument,0,'F'}, {"fl_lst_in",no_argument,0,'H'}, {"file_list",no_argument,0,'H'}, {"history",no_argument,0,'h'}, {"hst",no_argument,0,'h'}, {"dfl_lvl",required_argument,0,'L'}, /* [enm] Deflate level */ {"deflate",required_argument,0,'L'}, /* [enm] Deflate level */ {"local",required_argument,0,'l'}, {"lcl",required_argument,0,'l'}, {"nintap",required_argument,0,'n'}, {"overwrite",no_argument,0,'O'}, {"ovr",no_argument,0,'O'}, {"output",required_argument,0,'o'}, {"fl_out",required_argument,0,'o'}, {"path",required_argument,0,'p'}, {"pack",required_argument,0,'P'}, {"retain",no_argument,0,'R'}, {"rtn",no_argument,0,'R'}, {"revision",no_argument,0,'r'}, {"suspend", no_argument,0,'S'}, {"thr_nbr",required_argument,0,'t'}, {"threads",required_argument,0,'t'}, {"omp_num_threads",required_argument,0,'t'}, {"variable",required_argument,0,'v'}, {"exclude",no_argument,0,'x'}, {"xcl",no_argument,0,'x'}, {"pseudonym",required_argument,0,'Y'}, {"program",required_argument,0,'Y'}, {"prg_nm",required_argument,0,'Y'}, {"math",required_argument,0,'y'}, {"help",no_argument,0,'?'}, {"hlp",no_argument,0,'?'}, {0,0,0,0} }; /* end opt_lng */ int opt_idx=0; /* Index of current long option into opt_lng array */ #ifdef _LIBINTL_H setlocale(LC_ALL,""); /* LC_ALL sets all localization tokens to same value */ bindtextdomain("nco","/home/zender/share/locale"); /* ${LOCALEDIR} is e.g., /usr/share/locale */ /* MO files should be in ${LOCALEDIR}/es/LC_MESSAGES */ textdomain("nco"); /* PACKAGE is name of program */ #endif /* not _LIBINTL_H */ #ifdef ENABLE_MPI /* MPI Initialization */ MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&prc_nbr); MPI_Comm_rank(MPI_COMM_WORLD,&prc_rnk); #endif /* !ENABLE_MPI */ /* Start clock and save command line */ cmd_ln=nco_cmd_ln_sng(argc,argv); /* Get program name and set program enum (e.g., nco_prg_id=ncra) */ nco_prg_nm=nco_prg_prs(argv[0],&nco_prg_id); /* Parse command line arguments */ while(1){ /* getopt_long_only() allows one dash to prefix long options */ opt=getopt_long(argc,argv,opt_sht_lst,opt_lng,&opt_idx); /* NB: access to opt_crr is only valid when long_opt is detected */ if(opt == EOF) break; /* Parse positional arguments once getopt_long() returns EOF */ opt_crr=(char *)strdup(opt_lng[opt_idx].name); /* Process long options without short option counterparts */ if(opt == 0){ if(!strcmp(opt_crr,"bfr_sz_hnt") || !strcmp(opt_crr,"buffer_size_hint")){ bfr_sz_hnt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_byt") || !strcmp(opt_crr,"chunk_byte")){ cnk_sz_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_byt */ if(!strcmp(opt_crr,"cnk_min") || !strcmp(opt_crr,"chunk_min")){ cnk_min_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_min */ if(!strcmp(opt_crr,"cnk_dmn") || !strcmp(opt_crr,"chunk_dimension")){ /* Copy limit argument for later processing */ cnk_arg[cnk_nbr]=(char *)strdup(optarg); cnk_nbr++; } /* endif cnk */ if(!strcmp(opt_crr,"cnk_scl") || !strcmp(opt_crr,"chunk_scalar")){ cnk_sz_scl=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_map") || !strcmp(opt_crr,"chunk_map")){ /* Chunking map */ cnk_map_sng=(char *)strdup(optarg); cnk_map=nco_cnk_map_get(cnk_map_sng); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_plc") || !strcmp(opt_crr,"chunk_policy")){ /* Chunking policy */ cnk_plc_sng=(char *)strdup(optarg); cnk_plc=nco_cnk_plc_get(cnk_plc_sng); } /* endif cnk */ if(!strcmp(opt_crr,"mmr_cln") || !strcmp(opt_crr,"clean")) flg_mmr_cln=True; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"drt") || !strcmp(opt_crr,"mmr_drt") || !strcmp(opt_crr,"dirty")) flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"fl_fmt") || !strcmp(opt_crr,"file_format")) rcd=nco_create_mode_prs(optarg,&fl_out_fmt); if(!strcmp(opt_crr,"gaa") || !strcmp(opt_crr,"glb_att_add")){ gaa_arg=(char **)nco_realloc(gaa_arg,(gaa_nbr+1)*sizeof(char *)); gaa_arg[gaa_nbr++]=(char *)strdup(optarg); } /* endif gaa */ if(!strcmp(opt_crr,"hdr_pad") || !strcmp(opt_crr,"header_pad")){ hdr_pad=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif "hdr_pad" */ if(!strcmp(opt_crr,"log_lvl") || !strcmp(opt_crr,"log_level")){ log_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); nc_set_log_level(log_lvl); } /* !log_lvl */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"create_ram") || !strcmp(opt_crr,"diskless_all")) RAM_CREATE=True; /* [flg] Create (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"open_ram") || !strcmp(opt_crr,"diskless_all")) RAM_OPEN=True; /* [flg] Open (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"create_share")) SHARE_CREATE=True; /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"open_share")) SHARE_OPEN=True; /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"vrs") || !strcmp(opt_crr,"version")){ (void)nco_vrs_prn(CVS_Id,CVS_Revision); nco_exit(EXIT_SUCCESS); } /* endif "vrs" */ if(!strcmp(opt_crr,"wrt_tmp_fl") || !strcmp(opt_crr,"write_tmp_fl")) WRT_TMP_FL=True; if(!strcmp(opt_crr,"no_tmp_fl")) WRT_TMP_FL=False; } /* opt != 0 */ /* Process short options */ switch(opt){ case 0: /* Long options have already been processed, return */ break; case '3': /* Request netCDF3 output storage format */ fl_out_fmt=NC_FORMAT_CLASSIC; break; case '4': /* Request netCDF4 output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4; break; case '5': /* Request netCDF3 64-bit offset+data storage (i.e., pnetCDF) format */ fl_out_fmt=NC_FORMAT_CDF5; break; case '6': /* Request netCDF3 64-bit offset output storage format */ fl_out_fmt=NC_FORMAT_64BIT_OFFSET; break; case '7': /* Request netCDF4-classic output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4_CLASSIC; break; case 'A': /* Toggle FORCE_APPEND */ FORCE_APPEND=!FORCE_APPEND; break; case 'C': /* Extract all coordinates associated with extracted variables? */ EXTRACT_ASSOCIATED_COORDINATES=False; break; case 'c': EXTRACT_ALL_COORDINATES=True; break; case 'D': /* Debugging level. Default is 0. */ nco_dbg_lvl=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); break; case 'd': /* Copy limit argument for later processing */ lmt_arg[lmt_nbr]=(char *)strdup(optarg); lmt_nbr++; break; case 'F': /* Toggle index convention. Default is 0-based arrays (C-style). */ FORTRAN_IDX_CNV=!FORTRAN_IDX_CNV; break; case 'H': /* Toggle writing input file list attribute */ FL_LST_IN_APPEND=!FL_LST_IN_APPEND; break; case 'h': /* Toggle appending to history global attribute */ HISTORY_APPEND=!HISTORY_APPEND; break; case 'L': /* [enm] Deflate level. Default is 0. */ dfl_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'l': /* Local path prefix for files retrieved from remote file system */ fl_pth_lcl=(char *)strdup(optarg); break; case 'n': /* NINTAP-style abbreviation of files to average */ fl_lst_abb=nco_lst_prs_2D(optarg,",",&abb_arg_nbr); if(abb_arg_nbr < 1 || abb_arg_nbr > 6){ (void)fprintf(stdout,gettext("%s: ERROR Incorrect abbreviation for file list\n"),nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); } /* end if */ break; case 'O': /* Toggle FORCE_OVERWRITE */ FORCE_OVERWRITE=!FORCE_OVERWRITE; break; case 'o': /* Name of output file */ fl_out=(char *)strdup(optarg); break; case 'p': /* Common file path */ fl_pth=(char *)strdup(optarg); break; case 'P': /* Packing policy */ nco_pck_plc_sng=(char *)strdup(optarg); nco_pck_plc=nco_pck_plc_get(nco_pck_plc_sng); break; case 'R': /* Toggle removal of remotely-retrieved-files. Default is True. */ RM_RMT_FL_PST_PRC=!RM_RMT_FL_PST_PRC; break; case 'r': /* Print CVS program information and copyright notice */ (void)nco_vrs_prn(CVS_Id,CVS_Revision); (void)nco_lbr_vrs_prn(); (void)nco_cpy_prn(); (void)nco_cnf_prn(); nco_exit(EXIT_SUCCESS); break; #ifdef ENABLE_MPI case 'S': /* Suspend with signal handler to facilitate debugging */ if(signal(SIGUSR1,nco_cnt_run) == SIG_ERR) (void)fprintf(fp_stderr,"%s: ERROR Could not install suspend handler.\n",nco_prg_nm_get()); while(!nco_spn_lck_brk) usleep(nco_spn_lck_us); /* Spinlock. fxm: should probably insert a sched_yield */ break; #endif /* !ENABLE_MPI */ case 't': /* Thread number */ thr_nbr=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'v': /* Variables to extract/exclude */ /* Replace commas with hashes when within braces (convert back later) */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); var_lst_in=nco_lst_prs_2D(optarg_lcl,",",&var_lst_in_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); xtr_nbr=var_lst_in_nbr; break; case 'x': /* Exclude rather than extract variables specified with -v */ EXCLUDE_INPUT_LIST=True; break; case 'Y': /* Pseudonym */ /* Call nco_prg_prs to reset pseudonym */ optarg_lcl=(char *)strdup(optarg); if(nco_prg_nm) nco_prg_nm=(char *)nco_free(nco_prg_nm); nco_prg_nm=nco_prg_prs(optarg_lcl,&nco_prg_id); optarg_lcl=(char *)nco_free(optarg_lcl); break; case 'y': /* Operation type */ nco_op_typ_sng=(char *)strdup(optarg); if(nco_prg_id == ncra || nco_prg_id == ncfe || nco_prg_id == ncge) nco_op_typ=nco_op_typ_get(nco_op_typ_sng); break; case '?': /* Print proper usage */ (void)nco_usg_prn(); nco_exit(EXIT_SUCCESS); break; case '-': /* Long options are not allowed */ (void)fprintf(stderr,"%s: ERROR Long options are not available in this build. Use single letter options instead.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); break; default: /* Print proper usage */ (void)fprintf(stdout,"%s ERROR in command-line syntax/options. Please reformulate command accordingly.\n",nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); break; } /* end switch */ if(opt_crr) opt_crr=(char *)nco_free(opt_crr); } /* end while loop */ /* Process positional arguments and fill-in filenames */ fl_lst_in=nco_fl_lst_mk(argv,argc,optind,&fl_nbr,&fl_out,&FL_LST_IN_FROM_STDIN,FORCE_OVERWRITE); /* Make uniform list of user-specified chunksizes */ if(cnk_nbr > 0) cnk_dmn=nco_cnk_prs(cnk_nbr,cnk_arg); /* Make uniform list of user-specified dimension limits */ if(lmt_nbr > 0) lmt=nco_lmt_prs(lmt_nbr,lmt_arg); /* Initialize thread information */ thr_nbr=nco_openmp_ini(thr_nbr); in_id_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); /* Parse filename */ fl_in=nco_fl_nm_prs(fl_in,0,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); /* Make sure file is on local system and is readable or die trying */ fl_in=nco_fl_mk_lcl(fl_in,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_in,md_open,&bfr_sz_hnt,&in_id); /* Get number of variables, dimensions, and record dimension ID of input file */ (void)nco_inq(in_id,&nbr_dmn_fl,&nbr_var_fl,(int *)NULL,&rec_dmn_id); (void)nco_inq_format(in_id,&fl_in_fmt); /* Form initial extraction list which may include extended regular expressions */ xtr_lst=nco_var_lst_mk(in_id,nbr_var_fl,var_lst_in,EXCLUDE_INPUT_LIST,EXTRACT_ALL_COORDINATES,&xtr_nbr); /* Change included variables to excluded variables */ if(EXCLUDE_INPUT_LIST) xtr_lst=nco_var_lst_xcl(in_id,nbr_var_fl,xtr_lst,&xtr_nbr); /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id); /* Add all coordinate variables to extraction list */ if(EXTRACT_ALL_COORDINATES) xtr_lst=nco_var_lst_crd_add(in_id,nbr_dmn_fl,nbr_var_fl,xtr_lst,&xtr_nbr,cnv); /* Extract coordinates associated with extracted variables */ if(EXTRACT_ASSOCIATED_COORDINATES) xtr_lst=nco_var_lst_crd_ass_add(in_id,xtr_lst,&xtr_nbr,cnv); /* Sort extraction list by variable ID for fastest I/O */ if(xtr_nbr > 1) xtr_lst=nco_lst_srt_nm_id(xtr_lst,xtr_nbr,False); /* We now have final list of variables to extract. Phew. */ /* Find coordinate/dimension values associated with user-specified limits NB: nco_lmt_evl() with same nc_id contains OpenMP critical region */ for(idx=0;idx<lmt_nbr;idx++) (void)nco_lmt_evl(in_id,lmt[idx],0L,FORTRAN_IDX_CNV); /* Place all dimensions in lmt_all_lst */ lmt_all_lst=(lmt_all_sct **)nco_malloc(nbr_dmn_fl*sizeof(lmt_all_sct *)); /* Initialize lmt_all_sct's */ (void)nco_msa_lmt_all_ntl(in_id,MSA_USR_RDR,lmt_all_lst,nbr_dmn_fl,lmt,lmt_nbr); /* Find dimensions associated with variables to be extracted */ dmn_lst=nco_dmn_lst_ass_var(in_id,xtr_lst,xtr_nbr,&nbr_dmn_xtr); /* Fill-in dimension structure for all extracted dimensions */ dim=(dmn_sct **)nco_malloc(nbr_dmn_xtr*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr;idx++) dim[idx]=nco_dmn_fll(in_id,dmn_lst[idx].id,dmn_lst[idx].nm); /* Dimension list no longer needed */ dmn_lst=nco_nm_id_lst_free(dmn_lst,nbr_dmn_xtr); /* Merge hyperslab limit information into dimension structures */ if(nbr_dmn_fl > 0) (void)nco_dmn_lmt_all_mrg(dmn_out,nbr_dmn_xtr,lmt_all_lst,nbr_dmn_fl); /* Duplicate input dimension structures for output dimension structures */ dmn_out=(dmn_sct **)nco_malloc(nbr_dmn_xtr*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr;idx++){ dmn_out[idx]=nco_dmn_dpl(dim[idx]); (void)nco_dmn_xrf(dim[idx],dmn_out[idx]); } /* end loop over idx */ /* Create stand-alone limit structure just for record dimension */ if(rec_dmn_id == NCO_REC_DMN_UNDEFINED){ if(nco_prg_id == ncra || nco_prg_id == ncrcat){ (void)fprintf(stdout,gettext("%s: ERROR input file %s lacks a record dimension\n"),nco_prg_nm_get(),fl_in); if(fl_nbr == 1)(void)fprintf(stdout,gettext("%s: HINT Use ncks instead of %s\n"),nco_prg_nm_get(),nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* endif */ }else{ /* Record dimension exists */ lmt_rec=nco_lmt_sct_mk(in_id,rec_dmn_id,lmt,lmt_nbr,FORTRAN_IDX_CNV); /* Initialize record coordinate re-basing */ if(nco_prg_id == ncra || nco_prg_id == ncrcat){ int var_id; lmt_rec->cln_typ=cln_nil; lmt_rec->origin=0.0; lmt_rec->rbs_sng=NULL; /* Obtain metadata for record coordinate */ rcd=nco_inq_varid_flg(in_id,lmt_rec->nm,&var_id); if(rcd == NC_NOERR){ char *cln_att_sng=NULL; lmt_rec->rbs_sng=nco_lmt_get_udu_att(in_id,var_id,"units"); cln_att_sng=nco_lmt_get_udu_att(in_id,var_id,"calendar"); lmt_rec->cln_typ=nco_cln_get_cln_typ(cln_att_sng); if(cln_att_sng) cln_att_sng=(char*)nco_free(cln_att_sng); }else{ /* endif record coordinate exists */ /* Record dimension, but not record coordinate, exists, which is fine. Reset return code. */ rcd=NC_NOERR; } /* endif record coordinate exists */ } /* endif ncra, ncrcat */ } /* endif record dimension exists */ if(rec_dmn_id != NCO_REC_DMN_UNDEFINED){ for(idx=0;idx<nbr_dmn_fl;idx++){ if(!strcmp(lmt_rec->nm,lmt_all_lst[idx]->dmn_nm)){ lmt_all_rec=lmt_all_lst[idx]; /* Can only have one record limit */ if(lmt_all_rec->lmt_dmn_nbr > 1L){ (void)fprintf(stdout,"%s: Although this program allows multiple hyperslab limits for a single dimension, it allows only one unwrapped limit for the record dimension \"%s\". You have specified %i.\n",nco_prg_nm_get(),lmt_all_rec->dmn_nm,lmt_all_rec->lmt_dmn_nbr); nco_exit(EXIT_FAILURE); } /* end if */ if(nco_prg_id==ncra || nco_prg_id==ncrcat){ /* Change record dim in lmt_all_lst so that cnt=1 */ lmt_all_lst[idx]->dmn_cnt=1L; lmt_all_lst[idx]->lmt_dmn[0]->srt=0L; lmt_all_lst[idx]->lmt_dmn[0]->end=0L; lmt_all_lst[idx]->lmt_dmn[0]->cnt=1L; lmt_all_lst[idx]->lmt_dmn[0]->srd=1L; } /* endif ncra || ncrcat */ break; } /* endif current limit applies to record dimension */ } /* end loop over all dimensions */ } /* end if file has record dimension */ /* Is this an ARM-format data file? */ CNV_ARM=nco_cnv_arm_inq(in_id); /* NB: nco_cnv_arm_base_time_get() with same nc_id contains OpenMP critical region */ if(CNV_ARM) base_time_srt=nco_cnv_arm_base_time_get(in_id); /* Fill-in variable structure list for all extracted variables */ var=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); var_out=(var_sct **)nco_malloc(xtr_nbr*sizeof(var_sct *)); for(idx=0;idx<xtr_nbr;idx++){ var[idx]=nco_var_fll(in_id,xtr_lst[idx].id,xtr_lst[idx].nm,dim,nbr_dmn_xtr); var_out[idx]=nco_var_dpl(var[idx]); (void)nco_xrf_var(var[idx],var_out[idx]); (void)nco_xrf_dmn(var_out[idx]); } /* end loop over idx */ /* Extraction list no longer needed */ xtr_lst=nco_nm_id_lst_free(xtr_lst,xtr_nbr); /* Divide variable lists into lists of fixed variables and variables to be processed */ (void)nco_var_lst_dvd(var,var_out,xtr_nbr,cnv,True,nco_pck_plc_nil,nco_pck_map_nil,NULL,0,&var_fix,&var_fix_out,&nbr_var_fix,&var_prc,&var_prc_out,&nbr_var_prc); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ #endif /* !ENABLE_MPI */ /* Make output and input files consanguinous */ if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt; /* Verify output file format supports requested actions */ (void)nco_fl_fmt_vet(fl_out_fmt,cnk_nbr,dfl_lvl); /* Open output file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Copy global attributes */ (void)nco_att_cpy(in_id,out_id,NC_GLOBAL,NC_GLOBAL,(nco_bool)True); /* Catenate time-stamped command line to "history" global attribute */ if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln); if(HISTORY_APPEND && FORCE_APPEND) (void)nco_prv_att_cat(fl_in,in_id,out_id); if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr); if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id); /* Add input file list global attribute */ if(FL_LST_IN_APPEND && HISTORY_APPEND && FL_LST_IN_FROM_STDIN) (void)nco_fl_lst_att_cat(out_id,fl_lst_in,fl_nbr); #ifdef ENABLE_MPI /* Initialize MPI task information */ if(prc_nbr > 0 && HISTORY_APPEND) (void)nco_mpi_att_cat(out_id,prc_nbr); #endif /* !ENABLE_MPI */ if(thr_nbr > 1 && HISTORY_APPEND) (void)nco_thr_att_cat(out_id,thr_nbr); /* Define dimensions in output file */ (void)nco_dmn_dfn(fl_out,out_id,dmn_out,nbr_dmn_xtr); /* Define variables in output file, copy their attributes */ (void)nco_var_dfn(in_id,fl_out,out_id,var_out,xtr_nbr,(dmn_sct **)NULL,(int)0,nco_pck_plc_nil,nco_pck_map_nil,dfl_lvl); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ (void)nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Take output file out of define mode */ if(hdr_pad == 0UL){ (void)nco_enddef(out_id); }else{ (void)nco__enddef(out_id,hdr_pad); if(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO Padding header with %lu extra bytes\n",nco_prg_nm_get(),(unsigned long)hdr_pad); } /* hdr_pad */ #ifdef ENABLE_MPI } /* prc_rnk != rnk_mgr */ /* Manager obtains output filename and broadcasts to workers */ if(prc_rnk == rnk_mgr) fl_nm_lng=(int)strlen(fl_out_tmp); MPI_Bcast(&fl_nm_lng,1,MPI_INT,0,MPI_COMM_WORLD); if(prc_rnk != rnk_mgr) fl_out_tmp=(char *)nco_malloc((fl_nm_lng+1)*sizeof(char)); MPI_Bcast(fl_out_tmp,fl_nm_lng+1,MPI_CHAR,0,MPI_COMM_WORLD); #endif /* !ENABLE_MPI */ /* Pre-processor token spaghetti here is necessary so that 1. UP/SMP/MPI codes all zero srt vectors before calling nco_var_val_cpy() 2. No codes zero srt vectors more than once */ /* Assign zero to start and unity to stride vectors in output variables */ (void)nco_var_srd_srt_set(var_out,xtr_nbr); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ TKN_WRT_FREE=False; #endif /* !ENABLE_MPI */ /* Copy variable data for non-processed variables */ /* (void)nco_var_val_cpy(in_id,out_id,var_fix,nbr_var_fix); */ (void)nco_msa_var_val_cpy(in_id,out_id,var_fix,nbr_var_fix,lmt_all_lst,nbr_dmn_fl); #ifdef ENABLE_MPI /* Close output file so workers can open it */ nco_close(out_id); TKN_WRT_FREE=True; } /* prc_rnk != rnk_mgr */ #else /* !ENABLE_MPI */ /* Close first input netCDF file (SMP only since MPI code immediate re-opens) */ (void)nco_close(in_id); #endif /* !ENABLE_MPI */ /* Allocate and, if necesssary, initialize accumulation space for processed variables */ for(idx=0;idx<nbr_var_prc;idx++){ if(nco_prg_id == ncra || nco_prg_id == ncrcat){ /* Allocate space for only one record */ var_prc_out[idx]->sz=var_prc[idx]->sz=var_prc[idx]->sz_rec; } /* endif */ if(nco_prg_id == ncra || nco_prg_id == ncfe){ var_prc_out[idx]->tally=var_prc[idx]->tally=(long *)nco_malloc(var_prc_out[idx]->sz*sizeof(long int)); (void)nco_zero_long(var_prc_out[idx]->sz,var_prc_out[idx]->tally); var_prc_out[idx]->val.vp=(void *)nco_malloc(var_prc_out[idx]->sz*nco_typ_lng(var_prc_out[idx]->type)); (void)nco_var_zero(var_prc_out[idx]->type,var_prc_out[idx]->sz,var_prc_out[idx]->val); } /* end if */ } /* end loop over idx */ #ifdef ENABLE_MPI /* NB: Only manager code manipulates value of TKN_WRT_FREE Pass 1: Workers construct local persistant variable lists Open first file mpncra and mpncrcat process first record only mpnces ingests complete file Workers create local list of their variables Pass 2: Complete record/file loops with local variable lists Workers skip first timestep (mpncra/mpncrcat) Workers process only variables in their local list from Pass 1 This variable persistance is necessary for mpncra and mpnces since their workers must maintain running tallies for each variable. Variable persistance is not necessary for mpncrcat However, we do it anyway to keep mpncrcat and mpncra similar mpncrcat writes records as it reads them and finishes after pass 2 Pass 3: mpnces and mpncra require a final loop to normalize and write Write-token for this loop is passed sequentially through the ranks */ /* Begin Pass 1: Workers construct local persistant variable lists */ fl_idx=0; /* Variables may have different ID, missing_value, type, in each file */ for(idx=0;idx<nbr_var_prc;idx++) (void)nco_var_mtd_refresh(in_id,var_prc[idx]); /* Each file can have a different number of records to process NB: nco_lmt_evl() with same nc_id contains OpenMP critical region */ if(nco_prg_id == ncra || nco_prg_id == ncrcat) (void)nco_lmt_evl(in_id,lmt_rec,rec_usd_cml,FORTRAN_IDX_CNV); /* NB: nco_cnv_arm_base_time_get() with same nc_id contains OpenMP critical region */ if(CNV_ARM) base_time_crr=nco_cnv_arm_base_time_get(in_id); /* Perform various error-checks on input file */ if(False) (void)nco_fl_cmp_err_chk(); if(nco_prg_id == ncra || nco_prg_id == ncrcat){ /* ncfe jumps to else branch */ /* Loop over each record in current file */ if(nco_dbg_lvl >= nco_dbg_std && lmt_rec->srt > lmt_rec->end) (void)fprintf(stdout,gettext("%s: WARNING %s (input file %d) is superfluous\n"),nco_prg_nm_get(),fl_in,fl_idx); idx_rec=lmt_rec->srt; if(fl_idx == fl_nbr-1 && idx_rec >= 1L+lmt_rec->end-lmt_rec->srd) LAST_RECORD=True; /* Process all variables in first record */ if(nco_dbg_lvl > nco_dbg_scl) (void)fprintf(stderr,gettext("Record %ld of %s is output record %ld\n"),idx_rec,fl_in,rec_usd_cml); if(prc_rnk == rnk_mgr){ /* MPI manager code */ /* Compensate for incrementing on each worker's first message */ var_wrt_nbr=-prc_nbr+1; idx=0; /* While variables remain to be processed or written... */ while(var_wrt_nbr < nbr_var_prc){ /* Receive any message from any worker */ MPI_Recv(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&mpi_stt); /* Obtain MPI message tag type */ msg_tag_typ=mpi_stt.MPI_TAG; /* Get sender's prc_rnk */ rnk_wrk=wrk_id_bfr[0]; /* Allocate next variable, if any, to worker */ if(msg_tag_typ == msg_tag_wrk_rqs){ var_wrt_nbr++; /* [nbr] Number of variables written */ /* Worker closed output file before sending msg_tag_wrk_rqs */ if(nco_prg_id == ncrcat) TKN_WRT_FREE=True; /* File written to at this point only for ncrcat */ if(idx > nbr_var_prc-1){ msg_bfr[0]=idx_all_wrk_ass; /* [enm] All variables already assigned */ msg_bfr[1]=out_id; /* Output file ID */ }else{ /* Tell requesting worker to allocate space for next variable */ msg_bfr[0]=idx; /* [idx] Variable to be processed */ /* csz: fxm Workers do not need to know Master's out_id */ msg_bfr[1]=out_id; /* Output file ID */ msg_bfr[2]=var_prc_out[idx]->id; /* [id] Variable ID in output file */ /* Point to next variable on list */ idx++; } /* endif idx */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_wrk_rsp,MPI_COMM_WORLD); }else if(msg_tag_typ == msg_tag_tkn_wrt_rqs && nco_prg_id == ncrcat){ /* msg_tag_typ != msg_tag_wrk_rqs */ /* Allocate token if free, else ask worker to try later */ if(TKN_WRT_FREE){ TKN_WRT_FREE=False; msg_bfr[0]=tkn_wrt_rqs_xcp; /* Accept request for write token */ }else{ msg_bfr[0]=tkn_wrt_rqs_dny; /* Deny request for write token */ } /* !TKN_WRT_FREE */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* msg_tag_typ != msg_tag_tkn_wrt_rqs */ } /* end while var_wrt_nbr < nbr_var_prc */ }else{ /* prc_rnk != rnk_mgr, end Manager code begin Worker code */ /* csz: fxm delete redundant statement with two lines further down */ wrk_id_bfr[0]=prc_rnk; var_wrt_nbr=0; while(1){ /* While work remains... */ /* Send msg_tag_wrk_rqs */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rqs,MPI_COMM_WORLD); /* Receive msg_tag_wrk_rsp */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rsp,MPI_COMM_WORLD,&mpi_stt); idx=msg_bfr[0]; /* csz: fxm dangerous---workers must get and use their own out_id's, not master's out_id */ out_id=msg_bfr[1]; if(idx == idx_all_wrk_ass){ break; }else{ /* idx != idx_all_wrk_ass */ /* Assign this variable to this worker for rest of program */ lcl_idx_lst[lcl_nbr_var]=idx; /* csz: got to here reading logic */ lcl_nbr_var++; var_prc_out[idx]->id=msg_bfr[2]; if(nco_dbg_lvl >= nco_dbg_var) rcd+=nco_var_prc_crr_prn(idx,var_prc[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); /* Update hyperslab start indices to current record for each variable */ var_prc[idx]->srt[0]=idx_rec; var_prc[idx]->end[0]=idx_rec; var_prc[idx]->cnt[0]=1L; /* Retrieve variable from disk into memory */ /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_var_get(in_id,var_prc[idx]); if(nco_prg_id == ncra){ /* Convert char, short, long, int, and float types to doubles before arithmetic */ /* Output variable type is "sticky" so only convert on first record */ if(rec_usd_cml == 0) var_prc_out[idx]=nco_typ_cnv_rth(var_prc_out[idx],nco_op_typ); /* Convert var_prc to type of var_prc_out in case type of variable on disk has changed */ var_prc[idx]=nco_var_cnf_typ(var_prc_out[idx]->type,var_prc[idx]); /* Perform arithmetic operations: avg, min, max, ttl, ... */ nco_opr_drv(rec_usd_cml,nco_op_typ,var_prc[idx],var_prc_out[idx]); } /* !ncra */ /* Append current record to output file */ if(nco_prg_id == ncrcat){ var_prc_out[idx]->srt[0]=var_prc_out[idx]->end[0]=rec_usd_cml; var_prc_out[idx]->cnt[0]=1L; /* Replace this time_offset value with time_offset from initial file base_time */ if(CNV_ARM && !strcmp(var_prc[idx]->nm,"time_offset")) var_prc[idx]->val.dp[0]+=(base_time_crr-base_time_srt); /* Obtain token and prepare to write */ while(1){ /* Send msg_tag_tkn_wrt_rqs repeatedly until token obtained */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rqs,MPI_COMM_WORLD); MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); tkn_wrt_rsp=msg_bfr[0]; /* Wait then re-send request */ if(tkn_wrt_rsp == tkn_wrt_rqs_dny) sleep(tkn_wrt_rqs_ntv); else break; } /* end while loop waiting for write token */ /* Worker has token---prepare to write */ if(tkn_wrt_rsp == tkn_wrt_rqs_xcp){ if(RAM_OPEN) md_open=NC_WRITE|NC_SHARE|NC_DISKLESS; else md_open=NC_WRITE|NC_SHARE; rcd=nco_fl_open(fl_out_tmp,md_open,&bfr_sz_hnt,&out_id); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); if(var_prc_out[idx]->sz_rec > 1L) (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc[idx]->val.vp,var_prc_out[idx]->type); else (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc[idx]->val.vp,var_prc_out[idx]->type); /* Close output file and increment written counter */ nco_close(out_id); var_wrt_nbr++; } /* endif tkn_wrt_rqs_xcp */ } /* end if ncrcat */ /* Make sure record coordinate, if any, is monotonic */ if(nco_prg_id == ncrcat && var_prc[idx]->is_crd_var) (void)rec_crd_chk(var_prc[idx],fl_in,fl_out,idx_rec,rec_usd_cml); /* Convert missing_value, if any, back to unpacked type */ if(var_prc[idx]->has_mss_val && var_prc[idx]->type != var_prc[idx]->typ_upk && !LAST_RECORD) var_prc[idx]=nco_cnv_mss_val_typ(var_prc[idx],var_prc[idx]->typ_upk); /* Free current input buffer */ var_prc[idx]->val.vp=nco_free(var_prc[idx]->val.vp); if(nco_dbg_lvl >= nco_dbg_var) (void)fprintf(stderr,"\n"); } /* !idx_all_wrk_ass */ } /* while(1) loop requesting work/token in Worker */ rec_usd_cml++; /* [idx] Index of current record in output file (0 is first, ...) */ } /* endif Worker */ printf("DEBUG: End of first pass of ncra/ncrcat at node %d\n",prc_rnk); /* End of ncra, ncrcat section */ }else{ /* ncfe */ if(prc_rnk == rnk_mgr){ /* MPI manager code */ /* Compensate for incrementing on each worker's first message */ var_wrt_nbr=-prc_nbr+1; idx=0; /* While variables remain to be processed or written... */ while(var_wrt_nbr < nbr_var_prc){ /* Receive message from any worker */ MPI_Recv(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&mpi_stt); /* Obtain MPI message tag type */ msg_tag_typ=mpi_stt.MPI_TAG; /* Get sender's prc_rnk */ rnk_wrk=wrk_id_bfr[0]; /* Allocate next variable, if any, to worker */ if(msg_tag_typ == msg_tag_wrk_rqs){ var_wrt_nbr++; /* [nbr] Number of variables written */ /* Worker closed output file before sending msg_tag_wrk_rqs */ /* TKN_WRT_FREE=True; ncfe does not do file write here */ if(idx > nbr_var_prc-1){ msg_bfr[0]=idx_all_wrk_ass; /* [enm] All variables already assigned */ msg_bfr[1]=out_id; /* Output file ID */ }else{ /* Tell requesting worker to allocate space for next variable */ msg_bfr[0]=idx; /* [idx] Variable to be processed */ msg_bfr[1]=out_id; /* Output file ID */ msg_bfr[2]=var_prc_out[idx]->id; /* [id] Variable ID in output file */ /* Point to next variable on list */ idx++; } /* endif idx */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_wrk_rsp,MPI_COMM_WORLD); } /* msg_tag_typ != msg_tag_wrk_rqs */ } /* end while var_wrt_nbr < nbr_var_prc */ }else{ /* prc_rnk != rnk_mgr, end Manager code begin Worker code */ while(1){ /* While work remains... */ /* Send msg_tag_wrk_rqs */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rqs,MPI_COMM_WORLD); /* Receive msg_tag_wrk_rsp */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rsp,MPI_COMM_WORLD,&mpi_stt); idx=msg_bfr[0]; out_id=msg_bfr[1]; if(idx == idx_all_wrk_ass) break; else{ lcl_idx_lst[lcl_nbr_var]=idx; /* storing the indices for subsequent processing by the worker */ lcl_nbr_var++; var_prc_out[idx]->id=msg_bfr[2]; if(nco_dbg_lvl >= nco_dbg_var) rcd+=nco_var_prc_crr_prn(idx,var_prc[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); /* Retrieve variable from disk into memory */ /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_var_get(in_id,var_prc[idx]); /* Convert char, short, long, int, and float types to doubles before arithmetic */ /* var_prc[idx]=nco_typ_cnv_rth(var_prc[idx],nco_op_typ); */ /* Output variable type is "sticky" so only convert on first record */ if(fl_idx == 0) var_prc_out[idx]=nco_typ_cnv_rth(var_prc_out[idx],nco_op_typ); /* Convert var_prc to type of var_prc_out in case type of variable on disk has changed */ var_prc[idx]=nco_var_cnf_typ(var_prc_out[idx]->type,var_prc[idx]); /* Perform arithmetic operations: avg, min, max, ttl, ... */ /* Note: fl_idx not rec_usd_cml! */ nco_opr_drv(fl_idx,nco_op_typ,var_prc[idx],var_prc_out[idx]); /* Free current input buffer */ var_prc[idx]->val.vp=nco_free(var_prc[idx]->val.vp); } /* !idx_all_wrk_ass */ } /* while(1) loop requesting work/token in Worker */ } /* endif Worker */ } /* end else ncfe */ if(nco_dbg_lvl > nco_dbg_scl) (void)fprintf(stderr,"\n"); /* Close input netCDF file */ nco_close(in_id); #ifdef ENABLE_MPI /* This barrier ensures that all nodes have reached this point together. Otherwise, the manager code should be altered so it can deal with nodes in different stages of execution at any time. Daniel: I think we should be convinced of this parallelization structure before bothering with implementing the code restructuring in the manager that would let us remove the barrier. The barrier should only negligibly impact performance. */ checkpointMpi(prc_rnk, 1); #endif /* ENABLE_MPI */ /* End Pass 1: Workers construct local persistant variable lists */ printf("DEBUG: prc_rnk %d is done with 1st pass\n",prc_rnk); /* Begin Pass 2: Complete record/file loops with local variable lists */ #endif /* !ENABLE_MPI */ /* Loop over input files */ for(fl_idx=0;fl_idx<fl_nbr;fl_idx++){ /* Parse filename */ if(fl_idx != 0) fl_in=nco_fl_nm_prs(fl_in,fl_idx,(int *)NULL,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,gettext("\nInput file %d is %s; "),fl_idx,fl_in); /* Make sure file is on local system and is readable or die trying */ if(fl_idx != 0) fl_in=nco_fl_mk_lcl(fl_in,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,gettext("local file %s:\n"),fl_in); /* Open file once per thread to improve caching */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in,md_open,&bfr_sz_hnt,in_id_arr+thr_idx); in_id=in_id_arr[0]; #ifdef ENABLE_MPI printf("DEBUG: input file opened in prc_rnk %d inside the loop\n",prc_rnk); #endif /* !ENABLE_MPI */ /* Variables may have different IDs and missing_values in each file */ for(idx=0;idx<nbr_var_prc;idx++) (void)nco_var_mtd_refresh(in_id,var_prc[idx]); /* Each file can have a different number of records to process NB: nco_lmt_evl() with same nc_id contains OpenMP critical region */ if(nco_prg_id == ncra || nco_prg_id == ncrcat) (void)nco_lmt_evl(in_id,lmt_rec,rec_usd_cml,FORTRAN_IDX_CNV); /* NB: nco_cnv_arm_base_time_get() with same nc_id contains OpenMP critical region */ if(CNV_ARM) base_time_crr=nco_cnv_arm_base_time_get(in_id); /* Perform various error-checks on input file */ if(False) (void)nco_fl_cmp_err_chk(); if(nco_prg_id == ncra || nco_prg_id == ncrcat){ /* ncfe jumps to else branch */ /* Loop over each record in current file */ if(nco_dbg_lvl >= nco_dbg_std && lmt_rec->srt > lmt_rec->end) (void)fprintf(stdout,gettext("%s: WARNING %s (input file %d) is superfluous\n"),nco_prg_nm_get(),fl_in,fl_idx); for(idx_rec=lmt_rec->srt;idx_rec<=lmt_rec->end;idx_rec+=lmt_rec->srd){ if(fl_idx == fl_nbr-1 && idx_rec >= 1L+lmt_rec->end-lmt_rec->srd) LAST_RECORD=True; #ifdef ENABLE_MPI if(fl_idx == 0 && idx_rec == lmt_rec->srt){ /* MPI operators processed first record in first-stage loop */ continue; }else{ /* a loop of idx = stored indices */ if(prc_rnk == rnk_mgr){ /* For ncrcat, Manager gives write access for each record in each file */ if(nco_prg_id == ncrcat){ /* Give Write access to write current record */ /* var_wrt_nbr=-prc_nbr+1; */ var_wrt_nbr=0; while(var_wrt_nbr < nbr_var_prc){ /* Give write access to Workers who have some variables; wrong condn? */ /* Receive message from any worker */ MPI_Recv(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&mpi_stt); /* Obtain MPI message tag type */ msg_tag_typ=mpi_stt.MPI_TAG; /* Get sender's prc_rnk */ rnk_wrk=wrk_id_bfr[0]; if(msg_tag_typ == msg_tag_wrk_done) TKN_WRT_FREE=True; if(msg_tag_typ == msg_tag_tkn_wrt_rqs){ if(rnk_wrk == tkn_wrt_rnk){ /* Prev write completed */ TKN_WRT_FREE=True; } /* rnk_wrk != tkn_wrt_rnk */ /* Allocate token if free, else ask worker to try later */ if(TKN_WRT_FREE){ TKN_WRT_FREE=False; msg_bfr[0]=tkn_wrt_rqs_xcp; /* Accept request for write token */ tkn_wrt_rnk=rnk_wrk; /* To track who has the token */ var_wrt_nbr++; }else{ msg_bfr[0]=tkn_wrt_rqs_dny; /* Deny request for write token */ } /* !TKN_WRT_FREE */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* msg_tag_typ != msg_tag_tkn_wrt_rqs */ } /* End-while token request loop */ } /* !ncrcat */ }else{ /* prc_rnk != rnk_mgr, end Manager code begin Worker code */ wrk_id_bfr[0]=prc_rnk; var_wrt_nbr=0; /* if(fl_idx == 0 && idx_rec == lmt_rec->srt) continue; else a loop of idx = stored indices */ for(jdx=0;jdx<lcl_nbr_var;jdx++){ idx=lcl_idx_lst[jdx]; #endif /* !ENABLE_MPI */ /* Process all variables in current record */ if(nco_dbg_lvl > nco_dbg_scl) (void)fprintf(stderr,gettext("Record %ld of %s is output record %ld\n"),idx_rec,fl_in,rec_usd_cml); #if 0 /* NB: Immediately preceding MPI for scope confounds Emacs indentation Fake end scope restores correct indentation, simplifies code-checking */ } /* fake end for */ #endif /* !0 */ #ifndef ENABLE_MPI #ifdef _OPENMP #pragma omp parallel for default(none) private(idx,in_id) shared(CNV_ARM,base_time_crr,base_time_srt,nco_dbg_lvl,fl_in,fl_out,idx_rec,rec_usd_cml,in_id_arr,LAST_RECORD,nbr_var_prc,nco_op_typ,out_id,prg,rcd,var_prc,var_prc_out) #endif /* !_OPENMP */ /* UP and SMP codes main loop over variables */ for(idx=0;idx<nbr_var_prc;idx++){ #endif /* ENABLE_MPI */ in_id=in_id_arr[omp_get_thread_num()]; if(nco_dbg_lvl >= nco_dbg_var) rcd+=nco_var_prc_crr_prn(idx,var_prc[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); /* Update hyperslab start indices to current record for each variable */ var_prc[idx]->srt[0]=idx_rec; var_prc[idx]->end[0]=idx_rec; var_prc[idx]->cnt[0]=1L; /* Retrieve variable from disk into memory */ /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_var_get(in_id,var_prc[idx]); if(nco_prg_id == ncra){ /* Convert char, short, long, int, and float types to doubles before arithmetic */ var_prc[idx]=nco_typ_cnv_rth(var_prc[idx],nco_op_typ); /* Output variable type is "sticky" so only convert on first record */ if(rec_usd_cml == 0) var_prc_out[idx]=nco_typ_cnv_rth(var_prc_out[idx],nco_op_typ); /* Convert var_prc to type of var_prc_out in case type of variable on disk has changed */ var_prc[idx]=nco_var_cnf_typ(var_prc_out[idx]->type,var_prc[idx]); /* Perform arithmetic operations: avg, min, max, ttl, ... */ nco_opr_drv(rec_usd_cml,nco_op_typ,var_prc[idx],var_prc_out[idx]); } /* end if ncra */ /* Append current record to output file */ if(nco_prg_id == ncrcat){ var_prc_out[idx]->srt[0]=var_prc_out[idx]->end[0]=rec_usd_cml; var_prc_out[idx]->cnt[0]=1L; /* Replace this time_offset value with time_offset from initial file base_time */ if(CNV_ARM && !strcmp(var_prc[idx]->nm,"time_offset")) var_prc[idx]->val.dp[0]+=(base_time_crr-base_time_srt); #ifdef ENABLE_MPI /* Obtain token and prepare to write */ while(1){ /* Send msg_tag_tkn_wrt_rqs repeatedly until token obtained */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rqs,MPI_COMM_WORLD); MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); tkn_wrt_rsp=msg_bfr[0]; /* Wait then re-send request */ if(tkn_wrt_rsp == tkn_wrt_rqs_dny) sleep(tkn_wrt_rqs_ntv); else break; } /* end while loop waiting for write token */ /* Worker has token---prepare to write */ if(tkn_wrt_rsp == tkn_wrt_rqs_xcp){ rcd=nco_fl_open(fl_out_tmp,NC_WRITE|NC_SHARE,&bfr_sz_hnt,&out_id); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp critical #endif /* _OPENMP */ #endif /* !ENABLE_MPI */ if(var_prc_out[idx]->sz_rec > 1) (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc[idx]->val.vp,var_prc_out[idx]->type); else (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc[idx]->val.vp,var_prc_out[idx]->type); #ifdef ENABLE_MPI /* Close output file and increment written counter */ nco_close(out_id); var_wrt_nbr++; } /* endif tkn_wrt_rqs_xcp */ #endif /* !ENABLE_MPI */ } /* end if ncrcat */ /* Make sure record coordinate, if any, is monotonic */ if(nco_prg_id == ncrcat && var_prc[idx]->is_crd_var) (void)rec_crd_chk(var_prc[idx],fl_in,fl_out,idx_rec,rec_usd_cml); /* Convert missing_value, if any, back to disk type */ if(var_prc[idx]->has_mss_val && var_prc[idx]->type != var_prc[idx]->typ_upk && !LAST_RECORD) var_prc[idx]=nco_cnv_mss_val_typ(var_prc[idx],var_prc[idx]->typ_upk); /* Free current input buffer */ var_prc[idx]->val.vp=nco_free(var_prc[idx]->val.vp); } /* end (OpenMP Parallel for) loop over variables */ #ifdef ENABLE_MPI if(nco_prg_id == ncrcat){ /* Return token after writing record's last variable */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_done,MPI_COMM_WORLD); } /* !ncrcat */ #endif /* !ENABLE_MPI */ rec_usd_cml++; /* [idx] Index of current record in output file (0 is first, ...) */ if(nco_dbg_lvl >= nco_dbg_var) (void)fprintf(stderr,"\n"); #ifdef ENABLE_MPI } /* !Worker */ } /* end else ! fl_idx=0,idx_rec=srt */ #endif /* !ENABLE_MPI */ } /* end loop over idx_rec */ #ifdef ENABLE_MPI if(prc_rnk != rnk_mgr){ /* Only Worker */ #endif /* !ENABLE_MPI */ /* Warn if fewer than number of requested records were read and final file has been processed */ if(lmt_rec->lmt_typ == lmt_dmn_idx && lmt_rec->is_usr_spc_min && lmt_rec->is_usr_spc_max){ long rec_nbr_rqs; /* Number of records user requested */ rec_nbr_rqs=1L+(lmt_rec->max_idx-lmt_rec->min_idx)/lmt_rec->srd; if(nco_dbg_lvl >= nco_dbg_std && fl_idx == fl_nbr-1 && rec_nbr_rqs != rec_usd_cml) (void)fprintf(stdout,gettext("%s: WARNING User requested %li records but only %li were found\n"),nco_prg_nm_get(),rec_nbr_rqs,rec_usd_cml); } /* end if */ /* Error if no records were read and final file has been processed */ if(rec_usd_cml <= 0 && fl_idx == fl_nbr-1){ (void)fprintf(stdout,gettext("%s: ERROR No records lay within specified hyperslab\n"),nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* end if */ #ifdef ENABLE_MPI } /* !Worker */ printf("DEBUG: prc_rnk %d at the end of ncra/rcat\n",prc_rnk); #endif /* !ENABLE_MPI */ /* End of ncra, ncrcat section */ }else{ /* ncfe */ #ifdef ENABLE_MPI if(prc_rnk != rnk_mgr){ /* Only Worker does the ncfe processing */ if(fl_idx == 0){ continue; }else{ /* a loop of idx = stored indices */ for(jdx=0;jdx<lcl_nbr_var;jdx++){ idx=lcl_idx_lst[jdx]; #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp parallel for default(none) private(idx,in_id) shared(nco_dbg_lvl,fl_idx,in_id_arr,nbr_var_prc,nco_op_typ,rcd,var_prc,var_prc_out) #endif /* !_OPENMP */ for(idx=0;idx<nbr_var_prc;idx++){ /* Process all variables in current file */ #endif /* !ENABLE_MPI */ in_id=in_id_arr[omp_get_thread_num()]; if(nco_dbg_lvl >= nco_dbg_var) rcd+=nco_var_prc_crr_prn(idx,var_prc[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); /* Retrieve variable from disk into memory */ /* NB: nco_var_get() with same nc_id contains OpenMP critical region */ (void)nco_var_get(in_id,var_prc[idx]); /* Convert char, short, long, int, and float types to doubles before arithmetic */ /* var_prc[idx]=nco_typ_cnv_rth(var_prc[idx],nco_op_typ); */ /* Output variable type is "sticky" so only convert on first record */ if(fl_idx == 0) var_prc_out[idx]=nco_typ_cnv_rth(var_prc_out[idx],nco_op_typ); /* Convert var_prc to type of var_prc_out in case type of variable on disk has changed */ var_prc[idx]=nco_var_cnf_typ(var_prc_out[idx]->type,var_prc[idx]); /* Perform arithmetic operations: avg, min, max, ttl, ... */ /* Note: fl_idx not rec_usd_cml! */ nco_opr_drv(fl_idx,nco_op_typ,var_prc[idx],var_prc_out[idx]); /* Free current input buffer */ var_prc[idx]->val.vp=nco_free(var_prc[idx]->val.vp); } /* end (OpenMP parallel for) loop over idx */ #ifdef ENABLE_MPI } /* end else !fl_idx=0 */ } /* !Worker */ #endif /* !ENABLE_MPI */ } /* end else ncfe */ if(nco_dbg_lvl > nco_dbg_scl) (void)fprintf(stderr,"\n"); /* Close input netCDF file */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_arr[thr_idx]); /* Dispose local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in); } /* end loop over fl_idx */ #ifdef ENABLE_MPI printf("DEBUG: prc_rnk %d is out of file idx loop\n",prc_rnk); #endif /* !ENABLE_MPI */ /* Normalize, multiply, etc where necessary */ if(nco_prg_id == ncra || nco_prg_id == ncfe){ #ifdef ENABLE_MPI if(prc_rnk != rnk_mgr){ /* Only workers have indices of variables to process */ for(jdx=0;jdx<lcl_nbr_var;jdx++){ idx=lcl_idx_lst[jdx]; #if 0 /* NB: Immediately preceding MPI if/for scopes confound Emacs indentation Fake end scopes restore correct indentation, simplify code-checking */ } /* fake end for */ } /* fake end if */ #endif /* !0 */ #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp parallel for default(none) private(idx) shared(nbr_var_prc,nco_op_typ,var_prc,var_prc_out) #endif /* !_OPENMP */ for(idx=0;idx<nbr_var_prc;idx++){ #endif /* !ENABLE_MPI */ if(var_prc[idx]->is_crd_var){ /* Return linear averages of coordinates unless computing extrema Prevent coordinate variables from encountering nco_var_nrm_sdn() */ if((nco_op_typ != nco_op_min) && (nco_op_typ != nco_op_max)) (void)nco_var_nrm(var_prc_out[idx]->type,var_prc_out[idx]->sz,var_prc[idx]->has_mss_val,var_prc[idx]->mss_val,var_prc[idx]->tally,var_prc_out[idx]->val); }else{ /* !var_prc[idx]->is_crd_var */ switch(nco_op_typ){ case nco_op_avg: /* Normalize sum by tally to create mean */ case nco_op_sqrt: /* Normalize sum by tally to create mean */ case nco_op_sqravg: /* Normalize sum by tally to create mean */ case nco_op_rms: /* Normalize sum of squares by tally to create mean square */ case nco_op_avgsqr: /* Normalize sum of squares by tally to create mean square */ (void)nco_var_nrm(var_prc_out[idx]->type,var_prc_out[idx]->sz,var_prc[idx]->has_mss_val,var_prc[idx]->mss_val,var_prc[idx]->tally,var_prc_out[idx]->val); break; case nco_op_rmssdn: /* Normalize sum of squares by tally-1 to create mean square for sdn */ (void)nco_var_nrm_sdn(var_prc_out[idx]->type,var_prc_out[idx]->sz,var_prc[idx]->has_mss_val,var_prc[idx]->mss_val,var_prc[idx]->tally,var_prc_out[idx]->val); break; case nco_op_min: /* Minimum is already in buffer, do nothing */ case nco_op_max: /* Maximum is already in buffer, do nothing */ case nco_op_ttl: /* Total is already in buffer, stuff missing values into elements with zero tally */ (void)nco_var_tll_zro_mss_val(var_prc_out[idx]->type,var_prc_out[idx]->sz,var_prc[idx]->has_mss_val,var_prc[idx]->mss_val,var_prc[idx]->tally,var_prc_out[idx]->val); default: break; } /* end switch */ /* Some operations require additional processing */ switch(nco_op_typ){ case nco_op_rms: /* Take root of mean of sum of squares to create root mean square */ case nco_op_rmssdn: /* Take root of sdn mean of sum of squares to create root mean square for sdn */ case nco_op_sqrt: /* Take root of mean to create root mean */ (void)nco_var_sqrt(var_prc_out[idx]->type,var_prc_out[idx]->sz,var_prc[idx]->has_mss_val,var_prc[idx]->mss_val,var_prc[idx]->tally,var_prc_out[idx]->val,var_prc_out[idx]->val); break; case nco_op_sqravg: /* Square mean to create square of the mean (for sdn) */ (void)nco_var_mlt(var_prc_out[idx]->type,var_prc_out[idx]->sz,var_prc_out[idx]->has_mss_val,var_prc_out[idx]->mss_val,var_prc_out[idx]->val,var_prc_out[idx]->val); break; default: break; } /* end switch */ } /* !var_prc[idx]->is_crd_var */ var_prc_out[idx]->tally=var_prc[idx]->tally=(long *)nco_free(var_prc[idx]->tally); } /* end (OpenMP parallel for) loop over variables */ #ifdef ENABLE_MPI printf("DEBUG: End of Normzn at prc_rnk %d\n",prc_rnk); } /* prc_rnk == rnk_mgr */ for(idx = 0; idx < nbr_var_prc; idx++) { assert(var_prc_out[idx]->tally == var_prc[idx]->tally); if (var_prc_out[idx]->tally == 0) continue; printf("DEBUG: node %d reset idx %d tally for var_prc(out) (cleanup)\n",prc_rnk,idx); var_prc_out[idx]->tally=var_prc[idx]->tally=(long *)nco_free(var_prc[idx]->tally); } printf("DEBUG: Mgr shud prnt this too, prc_rnk %d\n",prc_rnk); #endif /* !ENABLE_MPI */ } /* !ncra/ncfe */ #ifdef ENABLE_MPI printf("DEBUG: After all processing; Before barrier, prc_rnk %d\n",prc_rnk); if(prc_rnk == rnk_mgr){ /* Only Manager */ rcd=nco_fl_open(fl_out_tmp,NC_WRITE|NC_SHARE,&bfr_sz_hnt,&out_id); printf("DEBUG: prc_rnk %d opened out file\n",prc_rnk); #endif /* !ENABLE_MPI */ /* Manually fix YYMMDD date which was mangled by averaging */ if(cnv->CCM_CCSM_CF && nco_prg_id == ncra) (void)nco_cnv_ccm_ccsm_cf_date(out_id,var_out,xtr_nbr); /* End Pass 2: Complete record/file loops with local variable lists */ /* Begin Pass 3: */ /* End Pass 3: */ /* Add time variable to output file NB: nco_cnv_arm_time_install() contains OpenMP critical region */ if(CNV_ARM && nco_prg_id == ncrcat) (void)nco_cnv_arm_time_install(out_id,base_time_srt,dfl_lvl); #ifdef ENABLE_MPI nco_close(out_id); printf("DEBUG: Mgr prc_rnk %d closed out file %d after fixing date, time \n", prc_rnk, out_id); MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,prc_rnk+1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); printf("DEBUG: Mgr sent token to worker 1 for final write\n"); }else{ /* Workers */ printf("DEBUG: prc_rnk %d waiting for msg from Mgr for final write\n",prc_rnk); MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,prc_rnk-1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); printf("DEBUG: prc_rnk %d got token for final write to %d\n",prc_rnk, out_id); if(nco_prg_id == ncra || nco_prg_id == ncfe){ /* Copy averages to output file and free averaging buffers */ rcd=nco_fl_open(fl_out_tmp,NC_WRITE|NC_SHARE,&bfr_sz_hnt,&out_id); printf("DEBUG: prc_rnk %d opened output file for final write\n",prc_rnk); for(jdx=0;jdx<lcl_nbr_var;jdx++){ idx=lcl_idx_lst[jdx]; /* Revert any arithmetic promotion but leave unpacked (for now) */ /* printf("DEBUG: Before nco_var_cnf_typ prc_rnk %d var val %f\n",prc_rnk,var_prc_out[idx]->val.ip[0]); */ var_prc_out[idx]=nco_var_cnf_typ(var_prc_out[idx]->typ_upk,var_prc_out[idx]); /* printf("DEBUG: After nco_var_cnf_typ prc_rnk %d var val %f\n",prc_rnk,var_prc_out[idx]->val.ip[0]); */ /* Packing/Unpacking */ if(nco_pck_plc == nco_pck_plc_all_new_att) var_prc_out[idx]=nco_put_var_pck(out_id,var_prc_out[idx],nco_pck_plc); printf("DEBUG: prc_rnk %d to final write var %s with idx %d val %g\n",prc_rnk,var_prc_out[idx]->nm,idx,var_prc_out[idx]->val.fp[0]); if(var_prc_out[idx]->nbr_dim == 0){ (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->val.vp,var_prc_out[idx]->type); }else{ /* end if variable is scalar */ /* Size of record dimension is one in output file */ if(nco_prg_id == ncra) var_prc_out[idx]->cnt[0]=1L; (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc_out[idx]->val.vp,var_prc_out[idx]->type); } /* end if variable is an array */ var_prc_out[idx]->val.vp=nco_free(var_prc_out[idx]->val.vp); } /* end loop over jdx */ /* Close output file */ nco_close(out_id); printf("DEBUG: prc_rnk %d closed out file after writing\n",prc_rnk); /* Send Token to Manager */ } /* end if */ if(prc_rnk == prc_nbr-1) MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); else MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,prc_rnk+1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* !Workers */ if(prc_rnk == rnk_mgr){ /* Only Manager */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,prc_nbr-1,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); (void)nco_fl_mv(fl_out_tmp,fl_out); } /* !Manager */ MPI_Finalize(); #else /* !ENABLE_MPI */ /* Copy averages to output file and free averaging buffers */ if(nco_prg_id == ncra || nco_prg_id == ncfe){ for(idx=0;idx<nbr_var_prc;idx++){ /* Revert any arithmetic promotion but leave unpacked (for now) */ var_prc_out[idx]=nco_var_cnf_typ(var_prc_out[idx]->typ_upk,var_prc_out[idx]); /* Packing/Unpacking */ if(nco_pck_plc == nco_pck_plc_all_new_att) var_prc_out[idx]=nco_put_var_pck(out_id,var_prc_out[idx],nco_pck_plc); if(var_prc_out[idx]->nbr_dim == 0){ (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->val.vp,var_prc_out[idx]->type); }else{ /* end if variable is scalar */ /* Size of record dimension is 1 in output file */ if(nco_prg_id == ncra) var_prc_out[idx]->cnt[0]=1L; (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc_out[idx]->val.vp,var_prc_out[idx]->type); } /* end if variable is an array */ var_prc_out[idx]->val.vp=nco_free(var_prc_out[idx]->val.vp); } /* end loop over idx */ } /* end if */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); #endif /* !ENABLE_MPI */ /* Clean memory unless dirty memory allowed */ if(flg_mmr_cln){ /* ncra-specific memory cleanup */ if(nco_prg_id == ncra || nco_prg_id == ncrcat) lmt_rec=nco_lmt_free(lmt_rec); /* NCO-generic clean-up */ /* Free individual strings/arrays */ if(cmd_ln) cmd_ln=(char *)nco_free(cmd_ln); if(cnk_map_sng) cnk_map_sng=(char *)nco_free(cnk_map_sng); if(cnk_plc_sng) cnk_plc_sng=(char *)nco_free(cnk_plc_sng); if(fl_in) fl_in=(char *)nco_free(fl_in); if(fl_out) fl_out=(char *)nco_free(fl_out); if(fl_out_tmp) fl_out_tmp=(char *)nco_free(fl_out_tmp); if(fl_pth) fl_pth=(char *)nco_free(fl_pth); if(fl_pth_lcl) fl_pth_lcl=(char *)nco_free(fl_pth_lcl); if(in_id_arr) in_id_arr=(int *)nco_free(in_id_arr); /* Free lists of strings */ if(fl_lst_in && fl_lst_abb == NULL) fl_lst_in=nco_sng_lst_free(fl_lst_in,fl_nbr); if(fl_lst_in && fl_lst_abb) fl_lst_in=nco_sng_lst_free(fl_lst_in,1); if(fl_lst_abb) fl_lst_abb=nco_sng_lst_free(fl_lst_abb,abb_arg_nbr); if(gaa_nbr > 0) gaa_arg=nco_sng_lst_free(gaa_arg,gaa_nbr); if(var_lst_in_nbr > 0) var_lst_in=nco_sng_lst_free(var_lst_in,var_lst_in_nbr); /* Free limits */ for(idx=0;idx<lmt_nbr;idx++) lmt_arg[idx]=(char *)nco_free(lmt_arg[idx]); if(lmt_nbr > 0) lmt=nco_lmt_lst_free(lmt,lmt_nbr); /* Free chunking information */ for(idx=0;idx<cnk_nbr;idx++) cnk_arg[idx]=(char *)nco_free(cnk_arg[idx]); if(cnk_nbr > 0) cnk_dmn=nco_cnk_lst_free(cnk_dmn,cnk_nbr); /* Free dimension lists */ if(nbr_dmn_xtr > 0) dim=nco_dmn_lst_free(dim,nbr_dmn_xtr); if(nbr_dmn_xtr > 0) dmn_out=nco_dmn_lst_free(dmn_out,nbr_dmn_xtr); #if 1 /* Free variable lists */ if(xtr_nbr > 0) var=nco_var_lst_free(var,xtr_nbr); if(xtr_nbr > 0) var_out=nco_var_lst_free(var_out,xtr_nbr); var_prc=(var_sct **)nco_free(var_prc); var_prc_out=(var_sct **)nco_free(var_prc_out); var_fix=(var_sct **)nco_free(var_fix); var_fix_out=(var_sct **)nco_free(var_fix_out); #endif /* !1 */ #if 0 /* 20051027: Try ncwa free()'ing technique to avoid freeing dangling pointers */ if(xtr_nbr > 0) var=nco_var_lst_free(var,xtr_nbr); /* ncwa uses nco_var_lst_free() on var_prc_out because var_out has dangling pointers */ if(nbr_var_fix > 0) var_fix_out=nco_var_lst_free(var_fix_out,nbr_var_fix); if(nbr_var_prc > 0) var_prc_out=nco_var_lst_free(var_prc_out,nbr_var_prc); var_prc=(var_sct **)nco_free(var_prc); var_fix=(var_sct **)nco_free(var_fix); var_out=(var_sct **)nco_free(var_out); #endif /* !0 */ } /* !flg_mmr_cln */ nco_exit_gracefully(); return EXIT_SUCCESS; } /* end main() */
omp5.c
#include<stdio.h> #define N 5000 int m[N][N], s[N]; int main() { int i, j, sum; #pragma omp parallel for for (i = 0; i < N; i++) { sum = 0; for (j = 0; j < N; j++) { m[i][j] = i + j; sum += m[i][j]; } s[i] = sum; } for (i = 0; i < N; ++i) printf("%d %d\n", i, s[i]); return 0; }
bml_submatrix_ellsort_typed.c
#ifdef BML_USE_MAGMA #include "magma_v2.h" #endif #include "../../macros.h" #include "../../typed.h" #include "../bml_allocate.h" #include "../bml_logger.h" #include "../bml_submatrix.h" #include "../bml_types.h" #include "../dense/bml_allocate_dense.h" #include "bml_allocate_ellsort.h" #include "bml_submatrix_ellsort.h" #include "bml_types_ellsort.h" #include <complex.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif /** Determine element indices for submatrix, given a set of nodes/orbitals. * * \ingroup submatrix_group_C * * \param A Hamiltonian matrix A * \param B Graph matrix B * \param nodelist List of node/orbital indeces * \param nsize Size of nodelist * \param core_halo_index List of core+halo indeces * \param vsize Size of core_halo_index and number of cores * \param double_jump_flag Flag to use double jump (0=no, 1=yes) */ void TYPED_FUNC( bml_matrix2submatrix_index_ellsort) ( bml_matrix_ellsort_t * A, bml_matrix_ellsort_t * B, int *nodelist, int nsize, int *core_halo_index, int *vsize, int double_jump_flag) { int l, ll, ii, ls, k; int A_N = A->N; int A_M = A->M; int *A_nnz = A->nnz; int *A_index = A->index; int B_N = B->N; int B_M = B->M; int *B_nnz = B->nnz; int *B_index = B->index; int ix[A_N]; memset(ix, 0, A_N * sizeof(int)); l = 0; ll = 0; // Cores are first followed by halos for (int j = 0; j < nsize; j++) { ii = nodelist[j]; if (ix[ii] == 0) { ix[ii] = ii + 1; core_halo_index[l] = ii; l++; ll++; } } // Collect halo indeces from graph for (int j = 0; j < nsize; j++) { ii = nodelist[j]; for (int jp = 0; jp < B_nnz[ii]; jp++) { k = B_index[ROWMAJOR(ii, jp, B_N, B_M)]; if (ix[k] == 0) { ix[k] = ii + 1; core_halo_index[l] = k; l++; } } } // Add more halo elements from H for (int j = 0; j < nsize; j++) { ii = nodelist[j]; for (int jp = 0; jp < A_nnz[ii]; jp++) { k = A_index[ROWMAJOR(ii, jp, A_N, A_M)]; if (ix[k] == 0) { ix[k] = ii + 1; core_halo_index[l] = k; l++; } } } // Perform a "double jump" for extra halo elements // based on graph, like performing a symbolic X^2 if (double_jump_flag == 1) { ls = l; for (int j = 0; j < ls; j++) { ii = core_halo_index[j]; for (int jp = 0; jp < B_nnz[ii]; jp++) { k = B_index[ROWMAJOR(ii, jp, B_N, B_M)]; if (ix[k] == 0) { ix[k] = ii + 1; core_halo_index[l] = k; l++; } } } } vsize[0] = l; vsize[1] = ll; } /** Determine element indices for submatrix, given a set of nodes/orbitals. * * \ingroup submatrix_group_C * * \param B Graph matrix B * \param nodelist List of node/orbital indeces * \param nsize Size of nodelist * \param core_halo_index List of core+halo indeces * \param vsize Size of core_halo_index and number of cores * \param double_jump_flag Flag to use double jump (0=no, 1=yes) */ void TYPED_FUNC( bml_matrix2submatrix_index_graph_ellsort) ( bml_matrix_ellsort_t * B, int *nodelist, int nsize, int *core_halo_index, int *vsize, int double_jump_flag) { int l, ll, ii, ls, k; int B_N = B->N; int B_M = B->M; int *B_index = B->index; int *B_nnz = B->nnz; int ix[B_N]; memset(ix, 0, B_N * sizeof(int)); l = 0; ll = 0; // Cores are first followed by halos for (int j = 0; j < nsize; j++) { ii = nodelist[j]; if (ix[ii] == 0) { ix[ii] = ii + 1; core_halo_index[l] = ii; l++; ll++; } } // Collext halo indeces from graph for (int j = 0; j < nsize; j++) { ii = nodelist[j]; for (int jp = 0; jp < B_nnz[ii]; jp++) { k = B_index[ROWMAJOR(ii, jp, B_N, B_M)]; if (ix[k] == 0) { ix[k] = ii + 1; core_halo_index[l] = k; l++; } } } // Use graph for double jumps if (double_jump_flag == 1) { ls = l; for (int j = 0; j < ls; j++) { ii = core_halo_index[j]; for (int jp = 0; jp < B_nnz[ii]; jp++) { k = B_index[ROWMAJOR(ii, jp, B_N, B_M)]; if (ix[k] == 0) { ix[k] = ii + 1; core_halo_index[l] = k; l++; } } } } vsize[0] = l; vsize[1] = ll; } /** Extract a submatrix from a matrix given a set of core+halo rows. * * \ingroup submatrix_group_C * * \param A Matrix A * \param B Submatrix B * \param core_halo_index Set of row indeces for submatrix * \param llsize Number of indeces */ void TYPED_FUNC( bml_matrix2submatrix_ellsort) ( bml_matrix_ellsort_t * A, bml_matrix_dense_t * B, int *core_halo_index, int lsize) { REAL_T *rvalue; int B_N = B->N; #ifdef BML_USE_MAGMA REAL_T *B_matrix = bml_allocate_memory(sizeof(REAL_T) * B->N * B->N); #else REAL_T *B_matrix = B->matrix; #endif #pragma omp parallel for \ private(rvalue) \ shared(core_halo_index) \ shared(A, B_matrix, B_N) for (int jb = 0; jb < lsize; jb++) { rvalue = TYPED_FUNC(bml_getVector_ellsort) (A, core_halo_index, core_halo_index[jb], lsize); for (int j = 0; j < lsize; j++) { B_matrix[ROWMAJOR(jb, j, B_N, B_N)] = rvalue[j]; } free(rvalue); } #ifdef BML_USE_MAGMA MAGMA(setmatrix) (B_N, B_N, (MAGMA_T *) B_matrix, B_N, B->matrix, B->ld, B->queue); free(B_matrix); #endif } /** Assemble submatrix into a full matrix based on core+halo indeces. * * \ingroup submatrix_group_C * * \param A Submatrix A * \param B Matrix B * \param core_halo_index Set of submatrix row indeces * \param lsize Number of indeces * \param llsize Number of core positions */ void TYPED_FUNC( bml_submatrix2matrix_ellsort) ( bml_matrix_dense_t * A, bml_matrix_ellsort_t * B, int *core_halo_index, int lsize, int llsize, double threshold) { int A_N = A->N; #ifdef BML_USE_MAGMA REAL_T *A_matrix = bml_allocate_memory(sizeof(REAL_T) * A->N * A->N); MAGMA(getmatrix) (A->N, A->N, A->matrix, A->ld, (MAGMA_T *) A_matrix, A->N, A->queue); #else REAL_T *A_matrix = A->matrix; #endif int B_N = B->N; int B_M = B->M; int *B_nnz = B->nnz; int *B_index = B->index; REAL_T *B_value = B->value; int ii, icol; #pragma omp parallel for \ private(ii, icol) \ shared(core_halo_index) \ shared(A_N, A_matrix) \ shared(B_N, B_M, B_nnz, B_index, B_value) for (int ja = 0; ja < llsize; ja++) { ii = core_halo_index[ja]; icol = 0; for (int jb = 0; jb < lsize; jb++) { if (ABS(A_matrix[ROWMAJOR(ja, jb, A_N, A_N)]) > threshold) { B_index[ROWMAJOR(ii, icol, B_N, B_M)] = core_halo_index[jb]; B_value[ROWMAJOR(ii, icol, B_N, B_M)] = A_matrix[ROWMAJOR(ja, jb, A_N, A_N)]; icol++; } } if (icol > B_M) { LOG_ERROR("Number of non-zeroes per row >= M, Increase M\n"); } B_nnz[ii] = icol; } #ifdef BML_USE_MAGMA free(A_matrix); #endif } // Get matching vector of values void *TYPED_FUNC( bml_getVector_ellsort) ( bml_matrix_ellsort_t * A, int *jj, int irow, int colCnt) { REAL_T ZERO = 0.0; int A_N = A->N; int A_M = A->M; int *A_nnz = A->nnz; int *A_index = A->index; REAL_T *A_value = A->value; REAL_T *rvalue = bml_noinit_allocate_memory(colCnt * sizeof(REAL_T)); for (int i = 0; i < colCnt; i++) { for (int j = 0; j < A_nnz[irow]; j++) { if (A_index[ROWMAJOR(irow, j, A_N, A_M)] == jj[i]) { rvalue[i] = A_value[ROWMAJOR(irow, j, A_N, A_M)]; break; } rvalue[i] = ZERO; } } return rvalue; } /** Assemble matrix based on groups of rows from a matrix. * * \ingroup submatrix_group_C * * \param A Matrix A * \param hindex Indeces of nodes * \param ngroups Number of groups * \param threshold Threshold for graph */ bml_matrix_ellsort_t *TYPED_FUNC( bml_group_matrix_ellsort) ( bml_matrix_ellsort_t * A, int *hindex, int ngroups, double threshold) { int A_N = A->N; int A_M = A->M; int *A_index = A->index; int *A_nnz = A->nnz; REAL_T *A_value = A->value; #if !(defined(__IBMC_) || defined(__ibmxl__)) int ix[ngroups]; memset(ix, 0, sizeof(int) * ngroups); #endif int hnode[A_N]; int hend; bml_matrix_dimension_t matrix_dimension = { ngroups, ngroups, ngroups }; bml_matrix_ellsort_t *B = TYPED_FUNC(bml_noinit_matrix_ellsort) (matrix_dimension, A->distribution_mode); int B_N = B->N; int B_M = B->M; int *B_index = B->index; int *B_nnz = B->nnz; REAL_T *B_value = B->value; #pragma omp parallel for \ private(hend) \ shared(hindex, hnode, A_N) for (int i = 0; i < ngroups; i++) { hend = hindex[i + 1] - 1; if (i == ngroups - 1) hend = A_N; for (int j = hindex[i] - 1; j < hend; j++) { hnode[j] = i; } } #if defined(__IBMC_) || defined(__ibmxl__) #pragma omp parallel for \ private(hend) \ shared(hindex, hnode) \ shared(A_nnz, A_index, A_value, A_N, A_M) \ shared(B_nnz, B_index, B_value, B_N, B_M) #else #pragma omp parallel for \ private(hend) \ shared(hindex, hnode) \ shared(A_nnz, A_index, A_value, A_N, A_M) \ shared(B_nnz, B_index, B_value, B_N, B_M) \ firstprivate(ix) #endif for (int i = 0; i < B_N; i++) { #if defined(__IBMC_) || defined(__ibmxl__) int ix[ngroups]; memset(ix, 0, sizeof(int) * ngroups); #endif B_nnz[i] = 0; hend = hindex[i + 1] - 1; if (i == B_N - 1) hend = A_N; for (int j = hindex[i] - 1; j < hend; j++) { for (int k = 0; k < A_nnz[j]; k++) { int ii = hnode[A_index[ROWMAJOR(j, k, A_N, A_M)]]; if (ix[ii] == 0 && is_above_threshold(A_value[ROWMAJOR(j, k, A_N, A_M)], threshold)) { ix[ii] = i + 1; B_index[ROWMAJOR(i, B_nnz[i], B_N, B_M)] = ii; B_value[ROWMAJOR(i, B_nnz[i], B_N, B_M)] = 1.0; B_nnz[i]++; } } } } return B; }
declare6.c
/* Example of the ref and uval modifiers in the linear clause The ref modifier declares that the address of x is linear. The uval modifier declares that the address of c is uniform, and its value is linear. */ #pragma omp declare simd linear(ref(x)) linear(uval(c)) void increment(int& x, int& c) { x += c; } void Fref(int *a, int n) { #pragma omp simd for (int i=0; i<n; i++) { increment(a[i], i); } // End simd region }
particle.h
#pragma once #define SAFTY_FACTOR 1.05 ///////////// /// Force /// ///////////// class ForceGrav{ public: PS::F32vec acc; PS::F32 phi; PS::S32 neighbor; PS::S32 DUMMY_; #ifdef FOR_PIKG01 PS::S32 id_neighbor; PS::S32 id_neighbor_dmmy; #else PS::S64 id_neighbor; #endif void clear(){ acc = 0.; phi = 0.; neighbor = 0; id_neighbor = -1; } }; ////////////////////////// /// Essential Particle /// ////////////////////////// class EPIGrav{ public: PS::F64vec pos; // position in cartesian #ifdef USE_POLAR_COORDINATE PS::F64vec pos_pol; // position in polar #endif #ifdef FOR_PIKG01 PS::S32 id; PS::S32 id_dmmy; #else PS::S64 id; // id number #endif #ifdef USE_INDIVIDUAL_CUTOFF PS::F64 r_out; // cut-off radius PS::F64 r_search; // search radius #else static PS::F64 r_out; static PS::F64 r_search; #endif PS::F64vec getPos() const { #ifdef USE_POLAR_COORDINATE return pos_pol; #else return pos; #endif } PS::F64vec getPosCar() const { return pos; } PS::F64 getRSearch() const { #ifdef USE_POLAR_COORDINATE return SAFTY_FACTOR * r_search / sqrt(pos*pos); #else return SAFTY_FACTOR * r_search; #endif } void copyFromFP(const EPIGrav & fp){ pos = fp.pos; #ifdef USE_POLAR_COORDINATE pos_pol = fp.pos_pol; #endif id = fp.id; #ifdef USE_INDIVIDUAL_CUTOFF r_out = fp.r_out; r_search = fp.r_search; #endif } }; #ifndef USE_INDIVIDUAL_CUTOFF PS::F64 EPIGrav::r_out; PS::F64 EPIGrav::r_search; #endif class EPJGrav : public EPIGrav { public: PS::F64 mass; // mass PS::F64vec vel; // valocity PS::F64vec acc_d; // acceleration for hard part PS::S32 id_local; // local id number PS::S32 myrank; // rank number PS::F64 getCharge() const { return mass; } void copyFromFP(const EPJGrav & fp){ EPIGrav::copyFromFP(fp); mass = fp.mass; vel = fp.vel; acc_d = fp.acc_d; id_local = fp.id_local; myrank = fp.myrank; } }; ///////////////////// /// Full Particle /// ///////////////////// #define SECONDORDER 5.e-1 #define THIRDORDER 1.6666666666666667e-1 #define FOURTHORDER 4.1666666666666667e-2 #define FIFTHORDER 8.3333333333333333e-3 #define SIXTHORDER 1.3888888888888889e-3 #define SEVENTHORDER 1.9841269841269841e-4 #define ALPHA 1.1666666666666667e-3 #define ONE_TWELFTH 8.3333333333333333e-2 #define ONE_SIXTIETH 1.6666666666666667e-2 #define ONE_420TH 2.3809523809523810e-3 inline PS::F64 calcDt2nd(PS::F64 eta, PS::F64 alpha2, PS::F64 acc0, PS::F64vec acc, PS::F64vec jerk){ PS::F64 Acc2 = acc*acc + alpha2*acc0*acc0; PS::F64 Jerk2 = jerk*jerk; //PS::F64 dt2 = (Jerk2>0.) ? Acc2/Jerk2 : std::numeric_limits<double>::max(); //return eta * sqrt(dt2); return (Jerk2>0.) ? eta*sqrt(Acc2/Jerk2) : std::numeric_limits<double>::max(); } inline PS::F64 calcDt3rd(PS::F64 eta, PS::F64 alpha2, PS::F64 acc0, PS::F64vec acc, PS::F64vec snap){ PS::F64 Acc2 = acc*acc + alpha2*acc0*acc0; PS::F64 Snap2 = snap*snap; return (Snap2>0.) ? eta*pow(Acc2/Snap2, 0.25) : std::numeric_limits<double>::max(); } inline PS::F64 calcDt4th(PS::F64 eta, PS::F64 alpha2, PS::F64 acc0, PS::F64vec acc, PS::F64vec jerk, PS::F64vec snap, PS::F64vec crac){ PS::F64 Acc = sqrt(acc*acc + alpha2*acc0*acc0); PS::F64 Jerk2 = jerk*jerk; PS::F64 Jerk = sqrt(Jerk2); PS::F64 Snap2 = snap*snap; PS::F64 Snap = sqrt(Snap2); PS::F64 Crac = sqrt(crac*crac); //PS::F64 dt2 = (Jerk>0.) ? (Acc*Snap + Jerk2)/(Jerk*Crac + Snap2) : std::numeric_limits<double>::max(); //return eta * sqrt(dt2); return (Jerk>0.) ? eta*sqrt((Acc*Snap + Jerk2)/(Jerk*Crac + Snap2)) : std::numeric_limits<double>::max(); } inline PS::F64 calcDt6th(PS::F64 eta, PS::F64 alpha2, PS::F64 acc0, PS::F64vec acc, PS::F64vec jerk, PS::F64vec snap, PS::F64vec crac, PS::F64vec pop, PS::F64vec a5){ PS::F64 Acc = sqrt(acc*acc + alpha2*acc0*acc0); PS::F64 Jerk2 = jerk*jerk; PS::F64 Snap = sqrt(snap*snap); PS::F64 Crac = sqrt(crac*crac); PS::F64 Pop2 = pop*pop; PS::F64 A5 = sqrt(a5*a5); return (Jerk2>0.) ? eta*pow((Acc*Snap + Jerk2)/(Crac*A5 + Pop2),THIRDORDER) : std::numeric_limits<double>::max(); } class FPGrav : public EPJGrav { public: PS::F64vec acc; // acceleration for soft part PS::F64vec acc_s; // acceleration by sun PS::F64vec jerk_d; // jerk by planet PS::F64vec jerk_s; // jerk by sun #ifdef INTEGRATE_6TH_SUN PS::F64vec acc_; PS::F64vec snap_s; #endif PS::F64vec acc_gd; // acceleration by gas drag PS::F64 phi; // potential for soft part PS::F64 phi_d; // potential by planets PS::F64 phi_s; // potential by sun static PS::F64 m_sun; static PS::F64 dens; static PS::F64 eps2; static PS::F64 eps2_sun; static PS::F64 R_cut0; static PS::F64 R_cut1; static PS::F64 R_search0; static PS::F64 R_search1; #ifdef USE_RE_SEARCH_NEIGHBOR static PS::F64 R_search2; static PS::F64 R_search3; #endif static PS::F64 gamma; static PS::F64 g_1_inv; // 1/(g-1) static PS::F64 g_1_inv7; // 1/(g-1)^7 static PS::F64 w_y; // dW/dy if y<g static PS::F64 f1; // f(1;g) #ifdef INDIRECT_TERM static PS::F64vec acc_indirect; static PS::F64vec pos_g; static PS::F64vec vel_g; static PS::F64 mass_tot; #endif #ifdef USE_INDIVIDUAL_CUTOFF #ifndef CONSTANT_RANDOM_VELOCITY PS::F64 v_disp; #else static PS::F64 v_disp; #endif #endif #ifdef USE_INDIVIDUAL_CUTOFF PS::F64 r_out_inv; #else static PS::F64 r_out_inv; #endif PS::F64 time; PS::F64 dt; PS::F64 acc0; static PS::F64 dt_tree; static PS::F64 dt_min; static PS::F64 eta; static PS::F64 eta_0; static PS::F64 eta_sun; static PS::F64 eta_sun0; static PS::F64 alpha2; PS::F64 r_planet; PS::F64 f; static PS::F64 r_cut_min; static PS::F64 r_cut_max; static PS::F64 p_cut; static PS::F64 increase_factor; PS::S64 id_neighbor; PS::S64 id_cluster; PS::S32 n_cluster; PS::S32 neighbor; bool inDomain; bool isSent; bool isDead; bool isMerged; #ifdef MERGE_BINARY bool isBinary; static PS::F64 R_merge; #endif static void setGamma(PS::F64 g){ gamma = g; g_1_inv = 1./(g - 1.); PS::F64 g2 = g*g; PS::F64 g_1_inv3 = g_1_inv * g_1_inv * g_1_inv; g_1_inv7 = g_1_inv3 * g_1_inv3 * g_1_inv; w_y = 7./3. * ((((((g- 9.)*g +45.)*g -60.*log(g))*g -45.)*g +9.)*g -1.) * g_1_inv7; f1 = (-10./3. + 14.*(g+1.) - 21.*((g+3.)*g+1.) + 35./3.*(((g+9.)*g+9.)*g+1.) - 70.*((g+3.)*g+1.)*g + 210.*(g+1.)*g2 + (((g-7.)*g+21.)*g-35.)*g2*g2 ) * g_1_inv7; } PS::F64 getGamma() const{ return gamma; } PS::F64 getEps2() const{ return eps2;} PS::F64 getEps2_sun() const{ return eps2_sun;} PS::F64 getROut() const { return r_out; } PS::F64 getROut_inv() const { return r_out_inv; } #ifdef USE_POLAR_COORDINATE void setPosPolar() { PS::F64 r = sqrt(pos*pos); pos_pol.x = atan2(pos.y, pos.x); pos_pol.y = log(r); pos_pol.z = asin(pos.z / r); } #endif static PS::F64 getSolarMass() { return m_sun; } #ifndef WITHOUT_SUN PS::F64 getSemimajorAxis() const { #ifndef INDIRECT_TERM return 1.0 / (2.0/sqrt(pos*pos) - vel*vel/m_sun); #else return 1.0 / (2.0/sqrt(pos*pos) - vel*vel/(m_sun+mass)); #endif } PS::F64 getSemimajorAxis2() const { PS::F64 ax; if ( getEccentricity(ax) < 0.6 ) { return ax; } else { return sqrt(pos*pos); } } PS::F64 getEccentricity(PS::F64 & ax) const { PS::F64 r = sqrt(pos*pos); PS::F64 rv = pos*vel; #ifndef INDIRECT_TERM ax = 1.0 / (2.0/r - vel*vel/m_sun); PS::F64 ecccosu = 1. - r/ax; PS::F64 eccsinu2 = rv*rv/(m_sun*ax); #else ax = 1.0 / (2.0/r - vel*vel/(m_sun+mass)); PS::F64 ecccosu = 1. - r/ax; PS::F64 eccsinu2 = rv*rv/((m_sun+mass)*ax); #endif return sqrt(ecccosu*ecccosu + eccsinu2); } PS::F64 getEccentricity() const { PS::F64 ax; return getEccentricity(ax); } PS::F64 getInclination(PS::F64vec & h) const { h.x = pos.y*vel.z - pos.z*vel.y; h.y = pos.z*vel.x - pos.x*vel.z; h.z = pos.x*vel.y - pos.y*vel.x; return atan2(sqrt(h.x*h.x + h.y*h.y), h.z); } PS::F64 getInclination() const { PS::F64vec h; return getInclination(h); } PS::F64 getRHill() const { PS::F64 ax = getSemimajorAxis2(); return pow(mass/(3.*m_sun), 1./3.) * ax; } PS::F64 getKeplerVelocity() const { PS::F64 r = sqrt(pos.x * pos.x + pos.y * pos.y); return sqrt(m_sun/r); } #endif // WITHOUT_SUN #ifdef INTEGRATE_6TH_SUN void setAcc_() { acc_ = acc_s + acc_d; } #endif #ifdef USE_INDIVIDUAL_CUTOFF PS::F64 setROutRSearch(){ #ifndef WITHOUT_SUN PS::F64 rHill = getRHill(); PS::F64 ax = getSemimajorAxis2(); PS::F64 r_out_i = std::max(R_cut0*pow(ax,-p_cut)*rHill, R_cut1*v_disp*dt_tree); #else PS::F64 rHill = 0.; PS::F64 r_out_i = std::max(R_cut0*pow(mass * dt_tree * dt_tree, 1./3.), R_cut1*v_disp*dt_tree); #endif r_out = std::max(r_out_i, r_cut_min); if ( r_cut_max > 0. ) r_out = std::min(r_cut_max, r_out); r_out_inv = 1. / r_out; r_search = R_search0*r_out + R_search1*v_disp*dt_tree; assert ( r_out > 0. && r_search > 0. && r_search > r_out ); return rHill; } #else //USE_INDIVIDUAL_CUTOFF static void setROutRSearch(PS::F64 rHill_a_glb, PS::F64 v_disp_glb){ #ifndef WITHOUT_SUN PS::F64 r_out_i = std::max(R_cut0*rHill_a_glb, R_cut1*v_disp_glb*dt_tree); #else PS::F64 r_out_i = std::max(R_cut0*pow(rHill_a_glb * dt_tree * dt_tree, 1./3.), R_cut1*v_disp_glb*dt_tree); #endif r_out = std::max(r_out_i, r_cut_min); if ( r_cut_max > 0. ) r_out = std::min(r_cut_max, r_out); r_out_inv = 1. / r_out; r_search = R_search0*r_out + R_search1*v_disp_glb*dt_tree; assert ( r_out > 0. && r_search > 0. ); } #endif //USE_INDIVIDUAL_CUTOFF void setRPlanet() { r_planet = pow(0.75*mass/(MY_PI*dens), 1./3.); } void copyFromForce(const ForceGrav & force){ acc = force.acc; phi = force.phi; neighbor = force.neighbor; id_neighbor = force.id_neighbor; } void copy(const FPGrav & fp){ EPJGrav::copyFromFP(fp); acc = fp.acc; acc_s = fp.acc_s; jerk_d = fp.jerk_d; jerk_s = fp.jerk_s; #ifdef INTEGRATE_6TH_SUN acc_ = fp.acc_; snap_s = fp.snap_s; #endif acc_gd = fp.acc_gd; phi = fp.phi; phi_d = fp.phi_d; phi_s = fp.phi_s; #ifdef USE_INDIVIDUAL_CUTOFF #ifndef CONSTANT_RANDOM_VELOCITY v_disp = fp.v_disp; #endif #endif #ifdef USE_INDIVIDUAL_CUTOFF r_out_inv = fp.r_out_inv; #endif time = fp.time; dt = fp.dt; acc0 = fp.acc0; r_planet = fp.r_planet; f = fp.f; id_neighbor = fp.id_neighbor; id_cluster = fp.id_cluster; n_cluster = fp.n_cluster; neighbor = fp.neighbor; inDomain = fp.inDomain; isSent = fp.isSent; isDead = fp.isDead; isMerged = fp.isMerged; #ifdef MERGE_BINARY isBinary = fp.isBinary; #endif } void dump(std::ostream & fout = std::cout) const { fout<<"id= "<<id<<std::endl; fout<<"mass= "<<mass<<std::endl; fout<<"pos= "<<pos<<std::endl; #ifdef USE_POLAR_COORDINATE fout<<"pos_pol="<<pos_pol<<std::endl; #endif fout<<"vel= "<<vel<<std::endl; fout<<"acc="<<acc<<std::endl; fout<<"phi="<<phi<<std::endl; } void readAscii(FILE* fp) { PS::S32 Flag; if ( !fscanf(fp, "%d\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%d\t%d\n", &this->id, &this->mass, &this->r_planet, &this->f, &this->pos.x, &this->pos.y, &this->pos.z, &this->vel.x, &this->vel.y, &this->vel.z, &this->neighbor, &Flag) ) { //&this->r_out, &this->r_search) ) { errorMessage("The particle data have NOT been correctly read."); PS::Abort(); } #ifdef MERGE_BINARY isBinary = (bool)(Flag & (1<<0)); #endif } void writeAscii(FILE* fp) const { PS::S32 Flag = 0; #ifdef MERGE_BINARY Flag |= ((PS::S32)isBinary)<<0; #endif if ( !fprintf(fp, "%d\t%20.15e\t%20.15e\t%20.15e\t%20.15e\t%20.15e\t%20.15e\t%20.15e\t%20.15e\t%20.15e\t%d\t%d\n", this->id, this->mass, this->r_planet, this->f, this->pos.x, this->pos.y, this->pos.z, this->vel.x, this->vel.y, this->vel.z, this->neighbor, Flag) ) { //this->r_out, this->r_search) ){ errorMessage("The particle data have NOT been correctly written."); PS::Abort(); } } void readBinary(FILE* fp) { FPGrav buf; if ( !fread(&buf, sizeof(buf), 1, fp) ) { errorMessage("The particle data have NOT been correctly read."); PS::Abort(); } copy(buf); } void writeBinary(FILE* fp) const { FPGrav buf; buf.copy(*this); if ( !fwrite(&buf, sizeof(buf), 1, fp) ) { errorMessage("The particle data have NOT been correctly written."); PS::Abort(); } } void velKick(){ #ifdef INDIRECT_TERM vel += 0.5*dt_tree*(acc + acc_indirect); #else vel += 0.5*dt_tree*acc; #endif } void calcDeltatInitial(){ PS::F64 dt_next = 0.5*dt_tree; #ifndef INTEGRATE_6TH_SUN PS::F64 dt_1 = std::min(calcDt2nd(eta_0, alpha2, acc0, acc_d, jerk_d), calcDt2nd(eta_sun0, alpha2, 0., acc_s, jerk_s)); //PS::F64 dt_1 = calcDt2nd(eta_0, alpha2, acc0, acc_d, jerk_d); #else #ifdef AARSETH PS::F64 dt_1 = std::min(calcDt2nd(eta_0, alpha2, acc0, acc_d, jerk_d), calcDt2nd(eta_sun0, alpha2, 0., acc_s, jerk_s)); #else PS::F64 dt_1 = std::min(calcDt2nd(eta_0, alpha2, acc0, acc_d, jerk_d), calcDt3rd(eta_sun0, alpha2, 0., acc_s, snap_s)); #endif #endif PS::F64 rem = fmod(time, dt_next); while( rem != 0.0 ){ dt_next *= 0.5; rem = fmod(time, dt_next); } if ( dt > 0. ) while( 2.*dt < dt_next ) dt_next *= 0.5; while( dt_1 < dt_next ) dt_next *= 0.5; if( dt_next < 2.*dt_min ) dt_next = dt_min; dt = dt_next; } }; PS::F64 FPGrav::m_sun = 1.; PS::F64 FPGrav::dens = 5.049667e6; PS::F64 FPGrav::eps2 = 0.; PS::F64 FPGrav::eps2_sun = 0.; PS::F64 FPGrav::R_cut0 = 2.; PS::F64 FPGrav::R_cut1 = 8.; PS::F64 FPGrav::R_search0 = 1.; PS::F64 FPGrav::R_search1 = 4.; #ifdef USE_RE_SEARCH_NEIGHBOR PS::F64 FPGrav::R_search2 = 1.; PS::F64 FPGrav::R_search3 = 4.; #endif PS::F64 FPGrav::gamma = 0.5; PS::F64 FPGrav::g_1_inv = -2.; // 1/(gamma-1) PS::F64 FPGrav::g_1_inv7 = -128.; // 1/(gamma-1)^7 PS::F64 FPGrav::w_y; // dW/dy when y<g PS::F64 FPGrav::f1; // f(1;g) #ifdef INDIRECT_TERM PS::F64vec FPGrav::acc_indirect = 0.; PS::F64vec FPGrav::pos_g = 0.; PS::F64vec FPGrav::vel_g = 0.; PS::F64 FPGrav::mass_tot = 0.; #endif #ifdef CONSTANT_RANDOM_VELOCITY PS::F64 FPGrav::v_disp = 0.; #endif #ifndef USE_INDIVIDUAL_CUTOFF PS::F64 FPGrav::r_out_inv; #endif PS::F64 FPGrav::dt_tree = pow2(-5); PS::F64 FPGrav::dt_min = pow2(-13); PS::F64 FPGrav::eta = 0.01; PS::F64 FPGrav::eta_0 = 0.001; PS::F64 FPGrav::eta_sun = 0.01; PS::F64 FPGrav::eta_sun0 = 0.001; PS::F64 FPGrav::alpha2 = 1.; PS::F64 FPGrav::r_cut_min = 0.; PS::F64 FPGrav::r_cut_max = 0.; PS::F64 FPGrav::p_cut = 0.; PS::F64 FPGrav::increase_factor = 1.; #ifdef MERGE_BINARY PS::F64 FPGrav::R_merge = 0.2; #endif class FPHard : public FPGrav { public: PS::F64vec x0; PS::F64vec v0; PS::F64vec a0_s; PS::F64vec j0_s; PS::F64vec a0_d; PS::F64vec j0_d; PS::F64vec xp; PS::F64vec vp; #ifdef INTEGRATE_6TH_SUN PS::F64vec s0_s; PS::F64vec ap; #endif #ifndef INTEGRATE_6TH_SUN PS::F64vec a2_s; PS::F64vec a3_s; #else PS::F64vec a3_s; PS::F64vec a4_s; PS::F64vec a5_s; #endif PS::F64vec a2_d; PS::F64vec a3_d; PS::F64 time_c; std::vector<PS::S64> n_list; std::vector<PS::S32> n_hard_list; void clearList(){ //std::vector<PS::S32> tmp0, tmp1; //tmp0.swap(n_list); //tmp1.swap(n_hard_list); n_list.clear(); n_hard_list.clear(); } void copyList(std::vector<PS::S64> list){ n_list.resize(list.size()); std::copy(list.begin(),list.end(),n_list.begin()); } void copyList(PS::S64 * list){ n_list.clear(); n_list.reserve(neighbor); for ( PS::S32 i=0; i<neighbor; i++ ) n_list.push_back(list[i]); } void copyHardList(std::vector<PS::S32> list){ n_hard_list.resize(list.size()); std::copy(list.begin(),list.end(),n_hard_list.begin()); } void copyHardList(PS::S32 * list){ n_hard_list.clear(); n_hard_list.reserve(neighbor); for ( PS::S32 i=0; i<neighbor; i++ ) n_hard_list.push_back(list[i]); } void makeHardList(std::map<PS::S64,PS::S32> & id_map){ n_hard_list.clear(); n_hard_list.reserve(neighbor); for ( PS::S32 i=0; i<neighbor; i++){ n_hard_list.push_back(id_map.at(n_list.at(i))); } } template <class Tpsys> void makeHardList(std::map<PS::S64,PS::S32> & id_map, Tpsys & pp){ n_hard_list.clear(); for ( PS::S32 i=0; i<neighbor; i++){ PS::S32 id_hard = id_map.at(n_list.at(i)); if ( pp[id_hard].mass > 0. ) n_hard_list.push_back(id_hard); } neighbor = n_hard_list.size(); } FPHard(){ x0 = v0 = 0.; a0_s = j0_s = 0.; a0_d = j0_d = 0.; xp = vp = 0.; #ifdef INTEGRATE_6TH_SUN s0_s = 0.; ap = 0.; #endif #ifndef INTEGRATE_6TH_SUN a2_s = a3_s = 0.; #else a3_s = a4_s = a5_s = 0.; #endif a2_d = a3_d = 0.; time_c = 0.; r_planet = f = 0.; clearList(); } FPHard(const FPHard & fp) : FPGrav(fp){ x0 = fp.x0; v0 = fp.v0; a0_s = fp.a0_s; j0_s = fp.j0_s; a0_d = fp.a0_d; j0_d = fp.j0_d; xp = fp.xp; vp = fp.vp; #ifdef INTEGRATE_6TH_SUN s0_s = fp.s0_s; ap = fp.ap; #endif #ifndef INTEGRATE_6TH_SUN a2_s = fp.a2_s; a3_s = fp.a3_s; #else a3_s = fp.a3_s; a4_s = fp.a4_s; a5_s = fp.a5_s; #endif a2_d = fp.a2_d; a3_d = fp.a3_d; time_c = fp.time_c; copyList(fp.n_list); copyHardList(fp.n_hard_list); } FPHard(const FPGrav & fp) : FPGrav(fp){ x0 = v0 = 0.; a0_s = j0_s = 0.; a0_d = j0_d = 0.; xp = vp = 0.; #ifdef INTEGRATE_6TH_SUN s0_s = 0; ap = 0; #endif #ifndef INTEGRATE_6TH_SUN a2_s = a3_s = 0.; #else a3_s = a4_s = a5_s = 0.; #endif a2_d = a3_d = 0.; time_c = fp.time; time = 0; clearList(); } FPHard &operator=(const FPHard & fp){ FPGrav::operator=(fp); if ( this != &fp ){ x0 = fp.x0; v0 = fp.v0; a0_s = fp.a0_s; j0_s = fp.j0_s; a0_d = fp.a0_d; j0_d = fp.j0_d; xp = fp.xp; vp = fp.vp; #ifdef INTEGRATE_6TH_SUN s0_s = fp.s0_s; ap = fp.ap; #endif #ifndef INTEGRATE_6TH_SUN a2_s = fp.a2_s; a3_s = fp.a3_s; #else a3_s = fp.a3_s; a4_s = fp.a4_s; a5_s = fp.a5_s; #endif a2_d = fp.a2_d; a3_d = fp.a3_d; time_c = fp.time_c; copyList(fp.n_list); copyHardList(fp.n_hard_list); } return *this; } FPHard &operator=(const FPGrav & fp){ FPGrav::operator=(fp); if ( this != &fp ){ x0 = v0 = 0.; a0_s = j0_s = 0.; a0_d = j0_d = 0.; xp = vp = 0.; #ifdef INTEGRATE_6TH_SUN s0_s = 0; ap = 0; #endif #ifndef INTEGRATE_6TH_SUN a2_s = a3_s = 0.; #else a3_s = a4_s = a5_s = 0.; #endif a2_d = a3_d = 0.; time_c = fp.time; time = 0; clearList(); } return *this; } void resetTime() { time = time_c + time; time_c = 0.; } PS::F64 getTime() const { return time_c + time; } void predict(PS::F64 Dt){ x0 = pos; v0 = vel; a0_s = acc_s; j0_s = jerk_s; #ifdef INTEGRATE_6TH_SUN s0_s = snap_s; #endif j0_d = jerk_d; a0_d = acc_d; #ifndef INTEGRATE_6TH_SUN PS::F64vec acc_sd = acc_s + acc_d; PS::F64vec jerk_sd = jerk_s + jerk_d; xp = pos + Dt*(vel + Dt*(SECONDORDER*acc_sd + THIRDORDER*Dt*jerk_sd)); vp = vel + Dt*(acc_sd + Dt* SECONDORDER*jerk_sd); #else assert ( acc_ == acc_s + acc_d ); PS::F64vec jerk_sd = jerk_s + jerk_d; PS::F64vec snap_sd = snap_s; xp = pos + Dt*(vel + Dt*(SECONDORDER*acc_ + Dt*(THIRDORDER*jerk_sd + Dt*FOURTHORDER*snap_sd))); vp = vel + Dt*(acc_ + Dt*(SECONDORDER*jerk_sd + Dt* THIRDORDER*snap_sd)); ap = acc_ + Dt*(jerk_sd + Dt* SECONDORDER*snap_sd); #endif } void correct(PS::F64 Dt){ PS::F64 Dt2 = Dt*Dt; PS::F64 Dt_inv = 1./Dt; PS::F64 Dt_inv2 = Dt_inv *Dt_inv; PS::F64 Dt_inv3 = Dt_inv2*Dt_inv; #ifndef WITHOUT_SUN PS::F64vec Am_s = acc_s - a0_s; PS::F64vec J0_s = Dt*j0_s; PS::F64vec J1_s = Dt*jerk_s; #ifndef INTEGRATE_6TH_SUN PS::F64vec A2_s = 3.*Am_s - (J1_s + 2.*J0_s); PS::F64vec A3_s = -2.*Am_s + (J1_s + J0_s); a2_s = 2.*Dt_inv2*(A2_s + 3.*A3_s); a3_s = 6.*Dt_inv3* A3_s; #else PS::F64vec S0_s = SECONDORDER*Dt2*s0_s; PS::F64vec S1_s = SECONDORDER*Dt2*snap_s; PS::F64vec A3_s = 10.*Am_s - (4.*J1_s + 6.*J0_s) + ( S1_s - 3.*S0_s); PS::F64vec A4_s = -15.*Am_s + (7.*J1_s + 8.*J0_s) - (2.*S1_s - 3.*S0_s); PS::F64vec A5_s = 6.*Am_s - 3.*(J1_s + J0_s) + ( S1_s - S0_s); PS::F64 Dt_inv4 = Dt_inv2*Dt_inv2; PS::F64 Dt_inv5 = Dt_inv3*Dt_inv2; a3_s = 3.*Dt_inv3*(A3_s + 4.*A4_s + 10.*A5_s); a4_s = 24.*Dt_inv4*(A4_s + 5.*A5_s); a5_s = 120.*Dt_inv5*A5_s; #endif #else //WITHOUT_SUN #ifndef INTEGRATE_6TH_SUN PS::F64vec A2_s = 0.; PS::F64vec A3_s = 0.; a2_s = a3_s = 0.; #else PS::F64vec A3_s = 0.; PS::F64vec A4_s = 0.; PS::F64vec A5_s = 0.; a3_s = a4_s = a5_s = 0.; #endif #endif //WITHOUT_SUN PS::F64vec Am_d = acc_d - a0_d; PS::F64vec J0_d = j0_d * Dt; PS::F64vec J1_d = jerk_d * Dt; PS::F64vec A2_d = 3.*Am_d - (J1_d + 2.*J0_d); PS::F64vec A3_d = -2.*Am_d + (J1_d + J0_d); a2_d = 2. * (A2_d + 3.*A3_d) * Dt_inv2; a3_d = 6. * A3_d * Dt_inv3; #ifndef INTEGRATE_6TH_SUN PS::F64vec A2_sd = A2_s+A2_d; PS::F64vec A3_sd = A3_s+A3_d; pos = xp + ONE_SIXTIETH*Dt2*(5.*A2_sd + 3.*ALPHA*A3_sd); vel = vp + ONE_TWELFTH *Dt *(4.*A2_sd + 3. *A3_sd); #else PS::F64vec A2_sd = A2_d; PS::F64vec A3_sd = A3_s+A3_d; PS::F64vec A4_sd = A4_s; PS::F64vec A5_sd = A5_s; pos = xp + ONE_420TH *Dt2*(35.*A2_sd + 21.*A3_sd + 14.*A4_sd + 10.*A5_sd); vel = vp + ONE_SIXTIETH*Dt *(20.*A2_sd + 15.*A3_sd + 12.*A4_sd + 10.*A5_sd); assert( acc_ == acc_s + acc_d ); #endif } void calcDeltat(){ PS::F64 dt_next = std::min(2.*dt, 0.5*dt_tree); #ifndef INTEGRATE_6TH_SUN #ifndef WITHOUT_SUN PS::F64 dt_1 = std::min(calcDt4th(eta, alpha2, acc0, acc_d, jerk_d, a2_d, a3_d), calcDt4th(eta_sun, alpha2, 0., acc_s, jerk_s, a2_s, a3_s)); //PS::F64 dt_1 = calcDt4th(eta, alpha2, acc0, acc_d, jerk_d, a2_d+a3_d*dt, a3_d); #else PS::F64 dt_1 = calcDt4th(eta, alpha2, acc0, acc_d, jerk_d, a2_d, a3_d); #endif #else #ifdef AARSETH #ifndef WITHOUT_SUN PS::F64 dt_1 = std::min(calcDt4th(eta, alpha2, acc0, acc_d, jerk_d, a2_d, a3_d), calcDt4th(eta_sun, alpha2, 0., acc_s, jerk_s, snap_s, a3_s)); #else PS::F64 dt_1 = calcDt4th(eta, alpha2, acc0, acc_d, jerk_d, a2_d, a3_d); #endif #else #ifndef WITHOUT_SUN PS::F64 dt_1 = std::min(calcDt4th(eta, alpha2, acc0, acc_d, jerk_d, a2_d, a3_d), calcDt6th(eta_sun, alpha2, 0., acc_s, jerk_s, snap_s, a3_s, a4_s, a5_s)); #else PS::F64 dt_1 = calcDt4th(eta, alpha2, acc0, acc_d, jerk_d, a2_d, a3_d); #endif #endif #endif PS::F64 rem = fmod(time, dt_next); while(rem != 0.0){ dt_next *= 0.5; rem = fmod(time, dt_next); } while(dt_1 < dt_next && 0.5*dt < dt_next) dt_next *= 0.5; if( dt_next < 2.*dt_min ) dt_next = dt_min; dt = dt_next; } }; template <class Tpsys> void calcRandomVel(Tpsys & pp, const PS::S32 n_tot, const PS::S32 n_loc) { PS::F64 r_max=0., r_min=-std::numeric_limits<PS::F64>::max(); #pragma omp parallel for reduction (max: r_max, r_min) for(PS::S32 i=0; i<n_loc; i++){ PS::F64vec pos = pp[i].pos; PS::F64 r2 = pos.x*pos.x + pos.y*pos.y; r_max = std::max(r_max, r2); r_min = std::max(r_min, -r2); } r_max = sqrt(r_max) * 1.01; r_min = sqrt(-r_min) * 0.99; r_max = PS::Comm::getMaxValue(r_max); r_min = PS::Comm::getMinValue(r_min); const PS::S32 N = 32; const PS::F64 dr = (r_max - r_min) /N; const PS::F64 drinv = 1./dr; #ifdef ISOTROPIC PS::F64vec v_ave_loc[N]; PS::F64vec v_ave_glb[N]; PS::F64 v_sq_loc[N]; PS::F64 v_sq_glb[N]; #else PS::F64 v_disp_loc[N]; #endif PS::F64 v_disp_glb[N]; PS::S32 n_ptcl_loc[N]; PS::S32 n_ptcl_glb[N]; #ifdef ISOTROPIC for(PS::S32 i=0; i<N; i++) { v_ave_loc[i] = 0.; v_sq_loc[i] = 0.; n_ptcl_loc[i] = 0; } //#pragma omp parallel for reduction (+:v_ave_loc[:N], v_sq_loc[:N], n_ptcl_loc[:N]) for(PS::S32 i=0; i<n_loc; i++){ PS::F64vec pos = pp[i].pos; PS::F64 r2 = pos.x*pos.x + pos.y*pos.y; PS::S32 j = (PS::S32)((sqrt(r2) - r_min) * drinv); if ( j == N ) j = N - 1; assert ( 0<= j && j < N ); PS::F64vec vec = pp[i].vel; v_ave_loc[j] += vec; v_sq_loc[j] += vec*vec; n_ptcl_loc[j] ++; } #ifdef PARTICLE_SIMULATOR_MPI_PARALLEL MPI_Allreduce(v_ave_loc, v_ave_glb, N, PS::GetDataType(*v_ave_loc), MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(v_sq_loc, v_sq_glb, N, PS::GetDataType(*v_sq_loc), MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(n_ptcl_loc, n_ptcl_glb, N, PS::GetDataType(*n_ptcl_loc), MPI_SUM, MPI_COMM_WORLD); #else for(PS::S32 i=0; i<N; i++) { v_ave_glb[i] = v_ave_loc[i]; v_sq_glb[i] = v_sq_loc[i]; n_ptcl_glb[i] = n_ptcl_loc[i]; } #endif PS::S32 n_tot0 = 0; for(PS::S32 i=0; i<N; i++) { v_disp_glb[i] = (n_ptcl_glb[i] > 1) ? sqrt(v_sq_glb[i] / n_ptcl_glb[i] - v_ave_glb[i]*v_ave_glb[i]/( n_ptcl_glb[i]* n_ptcl_glb[i]) ) : 0.; n_tot0 += n_ptcl_glb[i]; } assert ( n_tot == n_tot0 ); #else //ISOTROPIC for(PS::S32 i=0; i<N; i++) { v_disp_loc[i] = 0.; n_ptcl_loc[i] = 0; } #pragma omp parallel for reduction (+:v_disp_loc[:N], n_ptcl_loc[:N]) for(PS::S32 i=0; i<n_loc; i++){ PS::F64vec pos = pp[i].pos; PS::F64 r2 = pos.x*pos.x + pos.y*pos.y; PS::F64 ri = sqrt(r2); PS::S32 j = (PS::S32)((ri - r_min) * drinv); if ( j == N ) j = N - 1; assert ( 0<= j && j < N ); #if 1 PS::F64vec v_kep; v_kep.x=-pos.y/ri ; v_kep.y=pos.x/ri; v_kep.z=0.; v_kep *= pp[i].getKeplerVelocity(); PS::F64vec v_ran = pp[i].vel - v_kep; #else PS::F64 ax; PS::F64 ecc = pp[i].getEccentricity(ax); PS::F64vec h; PS::F64 inc = pp[i].getInclination(h); PS::F64vec v_kep = pp[i].getKeplerVelocity(); PS::F64 v_ran = (ecc*ecc + inc*inc) * v_kep*v_kep; #endif v_disp_loc[j] += v_ran * v_ran; n_ptcl_loc[j] ++; } #ifdef PARTICLE_SIMULATOR_MPI_PARALLEL MPI_Allreduce(v_disp_loc, v_disp_glb, N, PS::GetDataType(*v_disp_loc), MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(n_ptcl_loc, n_ptcl_glb, N, PS::GetDataType(*n_ptcl_loc), MPI_SUM, MPI_COMM_WORLD); #else for(PS::S32 i=0; i<N; i++) { v_disp_glb[i] = v_disp_loc[i]; n_ptcl_glb[i] = n_ptcl_loc[i]; } #endif PS::S32 n_tot0 = 0; for(PS::S32 i=0; i<N; i++) { v_disp_glb[i] = (n_ptcl_glb[i] > 0) ? sqrt(v_disp_glb[i] / n_ptcl_glb[i]) : 0.; n_tot0 += n_ptcl_glb[i]; } assert ( n_tot == n_tot0 ); #endif //ISOTROPIC #pragma omp parallel for for(PS::S32 i=0; i<n_loc; i++){ PS::F64vec pos = pp[i].pos; PS::F64 r2 = pos.x*pos.x + pos.y*pos.y; PS::F64 v_dispi = 0.; PS::F64 ni = 0.; for(PS::S32 j=0; j<N; j++){ PS::F64 ddr = r_min + (j+0.5)*dr - sqrt(r2); PS::F64 expr = exp(-ddr*ddr * drinv*drinv); v_dispi += v_disp_glb[j] * expr; ni += (v_disp_glb[j] > 0) ? expr : 0.; } pp[i].v_disp = v_dispi / ni; assert ( pp[i].v_disp > 0. ); } } template <class Tpsys> PS::F64 calcRandomVelAll(Tpsys & pp, const PS::S32 n_tot, const PS::S32 n_loc) { #ifdef ISOTROPIC PS::F64vec v_ave_loc = 0.; PS::F64vec v_ave_glb = 0.; PS::F64 v_sq_loc = 0.; PS::F64 v_sq_glb = 0.; #else PS::F64 v_disp_loc = 0.; #endif PS::F64 v_disp_glb = 0.; PS::S32 n_ptcl_loc = 0; PS::S32 n_ptcl_glb = 0; #ifdef ISOTROPIC #pragma omp parallel for reduction (+:v_ave_loc, v_sq_loc, n_ptcl_loc) for(PS::S32 i=0; i<n_loc; i++){ PS::F64vec vec = pp[i].vel; v_ave_loc += vec; v_sq_loc += vec*vec; n_ptcl_loc ++; } v_ave_glb = PS::Comm::getSum(v_ave_loc); v_sq_glb = PS::Comm::getSum(v_sq_loc); n_ptcl_glb = PS::Comm::getSum(n_ptcl_loc); assert ( n_ptcl_glb == n_tot ); v_disp_glb = sqrt(v_sq_glb / n_ptcl_glb - v_ave_glb*v_ave_glb); #else //ISOTROPIC #pragma omp parallel for reduction (+:v_disp_loc, n_ptcl_loc) for(PS::S32 i=0; i<n_loc; i++){ #if 1 PS::F64vec pos = pp[i].pos; PS::F64 r2 = pos.x*pos.x + pos.y*pos.y; PS::F64 ri = sqrt(r2); PS::F64vec v_kep; v_kep.x=-pos.y/ri ; v_kep.y=pos.x/ri; v_kep.z=0.; v_kep *= pp[i].getKeplerVelocity(); PS::F64vec v_ran = pp[i].vel - v_kep; #else PS::F64 ax; PS::F64 ecc = pp[i].getEccentricity(ax); PS::F64vec h; PS::F64 inc = pp[i].getInclination(h); PS::F64vec v_kep = pp[i].getKeplerVelocity(); PS::F64 v_ran = (ecc*ecc + inc*inc) * v_kep*v_kep; #endif v_disp_loc += v_ran * v_ran; n_ptcl_loc ++; } v_disp_glb = PS::Comm::getSum(v_disp_loc); n_ptcl_glb = PS::Comm::getSum(n_ptcl_loc); assert ( n_ptcl_glb == n_tot ); v_disp_glb = sqrt(v_disp_glb / n_ptcl_glb); #endif //ISOTROPIC return v_disp_glb; } #ifdef USE_INDIVIDUAL_CUTOFF template <class Tpsys> void setCutoffRadii(Tpsys & pp) { const PS::S32 n_loc = pp.getNumberOfParticleLocal(); const PS::S32 n_tot = pp.getNumberOfParticleGlobal(); #ifndef CONSTANT_RANDOM_VELOCITY calcRandomVel(pp, n_tot, n_loc); #endif #pragma omp parallel for for(PS::S32 i=0; i<n_loc; i++){ pp[i].setROutRSearch(); //pp[i].setRPlanet(); } } #else //USE_INDIVIDUAL_CUTOFF template <class Tpsys> void setCutoffRadii(Tpsys & pp) { const PS::S32 n_loc = pp.getNumberOfParticleLocal(); const PS::S32 n_tot = pp.getNumberOfParticleGlobal(); #ifndef CONSTANT_RANDOM_VELOCITY PS::F64 v_disp_glb = calcRandomVelAll(pp, n_tot, n_loc); #else PS::F64 v_disp_glb = v_disp; #endif PS::F64 rHill_a_loc = 0.; #pragma omp parallel for reduction (max: rHill_a_loc) for(PS::S32 i=0; i<n_loc; i++){ #ifndef WITHOUT_SUN PS::F64 ax = pp[i].getSemimajorAxis2(); PS::F64 rHill_a = pp[i].getRHill() * pow(ax,-FPGrav::p_cut); rHill_a_loc = std::max(rHill_a, rHill_a_loc); #else rHill_a_loc = std::max(pp[i].mass, rHill_a_loc); #endif //pp[i].setRPlanet(); } PS::F64 rHill_a_glb = PS::Comm::getMaxValue(rHill_a_loc); FPGrav::setROutRSearch(rHill_a_glb, v_disp_glb); } #endif //USE_INDIVIDUAL_CUTOFF ////////////////////// /// Super Particle /// ////////////////////// class MyMomentMonopole : public PS::MomentMonopole { public: #ifdef USE_POLAR_COORDINATE PS::F64vec pos_car; MyMomentMonopole() { pos_car = 0.; } MyMomentMonopole(const PS::F64 m, const PS::F64vec & p, const PS::F64vec & p_car) : PS::MomentMonopole(m, p) { pos_car = p_car; } void init(){ PS::MomentMonopole::init(); pos_car = 0.; } template<class Tepj> void accumulateAtLeaf(const Tepj & epj){ PS::MomentMonopole::accumulateAtLeaf(epj); pos_car += epj.getCharge() * epj.getPosCar(); } template<class Tepj> void accumulateAtLeaf2(const Tepj & epj){} void accumulate(const MyMomentMonopole & mom){ PS::MomentMonopole::accumulate(mom); pos_car += mom.mass * mom.pos_car; } void accumulate2(const MyMomentMonopole & mom){} // for DEBUG void dump(std::ostream & fout = std::cout) const { fout<<"mass="<<mass<<std::endl; fout<<"pos="<<pos<<std::endl; fout<<"pos_car="<<pos_car<<std::endl; } #endif void set(){ pos = (mass != 0.) ? pos / mass : 0.; #ifdef USE_POLAR_COORDINATE pos_car = (mass != 0.) ? pos_car / mass : 0.; #endif } }; class MySPJMonopole : public PS::SPJMonopole { public: #ifdef USE_POLAR_COORDINATE PS::F64vec pos_car; template<class Tmom> void copyFromMoment(const Tmom & mom){ PS::SPJMonopole::copyFromMoment(mom); this->pos_car = mom.pos_car; } void clear(){ PS::SPJMonopole::clear(); pos_car = 0.0; } PS::F64vec getPosCar() const { return pos_car; } MyMomentMonopole convertToMoment() const { return MyMomentMonopole(mass, pos, pos_car); } #endif }; class MyMomentQuadrupole : public PS::MomentQuadrupole { public: #ifdef USE_POLAR_COORDINATE PS::F64vec pos_car; MyMomentQuadrupole(){ pos_car = 0.; } MyMomentQuadrupole(const PS::F64 m, const PS::F64vec & p, const PS::F64mat & q, const PS::F64vec & p_car) : PS::MomentQuadrupole(m, p, q) { pos_car = p_car; } void init(){ PS::MomentQuadrupole::init(); pos_car = 0.; } template<class Tepj> void accumulateAtLeaf(const Tepj & epj){ PS::MomentQuadrupole::accumulateAtLeaf(epj); pos_car += epj.getCharge() * epj.getPosCar(); } template<class Tepj> void accumulateAtLeaf2(const Tepj & epj){ PS::F64 ctmp = epj.getCharge(); PS::F64vec ptmp = epj.getPosCar() - this->pos_car; PS::F64 cx = ctmp * ptmp.x; PS::F64 cy = ctmp * ptmp.y; PS::F64 cz = ctmp * ptmp.z; this->quad.xx += cx * ptmp.x; this->quad.yy += cy * ptmp.y; this->quad.zz += cz * ptmp.z; this->quad.xy += cx * ptmp.y; this->quad.xz += cx * ptmp.z; this->quad.yz += cy * ptmp.z; } void accumulate(const MyMomentQuadrupole & mom){ PS::MomentQuadrupole::accumulate(mom); pos_car += mom.mass * mom.pos_car; } void accumulate2(const MyMomentQuadrupole & mom){ PS::F64 mtmp = mom.mass; PS::F64vec ptmp = mom.pos_car - this->pos_car; PS::F64 cx = mtmp * ptmp.x; PS::F64 cy = mtmp * ptmp.y; PS::F64 cz = mtmp * ptmp.z; this->quad.xx += cx * ptmp.x + mom.quad.xx; this->quad.yy += cy * ptmp.y + mom.quad.yy; this->quad.zz += cz * ptmp.z + mom.quad.zz; this->quad.xy += cx * ptmp.y + mom.quad.xy; this->quad.xz += cx * ptmp.z + mom.quad.xz; this->quad.yz += cy * ptmp.z + mom.quad.yz; } void dump(std::ostream & fout = std::cout) const { fout<<"mass= "<<mass<<std::endl; fout<<"pos= "<<pos<<std::endl; fout<<"pos_car="<<pos_car<<std::endl; fout<<"quad= "<<quad<<std::endl; } #endif void set(){ pos = (mass != 0.) ? pos / mass : 0.; #ifdef USE_POLAR_COORDINATE pos_car = (mass != 0.) ? pos_car / mass : 0.; #endif } }; class MySPJQuadrupole : public PS::SPJQuadrupole { public: #ifdef USE_POLAR_COORDINATE PS::F64vec pos_car; PS::F64 getCharge() const { return mass; } PS::F64vec getPos() const { return pos; } PS::F64vec getPosCar() const { return pos_car; } void copyFromMoment(const MyMomentQuadrupole & mom){ PS::SPJQuadrupole::copyFromMoment(mom); pos_car = mom.pos_car; } MyMomentQuadrupole convertToMoment() const { return MyMomentQuadrupole(mass, pos, quad, pos_car); } void clear(){ PS::SPJQuadrupole::clear(); pos_car = 0.0; } #endif };
omp-low.c
/* Lowering pass for OMP directives. Converts OMP directives into explicit calls to the runtime library (libgomp), data marshalling to implement data sharing and copying clauses, offloading to accelerators, and more. Contributed by Diego Novillo <dnovillo@redhat.com> Copyright (C) 2005-2018 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "backend.h" #include "target.h" #include "tree.h" #include "gimple.h" #include "tree-pass.h" #include "ssa.h" #include "cgraph.h" #include "pretty-print.h" #include "diagnostic-core.h" #include "fold-const.h" #include "stor-layout.h" #include "internal-fn.h" #include "gimple-fold.h" #include "gimplify.h" #include "gimple-iterator.h" #include "gimplify-me.h" #include "gimple-walk.h" #include "tree-iterator.h" #include "tree-inline.h" #include "langhooks.h" #include "tree-dfa.h" #include "tree-ssa.h" #include "splay-tree.h" #include "omp-general.h" #include "omp-low.h" #include "omp-grid.h" #include "gimple-low.h" #include "symbol-summary.h" #include "tree-nested.h" #include "context.h" #include "gomp-constants.h" #include "gimple-pretty-print.h" #include "hsa-common.h" #include "stringpool.h" #include "attribs.h" /* Lowering of OMP parallel and workshare constructs proceeds in two phases. The first phase scans the function looking for OMP statements and then for variables that must be replaced to satisfy data sharing clauses. The second phase expands code for the constructs, as well as re-gimplifying things when variables have been replaced with complex expressions. Final code generation is done by pass_expand_omp. The flowgraph is scanned for regions which are then moved to a new function, to be invoked by the thread library, or offloaded. */ /* Context structure. Used to store information about each parallel directive in the code. */ struct omp_context { /* This field must be at the beginning, as we do "inheritance": Some callback functions for tree-inline.c (e.g., omp_copy_decl) receive a copy_body_data pointer that is up-casted to an omp_context pointer. */ copy_body_data cb; /* The tree of contexts corresponding to the encountered constructs. */ struct omp_context *outer; gimple *stmt; /* Map variables to fields in a structure that allows communication between sending and receiving threads. */ splay_tree field_map; tree record_type; tree sender_decl; tree receiver_decl; /* These are used just by task contexts, if task firstprivate fn is needed. srecord_type is used to communicate from the thread that encountered the task construct to task firstprivate fn, record_type is allocated by GOMP_task, initialized by task firstprivate fn and passed to the task body fn. */ splay_tree sfield_map; tree srecord_type; /* A chain of variables to add to the top-level block surrounding the construct. In the case of a parallel, this is in the child function. */ tree block_vars; /* Label to which GOMP_cancel{,llation_point} and explicit and implicit barriers should jump to during omplower pass. */ tree cancel_label; /* The sibling GIMPLE_OMP_FOR simd with _simt_ clause or NULL otherwise. */ gimple *simt_stmt; /* Nesting depth of this context. Used to beautify error messages re invalid gotos. The outermost ctx is depth 1, with depth 0 being reserved for the main body of the function. */ int depth; /* True if this parallel directive is nested within another. */ bool is_nested; /* True if this construct can be cancelled. */ bool cancellable; }; static splay_tree all_contexts; static int taskreg_nesting_level; static int target_nesting_level; static bitmap task_shared_vars; static vec<omp_context *> taskreg_contexts; static void scan_omp (gimple_seq *, omp_context *); static tree scan_omp_1_op (tree *, int *, void *); #define WALK_SUBSTMTS \ case GIMPLE_BIND: \ case GIMPLE_TRY: \ case GIMPLE_CATCH: \ case GIMPLE_EH_FILTER: \ case GIMPLE_TRANSACTION: \ /* The sub-statements for these should be walked. */ \ *handled_ops_p = false; \ break; /* Return true if CTX corresponds to an oacc parallel region. */ static bool is_oacc_parallel (omp_context *ctx) { enum gimple_code outer_type = gimple_code (ctx->stmt); return ((outer_type == GIMPLE_OMP_TARGET) && (gimple_omp_target_kind (ctx->stmt) == GF_OMP_TARGET_KIND_OACC_PARALLEL)); } /* Return true if CTX corresponds to an oacc kernels region. */ static bool is_oacc_kernels (omp_context *ctx) { enum gimple_code outer_type = gimple_code (ctx->stmt); return ((outer_type == GIMPLE_OMP_TARGET) && (gimple_omp_target_kind (ctx->stmt) == GF_OMP_TARGET_KIND_OACC_KERNELS)); } /* If DECL is the artificial dummy VAR_DECL created for non-static data member privatization, return the underlying "this" parameter, otherwise return NULL. */ tree omp_member_access_dummy_var (tree decl) { if (!VAR_P (decl) || !DECL_ARTIFICIAL (decl) || !DECL_IGNORED_P (decl) || !DECL_HAS_VALUE_EXPR_P (decl) || !lang_hooks.decls.omp_disregard_value_expr (decl, false)) return NULL_TREE; tree v = DECL_VALUE_EXPR (decl); if (TREE_CODE (v) != COMPONENT_REF) return NULL_TREE; while (1) switch (TREE_CODE (v)) { case COMPONENT_REF: case MEM_REF: case INDIRECT_REF: CASE_CONVERT: case POINTER_PLUS_EXPR: v = TREE_OPERAND (v, 0); continue; case PARM_DECL: if (DECL_CONTEXT (v) == current_function_decl && DECL_ARTIFICIAL (v) && TREE_CODE (TREE_TYPE (v)) == POINTER_TYPE) return v; return NULL_TREE; default: return NULL_TREE; } } /* Helper for unshare_and_remap, called through walk_tree. */ static tree unshare_and_remap_1 (tree *tp, int *walk_subtrees, void *data) { tree *pair = (tree *) data; if (*tp == pair[0]) { *tp = unshare_expr (pair[1]); *walk_subtrees = 0; } else if (IS_TYPE_OR_DECL_P (*tp)) *walk_subtrees = 0; return NULL_TREE; } /* Return unshare_expr (X) with all occurrences of FROM replaced with TO. */ static tree unshare_and_remap (tree x, tree from, tree to) { tree pair[2] = { from, to }; x = unshare_expr (x); walk_tree (&x, unshare_and_remap_1, pair, NULL); return x; } /* Convenience function for calling scan_omp_1_op on tree operands. */ static inline tree scan_omp_op (tree *tp, omp_context *ctx) { struct walk_stmt_info wi; memset (&wi, 0, sizeof (wi)); wi.info = ctx; wi.want_locations = true; return walk_tree (tp, scan_omp_1_op, &wi, NULL); } static void lower_omp (gimple_seq *, omp_context *); static tree lookup_decl_in_outer_ctx (tree, omp_context *); static tree maybe_lookup_decl_in_outer_ctx (tree, omp_context *); /* Return true if CTX is for an omp parallel. */ static inline bool is_parallel_ctx (omp_context *ctx) { return gimple_code (ctx->stmt) == GIMPLE_OMP_PARALLEL; } /* Return true if CTX is for an omp task. */ static inline bool is_task_ctx (omp_context *ctx) { return gimple_code (ctx->stmt) == GIMPLE_OMP_TASK; } /* Return true if CTX is for an omp taskloop. */ static inline bool is_taskloop_ctx (omp_context *ctx) { return gimple_code (ctx->stmt) == GIMPLE_OMP_FOR && gimple_omp_for_kind (ctx->stmt) == GF_OMP_FOR_KIND_TASKLOOP; } /* Return true if CTX is for an omp parallel or omp task. */ static inline bool is_taskreg_ctx (omp_context *ctx) { return is_parallel_ctx (ctx) || is_task_ctx (ctx); } /* Return true if EXPR is variable sized. */ static inline bool is_variable_sized (const_tree expr) { return !TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (expr))); } /* Lookup variables. The "maybe" form allows for the variable form to not have been entered, otherwise we assert that the variable must have been entered. */ static inline tree lookup_decl (tree var, omp_context *ctx) { tree *n = ctx->cb.decl_map->get (var); return *n; } static inline tree maybe_lookup_decl (const_tree var, omp_context *ctx) { tree *n = ctx->cb.decl_map->get (const_cast<tree> (var)); return n ? *n : NULL_TREE; } static inline tree lookup_field (tree var, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) var); return (tree) n->value; } static inline tree lookup_sfield (splay_tree_key key, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->sfield_map ? ctx->sfield_map : ctx->field_map, key); return (tree) n->value; } static inline tree lookup_sfield (tree var, omp_context *ctx) { return lookup_sfield ((splay_tree_key) var, ctx); } static inline tree maybe_lookup_field (splay_tree_key key, omp_context *ctx) { splay_tree_node n; n = splay_tree_lookup (ctx->field_map, key); return n ? (tree) n->value : NULL_TREE; } static inline tree maybe_lookup_field (tree var, omp_context *ctx) { return maybe_lookup_field ((splay_tree_key) var, ctx); } /* Return true if DECL should be copied by pointer. SHARED_CTX is the parallel context if DECL is to be shared. */ static bool use_pointer_for_field (tree decl, omp_context *shared_ctx) { if (AGGREGATE_TYPE_P (TREE_TYPE (decl)) || TYPE_ATOMIC (TREE_TYPE (decl))) return true; /* We can only use copy-in/copy-out semantics for shared variables when we know the value is not accessible from an outer scope. */ if (shared_ctx) { gcc_assert (!is_gimple_omp_oacc (shared_ctx->stmt)); /* ??? Trivially accessible from anywhere. But why would we even be passing an address in this case? Should we simply assert this to be false, or should we have a cleanup pass that removes these from the list of mappings? */ if (TREE_STATIC (decl) || DECL_EXTERNAL (decl)) return true; /* For variables with DECL_HAS_VALUE_EXPR_P set, we cannot tell without analyzing the expression whether or not its location is accessible to anyone else. In the case of nested parallel regions it certainly may be. */ if (TREE_CODE (decl) != RESULT_DECL && DECL_HAS_VALUE_EXPR_P (decl)) return true; /* Do not use copy-in/copy-out for variables that have their address taken. */ if (TREE_ADDRESSABLE (decl)) return true; /* lower_send_shared_vars only uses copy-in, but not copy-out for these. */ if (TREE_READONLY (decl) || ((TREE_CODE (decl) == RESULT_DECL || TREE_CODE (decl) == PARM_DECL) && DECL_BY_REFERENCE (decl))) return false; /* Disallow copy-in/out in nested parallel if decl is shared in outer parallel, otherwise each thread could store the shared variable in its own copy-in location, making the variable no longer really shared. */ if (shared_ctx->is_nested) { omp_context *up; for (up = shared_ctx->outer; up; up = up->outer) if (is_taskreg_ctx (up) && maybe_lookup_decl (decl, up)) break; if (up) { tree c; for (c = gimple_omp_taskreg_clauses (up->stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED && OMP_CLAUSE_DECL (c) == decl) break; if (c) goto maybe_mark_addressable_and_ret; } } /* For tasks avoid using copy-in/out. As tasks can be deferred or executed in different thread, when GOMP_task returns, the task hasn't necessarily terminated. */ if (is_task_ctx (shared_ctx)) { tree outer; maybe_mark_addressable_and_ret: outer = maybe_lookup_decl_in_outer_ctx (decl, shared_ctx); if (is_gimple_reg (outer) && !omp_member_access_dummy_var (outer)) { /* Taking address of OUTER in lower_send_shared_vars might need regimplification of everything that uses the variable. */ if (!task_shared_vars) task_shared_vars = BITMAP_ALLOC (NULL); bitmap_set_bit (task_shared_vars, DECL_UID (outer)); TREE_ADDRESSABLE (outer) = 1; } return true; } } return false; } /* Construct a new automatic decl similar to VAR. */ static tree omp_copy_decl_2 (tree var, tree name, tree type, omp_context *ctx) { tree copy = copy_var_decl (var, name, type); DECL_CONTEXT (copy) = current_function_decl; DECL_CHAIN (copy) = ctx->block_vars; /* If VAR is listed in task_shared_vars, it means it wasn't originally addressable and is just because task needs to take it's address. But we don't need to take address of privatizations from that var. */ if (TREE_ADDRESSABLE (var) && task_shared_vars && bitmap_bit_p (task_shared_vars, DECL_UID (var))) TREE_ADDRESSABLE (copy) = 0; ctx->block_vars = copy; return copy; } static tree omp_copy_decl_1 (tree var, omp_context *ctx) { return omp_copy_decl_2 (var, DECL_NAME (var), TREE_TYPE (var), ctx); } /* Build COMPONENT_REF and set TREE_THIS_VOLATILE and TREE_READONLY on it as appropriate. */ static tree omp_build_component_ref (tree obj, tree field) { tree ret = build3 (COMPONENT_REF, TREE_TYPE (field), obj, field, NULL); if (TREE_THIS_VOLATILE (field)) TREE_THIS_VOLATILE (ret) |= 1; if (TREE_READONLY (field)) TREE_READONLY (ret) |= 1; return ret; } /* Build tree nodes to access the field for VAR on the receiver side. */ static tree build_receiver_ref (tree var, bool by_ref, omp_context *ctx) { tree x, field = lookup_field (var, ctx); /* If the receiver record type was remapped in the child function, remap the field into the new record type. */ x = maybe_lookup_field (field, ctx); if (x != NULL) field = x; x = build_simple_mem_ref (ctx->receiver_decl); TREE_THIS_NOTRAP (x) = 1; x = omp_build_component_ref (x, field); if (by_ref) { x = build_simple_mem_ref (x); TREE_THIS_NOTRAP (x) = 1; } return x; } /* Build tree nodes to access VAR in the scope outer to CTX. In the case of a parallel, this is a component reference; for workshare constructs this is some variable. */ static tree build_outer_var_ref (tree var, omp_context *ctx, enum omp_clause_code code = OMP_CLAUSE_ERROR) { tree x; if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx))) x = var; else if (is_variable_sized (var)) { x = TREE_OPERAND (DECL_VALUE_EXPR (var), 0); x = build_outer_var_ref (x, ctx, code); x = build_simple_mem_ref (x); } else if (is_taskreg_ctx (ctx)) { bool by_ref = use_pointer_for_field (var, NULL); x = build_receiver_ref (var, by_ref, ctx); } else if ((gimple_code (ctx->stmt) == GIMPLE_OMP_FOR && gimple_omp_for_kind (ctx->stmt) & GF_OMP_FOR_SIMD) || (code == OMP_CLAUSE_PRIVATE && (gimple_code (ctx->stmt) == GIMPLE_OMP_FOR || gimple_code (ctx->stmt) == GIMPLE_OMP_SECTIONS || gimple_code (ctx->stmt) == GIMPLE_OMP_SINGLE))) { /* #pragma omp simd isn't a worksharing construct, and can reference even private vars in its linear etc. clauses. Similarly for OMP_CLAUSE_PRIVATE with outer ref, that can refer to private vars in all worksharing constructs. */ x = NULL_TREE; if (ctx->outer && is_taskreg_ctx (ctx)) x = lookup_decl (var, ctx->outer); else if (ctx->outer) x = maybe_lookup_decl_in_outer_ctx (var, ctx); if (x == NULL_TREE) x = var; } else if (code == OMP_CLAUSE_LASTPRIVATE && is_taskloop_ctx (ctx)) { gcc_assert (ctx->outer); splay_tree_node n = splay_tree_lookup (ctx->outer->field_map, (splay_tree_key) &DECL_UID (var)); if (n == NULL) { if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx->outer))) x = var; else x = lookup_decl (var, ctx->outer); } else { tree field = (tree) n->value; /* If the receiver record type was remapped in the child function, remap the field into the new record type. */ x = maybe_lookup_field (field, ctx->outer); if (x != NULL) field = x; x = build_simple_mem_ref (ctx->outer->receiver_decl); x = omp_build_component_ref (x, field); if (use_pointer_for_field (var, ctx->outer)) x = build_simple_mem_ref (x); } } else if (ctx->outer) { omp_context *outer = ctx->outer; if (gimple_code (outer->stmt) == GIMPLE_OMP_GRID_BODY) { outer = outer->outer; gcc_assert (outer && gimple_code (outer->stmt) != GIMPLE_OMP_GRID_BODY); } x = lookup_decl (var, outer); } else if (omp_is_reference (var)) /* This can happen with orphaned constructs. If var is reference, it is possible it is shared and as such valid. */ x = var; else if (omp_member_access_dummy_var (var)) x = var; else gcc_unreachable (); if (x == var) { tree t = omp_member_access_dummy_var (var); if (t) { x = DECL_VALUE_EXPR (var); tree o = maybe_lookup_decl_in_outer_ctx (t, ctx); if (o != t) x = unshare_and_remap (x, t, o); else x = unshare_expr (x); } } if (omp_is_reference (var)) x = build_simple_mem_ref (x); return x; } /* Build tree nodes to access the field for VAR on the sender side. */ static tree build_sender_ref (splay_tree_key key, omp_context *ctx) { tree field = lookup_sfield (key, ctx); return omp_build_component_ref (ctx->sender_decl, field); } static tree build_sender_ref (tree var, omp_context *ctx) { return build_sender_ref ((splay_tree_key) var, ctx); } /* Add a new field for VAR inside the structure CTX->SENDER_DECL. If BASE_POINTERS_RESTRICT, declare the field with restrict. */ static void install_var_field (tree var, bool by_ref, int mask, omp_context *ctx, bool base_pointers_restrict = false) { tree field, type, sfield = NULL_TREE; splay_tree_key key = (splay_tree_key) var; if ((mask & 8) != 0) { key = (splay_tree_key) &DECL_UID (var); gcc_checking_assert (key != (splay_tree_key) var); } gcc_assert ((mask & 1) == 0 || !splay_tree_lookup (ctx->field_map, key)); gcc_assert ((mask & 2) == 0 || !ctx->sfield_map || !splay_tree_lookup (ctx->sfield_map, key)); gcc_assert ((mask & 3) == 3 || !is_gimple_omp_oacc (ctx->stmt)); type = TREE_TYPE (var); /* Prevent redeclaring the var in the split-off function with a restrict pointer type. Note that we only clear type itself, restrict qualifiers in the pointed-to type will be ignored by points-to analysis. */ if (POINTER_TYPE_P (type) && TYPE_RESTRICT (type)) type = build_qualified_type (type, TYPE_QUALS (type) & ~TYPE_QUAL_RESTRICT); if (mask & 4) { gcc_assert (TREE_CODE (type) == ARRAY_TYPE); type = build_pointer_type (build_pointer_type (type)); } else if (by_ref) { type = build_pointer_type (type); if (base_pointers_restrict) type = build_qualified_type (type, TYPE_QUAL_RESTRICT); } else if ((mask & 3) == 1 && omp_is_reference (var)) type = TREE_TYPE (type); field = build_decl (DECL_SOURCE_LOCATION (var), FIELD_DECL, DECL_NAME (var), type); /* Remember what variable this field was created for. This does have a side effect of making dwarf2out ignore this member, so for helpful debugging we clear it later in delete_omp_context. */ DECL_ABSTRACT_ORIGIN (field) = var; if (type == TREE_TYPE (var)) { SET_DECL_ALIGN (field, DECL_ALIGN (var)); DECL_USER_ALIGN (field) = DECL_USER_ALIGN (var); TREE_THIS_VOLATILE (field) = TREE_THIS_VOLATILE (var); } else SET_DECL_ALIGN (field, TYPE_ALIGN (type)); if ((mask & 3) == 3) { insert_field_into_struct (ctx->record_type, field); if (ctx->srecord_type) { sfield = build_decl (DECL_SOURCE_LOCATION (var), FIELD_DECL, DECL_NAME (var), type); DECL_ABSTRACT_ORIGIN (sfield) = var; SET_DECL_ALIGN (sfield, DECL_ALIGN (field)); DECL_USER_ALIGN (sfield) = DECL_USER_ALIGN (field); TREE_THIS_VOLATILE (sfield) = TREE_THIS_VOLATILE (field); insert_field_into_struct (ctx->srecord_type, sfield); } } else { if (ctx->srecord_type == NULL_TREE) { tree t; ctx->srecord_type = lang_hooks.types.make_type (RECORD_TYPE); ctx->sfield_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); for (t = TYPE_FIELDS (ctx->record_type); t ; t = TREE_CHAIN (t)) { sfield = build_decl (DECL_SOURCE_LOCATION (t), FIELD_DECL, DECL_NAME (t), TREE_TYPE (t)); DECL_ABSTRACT_ORIGIN (sfield) = DECL_ABSTRACT_ORIGIN (t); insert_field_into_struct (ctx->srecord_type, sfield); splay_tree_insert (ctx->sfield_map, (splay_tree_key) DECL_ABSTRACT_ORIGIN (t), (splay_tree_value) sfield); } } sfield = field; insert_field_into_struct ((mask & 1) ? ctx->record_type : ctx->srecord_type, field); } if (mask & 1) splay_tree_insert (ctx->field_map, key, (splay_tree_value) field); if ((mask & 2) && ctx->sfield_map) splay_tree_insert (ctx->sfield_map, key, (splay_tree_value) sfield); } static tree install_var_local (tree var, omp_context *ctx) { tree new_var = omp_copy_decl_1 (var, ctx); insert_decl_map (&ctx->cb, var, new_var); return new_var; } /* Adjust the replacement for DECL in CTX for the new context. This means copying the DECL_VALUE_EXPR, and fixing up the type. */ static void fixup_remapped_decl (tree decl, omp_context *ctx, bool private_debug) { tree new_decl, size; new_decl = lookup_decl (decl, ctx); TREE_TYPE (new_decl) = remap_type (TREE_TYPE (decl), &ctx->cb); if ((!TREE_CONSTANT (DECL_SIZE (new_decl)) || private_debug) && DECL_HAS_VALUE_EXPR_P (decl)) { tree ve = DECL_VALUE_EXPR (decl); walk_tree (&ve, copy_tree_body_r, &ctx->cb, NULL); SET_DECL_VALUE_EXPR (new_decl, ve); DECL_HAS_VALUE_EXPR_P (new_decl) = 1; } if (!TREE_CONSTANT (DECL_SIZE (new_decl))) { size = remap_decl (DECL_SIZE (decl), &ctx->cb); if (size == error_mark_node) size = TYPE_SIZE (TREE_TYPE (new_decl)); DECL_SIZE (new_decl) = size; size = remap_decl (DECL_SIZE_UNIT (decl), &ctx->cb); if (size == error_mark_node) size = TYPE_SIZE_UNIT (TREE_TYPE (new_decl)); DECL_SIZE_UNIT (new_decl) = size; } } /* The callback for remap_decl. Search all containing contexts for a mapping of the variable; this avoids having to duplicate the splay tree ahead of time. We know a mapping doesn't already exist in the given context. Create new mappings to implement default semantics. */ static tree omp_copy_decl (tree var, copy_body_data *cb) { omp_context *ctx = (omp_context *) cb; tree new_var; if (TREE_CODE (var) == LABEL_DECL) { if (FORCED_LABEL (var) || DECL_NONLOCAL (var)) return var; new_var = create_artificial_label (DECL_SOURCE_LOCATION (var)); DECL_CONTEXT (new_var) = current_function_decl; insert_decl_map (&ctx->cb, var, new_var); return new_var; } while (!is_taskreg_ctx (ctx)) { ctx = ctx->outer; if (ctx == NULL) return var; new_var = maybe_lookup_decl (var, ctx); if (new_var) return new_var; } if (is_global_var (var) || decl_function_context (var) != ctx->cb.src_fn) return var; return error_mark_node; } /* Create a new context, with OUTER_CTX being the surrounding context. */ static omp_context * new_omp_context (gimple *stmt, omp_context *outer_ctx) { omp_context *ctx = XCNEW (omp_context); splay_tree_insert (all_contexts, (splay_tree_key) stmt, (splay_tree_value) ctx); ctx->stmt = stmt; if (outer_ctx) { ctx->outer = outer_ctx; ctx->cb = outer_ctx->cb; ctx->cb.block = NULL; ctx->depth = outer_ctx->depth + 1; } else { ctx->cb.src_fn = current_function_decl; ctx->cb.dst_fn = current_function_decl; ctx->cb.src_node = cgraph_node::get (current_function_decl); gcc_checking_assert (ctx->cb.src_node); ctx->cb.dst_node = ctx->cb.src_node; ctx->cb.src_cfun = cfun; ctx->cb.copy_decl = omp_copy_decl; ctx->cb.eh_lp_nr = 0; ctx->cb.transform_call_graph_edges = CB_CGE_MOVE; ctx->depth = 1; } ctx->cb.decl_map = new hash_map<tree, tree>; return ctx; } static gimple_seq maybe_catch_exception (gimple_seq); /* Finalize task copyfn. */ static void finalize_task_copyfn (gomp_task *task_stmt) { struct function *child_cfun; tree child_fn; gimple_seq seq = NULL, new_seq; gbind *bind; child_fn = gimple_omp_task_copy_fn (task_stmt); if (child_fn == NULL_TREE) return; child_cfun = DECL_STRUCT_FUNCTION (child_fn); DECL_STRUCT_FUNCTION (child_fn)->curr_properties = cfun->curr_properties; push_cfun (child_cfun); bind = gimplify_body (child_fn, false); gimple_seq_add_stmt (&seq, bind); new_seq = maybe_catch_exception (seq); if (new_seq != seq) { bind = gimple_build_bind (NULL, new_seq, NULL); seq = NULL; gimple_seq_add_stmt (&seq, bind); } gimple_set_body (child_fn, seq); pop_cfun (); /* Inform the callgraph about the new function. */ cgraph_node *node = cgraph_node::get_create (child_fn); node->parallelized_function = 1; cgraph_node::add_new_function (child_fn, false); } /* Destroy a omp_context data structures. Called through the splay tree value delete callback. */ static void delete_omp_context (splay_tree_value value) { omp_context *ctx = (omp_context *) value; delete ctx->cb.decl_map; if (ctx->field_map) splay_tree_delete (ctx->field_map); if (ctx->sfield_map) splay_tree_delete (ctx->sfield_map); /* We hijacked DECL_ABSTRACT_ORIGIN earlier. We need to clear it before it produces corrupt debug information. */ if (ctx->record_type) { tree t; for (t = TYPE_FIELDS (ctx->record_type); t ; t = DECL_CHAIN (t)) DECL_ABSTRACT_ORIGIN (t) = NULL; } if (ctx->srecord_type) { tree t; for (t = TYPE_FIELDS (ctx->srecord_type); t ; t = DECL_CHAIN (t)) DECL_ABSTRACT_ORIGIN (t) = NULL; } if (is_task_ctx (ctx)) finalize_task_copyfn (as_a <gomp_task *> (ctx->stmt)); XDELETE (ctx); } /* Fix up RECEIVER_DECL with a type that has been remapped to the child context. */ static void fixup_child_record_type (omp_context *ctx) { tree f, type = ctx->record_type; if (!ctx->receiver_decl) return; /* ??? It isn't sufficient to just call remap_type here, because variably_modified_type_p doesn't work the way we expect for record types. Testing each field for whether it needs remapping and creating a new record by hand works, however. */ for (f = TYPE_FIELDS (type); f ; f = DECL_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) break; if (f) { tree name, new_fields = NULL; type = lang_hooks.types.make_type (RECORD_TYPE); name = DECL_NAME (TYPE_NAME (ctx->record_type)); name = build_decl (DECL_SOURCE_LOCATION (ctx->receiver_decl), TYPE_DECL, name, type); TYPE_NAME (type) = name; for (f = TYPE_FIELDS (ctx->record_type); f ; f = DECL_CHAIN (f)) { tree new_f = copy_node (f); DECL_CONTEXT (new_f) = type; TREE_TYPE (new_f) = remap_type (TREE_TYPE (f), &ctx->cb); DECL_CHAIN (new_f) = new_fields; walk_tree (&DECL_SIZE (new_f), copy_tree_body_r, &ctx->cb, NULL); walk_tree (&DECL_SIZE_UNIT (new_f), copy_tree_body_r, &ctx->cb, NULL); walk_tree (&DECL_FIELD_OFFSET (new_f), copy_tree_body_r, &ctx->cb, NULL); new_fields = new_f; /* Arrange to be able to look up the receiver field given the sender field. */ splay_tree_insert (ctx->field_map, (splay_tree_key) f, (splay_tree_value) new_f); } TYPE_FIELDS (type) = nreverse (new_fields); layout_type (type); } /* In a target region we never modify any of the pointers in *.omp_data_i, so attempt to help the optimizers. */ if (is_gimple_omp_offloaded (ctx->stmt)) type = build_qualified_type (type, TYPE_QUAL_CONST); TREE_TYPE (ctx->receiver_decl) = build_qualified_type (build_reference_type (type), TYPE_QUAL_RESTRICT); } /* Instantiate decls as necessary in CTX to satisfy the data sharing specified by CLAUSES. If BASE_POINTERS_RESTRICT, install var field with restrict. */ static void scan_sharing_clauses (tree clauses, omp_context *ctx, bool base_pointers_restrict = false) { tree c, decl; bool scan_array_reductions = false; for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { bool by_ref; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: decl = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) goto do_private; else if (!is_variable_sized (decl)) install_var_local (decl, ctx); break; case OMP_CLAUSE_SHARED: decl = OMP_CLAUSE_DECL (c); /* Ignore shared directives in teams construct. */ if (gimple_code (ctx->stmt) == GIMPLE_OMP_TEAMS) { /* Global variables don't need to be copied, the receiver side will use them directly. */ tree odecl = maybe_lookup_decl_in_outer_ctx (decl, ctx); if (is_global_var (odecl)) break; insert_decl_map (&ctx->cb, decl, odecl); break; } gcc_assert (is_taskreg_ctx (ctx)); gcc_assert (!COMPLETE_TYPE_P (TREE_TYPE (decl)) || !is_variable_sized (decl)); /* Global variables don't need to be copied, the receiver side will use them directly. */ if (is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx))) break; if (OMP_CLAUSE_SHARED_FIRSTPRIVATE (c)) { use_pointer_for_field (decl, ctx); break; } by_ref = use_pointer_for_field (decl, NULL); if ((! TREE_READONLY (decl) && !OMP_CLAUSE_SHARED_READONLY (c)) || TREE_ADDRESSABLE (decl) || by_ref || omp_is_reference (decl)) { by_ref = use_pointer_for_field (decl, ctx); install_var_field (decl, by_ref, 3, ctx); install_var_local (decl, ctx); break; } /* We don't need to copy const scalar vars back. */ OMP_CLAUSE_SET_CODE (c, OMP_CLAUSE_FIRSTPRIVATE); goto do_private; case OMP_CLAUSE_REDUCTION: decl = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && TREE_CODE (decl) == MEM_REF) { tree t = TREE_OPERAND (decl, 0); if (TREE_CODE (t) == POINTER_PLUS_EXPR) t = TREE_OPERAND (t, 0); if (TREE_CODE (t) == INDIRECT_REF || TREE_CODE (t) == ADDR_EXPR) t = TREE_OPERAND (t, 0); install_var_local (t, ctx); if (is_taskreg_ctx (ctx) && !is_global_var (maybe_lookup_decl_in_outer_ctx (t, ctx)) && !is_variable_sized (t)) { by_ref = use_pointer_for_field (t, ctx); install_var_field (t, by_ref, 3, ctx); } break; } goto do_private; case OMP_CLAUSE_LASTPRIVATE: /* Let the corresponding firstprivate clause create the variable. */ if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_LINEAR: decl = OMP_CLAUSE_DECL (c); do_private: if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IS_DEVICE_PTR) && is_gimple_omp_offloaded (ctx->stmt)) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) install_var_field (decl, !omp_is_reference (decl), 3, ctx); else if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE) install_var_field (decl, true, 3, ctx); else install_var_field (decl, false, 3, ctx); } if (is_variable_sized (decl)) { if (is_task_ctx (ctx)) install_var_field (decl, false, 1, ctx); break; } else if (is_taskreg_ctx (ctx)) { bool global = is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx)); by_ref = use_pointer_for_field (decl, NULL); if (is_task_ctx (ctx) && (global || by_ref || omp_is_reference (decl))) { install_var_field (decl, false, 1, ctx); if (!global) install_var_field (decl, by_ref, 2, ctx); } else if (!global) install_var_field (decl, by_ref, 3, ctx); } install_var_local (decl, ctx); break; case OMP_CLAUSE_USE_DEVICE_PTR: decl = OMP_CLAUSE_DECL (c); if (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE) install_var_field (decl, true, 3, ctx); else install_var_field (decl, false, 3, ctx); if (DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { tree decl2 = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (decl2) == INDIRECT_REF); decl2 = TREE_OPERAND (decl2, 0); gcc_assert (DECL_P (decl2)); install_var_local (decl2, ctx); } install_var_local (decl, ctx); break; case OMP_CLAUSE_IS_DEVICE_PTR: decl = OMP_CLAUSE_DECL (c); goto do_private; case OMP_CLAUSE__LOOPTEMP_: gcc_assert (is_taskreg_ctx (ctx)); decl = OMP_CLAUSE_DECL (c); install_var_field (decl, false, 3, ctx); install_var_local (decl, ctx); break; case OMP_CLAUSE_COPYPRIVATE: case OMP_CLAUSE_COPYIN: decl = OMP_CLAUSE_DECL (c); by_ref = use_pointer_for_field (decl, NULL); install_var_field (decl, by_ref, 3, ctx); break; case OMP_CLAUSE_FINAL: case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_NUM_TEAMS: case OMP_CLAUSE_THREAD_LIMIT: case OMP_CLAUSE_DEVICE: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_DIST_SCHEDULE: case OMP_CLAUSE_DEPEND: case OMP_CLAUSE_PRIORITY: case OMP_CLAUSE_GRAINSIZE: case OMP_CLAUSE_NUM_TASKS: case OMP_CLAUSE_NUM_GANGS: case OMP_CLAUSE_NUM_WORKERS: case OMP_CLAUSE_VECTOR_LENGTH: if (ctx->outer) scan_omp_op (&OMP_CLAUSE_OPERAND (c, 0), ctx->outer); break; case OMP_CLAUSE_TO: case OMP_CLAUSE_FROM: case OMP_CLAUSE_MAP: if (ctx->outer) scan_omp_op (&OMP_CLAUSE_SIZE (c), ctx->outer); decl = OMP_CLAUSE_DECL (c); /* Global variables with "omp declare target" attribute don't need to be copied, the receiver side will use them directly. However, global variables with "omp declare target link" attribute need to be copied. */ if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && DECL_P (decl) && ((OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FIRSTPRIVATE_POINTER && (OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FIRSTPRIVATE_REFERENCE)) || TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE) && is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx)) && varpool_node::get_create (decl)->offloadable && !lookup_attribute ("omp declare target link", DECL_ATTRIBUTES (decl))) break; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER) { /* Ignore GOMP_MAP_POINTER kind for arrays in regions that are not offloaded; there is nothing to map for those. */ if (!is_gimple_omp_offloaded (ctx->stmt) && !POINTER_TYPE_P (TREE_TYPE (decl)) && !OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (c)) break; } if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_POINTER || (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_REFERENCE))) { if (TREE_CODE (decl) == COMPONENT_REF || (TREE_CODE (decl) == INDIRECT_REF && TREE_CODE (TREE_OPERAND (decl, 0)) == COMPONENT_REF && (TREE_CODE (TREE_TYPE (TREE_OPERAND (decl, 0))) == REFERENCE_TYPE))) break; if (DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { tree decl2 = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (decl2) == INDIRECT_REF); decl2 = TREE_OPERAND (decl2, 0); gcc_assert (DECL_P (decl2)); install_var_local (decl2, ctx); } install_var_local (decl, ctx); break; } if (DECL_P (decl)) { if (DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { tree decl2 = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (decl2) == INDIRECT_REF); decl2 = TREE_OPERAND (decl2, 0); gcc_assert (DECL_P (decl2)); install_var_field (decl2, true, 3, ctx); install_var_local (decl2, ctx); install_var_local (decl, ctx); } else { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER && !OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (c) && TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE) install_var_field (decl, true, 7, ctx); else install_var_field (decl, true, 3, ctx, base_pointers_restrict); if (is_gimple_omp_offloaded (ctx->stmt) && !OMP_CLAUSE_MAP_IN_REDUCTION (c)) install_var_local (decl, ctx); } } else { tree base = get_base_address (decl); tree nc = OMP_CLAUSE_CHAIN (c); if (DECL_P (base) && nc != NULL_TREE && OMP_CLAUSE_CODE (nc) == OMP_CLAUSE_MAP && OMP_CLAUSE_DECL (nc) == base && OMP_CLAUSE_MAP_KIND (nc) == GOMP_MAP_POINTER && integer_zerop (OMP_CLAUSE_SIZE (nc))) { OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (c) = 1; OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (nc) = 1; } else { if (ctx->outer) { scan_omp_op (&OMP_CLAUSE_DECL (c), ctx->outer); decl = OMP_CLAUSE_DECL (c); } gcc_assert (!splay_tree_lookup (ctx->field_map, (splay_tree_key) decl)); tree field = build_decl (OMP_CLAUSE_LOCATION (c), FIELD_DECL, NULL_TREE, ptr_type_node); SET_DECL_ALIGN (field, TYPE_ALIGN (ptr_type_node)); insert_field_into_struct (ctx->record_type, field); splay_tree_insert (ctx->field_map, (splay_tree_key) decl, (splay_tree_value) field); } } break; case OMP_CLAUSE__GRIDDIM_: if (ctx->outer) { scan_omp_op (&OMP_CLAUSE__GRIDDIM__SIZE (c), ctx->outer); scan_omp_op (&OMP_CLAUSE__GRIDDIM__GROUP (c), ctx->outer); } break; case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_MERGEABLE: case OMP_CLAUSE_PROC_BIND: case OMP_CLAUSE_SAFELEN: case OMP_CLAUSE_SIMDLEN: case OMP_CLAUSE_THREADS: case OMP_CLAUSE_SIMD: case OMP_CLAUSE_NOGROUP: case OMP_CLAUSE_DEFAULTMAP: case OMP_CLAUSE_ASYNC: case OMP_CLAUSE_WAIT: case OMP_CLAUSE_GANG: case OMP_CLAUSE_WORKER: case OMP_CLAUSE_VECTOR: case OMP_CLAUSE_INDEPENDENT: case OMP_CLAUSE_AUTO: case OMP_CLAUSE_SEQ: case OMP_CLAUSE_TILE: case OMP_CLAUSE__SIMT_: case OMP_CLAUSE_DEFAULT: break; case OMP_CLAUSE_ALIGNED: decl = OMP_CLAUSE_DECL (c); if (is_global_var (decl) && TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE) install_var_local (decl, ctx); break; case OMP_CLAUSE__CACHE_: default: gcc_unreachable (); } } for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_LASTPRIVATE: /* Let the corresponding firstprivate clause create the variable. */ if (OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)) scan_array_reductions = true; if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_LINEAR: case OMP_CLAUSE_IS_DEVICE_PTR: decl = OMP_CLAUSE_DECL (c); if (is_variable_sized (decl)) { if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IS_DEVICE_PTR) && is_gimple_omp_offloaded (ctx->stmt)) { tree decl2 = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (decl2) == INDIRECT_REF); decl2 = TREE_OPERAND (decl2, 0); gcc_assert (DECL_P (decl2)); install_var_local (decl2, ctx); fixup_remapped_decl (decl2, ctx, false); } install_var_local (decl, ctx); } fixup_remapped_decl (decl, ctx, OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE && OMP_CLAUSE_PRIVATE_DEBUG (c)); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR && OMP_CLAUSE_LINEAR_GIMPLE_SEQ (c)) scan_array_reductions = true; break; case OMP_CLAUSE_REDUCTION: decl = OMP_CLAUSE_DECL (c); if (TREE_CODE (decl) != MEM_REF) { if (is_variable_sized (decl)) install_var_local (decl, ctx); fixup_remapped_decl (decl, ctx, false); } if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) scan_array_reductions = true; break; case OMP_CLAUSE_SHARED: /* Ignore shared directives in teams construct. */ if (gimple_code (ctx->stmt) == GIMPLE_OMP_TEAMS) break; decl = OMP_CLAUSE_DECL (c); if (is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx))) break; if (OMP_CLAUSE_SHARED_FIRSTPRIVATE (c)) { if (is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx->outer))) break; bool by_ref = use_pointer_for_field (decl, ctx); install_var_field (decl, by_ref, 11, ctx); break; } fixup_remapped_decl (decl, ctx, false); break; case OMP_CLAUSE_MAP: if (!is_gimple_omp_offloaded (ctx->stmt)) break; decl = OMP_CLAUSE_DECL (c); if (DECL_P (decl) && ((OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FIRSTPRIVATE_POINTER && (OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FIRSTPRIVATE_REFERENCE)) || TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE) && is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx)) && varpool_node::get_create (decl)->offloadable) break; if (DECL_P (decl)) { if ((OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER || OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_POINTER) && TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE && !COMPLETE_TYPE_P (TREE_TYPE (decl))) { tree new_decl = lookup_decl (decl, ctx); TREE_TYPE (new_decl) = remap_type (TREE_TYPE (decl), &ctx->cb); } else if (DECL_SIZE (decl) && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST) { tree decl2 = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (decl2) == INDIRECT_REF); decl2 = TREE_OPERAND (decl2, 0); gcc_assert (DECL_P (decl2)); fixup_remapped_decl (decl2, ctx, false); fixup_remapped_decl (decl, ctx, true); } else fixup_remapped_decl (decl, ctx, false); } break; case OMP_CLAUSE_COPYPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_NUM_TEAMS: case OMP_CLAUSE_THREAD_LIMIT: case OMP_CLAUSE_DEVICE: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_DIST_SCHEDULE: case OMP_CLAUSE_NOWAIT: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_FINAL: case OMP_CLAUSE_MERGEABLE: case OMP_CLAUSE_PROC_BIND: case OMP_CLAUSE_SAFELEN: case OMP_CLAUSE_SIMDLEN: case OMP_CLAUSE_ALIGNED: case OMP_CLAUSE_DEPEND: case OMP_CLAUSE__LOOPTEMP_: case OMP_CLAUSE_TO: case OMP_CLAUSE_FROM: case OMP_CLAUSE_PRIORITY: case OMP_CLAUSE_GRAINSIZE: case OMP_CLAUSE_NUM_TASKS: case OMP_CLAUSE_THREADS: case OMP_CLAUSE_SIMD: case OMP_CLAUSE_NOGROUP: case OMP_CLAUSE_DEFAULTMAP: case OMP_CLAUSE_USE_DEVICE_PTR: case OMP_CLAUSE_ASYNC: case OMP_CLAUSE_WAIT: case OMP_CLAUSE_NUM_GANGS: case OMP_CLAUSE_NUM_WORKERS: case OMP_CLAUSE_VECTOR_LENGTH: case OMP_CLAUSE_GANG: case OMP_CLAUSE_WORKER: case OMP_CLAUSE_VECTOR: case OMP_CLAUSE_INDEPENDENT: case OMP_CLAUSE_AUTO: case OMP_CLAUSE_SEQ: case OMP_CLAUSE_TILE: case OMP_CLAUSE__GRIDDIM_: case OMP_CLAUSE__SIMT_: break; case OMP_CLAUSE__CACHE_: default: gcc_unreachable (); } } gcc_checking_assert (!scan_array_reductions || !is_gimple_omp_oacc (ctx->stmt)); if (scan_array_reductions) { for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { scan_omp (&OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c), ctx); scan_omp (&OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c), ctx); } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)) scan_omp (&OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c), ctx); else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR && OMP_CLAUSE_LINEAR_GIMPLE_SEQ (c)) scan_omp (&OMP_CLAUSE_LINEAR_GIMPLE_SEQ (c), ctx); } } /* Create a new name for omp child function. Returns an identifier. */ static tree create_omp_child_function_name (bool task_copy) { return clone_function_name (current_function_decl, task_copy ? "_omp_cpyfn" : "_omp_fn"); } /* Return true if CTX may belong to offloaded code: either if current function is offloaded, or any enclosing context corresponds to a target region. */ static bool omp_maybe_offloaded_ctx (omp_context *ctx) { if (cgraph_node::get (current_function_decl)->offloadable) return true; for (; ctx; ctx = ctx->outer) if (is_gimple_omp_offloaded (ctx->stmt)) return true; return false; } /* Build a decl for the omp child function. It'll not contain a body yet, just the bare decl. */ static void create_omp_child_function (omp_context *ctx, bool task_copy) { tree decl, type, name, t; name = create_omp_child_function_name (task_copy); if (task_copy) type = build_function_type_list (void_type_node, ptr_type_node, ptr_type_node, NULL_TREE); else type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE); decl = build_decl (gimple_location (ctx->stmt), FUNCTION_DECL, name, type); gcc_checking_assert (!is_gimple_omp_oacc (ctx->stmt) || !task_copy); if (!task_copy) ctx->cb.dst_fn = decl; else gimple_omp_task_set_copy_fn (ctx->stmt, decl); TREE_STATIC (decl) = 1; TREE_USED (decl) = 1; DECL_ARTIFICIAL (decl) = 1; DECL_IGNORED_P (decl) = 0; TREE_PUBLIC (decl) = 0; DECL_UNINLINABLE (decl) = 1; DECL_EXTERNAL (decl) = 0; DECL_CONTEXT (decl) = NULL_TREE; DECL_INITIAL (decl) = make_node (BLOCK); BLOCK_SUPERCONTEXT (DECL_INITIAL (decl)) = decl; DECL_ATTRIBUTES (decl) = DECL_ATTRIBUTES (current_function_decl); /* Remove omp declare simd attribute from the new attributes. */ if (tree a = lookup_attribute ("omp declare simd", DECL_ATTRIBUTES (decl))) { while (tree a2 = lookup_attribute ("omp declare simd", TREE_CHAIN (a))) a = a2; a = TREE_CHAIN (a); for (tree *p = &DECL_ATTRIBUTES (decl); *p != a;) if (is_attribute_p ("omp declare simd", get_attribute_name (*p))) *p = TREE_CHAIN (*p); else { tree chain = TREE_CHAIN (*p); *p = copy_node (*p); p = &TREE_CHAIN (*p); *p = chain; } } DECL_FUNCTION_SPECIFIC_OPTIMIZATION (decl) = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (current_function_decl); DECL_FUNCTION_SPECIFIC_TARGET (decl) = DECL_FUNCTION_SPECIFIC_TARGET (current_function_decl); DECL_FUNCTION_VERSIONED (decl) = DECL_FUNCTION_VERSIONED (current_function_decl); if (omp_maybe_offloaded_ctx (ctx)) { cgraph_node::get_create (decl)->offloadable = 1; if (ENABLE_OFFLOADING) g->have_offload = true; } if (cgraph_node::get_create (decl)->offloadable && !lookup_attribute ("omp declare target", DECL_ATTRIBUTES (current_function_decl))) { const char *target_attr = (is_gimple_omp_offloaded (ctx->stmt) ? "omp target entrypoint" : "omp declare target"); DECL_ATTRIBUTES (decl) = tree_cons (get_identifier (target_attr), NULL_TREE, DECL_ATTRIBUTES (decl)); } t = build_decl (DECL_SOURCE_LOCATION (decl), RESULT_DECL, NULL_TREE, void_type_node); DECL_ARTIFICIAL (t) = 1; DECL_IGNORED_P (t) = 1; DECL_CONTEXT (t) = decl; DECL_RESULT (decl) = t; tree data_name = get_identifier (".omp_data_i"); t = build_decl (DECL_SOURCE_LOCATION (decl), PARM_DECL, data_name, ptr_type_node); DECL_ARTIFICIAL (t) = 1; DECL_NAMELESS (t) = 1; DECL_ARG_TYPE (t) = ptr_type_node; DECL_CONTEXT (t) = current_function_decl; TREE_USED (t) = 1; TREE_READONLY (t) = 1; DECL_ARGUMENTS (decl) = t; if (!task_copy) ctx->receiver_decl = t; else { t = build_decl (DECL_SOURCE_LOCATION (decl), PARM_DECL, get_identifier (".omp_data_o"), ptr_type_node); DECL_ARTIFICIAL (t) = 1; DECL_NAMELESS (t) = 1; DECL_ARG_TYPE (t) = ptr_type_node; DECL_CONTEXT (t) = current_function_decl; TREE_USED (t) = 1; TREE_ADDRESSABLE (t) = 1; DECL_CHAIN (t) = DECL_ARGUMENTS (decl); DECL_ARGUMENTS (decl) = t; } /* Allocate memory for the function structure. The call to allocate_struct_function clobbers CFUN, so we need to restore it afterward. */ push_struct_function (decl); cfun->function_end_locus = gimple_location (ctx->stmt); init_tree_ssa (cfun); pop_cfun (); } /* Callback for walk_gimple_seq. Check if combined parallel contains gimple_omp_for_combined_into_p OMP_FOR. */ tree omp_find_combined_for (gimple_stmt_iterator *gsi_p, bool *handled_ops_p, struct walk_stmt_info *wi) { gimple *stmt = gsi_stmt (*gsi_p); *handled_ops_p = true; switch (gimple_code (stmt)) { WALK_SUBSTMTS; case GIMPLE_OMP_FOR: if (gimple_omp_for_combined_into_p (stmt) && gimple_omp_for_kind (stmt) == *(const enum gf_mask *) (wi->info)) { wi->info = stmt; return integer_zero_node; } break; default: break; } return NULL; } /* Add _LOOPTEMP_ clauses on OpenMP parallel or task. */ static void add_taskreg_looptemp_clauses (enum gf_mask msk, gimple *stmt, omp_context *outer_ctx) { struct walk_stmt_info wi; memset (&wi, 0, sizeof (wi)); wi.val_only = true; wi.info = (void *) &msk; walk_gimple_seq (gimple_omp_body (stmt), omp_find_combined_for, NULL, &wi); if (wi.info != (void *) &msk) { gomp_for *for_stmt = as_a <gomp_for *> ((gimple *) wi.info); struct omp_for_data fd; omp_extract_for_data (for_stmt, &fd, NULL); /* We need two temporaries with fd.loop.v type (istart/iend) and then (fd.collapse - 1) temporaries with the same type for count2 ... countN-1 vars if not constant. */ size_t count = 2, i; tree type = fd.iter_type; if (fd.collapse > 1 && TREE_CODE (fd.loop.n2) != INTEGER_CST) { count += fd.collapse - 1; /* If there are lastprivate clauses on the inner GIMPLE_OMP_FOR, add one more temporaries for the total number of iterations (product of count1 ... countN-1). */ if (omp_find_clause (gimple_omp_for_clauses (for_stmt), OMP_CLAUSE_LASTPRIVATE)) count++; else if (msk == GF_OMP_FOR_KIND_FOR && omp_find_clause (gimple_omp_parallel_clauses (stmt), OMP_CLAUSE_LASTPRIVATE)) count++; } for (i = 0; i < count; i++) { tree temp = create_tmp_var (type); tree c = build_omp_clause (UNKNOWN_LOCATION, OMP_CLAUSE__LOOPTEMP_); insert_decl_map (&outer_ctx->cb, temp, temp); OMP_CLAUSE_DECL (c) = temp; OMP_CLAUSE_CHAIN (c) = gimple_omp_taskreg_clauses (stmt); gimple_omp_taskreg_set_clauses (stmt, c); } } } /* Scan an OpenMP parallel directive. */ static void scan_omp_parallel (gimple_stmt_iterator *gsi, omp_context *outer_ctx) { omp_context *ctx; tree name; gomp_parallel *stmt = as_a <gomp_parallel *> (gsi_stmt (*gsi)); /* Ignore parallel directives with empty bodies, unless there are copyin clauses. */ if (optimize > 0 && empty_body_p (gimple_omp_body (stmt)) && omp_find_clause (gimple_omp_parallel_clauses (stmt), OMP_CLAUSE_COPYIN) == NULL) { gsi_replace (gsi, gimple_build_nop (), false); return; } if (gimple_omp_parallel_combined_p (stmt)) add_taskreg_looptemp_clauses (GF_OMP_FOR_KIND_FOR, stmt, outer_ctx); ctx = new_omp_context (stmt, outer_ctx); taskreg_contexts.safe_push (ctx); if (taskreg_nesting_level > 1) ctx->is_nested = true; ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_data_s"); name = build_decl (gimple_location (stmt), TYPE_DECL, name, ctx->record_type); DECL_ARTIFICIAL (name) = 1; DECL_NAMELESS (name) = 1; TYPE_NAME (ctx->record_type) = name; TYPE_ARTIFICIAL (ctx->record_type) = 1; if (!gimple_omp_parallel_grid_phony (stmt)) { create_omp_child_function (ctx, false); gimple_omp_parallel_set_child_fn (stmt, ctx->cb.dst_fn); } scan_sharing_clauses (gimple_omp_parallel_clauses (stmt), ctx); scan_omp (gimple_omp_body_ptr (stmt), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) ctx->record_type = ctx->receiver_decl = NULL; } /* Scan an OpenMP task directive. */ static void scan_omp_task (gimple_stmt_iterator *gsi, omp_context *outer_ctx) { omp_context *ctx; tree name, t; gomp_task *stmt = as_a <gomp_task *> (gsi_stmt (*gsi)); /* Ignore task directives with empty bodies, unless they have depend clause. */ if (optimize > 0 && empty_body_p (gimple_omp_body (stmt)) && !omp_find_clause (gimple_omp_task_clauses (stmt), OMP_CLAUSE_DEPEND)) { gsi_replace (gsi, gimple_build_nop (), false); return; } if (gimple_omp_task_taskloop_p (stmt)) add_taskreg_looptemp_clauses (GF_OMP_FOR_KIND_TASKLOOP, stmt, outer_ctx); ctx = new_omp_context (stmt, outer_ctx); taskreg_contexts.safe_push (ctx); if (taskreg_nesting_level > 1) ctx->is_nested = true; ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_data_s"); name = build_decl (gimple_location (stmt), TYPE_DECL, name, ctx->record_type); DECL_ARTIFICIAL (name) = 1; DECL_NAMELESS (name) = 1; TYPE_NAME (ctx->record_type) = name; TYPE_ARTIFICIAL (ctx->record_type) = 1; create_omp_child_function (ctx, false); gimple_omp_task_set_child_fn (stmt, ctx->cb.dst_fn); scan_sharing_clauses (gimple_omp_task_clauses (stmt), ctx); if (ctx->srecord_type) { name = create_tmp_var_name (".omp_data_a"); name = build_decl (gimple_location (stmt), TYPE_DECL, name, ctx->srecord_type); DECL_ARTIFICIAL (name) = 1; DECL_NAMELESS (name) = 1; TYPE_NAME (ctx->srecord_type) = name; TYPE_ARTIFICIAL (ctx->srecord_type) = 1; create_omp_child_function (ctx, true); } scan_omp (gimple_omp_body_ptr (stmt), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) { ctx->record_type = ctx->receiver_decl = NULL; t = build_int_cst (long_integer_type_node, 0); gimple_omp_task_set_arg_size (stmt, t); t = build_int_cst (long_integer_type_node, 1); gimple_omp_task_set_arg_align (stmt, t); } } /* Helper function for finish_taskreg_scan, called through walk_tree. If maybe_lookup_decl_in_outer_context returns non-NULL for some tree, replace it in the expression. */ static tree finish_taskreg_remap (tree *tp, int *walk_subtrees, void *data) { if (VAR_P (*tp)) { omp_context *ctx = (omp_context *) data; tree t = maybe_lookup_decl_in_outer_ctx (*tp, ctx); if (t != *tp) { if (DECL_HAS_VALUE_EXPR_P (t)) t = unshare_expr (DECL_VALUE_EXPR (t)); *tp = t; } *walk_subtrees = 0; } else if (IS_TYPE_OR_DECL_P (*tp)) *walk_subtrees = 0; return NULL_TREE; } /* If any decls have been made addressable during scan_omp, adjust their fields if needed, and layout record types of parallel/task constructs. */ static void finish_taskreg_scan (omp_context *ctx) { if (ctx->record_type == NULL_TREE) return; /* If any task_shared_vars were needed, verify all OMP_CLAUSE_SHARED clauses on GIMPLE_OMP_{PARALLEL,TASK} statements if use_pointer_for_field hasn't changed because of that. If it did, update field types now. */ if (task_shared_vars) { tree c; for (c = gimple_omp_taskreg_clauses (ctx->stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED && !OMP_CLAUSE_SHARED_FIRSTPRIVATE (c)) { tree decl = OMP_CLAUSE_DECL (c); /* Global variables don't need to be copied, the receiver side will use them directly. */ if (is_global_var (maybe_lookup_decl_in_outer_ctx (decl, ctx))) continue; if (!bitmap_bit_p (task_shared_vars, DECL_UID (decl)) || !use_pointer_for_field (decl, ctx)) continue; tree field = lookup_field (decl, ctx); if (TREE_CODE (TREE_TYPE (field)) == POINTER_TYPE && TREE_TYPE (TREE_TYPE (field)) == TREE_TYPE (decl)) continue; TREE_TYPE (field) = build_pointer_type (TREE_TYPE (decl)); TREE_THIS_VOLATILE (field) = 0; DECL_USER_ALIGN (field) = 0; SET_DECL_ALIGN (field, TYPE_ALIGN (TREE_TYPE (field))); if (TYPE_ALIGN (ctx->record_type) < DECL_ALIGN (field)) SET_TYPE_ALIGN (ctx->record_type, DECL_ALIGN (field)); if (ctx->srecord_type) { tree sfield = lookup_sfield (decl, ctx); TREE_TYPE (sfield) = TREE_TYPE (field); TREE_THIS_VOLATILE (sfield) = 0; DECL_USER_ALIGN (sfield) = 0; SET_DECL_ALIGN (sfield, DECL_ALIGN (field)); if (TYPE_ALIGN (ctx->srecord_type) < DECL_ALIGN (sfield)) SET_TYPE_ALIGN (ctx->srecord_type, DECL_ALIGN (sfield)); } } } if (gimple_code (ctx->stmt) == GIMPLE_OMP_PARALLEL) { layout_type (ctx->record_type); fixup_child_record_type (ctx); } else { location_t loc = gimple_location (ctx->stmt); tree *p, vla_fields = NULL_TREE, *q = &vla_fields; /* Move VLA fields to the end. */ p = &TYPE_FIELDS (ctx->record_type); while (*p) if (!TYPE_SIZE_UNIT (TREE_TYPE (*p)) || ! TREE_CONSTANT (TYPE_SIZE_UNIT (TREE_TYPE (*p)))) { *q = *p; *p = TREE_CHAIN (*p); TREE_CHAIN (*q) = NULL_TREE; q = &TREE_CHAIN (*q); } else p = &DECL_CHAIN (*p); *p = vla_fields; if (gimple_omp_task_taskloop_p (ctx->stmt)) { /* Move fields corresponding to first and second _looptemp_ clause first. There are filled by GOMP_taskloop and thus need to be in specific positions. */ tree c1 = gimple_omp_task_clauses (ctx->stmt); c1 = omp_find_clause (c1, OMP_CLAUSE__LOOPTEMP_); tree c2 = omp_find_clause (OMP_CLAUSE_CHAIN (c1), OMP_CLAUSE__LOOPTEMP_); tree f1 = lookup_field (OMP_CLAUSE_DECL (c1), ctx); tree f2 = lookup_field (OMP_CLAUSE_DECL (c2), ctx); p = &TYPE_FIELDS (ctx->record_type); while (*p) if (*p == f1 || *p == f2) *p = DECL_CHAIN (*p); else p = &DECL_CHAIN (*p); DECL_CHAIN (f1) = f2; DECL_CHAIN (f2) = TYPE_FIELDS (ctx->record_type); TYPE_FIELDS (ctx->record_type) = f1; if (ctx->srecord_type) { f1 = lookup_sfield (OMP_CLAUSE_DECL (c1), ctx); f2 = lookup_sfield (OMP_CLAUSE_DECL (c2), ctx); p = &TYPE_FIELDS (ctx->srecord_type); while (*p) if (*p == f1 || *p == f2) *p = DECL_CHAIN (*p); else p = &DECL_CHAIN (*p); DECL_CHAIN (f1) = f2; DECL_CHAIN (f2) = TYPE_FIELDS (ctx->srecord_type); TYPE_FIELDS (ctx->srecord_type) = f1; } } layout_type (ctx->record_type); fixup_child_record_type (ctx); if (ctx->srecord_type) layout_type (ctx->srecord_type); tree t = fold_convert_loc (loc, long_integer_type_node, TYPE_SIZE_UNIT (ctx->record_type)); if (TREE_CODE (t) != INTEGER_CST) { t = unshare_expr (t); walk_tree (&t, finish_taskreg_remap, ctx, NULL); } gimple_omp_task_set_arg_size (ctx->stmt, t); t = build_int_cst (long_integer_type_node, TYPE_ALIGN_UNIT (ctx->record_type)); gimple_omp_task_set_arg_align (ctx->stmt, t); } } /* Find the enclosing offload context. */ static omp_context * enclosing_target_ctx (omp_context *ctx) { for (; ctx; ctx = ctx->outer) if (gimple_code (ctx->stmt) == GIMPLE_OMP_TARGET) break; return ctx; } /* Return true if ctx is part of an oacc kernels region. */ static bool ctx_in_oacc_kernels_region (omp_context *ctx) { for (;ctx != NULL; ctx = ctx->outer) { gimple *stmt = ctx->stmt; if (gimple_code (stmt) == GIMPLE_OMP_TARGET && gimple_omp_target_kind (stmt) == GF_OMP_TARGET_KIND_OACC_KERNELS) return true; } return false; } /* Check the parallelism clauses inside a kernels regions. Until kernels handling moves to use the same loop indirection scheme as parallel, we need to do this checking early. */ static unsigned check_oacc_kernel_gwv (gomp_for *stmt, omp_context *ctx) { bool checking = true; unsigned outer_mask = 0; unsigned this_mask = 0; bool has_seq = false, has_auto = false; if (ctx->outer) outer_mask = check_oacc_kernel_gwv (NULL, ctx->outer); if (!stmt) { checking = false; if (gimple_code (ctx->stmt) != GIMPLE_OMP_FOR) return outer_mask; stmt = as_a <gomp_for *> (ctx->stmt); } for (tree c = gimple_omp_for_clauses (stmt); c; c = OMP_CLAUSE_CHAIN (c)) { switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_GANG: this_mask |= GOMP_DIM_MASK (GOMP_DIM_GANG); break; case OMP_CLAUSE_WORKER: this_mask |= GOMP_DIM_MASK (GOMP_DIM_WORKER); break; case OMP_CLAUSE_VECTOR: this_mask |= GOMP_DIM_MASK (GOMP_DIM_VECTOR); break; case OMP_CLAUSE_SEQ: has_seq = true; break; case OMP_CLAUSE_AUTO: has_auto = true; break; default: break; } } if (checking) { if (has_seq && (this_mask || has_auto)) error_at (gimple_location (stmt), "%<seq%> overrides other" " OpenACC loop specifiers"); else if (has_auto && this_mask) error_at (gimple_location (stmt), "%<auto%> conflicts with other" " OpenACC loop specifiers"); if (this_mask & outer_mask) error_at (gimple_location (stmt), "inner loop uses same" " OpenACC parallelism as containing loop"); } return outer_mask | this_mask; } /* Scan a GIMPLE_OMP_FOR. */ static omp_context * scan_omp_for (gomp_for *stmt, omp_context *outer_ctx) { omp_context *ctx; size_t i; tree clauses = gimple_omp_for_clauses (stmt); ctx = new_omp_context (stmt, outer_ctx); if (is_gimple_omp_oacc (stmt)) { omp_context *tgt = enclosing_target_ctx (outer_ctx); if (!tgt || is_oacc_parallel (tgt)) for (tree c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { char const *check = NULL; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_GANG: check = "gang"; break; case OMP_CLAUSE_WORKER: check = "worker"; break; case OMP_CLAUSE_VECTOR: check = "vector"; break; default: break; } if (check && OMP_CLAUSE_OPERAND (c, 0)) error_at (gimple_location (stmt), "argument not permitted on %qs clause in" " OpenACC %<parallel%>", check); } if (tgt && is_oacc_kernels (tgt)) { /* Strip out reductions, as they are not handled yet. */ tree *prev_ptr = &clauses; while (tree probe = *prev_ptr) { tree *next_ptr = &OMP_CLAUSE_CHAIN (probe); if (OMP_CLAUSE_CODE (probe) == OMP_CLAUSE_REDUCTION) *prev_ptr = *next_ptr; else prev_ptr = next_ptr; } gimple_omp_for_set_clauses (stmt, clauses); check_oacc_kernel_gwv (stmt, ctx); } } scan_sharing_clauses (clauses, ctx); scan_omp (gimple_omp_for_pre_body_ptr (stmt), ctx); for (i = 0; i < gimple_omp_for_collapse (stmt); i++) { scan_omp_op (gimple_omp_for_index_ptr (stmt, i), ctx); scan_omp_op (gimple_omp_for_initial_ptr (stmt, i), ctx); scan_omp_op (gimple_omp_for_final_ptr (stmt, i), ctx); scan_omp_op (gimple_omp_for_incr_ptr (stmt, i), ctx); } scan_omp (gimple_omp_body_ptr (stmt), ctx); return ctx; } /* Duplicate #pragma omp simd, one for SIMT, another one for SIMD. */ static void scan_omp_simd (gimple_stmt_iterator *gsi, gomp_for *stmt, omp_context *outer_ctx) { gbind *bind = gimple_build_bind (NULL, NULL, NULL); gsi_replace (gsi, bind, false); gimple_seq seq = NULL; gimple *g = gimple_build_call_internal (IFN_GOMP_USE_SIMT, 0); tree cond = create_tmp_var_raw (integer_type_node); DECL_CONTEXT (cond) = current_function_decl; DECL_SEEN_IN_BIND_EXPR_P (cond) = 1; gimple_bind_set_vars (bind, cond); gimple_call_set_lhs (g, cond); gimple_seq_add_stmt (&seq, g); tree lab1 = create_artificial_label (UNKNOWN_LOCATION); tree lab2 = create_artificial_label (UNKNOWN_LOCATION); tree lab3 = create_artificial_label (UNKNOWN_LOCATION); g = gimple_build_cond (NE_EXPR, cond, integer_zero_node, lab1, lab2); gimple_seq_add_stmt (&seq, g); g = gimple_build_label (lab1); gimple_seq_add_stmt (&seq, g); gimple_seq new_seq = copy_gimple_seq_and_replace_locals (stmt); gomp_for *new_stmt = as_a <gomp_for *> (new_seq); tree clause = build_omp_clause (gimple_location (stmt), OMP_CLAUSE__SIMT_); OMP_CLAUSE_CHAIN (clause) = gimple_omp_for_clauses (new_stmt); gimple_omp_for_set_clauses (new_stmt, clause); gimple_seq_add_stmt (&seq, new_stmt); g = gimple_build_goto (lab3); gimple_seq_add_stmt (&seq, g); g = gimple_build_label (lab2); gimple_seq_add_stmt (&seq, g); gimple_seq_add_stmt (&seq, stmt); g = gimple_build_label (lab3); gimple_seq_add_stmt (&seq, g); gimple_bind_set_body (bind, seq); update_stmt (bind); scan_omp_for (new_stmt, outer_ctx); scan_omp_for (stmt, outer_ctx)->simt_stmt = new_stmt; } /* Scan an OpenMP sections directive. */ static void scan_omp_sections (gomp_sections *stmt, omp_context *outer_ctx) { omp_context *ctx; ctx = new_omp_context (stmt, outer_ctx); scan_sharing_clauses (gimple_omp_sections_clauses (stmt), ctx); scan_omp (gimple_omp_body_ptr (stmt), ctx); } /* Scan an OpenMP single directive. */ static void scan_omp_single (gomp_single *stmt, omp_context *outer_ctx) { omp_context *ctx; tree name; ctx = new_omp_context (stmt, outer_ctx); ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_copy_s"); name = build_decl (gimple_location (stmt), TYPE_DECL, name, ctx->record_type); TYPE_NAME (ctx->record_type) = name; scan_sharing_clauses (gimple_omp_single_clauses (stmt), ctx); scan_omp (gimple_omp_body_ptr (stmt), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) ctx->record_type = NULL; else layout_type (ctx->record_type); } /* Return true if the CLAUSES of an omp target guarantee that the base pointers used in the corresponding offloaded function are restrict. */ static bool omp_target_base_pointers_restrict_p (tree clauses) { /* The analysis relies on the GOMP_MAP_FORCE_* mapping kinds, which are only used by OpenACC. */ if (flag_openacc == 0) return false; /* I. Basic example: void foo (void) { unsigned int a[2], b[2]; #pragma acc kernels \ copyout (a) \ copyout (b) { a[0] = 0; b[0] = 1; } } After gimplification, we have: #pragma omp target oacc_kernels \ map(force_from:a [len: 8]) \ map(force_from:b [len: 8]) { a[0] = 0; b[0] = 1; } Because both mappings have the force prefix, we know that they will be allocated when calling the corresponding offloaded function, which means we can mark the base pointers for a and b in the offloaded function as restrict. */ tree c; for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) return false; switch (OMP_CLAUSE_MAP_KIND (c)) { case GOMP_MAP_FORCE_ALLOC: case GOMP_MAP_FORCE_TO: case GOMP_MAP_FORCE_FROM: case GOMP_MAP_FORCE_TOFROM: break; default: return false; } } return true; } /* Scan a GIMPLE_OMP_TARGET. */ static void scan_omp_target (gomp_target *stmt, omp_context *outer_ctx) { omp_context *ctx; tree name; bool offloaded = is_gimple_omp_offloaded (stmt); tree clauses = gimple_omp_target_clauses (stmt); ctx = new_omp_context (stmt, outer_ctx); ctx->field_map = splay_tree_new (splay_tree_compare_pointers, 0, 0); ctx->record_type = lang_hooks.types.make_type (RECORD_TYPE); name = create_tmp_var_name (".omp_data_t"); name = build_decl (gimple_location (stmt), TYPE_DECL, name, ctx->record_type); DECL_ARTIFICIAL (name) = 1; DECL_NAMELESS (name) = 1; TYPE_NAME (ctx->record_type) = name; TYPE_ARTIFICIAL (ctx->record_type) = 1; bool base_pointers_restrict = false; if (offloaded) { create_omp_child_function (ctx, false); gimple_omp_target_set_child_fn (stmt, ctx->cb.dst_fn); base_pointers_restrict = omp_target_base_pointers_restrict_p (clauses); if (base_pointers_restrict && dump_file && (dump_flags & TDF_DETAILS)) fprintf (dump_file, "Base pointers in offloaded function are restrict\n"); } scan_sharing_clauses (clauses, ctx, base_pointers_restrict); scan_omp (gimple_omp_body_ptr (stmt), ctx); if (TYPE_FIELDS (ctx->record_type) == NULL) ctx->record_type = ctx->receiver_decl = NULL; else { TYPE_FIELDS (ctx->record_type) = nreverse (TYPE_FIELDS (ctx->record_type)); if (flag_checking) { unsigned int align = DECL_ALIGN (TYPE_FIELDS (ctx->record_type)); for (tree field = TYPE_FIELDS (ctx->record_type); field; field = DECL_CHAIN (field)) gcc_assert (DECL_ALIGN (field) == align); } layout_type (ctx->record_type); if (offloaded) fixup_child_record_type (ctx); } } /* Scan an OpenMP teams directive. */ static void scan_omp_teams (gomp_teams *stmt, omp_context *outer_ctx) { omp_context *ctx = new_omp_context (stmt, outer_ctx); scan_sharing_clauses (gimple_omp_teams_clauses (stmt), ctx); scan_omp (gimple_omp_body_ptr (stmt), ctx); } /* Check nesting restrictions. */ static bool check_omp_nesting_restrictions (gimple *stmt, omp_context *ctx) { tree c; if (ctx && gimple_code (ctx->stmt) == GIMPLE_OMP_GRID_BODY) /* GRID_BODY is an artificial construct, nesting rules will be checked in the original copy of its contents. */ return true; /* No nesting of non-OpenACC STMT (that is, an OpenMP one, or a GOMP builtin) inside an OpenACC CTX. */ if (!(is_gimple_omp (stmt) && is_gimple_omp_oacc (stmt)) /* Except for atomic codes that we share with OpenMP. */ && !(gimple_code (stmt) == GIMPLE_OMP_ATOMIC_LOAD || gimple_code (stmt) == GIMPLE_OMP_ATOMIC_STORE)) { if (oacc_get_fn_attrib (cfun->decl) != NULL) { error_at (gimple_location (stmt), "non-OpenACC construct inside of OpenACC routine"); return false; } else for (omp_context *octx = ctx; octx != NULL; octx = octx->outer) if (is_gimple_omp (octx->stmt) && is_gimple_omp_oacc (octx->stmt)) { error_at (gimple_location (stmt), "non-OpenACC construct inside of OpenACC region"); return false; } } if (ctx != NULL) { if (gimple_code (ctx->stmt) == GIMPLE_OMP_FOR && gimple_omp_for_kind (ctx->stmt) & GF_OMP_FOR_SIMD) { c = NULL_TREE; if (gimple_code (stmt) == GIMPLE_OMP_ORDERED) { c = gimple_omp_ordered_clauses (as_a <gomp_ordered *> (stmt)); if (omp_find_clause (c, OMP_CLAUSE_SIMD)) { if (omp_find_clause (c, OMP_CLAUSE_THREADS) && (ctx->outer == NULL || !gimple_omp_for_combined_into_p (ctx->stmt) || gimple_code (ctx->outer->stmt) != GIMPLE_OMP_FOR || (gimple_omp_for_kind (ctx->outer->stmt) != GF_OMP_FOR_KIND_FOR) || !gimple_omp_for_combined_p (ctx->outer->stmt))) { error_at (gimple_location (stmt), "%<ordered simd threads%> must be closely " "nested inside of %<for simd%> region"); return false; } return true; } } error_at (gimple_location (stmt), "OpenMP constructs other than %<#pragma omp ordered simd%>" " may not be nested inside %<simd%> region"); return false; } else if (gimple_code (ctx->stmt) == GIMPLE_OMP_TEAMS) { if ((gimple_code (stmt) != GIMPLE_OMP_FOR || ((gimple_omp_for_kind (stmt) != GF_OMP_FOR_KIND_DISTRIBUTE) && (gimple_omp_for_kind (stmt) != GF_OMP_FOR_KIND_GRID_LOOP))) && gimple_code (stmt) != GIMPLE_OMP_PARALLEL) { error_at (gimple_location (stmt), "only %<distribute%> or %<parallel%> regions are " "allowed to be strictly nested inside %<teams%> " "region"); return false; } } } switch (gimple_code (stmt)) { case GIMPLE_OMP_FOR: if (gimple_omp_for_kind (stmt) & GF_OMP_FOR_SIMD) return true; if (gimple_omp_for_kind (stmt) == GF_OMP_FOR_KIND_DISTRIBUTE) { if (ctx != NULL && gimple_code (ctx->stmt) != GIMPLE_OMP_TEAMS) { error_at (gimple_location (stmt), "%<distribute%> region must be strictly nested " "inside %<teams%> construct"); return false; } return true; } /* We split taskloop into task and nested taskloop in it. */ if (gimple_omp_for_kind (stmt) == GF_OMP_FOR_KIND_TASKLOOP) return true; if (gimple_omp_for_kind (stmt) == GF_OMP_FOR_KIND_OACC_LOOP) { bool ok = false; if (ctx) switch (gimple_code (ctx->stmt)) { case GIMPLE_OMP_FOR: ok = (gimple_omp_for_kind (ctx->stmt) == GF_OMP_FOR_KIND_OACC_LOOP); break; case GIMPLE_OMP_TARGET: switch (gimple_omp_target_kind (ctx->stmt)) { case GF_OMP_TARGET_KIND_OACC_PARALLEL: case GF_OMP_TARGET_KIND_OACC_KERNELS: ok = true; break; default: break; } default: break; } else if (oacc_get_fn_attrib (current_function_decl)) ok = true; if (!ok) { error_at (gimple_location (stmt), "OpenACC loop directive must be associated with" " an OpenACC compute region"); return false; } } /* FALLTHRU */ case GIMPLE_CALL: if (is_gimple_call (stmt) && (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_GOMP_CANCEL || DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_GOMP_CANCELLATION_POINT)) { const char *bad = NULL; const char *kind = NULL; const char *construct = (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_GOMP_CANCEL) ? "#pragma omp cancel" : "#pragma omp cancellation point"; if (ctx == NULL) { error_at (gimple_location (stmt), "orphaned %qs construct", construct); return false; } switch (tree_fits_shwi_p (gimple_call_arg (stmt, 0)) ? tree_to_shwi (gimple_call_arg (stmt, 0)) : 0) { case 1: if (gimple_code (ctx->stmt) != GIMPLE_OMP_PARALLEL) bad = "#pragma omp parallel"; else if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_GOMP_CANCEL && !integer_zerop (gimple_call_arg (stmt, 1))) ctx->cancellable = true; kind = "parallel"; break; case 2: if (gimple_code (ctx->stmt) != GIMPLE_OMP_FOR || gimple_omp_for_kind (ctx->stmt) != GF_OMP_FOR_KIND_FOR) bad = "#pragma omp for"; else if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_GOMP_CANCEL && !integer_zerop (gimple_call_arg (stmt, 1))) { ctx->cancellable = true; if (omp_find_clause (gimple_omp_for_clauses (ctx->stmt), OMP_CLAUSE_NOWAIT)) warning_at (gimple_location (stmt), 0, "%<#pragma omp cancel for%> inside " "%<nowait%> for construct"); if (omp_find_clause (gimple_omp_for_clauses (ctx->stmt), OMP_CLAUSE_ORDERED)) warning_at (gimple_location (stmt), 0, "%<#pragma omp cancel for%> inside " "%<ordered%> for construct"); } kind = "for"; break; case 4: if (gimple_code (ctx->stmt) != GIMPLE_OMP_SECTIONS && gimple_code (ctx->stmt) != GIMPLE_OMP_SECTION) bad = "#pragma omp sections"; else if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) == BUILT_IN_GOMP_CANCEL && !integer_zerop (gimple_call_arg (stmt, 1))) { if (gimple_code (ctx->stmt) == GIMPLE_OMP_SECTIONS) { ctx->cancellable = true; if (omp_find_clause (gimple_omp_sections_clauses (ctx->stmt), OMP_CLAUSE_NOWAIT)) warning_at (gimple_location (stmt), 0, "%<#pragma omp cancel sections%> inside " "%<nowait%> sections construct"); } else { gcc_assert (ctx->outer && gimple_code (ctx->outer->stmt) == GIMPLE_OMP_SECTIONS); ctx->outer->cancellable = true; if (omp_find_clause (gimple_omp_sections_clauses (ctx->outer->stmt), OMP_CLAUSE_NOWAIT)) warning_at (gimple_location (stmt), 0, "%<#pragma omp cancel sections%> inside " "%<nowait%> sections construct"); } } kind = "sections"; break; case 8: if (gimple_code (ctx->stmt) != GIMPLE_OMP_TASK) bad = "#pragma omp task"; else { for (omp_context *octx = ctx->outer; octx; octx = octx->outer) { switch (gimple_code (octx->stmt)) { case GIMPLE_OMP_TASKGROUP: break; case GIMPLE_OMP_TARGET: if (gimple_omp_target_kind (octx->stmt) != GF_OMP_TARGET_KIND_REGION) continue; /* FALLTHRU */ case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TEAMS: error_at (gimple_location (stmt), "%<%s taskgroup%> construct not closely " "nested inside of %<taskgroup%> region", construct); return false; default: continue; } break; } ctx->cancellable = true; } kind = "taskgroup"; break; default: error_at (gimple_location (stmt), "invalid arguments"); return false; } if (bad) { error_at (gimple_location (stmt), "%<%s %s%> construct not closely nested inside of %qs", construct, kind, bad); return false; } } /* FALLTHRU */ case GIMPLE_OMP_SECTIONS: case GIMPLE_OMP_SINGLE: for (; ctx != NULL; ctx = ctx->outer) switch (gimple_code (ctx->stmt)) { case GIMPLE_OMP_FOR: if (gimple_omp_for_kind (ctx->stmt) != GF_OMP_FOR_KIND_FOR && gimple_omp_for_kind (ctx->stmt) != GF_OMP_FOR_KIND_TASKLOOP) break; /* FALLTHRU */ case GIMPLE_OMP_SECTIONS: case GIMPLE_OMP_SINGLE: case GIMPLE_OMP_ORDERED: case GIMPLE_OMP_MASTER: case GIMPLE_OMP_TASK: case GIMPLE_OMP_CRITICAL: if (is_gimple_call (stmt)) { if (DECL_FUNCTION_CODE (gimple_call_fndecl (stmt)) != BUILT_IN_GOMP_BARRIER) return true; error_at (gimple_location (stmt), "barrier region may not be closely nested inside " "of work-sharing, %<critical%>, %<ordered%>, " "%<master%>, explicit %<task%> or %<taskloop%> " "region"); return false; } error_at (gimple_location (stmt), "work-sharing region may not be closely nested inside " "of work-sharing, %<critical%>, %<ordered%>, " "%<master%>, explicit %<task%> or %<taskloop%> region"); return false; case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TEAMS: return true; case GIMPLE_OMP_TARGET: if (gimple_omp_target_kind (ctx->stmt) == GF_OMP_TARGET_KIND_REGION) return true; break; default: break; } break; case GIMPLE_OMP_MASTER: for (; ctx != NULL; ctx = ctx->outer) switch (gimple_code (ctx->stmt)) { case GIMPLE_OMP_FOR: if (gimple_omp_for_kind (ctx->stmt) != GF_OMP_FOR_KIND_FOR && gimple_omp_for_kind (ctx->stmt) != GF_OMP_FOR_KIND_TASKLOOP) break; /* FALLTHRU */ case GIMPLE_OMP_SECTIONS: case GIMPLE_OMP_SINGLE: case GIMPLE_OMP_TASK: error_at (gimple_location (stmt), "%<master%> region may not be closely nested inside " "of work-sharing, explicit %<task%> or %<taskloop%> " "region"); return false; case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TEAMS: return true; case GIMPLE_OMP_TARGET: if (gimple_omp_target_kind (ctx->stmt) == GF_OMP_TARGET_KIND_REGION) return true; break; default: break; } break; case GIMPLE_OMP_TASK: for (c = gimple_omp_task_clauses (stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND && (OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_SOURCE || OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_SINK)) { enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_KIND (c); error_at (OMP_CLAUSE_LOCATION (c), "%<depend(%s)%> is only allowed in %<omp ordered%>", kind == OMP_CLAUSE_DEPEND_SOURCE ? "source" : "sink"); return false; } break; case GIMPLE_OMP_ORDERED: for (c = gimple_omp_ordered_clauses (as_a <gomp_ordered *> (stmt)); c; c = OMP_CLAUSE_CHAIN (c)) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND) { gcc_assert (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREADS || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SIMD); continue; } enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_KIND (c); if (kind == OMP_CLAUSE_DEPEND_SOURCE || kind == OMP_CLAUSE_DEPEND_SINK) { tree oclause; /* Look for containing ordered(N) loop. */ if (ctx == NULL || gimple_code (ctx->stmt) != GIMPLE_OMP_FOR || (oclause = omp_find_clause (gimple_omp_for_clauses (ctx->stmt), OMP_CLAUSE_ORDERED)) == NULL_TREE) { error_at (OMP_CLAUSE_LOCATION (c), "%<ordered%> construct with %<depend%> clause " "must be closely nested inside an %<ordered%> " "loop"); return false; } else if (OMP_CLAUSE_ORDERED_EXPR (oclause) == NULL_TREE) { error_at (OMP_CLAUSE_LOCATION (c), "%<ordered%> construct with %<depend%> clause " "must be closely nested inside a loop with " "%<ordered%> clause with a parameter"); return false; } } else { error_at (OMP_CLAUSE_LOCATION (c), "invalid depend kind in omp %<ordered%> %<depend%>"); return false; } } c = gimple_omp_ordered_clauses (as_a <gomp_ordered *> (stmt)); if (omp_find_clause (c, OMP_CLAUSE_SIMD)) { /* ordered simd must be closely nested inside of simd region, and simd region must not encounter constructs other than ordered simd, therefore ordered simd may be either orphaned, or ctx->stmt must be simd. The latter case is handled already earlier. */ if (ctx != NULL) { error_at (gimple_location (stmt), "%<ordered%> %<simd%> must be closely nested inside " "%<simd%> region"); return false; } } for (; ctx != NULL; ctx = ctx->outer) switch (gimple_code (ctx->stmt)) { case GIMPLE_OMP_CRITICAL: case GIMPLE_OMP_TASK: case GIMPLE_OMP_ORDERED: ordered_in_taskloop: error_at (gimple_location (stmt), "%<ordered%> region may not be closely nested inside " "of %<critical%>, %<ordered%>, explicit %<task%> or " "%<taskloop%> region"); return false; case GIMPLE_OMP_FOR: if (gimple_omp_for_kind (ctx->stmt) == GF_OMP_FOR_KIND_TASKLOOP) goto ordered_in_taskloop; if (omp_find_clause (gimple_omp_for_clauses (ctx->stmt), OMP_CLAUSE_ORDERED) == NULL) { error_at (gimple_location (stmt), "%<ordered%> region must be closely nested inside " "a loop region with an %<ordered%> clause"); return false; } return true; case GIMPLE_OMP_TARGET: if (gimple_omp_target_kind (ctx->stmt) != GF_OMP_TARGET_KIND_REGION) break; /* FALLTHRU */ case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TEAMS: error_at (gimple_location (stmt), "%<ordered%> region must be closely nested inside " "a loop region with an %<ordered%> clause"); return false; default: break; } break; case GIMPLE_OMP_CRITICAL: { tree this_stmt_name = gimple_omp_critical_name (as_a <gomp_critical *> (stmt)); for (; ctx != NULL; ctx = ctx->outer) if (gomp_critical *other_crit = dyn_cast <gomp_critical *> (ctx->stmt)) if (this_stmt_name == gimple_omp_critical_name (other_crit)) { error_at (gimple_location (stmt), "%<critical%> region may not be nested inside " "a %<critical%> region with the same name"); return false; } } break; case GIMPLE_OMP_TEAMS: if (ctx == NULL || gimple_code (ctx->stmt) != GIMPLE_OMP_TARGET || gimple_omp_target_kind (ctx->stmt) != GF_OMP_TARGET_KIND_REGION) { error_at (gimple_location (stmt), "%<teams%> construct not closely nested inside of " "%<target%> construct"); return false; } break; case GIMPLE_OMP_TARGET: for (c = gimple_omp_target_clauses (stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND && (OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_SOURCE || OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_SINK)) { enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_KIND (c); error_at (OMP_CLAUSE_LOCATION (c), "%<depend(%s)%> is only allowed in %<omp ordered%>", kind == OMP_CLAUSE_DEPEND_SOURCE ? "source" : "sink"); return false; } if (is_gimple_omp_offloaded (stmt) && oacc_get_fn_attrib (cfun->decl) != NULL) { error_at (gimple_location (stmt), "OpenACC region inside of OpenACC routine, nested " "parallelism not supported yet"); return false; } for (; ctx != NULL; ctx = ctx->outer) { if (gimple_code (ctx->stmt) != GIMPLE_OMP_TARGET) { if (is_gimple_omp (stmt) && is_gimple_omp_oacc (stmt) && is_gimple_omp (ctx->stmt)) { error_at (gimple_location (stmt), "OpenACC construct inside of non-OpenACC region"); return false; } continue; } const char *stmt_name, *ctx_stmt_name; switch (gimple_omp_target_kind (stmt)) { case GF_OMP_TARGET_KIND_REGION: stmt_name = "target"; break; case GF_OMP_TARGET_KIND_DATA: stmt_name = "target data"; break; case GF_OMP_TARGET_KIND_UPDATE: stmt_name = "target update"; break; case GF_OMP_TARGET_KIND_ENTER_DATA: stmt_name = "target enter data"; break; case GF_OMP_TARGET_KIND_EXIT_DATA: stmt_name = "target exit data"; break; case GF_OMP_TARGET_KIND_OACC_PARALLEL: stmt_name = "parallel"; break; case GF_OMP_TARGET_KIND_OACC_KERNELS: stmt_name = "kernels"; break; case GF_OMP_TARGET_KIND_OACC_DATA: stmt_name = "data"; break; case GF_OMP_TARGET_KIND_OACC_UPDATE: stmt_name = "update"; break; case GF_OMP_TARGET_KIND_OACC_ENTER_EXIT_DATA: stmt_name = "enter/exit data"; break; case GF_OMP_TARGET_KIND_OACC_HOST_DATA: stmt_name = "host_data"; break; default: gcc_unreachable (); } switch (gimple_omp_target_kind (ctx->stmt)) { case GF_OMP_TARGET_KIND_REGION: ctx_stmt_name = "target"; break; case GF_OMP_TARGET_KIND_DATA: ctx_stmt_name = "target data"; break; case GF_OMP_TARGET_KIND_OACC_PARALLEL: ctx_stmt_name = "parallel"; break; case GF_OMP_TARGET_KIND_OACC_KERNELS: ctx_stmt_name = "kernels"; break; case GF_OMP_TARGET_KIND_OACC_DATA: ctx_stmt_name = "data"; break; case GF_OMP_TARGET_KIND_OACC_HOST_DATA: ctx_stmt_name = "host_data"; break; default: gcc_unreachable (); } /* OpenACC/OpenMP mismatch? */ if (is_gimple_omp_oacc (stmt) != is_gimple_omp_oacc (ctx->stmt)) { error_at (gimple_location (stmt), "%s %qs construct inside of %s %qs region", (is_gimple_omp_oacc (stmt) ? "OpenACC" : "OpenMP"), stmt_name, (is_gimple_omp_oacc (ctx->stmt) ? "OpenACC" : "OpenMP"), ctx_stmt_name); return false; } if (is_gimple_omp_offloaded (ctx->stmt)) { /* No GIMPLE_OMP_TARGET inside offloaded OpenACC CTX. */ if (is_gimple_omp_oacc (ctx->stmt)) { error_at (gimple_location (stmt), "%qs construct inside of %qs region", stmt_name, ctx_stmt_name); return false; } else { warning_at (gimple_location (stmt), 0, "%qs construct inside of %qs region", stmt_name, ctx_stmt_name); } } } break; default: break; } return true; } /* Helper function scan_omp. Callback for walk_tree or operators in walk_gimple_stmt used to scan for OMP directives in TP. */ static tree scan_omp_1_op (tree *tp, int *walk_subtrees, void *data) { struct walk_stmt_info *wi = (struct walk_stmt_info *) data; omp_context *ctx = (omp_context *) wi->info; tree t = *tp; switch (TREE_CODE (t)) { case VAR_DECL: case PARM_DECL: case LABEL_DECL: case RESULT_DECL: if (ctx) { tree repl = remap_decl (t, &ctx->cb); gcc_checking_assert (TREE_CODE (repl) != ERROR_MARK); *tp = repl; } break; default: if (ctx && TYPE_P (t)) *tp = remap_type (t, &ctx->cb); else if (!DECL_P (t)) { *walk_subtrees = 1; if (ctx) { tree tem = remap_type (TREE_TYPE (t), &ctx->cb); if (tem != TREE_TYPE (t)) { if (TREE_CODE (t) == INTEGER_CST) *tp = wide_int_to_tree (tem, wi::to_wide (t)); else TREE_TYPE (t) = tem; } } } break; } return NULL_TREE; } /* Return true if FNDECL is a setjmp or a longjmp. */ static bool setjmp_or_longjmp_p (const_tree fndecl) { if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_SETJMP || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_LONGJMP)) return true; tree declname = DECL_NAME (fndecl); if (!declname) return false; const char *name = IDENTIFIER_POINTER (declname); return !strcmp (name, "setjmp") || !strcmp (name, "longjmp"); } /* Helper function for scan_omp. Callback for walk_gimple_stmt used to scan for OMP directives in the current statement in GSI. */ static tree scan_omp_1_stmt (gimple_stmt_iterator *gsi, bool *handled_ops_p, struct walk_stmt_info *wi) { gimple *stmt = gsi_stmt (*gsi); omp_context *ctx = (omp_context *) wi->info; if (gimple_has_location (stmt)) input_location = gimple_location (stmt); /* Check the nesting restrictions. */ bool remove = false; if (is_gimple_omp (stmt)) remove = !check_omp_nesting_restrictions (stmt, ctx); else if (is_gimple_call (stmt)) { tree fndecl = gimple_call_fndecl (stmt); if (fndecl) { if (setjmp_or_longjmp_p (fndecl) && ctx && gimple_code (ctx->stmt) == GIMPLE_OMP_FOR && gimple_omp_for_kind (ctx->stmt) & GF_OMP_FOR_SIMD) { remove = true; error_at (gimple_location (stmt), "setjmp/longjmp inside simd construct"); } else if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL) switch (DECL_FUNCTION_CODE (fndecl)) { case BUILT_IN_GOMP_BARRIER: case BUILT_IN_GOMP_CANCEL: case BUILT_IN_GOMP_CANCELLATION_POINT: case BUILT_IN_GOMP_TASKYIELD: case BUILT_IN_GOMP_TASKWAIT: case BUILT_IN_GOMP_TASKGROUP_START: case BUILT_IN_GOMP_TASKGROUP_END: remove = !check_omp_nesting_restrictions (stmt, ctx); break; default: break; } } } if (remove) { stmt = gimple_build_nop (); gsi_replace (gsi, stmt, false); } *handled_ops_p = true; switch (gimple_code (stmt)) { case GIMPLE_OMP_PARALLEL: taskreg_nesting_level++; scan_omp_parallel (gsi, ctx); taskreg_nesting_level--; break; case GIMPLE_OMP_TASK: taskreg_nesting_level++; scan_omp_task (gsi, ctx); taskreg_nesting_level--; break; case GIMPLE_OMP_FOR: if (((gimple_omp_for_kind (as_a <gomp_for *> (stmt)) & GF_OMP_FOR_KIND_MASK) == GF_OMP_FOR_KIND_SIMD) && omp_maybe_offloaded_ctx (ctx) && omp_max_simt_vf ()) scan_omp_simd (gsi, as_a <gomp_for *> (stmt), ctx); else scan_omp_for (as_a <gomp_for *> (stmt), ctx); break; case GIMPLE_OMP_SECTIONS: scan_omp_sections (as_a <gomp_sections *> (stmt), ctx); break; case GIMPLE_OMP_SINGLE: scan_omp_single (as_a <gomp_single *> (stmt), ctx); break; case GIMPLE_OMP_SECTION: case GIMPLE_OMP_MASTER: case GIMPLE_OMP_TASKGROUP: case GIMPLE_OMP_ORDERED: case GIMPLE_OMP_CRITICAL: case GIMPLE_OMP_GRID_BODY: ctx = new_omp_context (stmt, ctx); scan_omp (gimple_omp_body_ptr (stmt), ctx); break; case GIMPLE_OMP_TARGET: scan_omp_target (as_a <gomp_target *> (stmt), ctx); break; case GIMPLE_OMP_TEAMS: scan_omp_teams (as_a <gomp_teams *> (stmt), ctx); break; case GIMPLE_BIND: { tree var; *handled_ops_p = false; if (ctx) for (var = gimple_bind_vars (as_a <gbind *> (stmt)); var ; var = DECL_CHAIN (var)) insert_decl_map (&ctx->cb, var, var); } break; default: *handled_ops_p = false; break; } return NULL_TREE; } /* Scan all the statements starting at the current statement. CTX contains context information about the OMP directives and clauses found during the scan. */ static void scan_omp (gimple_seq *body_p, omp_context *ctx) { location_t saved_location; struct walk_stmt_info wi; memset (&wi, 0, sizeof (wi)); wi.info = ctx; wi.want_locations = true; saved_location = input_location; walk_gimple_seq_mod (body_p, scan_omp_1_stmt, scan_omp_1_op, &wi); input_location = saved_location; } /* Re-gimplification and code generation routines. */ /* Remove omp_member_access_dummy_var variables from gimple_bind_vars of BIND if in a method. */ static void maybe_remove_omp_member_access_dummy_vars (gbind *bind) { if (DECL_ARGUMENTS (current_function_decl) && DECL_ARTIFICIAL (DECL_ARGUMENTS (current_function_decl)) && (TREE_CODE (TREE_TYPE (DECL_ARGUMENTS (current_function_decl))) == POINTER_TYPE)) { tree vars = gimple_bind_vars (bind); for (tree *pvar = &vars; *pvar; ) if (omp_member_access_dummy_var (*pvar)) *pvar = DECL_CHAIN (*pvar); else pvar = &DECL_CHAIN (*pvar); gimple_bind_set_vars (bind, vars); } } /* Remove omp_member_access_dummy_var variables from BLOCK_VARS of block and its subblocks. */ static void remove_member_access_dummy_vars (tree block) { for (tree *pvar = &BLOCK_VARS (block); *pvar; ) if (omp_member_access_dummy_var (*pvar)) *pvar = DECL_CHAIN (*pvar); else pvar = &DECL_CHAIN (*pvar); for (block = BLOCK_SUBBLOCKS (block); block; block = BLOCK_CHAIN (block)) remove_member_access_dummy_vars (block); } /* If a context was created for STMT when it was scanned, return it. */ static omp_context * maybe_lookup_ctx (gimple *stmt) { splay_tree_node n; n = splay_tree_lookup (all_contexts, (splay_tree_key) stmt); return n ? (omp_context *) n->value : NULL; } /* Find the mapping for DECL in CTX or the immediately enclosing context that has a mapping for DECL. If CTX is a nested parallel directive, we may have to use the decl mappings created in CTX's parent context. Suppose that we have the following parallel nesting (variable UIDs showed for clarity): iD.1562 = 0; #omp parallel shared(iD.1562) -> outer parallel iD.1562 = iD.1562 + 1; #omp parallel shared (iD.1562) -> inner parallel iD.1562 = iD.1562 - 1; Each parallel structure will create a distinct .omp_data_s structure for copying iD.1562 in/out of the directive: outer parallel .omp_data_s.1.i -> iD.1562 inner parallel .omp_data_s.2.i -> iD.1562 A shared variable mapping will produce a copy-out operation before the parallel directive and a copy-in operation after it. So, in this case we would have: iD.1562 = 0; .omp_data_o.1.i = iD.1562; #omp parallel shared(iD.1562) -> outer parallel .omp_data_i.1 = &.omp_data_o.1 .omp_data_i.1->i = .omp_data_i.1->i + 1; .omp_data_o.2.i = iD.1562; -> ** #omp parallel shared(iD.1562) -> inner parallel .omp_data_i.2 = &.omp_data_o.2 .omp_data_i.2->i = .omp_data_i.2->i - 1; ** This is a problem. The symbol iD.1562 cannot be referenced inside the body of the outer parallel region. But since we are emitting this copy operation while expanding the inner parallel directive, we need to access the CTX structure of the outer parallel directive to get the correct mapping: .omp_data_o.2.i = .omp_data_i.1->i Since there may be other workshare or parallel directives enclosing the parallel directive, it may be necessary to walk up the context parent chain. This is not a problem in general because nested parallelism happens only rarely. */ static tree lookup_decl_in_outer_ctx (tree decl, omp_context *ctx) { tree t; omp_context *up; for (up = ctx->outer, t = NULL; up && t == NULL; up = up->outer) t = maybe_lookup_decl (decl, up); gcc_assert (!ctx->is_nested || t || is_global_var (decl)); return t ? t : decl; } /* Similar to lookup_decl_in_outer_ctx, but return DECL if not found in outer contexts. */ static tree maybe_lookup_decl_in_outer_ctx (tree decl, omp_context *ctx) { tree t = NULL; omp_context *up; for (up = ctx->outer, t = NULL; up && t == NULL; up = up->outer) t = maybe_lookup_decl (decl, up); return t ? t : decl; } /* Construct the initialization value for reduction operation OP. */ tree omp_reduction_init_op (location_t loc, enum tree_code op, tree type) { switch (op) { case PLUS_EXPR: case MINUS_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: case TRUTH_OR_EXPR: case TRUTH_ORIF_EXPR: case TRUTH_XOR_EXPR: case NE_EXPR: return build_zero_cst (type); case MULT_EXPR: case TRUTH_AND_EXPR: case TRUTH_ANDIF_EXPR: case EQ_EXPR: return fold_convert_loc (loc, type, integer_one_node); case BIT_AND_EXPR: return fold_convert_loc (loc, type, integer_minus_one_node); case MAX_EXPR: if (SCALAR_FLOAT_TYPE_P (type)) { REAL_VALUE_TYPE max, min; if (HONOR_INFINITIES (type)) { real_inf (&max); real_arithmetic (&min, NEGATE_EXPR, &max, NULL); } else real_maxval (&min, 1, TYPE_MODE (type)); return build_real (type, min); } else if (POINTER_TYPE_P (type)) { wide_int min = wi::min_value (TYPE_PRECISION (type), TYPE_SIGN (type)); return wide_int_to_tree (type, min); } else { gcc_assert (INTEGRAL_TYPE_P (type)); return TYPE_MIN_VALUE (type); } case MIN_EXPR: if (SCALAR_FLOAT_TYPE_P (type)) { REAL_VALUE_TYPE max; if (HONOR_INFINITIES (type)) real_inf (&max); else real_maxval (&max, 0, TYPE_MODE (type)); return build_real (type, max); } else if (POINTER_TYPE_P (type)) { wide_int max = wi::max_value (TYPE_PRECISION (type), TYPE_SIGN (type)); return wide_int_to_tree (type, max); } else { gcc_assert (INTEGRAL_TYPE_P (type)); return TYPE_MAX_VALUE (type); } default: gcc_unreachable (); } } /* Construct the initialization value for reduction CLAUSE. */ tree omp_reduction_init (tree clause, tree type) { return omp_reduction_init_op (OMP_CLAUSE_LOCATION (clause), OMP_CLAUSE_REDUCTION_CODE (clause), type); } /* Return alignment to be assumed for var in CLAUSE, which should be OMP_CLAUSE_ALIGNED. */ static tree omp_clause_aligned_alignment (tree clause) { if (OMP_CLAUSE_ALIGNED_ALIGNMENT (clause)) return OMP_CLAUSE_ALIGNED_ALIGNMENT (clause); /* Otherwise return implementation defined alignment. */ unsigned int al = 1; opt_scalar_mode mode_iter; auto_vector_sizes sizes; targetm.vectorize.autovectorize_vector_sizes (&sizes); poly_uint64 vs = 0; for (unsigned int i = 0; i < sizes.length (); ++i) vs = ordered_max (vs, sizes[i]); static enum mode_class classes[] = { MODE_INT, MODE_VECTOR_INT, MODE_FLOAT, MODE_VECTOR_FLOAT }; for (int i = 0; i < 4; i += 2) /* The for loop above dictates that we only walk through scalar classes. */ FOR_EACH_MODE_IN_CLASS (mode_iter, classes[i]) { scalar_mode mode = mode_iter.require (); machine_mode vmode = targetm.vectorize.preferred_simd_mode (mode); if (GET_MODE_CLASS (vmode) != classes[i + 1]) continue; while (maybe_ne (vs, 0U) && known_lt (GET_MODE_SIZE (vmode), vs) && GET_MODE_2XWIDER_MODE (vmode).exists ()) vmode = GET_MODE_2XWIDER_MODE (vmode).require (); tree type = lang_hooks.types.type_for_mode (mode, 1); if (type == NULL_TREE || TYPE_MODE (type) != mode) continue; poly_uint64 nelts = exact_div (GET_MODE_SIZE (vmode), GET_MODE_SIZE (mode)); type = build_vector_type (type, nelts); if (TYPE_MODE (type) != vmode) continue; if (TYPE_ALIGN_UNIT (type) > al) al = TYPE_ALIGN_UNIT (type); } return build_int_cst (integer_type_node, al); } /* This structure is part of the interface between lower_rec_simd_input_clauses and lower_rec_input_clauses. */ struct omplow_simd_context { omplow_simd_context () { memset (this, 0, sizeof (*this)); } tree idx; tree lane; vec<tree, va_heap> simt_eargs; gimple_seq simt_dlist; poly_uint64_pod max_vf; bool is_simt; }; /* Helper function of lower_rec_input_clauses, used for #pragma omp simd privatization. */ static bool lower_rec_simd_input_clauses (tree new_var, omp_context *ctx, omplow_simd_context *sctx, tree &ivar, tree &lvar) { if (known_eq (sctx->max_vf, 0U)) { sctx->max_vf = sctx->is_simt ? omp_max_simt_vf () : omp_max_vf (); if (maybe_gt (sctx->max_vf, 1U)) { tree c = omp_find_clause (gimple_omp_for_clauses (ctx->stmt), OMP_CLAUSE_SAFELEN); if (c) { poly_uint64 safe_len; if (!poly_int_tree_p (OMP_CLAUSE_SAFELEN_EXPR (c), &safe_len) || maybe_lt (safe_len, 1U)) sctx->max_vf = 1; else sctx->max_vf = lower_bound (sctx->max_vf, safe_len); } } if (maybe_gt (sctx->max_vf, 1U)) { sctx->idx = create_tmp_var (unsigned_type_node); sctx->lane = create_tmp_var (unsigned_type_node); } } if (known_eq (sctx->max_vf, 1U)) return false; if (sctx->is_simt) { if (is_gimple_reg (new_var)) { ivar = lvar = new_var; return true; } tree type = TREE_TYPE (new_var), ptype = build_pointer_type (type); ivar = lvar = create_tmp_var (type); TREE_ADDRESSABLE (ivar) = 1; DECL_ATTRIBUTES (ivar) = tree_cons (get_identifier ("omp simt private"), NULL, DECL_ATTRIBUTES (ivar)); sctx->simt_eargs.safe_push (build1 (ADDR_EXPR, ptype, ivar)); tree clobber = build_constructor (type, NULL); TREE_THIS_VOLATILE (clobber) = 1; gimple *g = gimple_build_assign (ivar, clobber); gimple_seq_add_stmt (&sctx->simt_dlist, g); } else { tree atype = build_array_type_nelts (TREE_TYPE (new_var), sctx->max_vf); tree avar = create_tmp_var_raw (atype); if (TREE_ADDRESSABLE (new_var)) TREE_ADDRESSABLE (avar) = 1; DECL_ATTRIBUTES (avar) = tree_cons (get_identifier ("omp simd array"), NULL, DECL_ATTRIBUTES (avar)); gimple_add_tmp_var (avar); ivar = build4 (ARRAY_REF, TREE_TYPE (new_var), avar, sctx->idx, NULL_TREE, NULL_TREE); lvar = build4 (ARRAY_REF, TREE_TYPE (new_var), avar, sctx->lane, NULL_TREE, NULL_TREE); } if (DECL_P (new_var)) { SET_DECL_VALUE_EXPR (new_var, lvar); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } return true; } /* Helper function of lower_rec_input_clauses. For a reference in simd reduction, add an underlying variable it will reference. */ static void handle_simd_reference (location_t loc, tree new_vard, gimple_seq *ilist) { tree z = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (new_vard))); if (TREE_CONSTANT (z)) { z = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (new_vard)), get_name (new_vard)); gimple_add_tmp_var (z); TREE_ADDRESSABLE (z) = 1; z = build_fold_addr_expr_loc (loc, z); gimplify_assign (new_vard, z, ilist); } } /* Generate code to implement the input clauses, FIRSTPRIVATE and COPYIN, from the receiver (aka child) side and initializers for REFERENCE_TYPE private variables. Initialization statements go in ILIST, while calls to destructors go in DLIST. */ static void lower_rec_input_clauses (tree clauses, gimple_seq *ilist, gimple_seq *dlist, omp_context *ctx, struct omp_for_data *fd) { tree c, dtor, copyin_seq, x, ptr; bool copyin_by_ref = false; bool lastprivate_firstprivate = false; bool reduction_omp_orig_ref = false; int pass; bool is_simd = (gimple_code (ctx->stmt) == GIMPLE_OMP_FOR && gimple_omp_for_kind (ctx->stmt) & GF_OMP_FOR_SIMD); omplow_simd_context sctx = omplow_simd_context (); tree simt_lane = NULL_TREE, simtrec = NULL_TREE; tree ivar = NULL_TREE, lvar = NULL_TREE, uid = NULL_TREE; gimple_seq llist[3] = { }; copyin_seq = NULL; sctx.is_simt = is_simd && omp_find_clause (clauses, OMP_CLAUSE__SIMT_); /* Set max_vf=1 (which will later enforce safelen=1) in simd loops with data sharing clauses referencing variable sized vars. That is unnecessarily hard to support and very unlikely to result in vectorized code anyway. */ if (is_simd) for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_LINEAR: if (OMP_CLAUSE_LINEAR_ARRAY (c)) sctx.max_vf = 1; /* FALLTHRU */ case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_LASTPRIVATE: if (is_variable_sized (OMP_CLAUSE_DECL (c))) sctx.max_vf = 1; break; case OMP_CLAUSE_REDUCTION: if (TREE_CODE (OMP_CLAUSE_DECL (c)) == MEM_REF || is_variable_sized (OMP_CLAUSE_DECL (c))) sctx.max_vf = 1; break; default: continue; } /* Add a placeholder for simduid. */ if (sctx.is_simt && maybe_ne (sctx.max_vf, 1U)) sctx.simt_eargs.safe_push (NULL_TREE); /* Do all the fixed sized types in the first pass, and the variable sized types in the second pass. This makes sure that the scalar arguments to the variable sized types are processed before we use them in the variable sized operations. */ for (pass = 0; pass < 2; ++pass) { for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { enum omp_clause_code c_kind = OMP_CLAUSE_CODE (c); tree var, new_var; bool by_ref; location_t clause_loc = OMP_CLAUSE_LOCATION (c); switch (c_kind) { case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_PRIVATE_DEBUG (c)) continue; break; case OMP_CLAUSE_SHARED: /* Ignore shared directives in teams construct. */ if (gimple_code (ctx->stmt) == GIMPLE_OMP_TEAMS) continue; if (maybe_lookup_decl (OMP_CLAUSE_DECL (c), ctx) == NULL) { gcc_assert (OMP_CLAUSE_SHARED_FIRSTPRIVATE (c) || is_global_var (OMP_CLAUSE_DECL (c))); continue; } case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: break; case OMP_CLAUSE_LINEAR: if (!OMP_CLAUSE_LINEAR_NO_COPYIN (c) && !OMP_CLAUSE_LINEAR_NO_COPYOUT (c)) lastprivate_firstprivate = true; break; case OMP_CLAUSE_REDUCTION: if (OMP_CLAUSE_REDUCTION_OMP_ORIG_REF (c)) reduction_omp_orig_ref = true; break; case OMP_CLAUSE__LOOPTEMP_: /* Handle _looptemp_ clauses only on parallel/task. */ if (fd) continue; break; case OMP_CLAUSE_LASTPRIVATE: if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) { lastprivate_firstprivate = true; if (pass != 0 || is_taskloop_ctx (ctx)) continue; } /* Even without corresponding firstprivate, if decl is Fortran allocatable, it needs outer var reference. */ else if (pass == 0 && lang_hooks.decls.omp_private_outer_ref (OMP_CLAUSE_DECL (c))) lastprivate_firstprivate = true; break; case OMP_CLAUSE_ALIGNED: if (pass == 0) continue; var = OMP_CLAUSE_DECL (c); if (TREE_CODE (TREE_TYPE (var)) == POINTER_TYPE && !is_global_var (var)) { new_var = maybe_lookup_decl (var, ctx); if (new_var == NULL_TREE) new_var = maybe_lookup_decl_in_outer_ctx (var, ctx); x = builtin_decl_explicit (BUILT_IN_ASSUME_ALIGNED); tree alarg = omp_clause_aligned_alignment (c); alarg = fold_convert_loc (clause_loc, size_type_node, alarg); x = build_call_expr_loc (clause_loc, x, 2, new_var, alarg); x = fold_convert_loc (clause_loc, TREE_TYPE (new_var), x); x = build2 (MODIFY_EXPR, TREE_TYPE (new_var), new_var, x); gimplify_and_add (x, ilist); } else if (TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE && is_global_var (var)) { tree ptype = build_pointer_type (TREE_TYPE (var)), t, t2; new_var = lookup_decl (var, ctx); t = maybe_lookup_decl_in_outer_ctx (var, ctx); t = build_fold_addr_expr_loc (clause_loc, t); t2 = builtin_decl_explicit (BUILT_IN_ASSUME_ALIGNED); tree alarg = omp_clause_aligned_alignment (c); alarg = fold_convert_loc (clause_loc, size_type_node, alarg); t = build_call_expr_loc (clause_loc, t2, 2, t, alarg); t = fold_convert_loc (clause_loc, ptype, t); x = create_tmp_var (ptype); t = build2 (MODIFY_EXPR, ptype, x, t); gimplify_and_add (t, ilist); t = build_simple_mem_ref_loc (clause_loc, x); SET_DECL_VALUE_EXPR (new_var, t); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } continue; default: continue; } new_var = var = OMP_CLAUSE_DECL (c); if (c_kind == OMP_CLAUSE_REDUCTION && TREE_CODE (var) == MEM_REF) { var = TREE_OPERAND (var, 0); if (TREE_CODE (var) == POINTER_PLUS_EXPR) var = TREE_OPERAND (var, 0); if (TREE_CODE (var) == INDIRECT_REF || TREE_CODE (var) == ADDR_EXPR) var = TREE_OPERAND (var, 0); if (is_variable_sized (var)) { gcc_assert (DECL_HAS_VALUE_EXPR_P (var)); var = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (var) == INDIRECT_REF); var = TREE_OPERAND (var, 0); gcc_assert (DECL_P (var)); } new_var = var; } if (c_kind != OMP_CLAUSE_COPYIN) new_var = lookup_decl (var, ctx); if (c_kind == OMP_CLAUSE_SHARED || c_kind == OMP_CLAUSE_COPYIN) { if (pass != 0) continue; } /* C/C++ array section reductions. */ else if (c_kind == OMP_CLAUSE_REDUCTION && var != OMP_CLAUSE_DECL (c)) { if (pass == 0) continue; tree bias = TREE_OPERAND (OMP_CLAUSE_DECL (c), 1); tree orig_var = TREE_OPERAND (OMP_CLAUSE_DECL (c), 0); if (TREE_CODE (orig_var) == POINTER_PLUS_EXPR) { tree b = TREE_OPERAND (orig_var, 1); b = maybe_lookup_decl (b, ctx); if (b == NULL) { b = TREE_OPERAND (orig_var, 1); b = maybe_lookup_decl_in_outer_ctx (b, ctx); } if (integer_zerop (bias)) bias = b; else { bias = fold_convert_loc (clause_loc, TREE_TYPE (b), bias); bias = fold_build2_loc (clause_loc, PLUS_EXPR, TREE_TYPE (b), b, bias); } orig_var = TREE_OPERAND (orig_var, 0); } if (TREE_CODE (orig_var) == INDIRECT_REF || TREE_CODE (orig_var) == ADDR_EXPR) orig_var = TREE_OPERAND (orig_var, 0); tree d = OMP_CLAUSE_DECL (c); tree type = TREE_TYPE (d); gcc_assert (TREE_CODE (type) == ARRAY_TYPE); tree v = TYPE_MAX_VALUE (TYPE_DOMAIN (type)); const char *name = get_name (orig_var); if (TREE_CONSTANT (v)) { x = create_tmp_var_raw (type, name); gimple_add_tmp_var (x); TREE_ADDRESSABLE (x) = 1; x = build_fold_addr_expr_loc (clause_loc, x); } else { tree atmp = builtin_decl_explicit (BUILT_IN_ALLOCA_WITH_ALIGN); tree t = maybe_lookup_decl (v, ctx); if (t) v = t; else v = maybe_lookup_decl_in_outer_ctx (v, ctx); gimplify_expr (&v, ilist, NULL, is_gimple_val, fb_rvalue); t = fold_build2_loc (clause_loc, PLUS_EXPR, TREE_TYPE (v), v, build_int_cst (TREE_TYPE (v), 1)); t = fold_build2_loc (clause_loc, MULT_EXPR, TREE_TYPE (v), t, TYPE_SIZE_UNIT (TREE_TYPE (type))); tree al = size_int (TYPE_ALIGN (TREE_TYPE (type))); x = build_call_expr_loc (clause_loc, atmp, 2, t, al); } tree ptype = build_pointer_type (TREE_TYPE (type)); x = fold_convert_loc (clause_loc, ptype, x); tree y = create_tmp_var (ptype, name); gimplify_assign (y, x, ilist); x = y; tree yb = y; if (!integer_zerop (bias)) { bias = fold_convert_loc (clause_loc, pointer_sized_int_node, bias); yb = fold_convert_loc (clause_loc, pointer_sized_int_node, x); yb = fold_build2_loc (clause_loc, MINUS_EXPR, pointer_sized_int_node, yb, bias); x = fold_convert_loc (clause_loc, TREE_TYPE (x), yb); yb = create_tmp_var (ptype, name); gimplify_assign (yb, x, ilist); x = yb; } d = TREE_OPERAND (d, 0); if (TREE_CODE (d) == POINTER_PLUS_EXPR) d = TREE_OPERAND (d, 0); if (TREE_CODE (d) == ADDR_EXPR) { if (orig_var != var) { gcc_assert (is_variable_sized (orig_var)); x = fold_convert_loc (clause_loc, TREE_TYPE (new_var), x); gimplify_assign (new_var, x, ilist); tree new_orig_var = lookup_decl (orig_var, ctx); tree t = build_fold_indirect_ref (new_var); DECL_IGNORED_P (new_var) = 0; TREE_THIS_NOTRAP (t); SET_DECL_VALUE_EXPR (new_orig_var, t); DECL_HAS_VALUE_EXPR_P (new_orig_var) = 1; } else { x = build2 (MEM_REF, TREE_TYPE (new_var), x, build_int_cst (ptype, 0)); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } } else { gcc_assert (orig_var == var); if (TREE_CODE (d) == INDIRECT_REF) { x = create_tmp_var (ptype, name); TREE_ADDRESSABLE (x) = 1; gimplify_assign (x, yb, ilist); x = build_fold_addr_expr_loc (clause_loc, x); } x = fold_convert_loc (clause_loc, TREE_TYPE (new_var), x); gimplify_assign (new_var, x, ilist); } tree y1 = create_tmp_var (ptype, NULL); gimplify_assign (y1, y, ilist); tree i2 = NULL_TREE, y2 = NULL_TREE; tree body2 = NULL_TREE, end2 = NULL_TREE; tree y3 = NULL_TREE, y4 = NULL_TREE; if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) || is_simd) { y2 = create_tmp_var (ptype, NULL); gimplify_assign (y2, y, ilist); tree ref = build_outer_var_ref (var, ctx); /* For ref build_outer_var_ref already performs this. */ if (TREE_CODE (d) == INDIRECT_REF) gcc_assert (omp_is_reference (var)); else if (TREE_CODE (d) == ADDR_EXPR) ref = build_fold_addr_expr (ref); else if (omp_is_reference (var)) ref = build_fold_addr_expr (ref); ref = fold_convert_loc (clause_loc, ptype, ref); if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) && OMP_CLAUSE_REDUCTION_OMP_ORIG_REF (c)) { y3 = create_tmp_var (ptype, NULL); gimplify_assign (y3, unshare_expr (ref), ilist); } if (is_simd) { y4 = create_tmp_var (ptype, NULL); gimplify_assign (y4, ref, dlist); } } tree i = create_tmp_var (TREE_TYPE (v), NULL); gimplify_assign (i, build_int_cst (TREE_TYPE (v), 0), ilist); tree body = create_artificial_label (UNKNOWN_LOCATION); tree end = create_artificial_label (UNKNOWN_LOCATION); gimple_seq_add_stmt (ilist, gimple_build_label (body)); if (y2) { i2 = create_tmp_var (TREE_TYPE (v), NULL); gimplify_assign (i2, build_int_cst (TREE_TYPE (v), 0), dlist); body2 = create_artificial_label (UNKNOWN_LOCATION); end2 = create_artificial_label (UNKNOWN_LOCATION); gimple_seq_add_stmt (dlist, gimple_build_label (body2)); } if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); tree decl_placeholder = OMP_CLAUSE_REDUCTION_DECL_PLACEHOLDER (c); SET_DECL_VALUE_EXPR (decl_placeholder, build_simple_mem_ref (y1)); DECL_HAS_VALUE_EXPR_P (decl_placeholder) = 1; SET_DECL_VALUE_EXPR (placeholder, y3 ? build_simple_mem_ref (y3) : error_mark_node); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; x = lang_hooks.decls.omp_clause_default_ctor (c, build_simple_mem_ref (y1), y3 ? build_simple_mem_ref (y3) : NULL_TREE); if (x) gimplify_and_add (x, ilist); if (OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c)) { gimple_seq tseq = OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c); lower_omp (&tseq, ctx); gimple_seq_add_seq (ilist, tseq); } OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c) = NULL; if (is_simd) { SET_DECL_VALUE_EXPR (decl_placeholder, build_simple_mem_ref (y2)); SET_DECL_VALUE_EXPR (placeholder, build_simple_mem_ref (y4)); gimple_seq tseq = OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c); lower_omp (&tseq, ctx); gimple_seq_add_seq (dlist, tseq); OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = NULL; } DECL_HAS_VALUE_EXPR_P (placeholder) = 0; DECL_HAS_VALUE_EXPR_P (decl_placeholder) = 0; x = lang_hooks.decls.omp_clause_dtor (c, build_simple_mem_ref (y2)); if (x) { gimple_seq tseq = NULL; dtor = x; gimplify_stmt (&dtor, &tseq); gimple_seq_add_seq (dlist, tseq); } } else { x = omp_reduction_init (c, TREE_TYPE (type)); enum tree_code code = OMP_CLAUSE_REDUCTION_CODE (c); /* reduction(-:var) sums up the partial results, so it acts identically to reduction(+:var). */ if (code == MINUS_EXPR) code = PLUS_EXPR; gimplify_assign (build_simple_mem_ref (y1), x, ilist); if (is_simd) { x = build2 (code, TREE_TYPE (type), build_simple_mem_ref (y4), build_simple_mem_ref (y2)); gimplify_assign (build_simple_mem_ref (y4), x, dlist); } } gimple *g = gimple_build_assign (y1, POINTER_PLUS_EXPR, y1, TYPE_SIZE_UNIT (TREE_TYPE (type))); gimple_seq_add_stmt (ilist, g); if (y3) { g = gimple_build_assign (y3, POINTER_PLUS_EXPR, y3, TYPE_SIZE_UNIT (TREE_TYPE (type))); gimple_seq_add_stmt (ilist, g); } g = gimple_build_assign (i, PLUS_EXPR, i, build_int_cst (TREE_TYPE (i), 1)); gimple_seq_add_stmt (ilist, g); g = gimple_build_cond (LE_EXPR, i, v, body, end); gimple_seq_add_stmt (ilist, g); gimple_seq_add_stmt (ilist, gimple_build_label (end)); if (y2) { g = gimple_build_assign (y2, POINTER_PLUS_EXPR, y2, TYPE_SIZE_UNIT (TREE_TYPE (type))); gimple_seq_add_stmt (dlist, g); if (y4) { g = gimple_build_assign (y4, POINTER_PLUS_EXPR, y4, TYPE_SIZE_UNIT (TREE_TYPE (type))); gimple_seq_add_stmt (dlist, g); } g = gimple_build_assign (i2, PLUS_EXPR, i2, build_int_cst (TREE_TYPE (i2), 1)); gimple_seq_add_stmt (dlist, g); g = gimple_build_cond (LE_EXPR, i2, v, body2, end2); gimple_seq_add_stmt (dlist, g); gimple_seq_add_stmt (dlist, gimple_build_label (end2)); } continue; } else if (is_variable_sized (var)) { /* For variable sized types, we need to allocate the actual storage here. Call alloca and store the result in the pointer decl that we created elsewhere. */ if (pass == 0) continue; if (c_kind != OMP_CLAUSE_FIRSTPRIVATE || !is_task_ctx (ctx)) { gcall *stmt; tree tmp, atmp; ptr = DECL_VALUE_EXPR (new_var); gcc_assert (TREE_CODE (ptr) == INDIRECT_REF); ptr = TREE_OPERAND (ptr, 0); gcc_assert (DECL_P (ptr)); x = TYPE_SIZE_UNIT (TREE_TYPE (new_var)); /* void *tmp = __builtin_alloca */ atmp = builtin_decl_explicit (BUILT_IN_ALLOCA_WITH_ALIGN); stmt = gimple_build_call (atmp, 2, x, size_int (DECL_ALIGN (var))); tmp = create_tmp_var_raw (ptr_type_node); gimple_add_tmp_var (tmp); gimple_call_set_lhs (stmt, tmp); gimple_seq_add_stmt (ilist, stmt); x = fold_convert_loc (clause_loc, TREE_TYPE (ptr), tmp); gimplify_assign (ptr, x, ilist); } } else if (omp_is_reference (var)) { /* For references that are being privatized for Fortran, allocate new backing storage for the new pointer variable. This allows us to avoid changing all the code that expects a pointer to something that expects a direct variable. */ if (pass == 0) continue; x = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (new_var))); if (c_kind == OMP_CLAUSE_FIRSTPRIVATE && is_task_ctx (ctx)) { x = build_receiver_ref (var, false, ctx); x = build_fold_addr_expr_loc (clause_loc, x); } else if (TREE_CONSTANT (x)) { /* For reduction in SIMD loop, defer adding the initialization of the reference, because if we decide to use SIMD array for it, the initilization could cause expansion ICE. */ if (c_kind == OMP_CLAUSE_REDUCTION && is_simd) x = NULL_TREE; else { x = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (new_var)), get_name (var)); gimple_add_tmp_var (x); TREE_ADDRESSABLE (x) = 1; x = build_fold_addr_expr_loc (clause_loc, x); } } else { tree atmp = builtin_decl_explicit (BUILT_IN_ALLOCA_WITH_ALIGN); tree rtype = TREE_TYPE (TREE_TYPE (new_var)); tree al = size_int (TYPE_ALIGN (rtype)); x = build_call_expr_loc (clause_loc, atmp, 2, x, al); } if (x) { x = fold_convert_loc (clause_loc, TREE_TYPE (new_var), x); gimplify_assign (new_var, x, ilist); } new_var = build_simple_mem_ref_loc (clause_loc, new_var); } else if (c_kind == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { if (pass == 0) continue; } else if (pass != 0) continue; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: /* Ignore shared directives in teams construct. */ if (gimple_code (ctx->stmt) == GIMPLE_OMP_TEAMS) continue; /* Shared global vars are just accessed directly. */ if (is_global_var (new_var)) break; /* For taskloop firstprivate/lastprivate, represented as firstprivate and shared clause on the task, new_var is the firstprivate var. */ if (OMP_CLAUSE_SHARED_FIRSTPRIVATE (c)) break; /* Set up the DECL_VALUE_EXPR for shared variables now. This needs to be delayed until after fixup_child_record_type so that we get the correct type during the dereference. */ by_ref = use_pointer_for_field (var, ctx); x = build_receiver_ref (var, by_ref, ctx); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; /* ??? If VAR is not passed by reference, and the variable hasn't been initialized yet, then we'll get a warning for the store into the omp_data_s structure. Ideally, we'd be able to notice this and not store anything at all, but we're generating code too early. Suppress the warning. */ if (!by_ref) TREE_NO_WARNING (var) = 1; break; case OMP_CLAUSE_LASTPRIVATE: if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) break; /* FALLTHRU */ case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_PRIVATE) x = build_outer_var_ref (var, ctx); else if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) { if (is_task_ctx (ctx)) x = build_receiver_ref (var, false, ctx); else x = build_outer_var_ref (var, ctx, OMP_CLAUSE_PRIVATE); } else x = NULL; do_private: tree nx; nx = lang_hooks.decls.omp_clause_default_ctor (c, unshare_expr (new_var), x); if (is_simd) { tree y = lang_hooks.decls.omp_clause_dtor (c, new_var); if ((TREE_ADDRESSABLE (new_var) || nx || y || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE) && lower_rec_simd_input_clauses (new_var, ctx, &sctx, ivar, lvar)) { if (nx) x = lang_hooks.decls.omp_clause_default_ctor (c, unshare_expr (ivar), x); if (nx && x) gimplify_and_add (x, &llist[0]); if (y) { y = lang_hooks.decls.omp_clause_dtor (c, ivar); if (y) { gimple_seq tseq = NULL; dtor = y; gimplify_stmt (&dtor, &tseq); gimple_seq_add_seq (&llist[1], tseq); } } break; } } if (nx) gimplify_and_add (nx, ilist); /* FALLTHRU */ do_dtor: x = lang_hooks.decls.omp_clause_dtor (c, new_var); if (x) { gimple_seq tseq = NULL; dtor = x; gimplify_stmt (&dtor, &tseq); gimple_seq_add_seq (dlist, tseq); } break; case OMP_CLAUSE_LINEAR: if (!OMP_CLAUSE_LINEAR_NO_COPYIN (c)) goto do_firstprivate; if (OMP_CLAUSE_LINEAR_NO_COPYOUT (c)) x = NULL; else x = build_outer_var_ref (var, ctx); goto do_private; case OMP_CLAUSE_FIRSTPRIVATE: if (is_task_ctx (ctx)) { if (omp_is_reference (var) || is_variable_sized (var)) goto do_dtor; else if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx)) || use_pointer_for_field (var, NULL)) { x = build_receiver_ref (var, false, ctx); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; goto do_dtor; } } do_firstprivate: x = build_outer_var_ref (var, ctx); if (is_simd) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR && gimple_omp_for_combined_into_p (ctx->stmt)) { tree t = OMP_CLAUSE_LINEAR_STEP (c); tree stept = TREE_TYPE (t); tree ct = omp_find_clause (clauses, OMP_CLAUSE__LOOPTEMP_); gcc_assert (ct); tree l = OMP_CLAUSE_DECL (ct); tree n1 = fd->loop.n1; tree step = fd->loop.step; tree itype = TREE_TYPE (l); if (POINTER_TYPE_P (itype)) itype = signed_type_for (itype); l = fold_build2 (MINUS_EXPR, itype, l, n1); if (TYPE_UNSIGNED (itype) && fd->loop.cond_code == GT_EXPR) l = fold_build2 (TRUNC_DIV_EXPR, itype, fold_build1 (NEGATE_EXPR, itype, l), fold_build1 (NEGATE_EXPR, itype, step)); else l = fold_build2 (TRUNC_DIV_EXPR, itype, l, step); t = fold_build2 (MULT_EXPR, stept, fold_convert (stept, l), t); if (OMP_CLAUSE_LINEAR_ARRAY (c)) { x = lang_hooks.decls.omp_clause_linear_ctor (c, new_var, x, t); gimplify_and_add (x, ilist); goto do_dtor; } if (POINTER_TYPE_P (TREE_TYPE (x))) x = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (x), x, t); else x = fold_build2 (PLUS_EXPR, TREE_TYPE (x), x, t); } if ((OMP_CLAUSE_CODE (c) != OMP_CLAUSE_LINEAR || TREE_ADDRESSABLE (new_var)) && lower_rec_simd_input_clauses (new_var, ctx, &sctx, ivar, lvar)) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR) { tree iv = create_tmp_var (TREE_TYPE (new_var)); x = lang_hooks.decls.omp_clause_copy_ctor (c, iv, x); gimplify_and_add (x, ilist); gimple_stmt_iterator gsi = gsi_start_1 (gimple_omp_body_ptr (ctx->stmt)); gassign *g = gimple_build_assign (unshare_expr (lvar), iv); gsi_insert_before_without_update (&gsi, g, GSI_SAME_STMT); tree t = OMP_CLAUSE_LINEAR_STEP (c); enum tree_code code = PLUS_EXPR; if (POINTER_TYPE_P (TREE_TYPE (new_var))) code = POINTER_PLUS_EXPR; g = gimple_build_assign (iv, code, iv, t); gsi_insert_before_without_update (&gsi, g, GSI_SAME_STMT); break; } x = lang_hooks.decls.omp_clause_copy_ctor (c, unshare_expr (ivar), x); gimplify_and_add (x, &llist[0]); x = lang_hooks.decls.omp_clause_dtor (c, ivar); if (x) { gimple_seq tseq = NULL; dtor = x; gimplify_stmt (&dtor, &tseq); gimple_seq_add_seq (&llist[1], tseq); } break; } } x = lang_hooks.decls.omp_clause_copy_ctor (c, unshare_expr (new_var), x); gimplify_and_add (x, ilist); goto do_dtor; case OMP_CLAUSE__LOOPTEMP_: gcc_assert (is_taskreg_ctx (ctx)); x = build_outer_var_ref (var, ctx); x = build2 (MODIFY_EXPR, TREE_TYPE (new_var), new_var, x); gimplify_and_add (x, ilist); break; case OMP_CLAUSE_COPYIN: by_ref = use_pointer_for_field (var, NULL); x = build_receiver_ref (var, by_ref, ctx); x = lang_hooks.decls.omp_clause_assign_op (c, new_var, x); append_to_statement_list (x, &copyin_seq); copyin_by_ref |= by_ref; break; case OMP_CLAUSE_REDUCTION: /* OpenACC reductions are initialized using the GOACC_REDUCTION internal function. */ if (is_gimple_omp_oacc (ctx->stmt)) break; if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); gimple *tseq; x = build_outer_var_ref (var, ctx); if (omp_is_reference (var) && !useless_type_conversion_p (TREE_TYPE (placeholder), TREE_TYPE (x))) x = build_fold_addr_expr_loc (clause_loc, x); SET_DECL_VALUE_EXPR (placeholder, x); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; tree new_vard = new_var; if (omp_is_reference (var)) { gcc_assert (TREE_CODE (new_var) == MEM_REF); new_vard = TREE_OPERAND (new_var, 0); gcc_assert (DECL_P (new_vard)); } if (is_simd && lower_rec_simd_input_clauses (new_var, ctx, &sctx, ivar, lvar)) { if (new_vard == new_var) { gcc_assert (DECL_VALUE_EXPR (new_var) == lvar); SET_DECL_VALUE_EXPR (new_var, ivar); } else { SET_DECL_VALUE_EXPR (new_vard, build_fold_addr_expr (ivar)); DECL_HAS_VALUE_EXPR_P (new_vard) = 1; } x = lang_hooks.decls.omp_clause_default_ctor (c, unshare_expr (ivar), build_outer_var_ref (var, ctx)); if (x) gimplify_and_add (x, &llist[0]); if (OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c)) { tseq = OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c); lower_omp (&tseq, ctx); gimple_seq_add_seq (&llist[0], tseq); } OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c) = NULL; tseq = OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c); lower_omp (&tseq, ctx); gimple_seq_add_seq (&llist[1], tseq); OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = NULL; DECL_HAS_VALUE_EXPR_P (placeholder) = 0; if (new_vard == new_var) SET_DECL_VALUE_EXPR (new_var, lvar); else SET_DECL_VALUE_EXPR (new_vard, build_fold_addr_expr (lvar)); x = lang_hooks.decls.omp_clause_dtor (c, ivar); if (x) { tseq = NULL; dtor = x; gimplify_stmt (&dtor, &tseq); gimple_seq_add_seq (&llist[1], tseq); } break; } /* If this is a reference to constant size reduction var with placeholder, we haven't emitted the initializer for it because it is undesirable if SIMD arrays are used. But if they aren't used, we need to emit the deferred initialization now. */ else if (omp_is_reference (var) && is_simd) handle_simd_reference (clause_loc, new_vard, ilist); x = lang_hooks.decls.omp_clause_default_ctor (c, unshare_expr (new_var), build_outer_var_ref (var, ctx)); if (x) gimplify_and_add (x, ilist); if (OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c)) { tseq = OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c); lower_omp (&tseq, ctx); gimple_seq_add_seq (ilist, tseq); } OMP_CLAUSE_REDUCTION_GIMPLE_INIT (c) = NULL; if (is_simd) { tseq = OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c); lower_omp (&tseq, ctx); gimple_seq_add_seq (dlist, tseq); OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = NULL; } DECL_HAS_VALUE_EXPR_P (placeholder) = 0; goto do_dtor; } else { x = omp_reduction_init (c, TREE_TYPE (new_var)); gcc_assert (TREE_CODE (TREE_TYPE (new_var)) != ARRAY_TYPE); enum tree_code code = OMP_CLAUSE_REDUCTION_CODE (c); /* reduction(-:var) sums up the partial results, so it acts identically to reduction(+:var). */ if (code == MINUS_EXPR) code = PLUS_EXPR; tree new_vard = new_var; if (is_simd && omp_is_reference (var)) { gcc_assert (TREE_CODE (new_var) == MEM_REF); new_vard = TREE_OPERAND (new_var, 0); gcc_assert (DECL_P (new_vard)); } if (is_simd && lower_rec_simd_input_clauses (new_var, ctx, &sctx, ivar, lvar)) { tree ref = build_outer_var_ref (var, ctx); gimplify_assign (unshare_expr (ivar), x, &llist[0]); if (sctx.is_simt) { if (!simt_lane) simt_lane = create_tmp_var (unsigned_type_node); x = build_call_expr_internal_loc (UNKNOWN_LOCATION, IFN_GOMP_SIMT_XCHG_BFLY, TREE_TYPE (ivar), 2, ivar, simt_lane); x = build2 (code, TREE_TYPE (ivar), ivar, x); gimplify_assign (ivar, x, &llist[2]); } x = build2 (code, TREE_TYPE (ref), ref, ivar); ref = build_outer_var_ref (var, ctx); gimplify_assign (ref, x, &llist[1]); if (new_vard != new_var) { SET_DECL_VALUE_EXPR (new_vard, build_fold_addr_expr (lvar)); DECL_HAS_VALUE_EXPR_P (new_vard) = 1; } } else { if (omp_is_reference (var) && is_simd) handle_simd_reference (clause_loc, new_vard, ilist); gimplify_assign (new_var, x, ilist); if (is_simd) { tree ref = build_outer_var_ref (var, ctx); x = build2 (code, TREE_TYPE (ref), ref, new_var); ref = build_outer_var_ref (var, ctx); gimplify_assign (ref, x, dlist); } } } break; default: gcc_unreachable (); } } } if (known_eq (sctx.max_vf, 1U)) sctx.is_simt = false; if (sctx.lane || sctx.is_simt) { uid = create_tmp_var (ptr_type_node, "simduid"); /* Don't want uninit warnings on simduid, it is always uninitialized, but we use it not for the value, but for the DECL_UID only. */ TREE_NO_WARNING (uid) = 1; c = build_omp_clause (UNKNOWN_LOCATION, OMP_CLAUSE__SIMDUID_); OMP_CLAUSE__SIMDUID__DECL (c) = uid; OMP_CLAUSE_CHAIN (c) = gimple_omp_for_clauses (ctx->stmt); gimple_omp_for_set_clauses (ctx->stmt, c); } /* Emit calls denoting privatized variables and initializing a pointer to structure that holds private variables as fields after ompdevlow pass. */ if (sctx.is_simt) { sctx.simt_eargs[0] = uid; gimple *g = gimple_build_call_internal_vec (IFN_GOMP_SIMT_ENTER, sctx.simt_eargs); gimple_call_set_lhs (g, uid); gimple_seq_add_stmt (ilist, g); sctx.simt_eargs.release (); simtrec = create_tmp_var (ptr_type_node, ".omp_simt"); g = gimple_build_call_internal (IFN_GOMP_SIMT_ENTER_ALLOC, 1, uid); gimple_call_set_lhs (g, simtrec); gimple_seq_add_stmt (ilist, g); } if (sctx.lane) { gimple *g = gimple_build_call_internal (IFN_GOMP_SIMD_LANE, 1, uid); gimple_call_set_lhs (g, sctx.lane); gimple_stmt_iterator gsi = gsi_start_1 (gimple_omp_body_ptr (ctx->stmt)); gsi_insert_before_without_update (&gsi, g, GSI_SAME_STMT); g = gimple_build_assign (sctx.lane, INTEGER_CST, build_int_cst (unsigned_type_node, 0)); gimple_seq_add_stmt (ilist, g); /* Emit reductions across SIMT lanes in log_2(simt_vf) steps. */ if (llist[2]) { tree simt_vf = create_tmp_var (unsigned_type_node); g = gimple_build_call_internal (IFN_GOMP_SIMT_VF, 0); gimple_call_set_lhs (g, simt_vf); gimple_seq_add_stmt (dlist, g); tree t = build_int_cst (unsigned_type_node, 1); g = gimple_build_assign (simt_lane, INTEGER_CST, t); gimple_seq_add_stmt (dlist, g); t = build_int_cst (unsigned_type_node, 0); g = gimple_build_assign (sctx.idx, INTEGER_CST, t); gimple_seq_add_stmt (dlist, g); tree body = create_artificial_label (UNKNOWN_LOCATION); tree header = create_artificial_label (UNKNOWN_LOCATION); tree end = create_artificial_label (UNKNOWN_LOCATION); gimple_seq_add_stmt (dlist, gimple_build_goto (header)); gimple_seq_add_stmt (dlist, gimple_build_label (body)); gimple_seq_add_seq (dlist, llist[2]); g = gimple_build_assign (simt_lane, LSHIFT_EXPR, simt_lane, integer_one_node); gimple_seq_add_stmt (dlist, g); gimple_seq_add_stmt (dlist, gimple_build_label (header)); g = gimple_build_cond (LT_EXPR, simt_lane, simt_vf, body, end); gimple_seq_add_stmt (dlist, g); gimple_seq_add_stmt (dlist, gimple_build_label (end)); } for (int i = 0; i < 2; i++) if (llist[i]) { tree vf = create_tmp_var (unsigned_type_node); g = gimple_build_call_internal (IFN_GOMP_SIMD_VF, 1, uid); gimple_call_set_lhs (g, vf); gimple_seq *seq = i == 0 ? ilist : dlist; gimple_seq_add_stmt (seq, g); tree t = build_int_cst (unsigned_type_node, 0); g = gimple_build_assign (sctx.idx, INTEGER_CST, t); gimple_seq_add_stmt (seq, g); tree body = create_artificial_label (UNKNOWN_LOCATION); tree header = create_artificial_label (UNKNOWN_LOCATION); tree end = create_artificial_label (UNKNOWN_LOCATION); gimple_seq_add_stmt (seq, gimple_build_goto (header)); gimple_seq_add_stmt (seq, gimple_build_label (body)); gimple_seq_add_seq (seq, llist[i]); t = build_int_cst (unsigned_type_node, 1); g = gimple_build_assign (sctx.idx, PLUS_EXPR, sctx.idx, t); gimple_seq_add_stmt (seq, g); gimple_seq_add_stmt (seq, gimple_build_label (header)); g = gimple_build_cond (LT_EXPR, sctx.idx, vf, body, end); gimple_seq_add_stmt (seq, g); gimple_seq_add_stmt (seq, gimple_build_label (end)); } } if (sctx.is_simt) { gimple_seq_add_seq (dlist, sctx.simt_dlist); gimple *g = gimple_build_call_internal (IFN_GOMP_SIMT_EXIT, 1, simtrec); gimple_seq_add_stmt (dlist, g); } /* The copyin sequence is not to be executed by the main thread, since that would result in self-copies. Perhaps not visible to scalars, but it certainly is to C++ operator=. */ if (copyin_seq) { x = build_call_expr (builtin_decl_explicit (BUILT_IN_OMP_GET_THREAD_NUM), 0); x = build2 (NE_EXPR, boolean_type_node, x, build_int_cst (TREE_TYPE (x), 0)); x = build3 (COND_EXPR, void_type_node, x, copyin_seq, NULL); gimplify_and_add (x, ilist); } /* If any copyin variable is passed by reference, we must ensure the master thread doesn't modify it before it is copied over in all threads. Similarly for variables in both firstprivate and lastprivate clauses we need to ensure the lastprivate copying happens after firstprivate copying in all threads. And similarly for UDRs if initializer expression refers to omp_orig. */ if (copyin_by_ref || lastprivate_firstprivate || reduction_omp_orig_ref) { /* Don't add any barrier for #pragma omp simd or #pragma omp distribute. */ if (gimple_code (ctx->stmt) != GIMPLE_OMP_FOR || gimple_omp_for_kind (ctx->stmt) == GF_OMP_FOR_KIND_FOR) gimple_seq_add_stmt (ilist, omp_build_barrier (NULL_TREE)); } /* If max_vf is non-zero, then we can use only a vectorization factor up to the max_vf we chose. So stick it into the safelen clause. */ if (maybe_ne (sctx.max_vf, 0U)) { tree c = omp_find_clause (gimple_omp_for_clauses (ctx->stmt), OMP_CLAUSE_SAFELEN); poly_uint64 safe_len; if (c == NULL_TREE || (poly_int_tree_p (OMP_CLAUSE_SAFELEN_EXPR (c), &safe_len) && maybe_gt (safe_len, sctx.max_vf))) { c = build_omp_clause (UNKNOWN_LOCATION, OMP_CLAUSE_SAFELEN); OMP_CLAUSE_SAFELEN_EXPR (c) = build_int_cst (integer_type_node, sctx.max_vf); OMP_CLAUSE_CHAIN (c) = gimple_omp_for_clauses (ctx->stmt); gimple_omp_for_set_clauses (ctx->stmt, c); } } } /* Generate code to implement the LASTPRIVATE clauses. This is used for both parallel and workshare constructs. PREDICATE may be NULL if it's always true. */ static void lower_lastprivate_clauses (tree clauses, tree predicate, gimple_seq *stmt_list, omp_context *ctx) { tree x, c, label = NULL, orig_clauses = clauses; bool par_clauses = false; tree simduid = NULL, lastlane = NULL, simtcond = NULL, simtlast = NULL; /* Early exit if there are no lastprivate or linear clauses. */ for (; clauses ; clauses = OMP_CLAUSE_CHAIN (clauses)) if (OMP_CLAUSE_CODE (clauses) == OMP_CLAUSE_LASTPRIVATE || (OMP_CLAUSE_CODE (clauses) == OMP_CLAUSE_LINEAR && !OMP_CLAUSE_LINEAR_NO_COPYOUT (clauses))) break; if (clauses == NULL) { /* If this was a workshare clause, see if it had been combined with its parallel. In that case, look for the clauses on the parallel statement itself. */ if (is_parallel_ctx (ctx)) return; ctx = ctx->outer; if (ctx == NULL || !is_parallel_ctx (ctx)) return; clauses = omp_find_clause (gimple_omp_parallel_clauses (ctx->stmt), OMP_CLAUSE_LASTPRIVATE); if (clauses == NULL) return; par_clauses = true; } bool maybe_simt = false; if (gimple_code (ctx->stmt) == GIMPLE_OMP_FOR && gimple_omp_for_kind (ctx->stmt) & GF_OMP_FOR_SIMD) { maybe_simt = omp_find_clause (orig_clauses, OMP_CLAUSE__SIMT_); simduid = omp_find_clause (orig_clauses, OMP_CLAUSE__SIMDUID_); if (simduid) simduid = OMP_CLAUSE__SIMDUID__DECL (simduid); } if (predicate) { gcond *stmt; tree label_true, arm1, arm2; enum tree_code pred_code = TREE_CODE (predicate); label = create_artificial_label (UNKNOWN_LOCATION); label_true = create_artificial_label (UNKNOWN_LOCATION); if (TREE_CODE_CLASS (pred_code) == tcc_comparison) { arm1 = TREE_OPERAND (predicate, 0); arm2 = TREE_OPERAND (predicate, 1); gimplify_expr (&arm1, stmt_list, NULL, is_gimple_val, fb_rvalue); gimplify_expr (&arm2, stmt_list, NULL, is_gimple_val, fb_rvalue); } else { arm1 = predicate; gimplify_expr (&arm1, stmt_list, NULL, is_gimple_val, fb_rvalue); arm2 = boolean_false_node; pred_code = NE_EXPR; } if (maybe_simt) { c = build2 (pred_code, boolean_type_node, arm1, arm2); c = fold_convert (integer_type_node, c); simtcond = create_tmp_var (integer_type_node); gimplify_assign (simtcond, c, stmt_list); gcall *g = gimple_build_call_internal (IFN_GOMP_SIMT_VOTE_ANY, 1, simtcond); c = create_tmp_var (integer_type_node); gimple_call_set_lhs (g, c); gimple_seq_add_stmt (stmt_list, g); stmt = gimple_build_cond (NE_EXPR, c, integer_zero_node, label_true, label); } else stmt = gimple_build_cond (pred_code, arm1, arm2, label_true, label); gimple_seq_add_stmt (stmt_list, stmt); gimple_seq_add_stmt (stmt_list, gimple_build_label (label_true)); } for (c = clauses; c ;) { tree var, new_var; location_t clause_loc = OMP_CLAUSE_LOCATION (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE || (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR && !OMP_CLAUSE_LINEAR_NO_COPYOUT (c))) { var = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c) && is_taskloop_ctx (ctx)) { gcc_checking_assert (ctx->outer && is_task_ctx (ctx->outer)); new_var = lookup_decl (var, ctx->outer); } else { new_var = lookup_decl (var, ctx); /* Avoid uninitialized warnings for lastprivate and for linear iterators. */ if (predicate && (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE || OMP_CLAUSE_LINEAR_NO_COPYIN (c))) TREE_NO_WARNING (new_var) = 1; } if (!maybe_simt && simduid && DECL_HAS_VALUE_EXPR_P (new_var)) { tree val = DECL_VALUE_EXPR (new_var); if (TREE_CODE (val) == ARRAY_REF && VAR_P (TREE_OPERAND (val, 0)) && lookup_attribute ("omp simd array", DECL_ATTRIBUTES (TREE_OPERAND (val, 0)))) { if (lastlane == NULL) { lastlane = create_tmp_var (unsigned_type_node); gcall *g = gimple_build_call_internal (IFN_GOMP_SIMD_LAST_LANE, 2, simduid, TREE_OPERAND (val, 1)); gimple_call_set_lhs (g, lastlane); gimple_seq_add_stmt (stmt_list, g); } new_var = build4 (ARRAY_REF, TREE_TYPE (val), TREE_OPERAND (val, 0), lastlane, NULL_TREE, NULL_TREE); } } else if (maybe_simt) { tree val = (DECL_HAS_VALUE_EXPR_P (new_var) ? DECL_VALUE_EXPR (new_var) : new_var); if (simtlast == NULL) { simtlast = create_tmp_var (unsigned_type_node); gcall *g = gimple_build_call_internal (IFN_GOMP_SIMT_LAST_LANE, 1, simtcond); gimple_call_set_lhs (g, simtlast); gimple_seq_add_stmt (stmt_list, g); } x = build_call_expr_internal_loc (UNKNOWN_LOCATION, IFN_GOMP_SIMT_XCHG_IDX, TREE_TYPE (val), 2, val, simtlast); new_var = unshare_expr (new_var); gimplify_assign (new_var, x, stmt_list); new_var = unshare_expr (new_var); } if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)) { lower_omp (&OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c), ctx); gimple_seq_add_seq (stmt_list, OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c)); OMP_CLAUSE_LASTPRIVATE_GIMPLE_SEQ (c) = NULL; } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR && OMP_CLAUSE_LINEAR_GIMPLE_SEQ (c)) { lower_omp (&OMP_CLAUSE_LINEAR_GIMPLE_SEQ (c), ctx); gimple_seq_add_seq (stmt_list, OMP_CLAUSE_LINEAR_GIMPLE_SEQ (c)); OMP_CLAUSE_LINEAR_GIMPLE_SEQ (c) = NULL; } x = NULL_TREE; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE && OMP_CLAUSE_LASTPRIVATE_TASKLOOP_IV (c)) { gcc_checking_assert (is_taskloop_ctx (ctx)); tree ovar = maybe_lookup_decl_in_outer_ctx (var, ctx->outer->outer); if (is_global_var (ovar)) x = ovar; } if (!x) x = build_outer_var_ref (var, ctx, OMP_CLAUSE_LASTPRIVATE); if (omp_is_reference (var)) new_var = build_simple_mem_ref_loc (clause_loc, new_var); x = lang_hooks.decls.omp_clause_assign_op (c, x, new_var); gimplify_and_add (x, stmt_list); } c = OMP_CLAUSE_CHAIN (c); if (c == NULL && !par_clauses) { /* If this was a workshare clause, see if it had been combined with its parallel. In that case, continue looking for the clauses also on the parallel statement itself. */ if (is_parallel_ctx (ctx)) break; ctx = ctx->outer; if (ctx == NULL || !is_parallel_ctx (ctx)) break; c = omp_find_clause (gimple_omp_parallel_clauses (ctx->stmt), OMP_CLAUSE_LASTPRIVATE); par_clauses = true; } } if (label) gimple_seq_add_stmt (stmt_list, gimple_build_label (label)); } /* Lower the OpenACC reductions of CLAUSES for compute axis LEVEL (which might be a placeholder). INNER is true if this is an inner axis of a multi-axis loop. FORK and JOIN are (optional) fork and join markers. Generate the before-loop forking sequence in FORK_SEQ and the after-loop joining sequence to JOIN_SEQ. The general form of these sequences is GOACC_REDUCTION_SETUP GOACC_FORK GOACC_REDUCTION_INIT ... GOACC_REDUCTION_FINI GOACC_JOIN GOACC_REDUCTION_TEARDOWN. */ static void lower_oacc_reductions (location_t loc, tree clauses, tree level, bool inner, gcall *fork, gcall *join, gimple_seq *fork_seq, gimple_seq *join_seq, omp_context *ctx) { gimple_seq before_fork = NULL; gimple_seq after_fork = NULL; gimple_seq before_join = NULL; gimple_seq after_join = NULL; tree init_code = NULL_TREE, fini_code = NULL_TREE, setup_code = NULL_TREE, teardown_code = NULL_TREE; unsigned offset = 0; for (tree c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION) { tree orig = OMP_CLAUSE_DECL (c); tree var = maybe_lookup_decl (orig, ctx); tree ref_to_res = NULL_TREE; tree incoming, outgoing, v1, v2, v3; bool is_private = false; enum tree_code rcode = OMP_CLAUSE_REDUCTION_CODE (c); if (rcode == MINUS_EXPR) rcode = PLUS_EXPR; else if (rcode == TRUTH_ANDIF_EXPR) rcode = BIT_AND_EXPR; else if (rcode == TRUTH_ORIF_EXPR) rcode = BIT_IOR_EXPR; tree op = build_int_cst (unsigned_type_node, rcode); if (!var) var = orig; incoming = outgoing = var; if (!inner) { /* See if an outer construct also reduces this variable. */ omp_context *outer = ctx; while (omp_context *probe = outer->outer) { enum gimple_code type = gimple_code (probe->stmt); tree cls; switch (type) { case GIMPLE_OMP_FOR: cls = gimple_omp_for_clauses (probe->stmt); break; case GIMPLE_OMP_TARGET: if (gimple_omp_target_kind (probe->stmt) != GF_OMP_TARGET_KIND_OACC_PARALLEL) goto do_lookup; cls = gimple_omp_target_clauses (probe->stmt); break; default: goto do_lookup; } outer = probe; for (; cls; cls = OMP_CLAUSE_CHAIN (cls)) if (OMP_CLAUSE_CODE (cls) == OMP_CLAUSE_REDUCTION && orig == OMP_CLAUSE_DECL (cls)) { incoming = outgoing = lookup_decl (orig, probe); goto has_outer_reduction; } else if ((OMP_CLAUSE_CODE (cls) == OMP_CLAUSE_FIRSTPRIVATE || OMP_CLAUSE_CODE (cls) == OMP_CLAUSE_PRIVATE) && orig == OMP_CLAUSE_DECL (cls)) { is_private = true; goto do_lookup; } } do_lookup: /* This is the outermost construct with this reduction, see if there's a mapping for it. */ if (gimple_code (outer->stmt) == GIMPLE_OMP_TARGET && maybe_lookup_field (orig, outer) && !is_private) { ref_to_res = build_receiver_ref (orig, false, outer); if (omp_is_reference (orig)) ref_to_res = build_simple_mem_ref (ref_to_res); tree type = TREE_TYPE (var); if (POINTER_TYPE_P (type)) type = TREE_TYPE (type); outgoing = var; incoming = omp_reduction_init_op (loc, rcode, type); } else { /* Try to look at enclosing contexts for reduction var, use original if no mapping found. */ tree t = NULL_TREE; omp_context *c = ctx->outer; while (c && !t) { t = maybe_lookup_decl (orig, c); c = c->outer; } incoming = outgoing = (t ? t : orig); } has_outer_reduction:; } if (!ref_to_res) ref_to_res = integer_zero_node; if (omp_is_reference (orig)) { tree type = TREE_TYPE (var); const char *id = IDENTIFIER_POINTER (DECL_NAME (var)); if (!inner) { tree x = create_tmp_var (TREE_TYPE (type), id); gimplify_assign (var, build_fold_addr_expr (x), fork_seq); } v1 = create_tmp_var (type, id); v2 = create_tmp_var (type, id); v3 = create_tmp_var (type, id); gimplify_assign (v1, var, fork_seq); gimplify_assign (v2, var, fork_seq); gimplify_assign (v3, var, fork_seq); var = build_simple_mem_ref (var); v1 = build_simple_mem_ref (v1); v2 = build_simple_mem_ref (v2); v3 = build_simple_mem_ref (v3); outgoing = build_simple_mem_ref (outgoing); if (!TREE_CONSTANT (incoming)) incoming = build_simple_mem_ref (incoming); } else v1 = v2 = v3 = var; /* Determine position in reduction buffer, which may be used by target. The parser has ensured that this is not a variable-sized type. */ fixed_size_mode mode = as_a <fixed_size_mode> (TYPE_MODE (TREE_TYPE (var))); unsigned align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT; offset = (offset + align - 1) & ~(align - 1); tree off = build_int_cst (sizetype, offset); offset += GET_MODE_SIZE (mode); if (!init_code) { init_code = build_int_cst (integer_type_node, IFN_GOACC_REDUCTION_INIT); fini_code = build_int_cst (integer_type_node, IFN_GOACC_REDUCTION_FINI); setup_code = build_int_cst (integer_type_node, IFN_GOACC_REDUCTION_SETUP); teardown_code = build_int_cst (integer_type_node, IFN_GOACC_REDUCTION_TEARDOWN); } tree setup_call = build_call_expr_internal_loc (loc, IFN_GOACC_REDUCTION, TREE_TYPE (var), 6, setup_code, unshare_expr (ref_to_res), incoming, level, op, off); tree init_call = build_call_expr_internal_loc (loc, IFN_GOACC_REDUCTION, TREE_TYPE (var), 6, init_code, unshare_expr (ref_to_res), v1, level, op, off); tree fini_call = build_call_expr_internal_loc (loc, IFN_GOACC_REDUCTION, TREE_TYPE (var), 6, fini_code, unshare_expr (ref_to_res), v2, level, op, off); tree teardown_call = build_call_expr_internal_loc (loc, IFN_GOACC_REDUCTION, TREE_TYPE (var), 6, teardown_code, ref_to_res, v3, level, op, off); gimplify_assign (v1, setup_call, &before_fork); gimplify_assign (v2, init_call, &after_fork); gimplify_assign (v3, fini_call, &before_join); gimplify_assign (outgoing, teardown_call, &after_join); } /* Now stitch things together. */ gimple_seq_add_seq (fork_seq, before_fork); if (fork) gimple_seq_add_stmt (fork_seq, fork); gimple_seq_add_seq (fork_seq, after_fork); gimple_seq_add_seq (join_seq, before_join); if (join) gimple_seq_add_stmt (join_seq, join); gimple_seq_add_seq (join_seq, after_join); } /* Generate code to implement the REDUCTION clauses. */ static void lower_reduction_clauses (tree clauses, gimple_seq *stmt_seqp, omp_context *ctx) { gimple_seq sub_seq = NULL; gimple *stmt; tree x, c; int count = 0; /* OpenACC loop reductions are handled elsewhere. */ if (is_gimple_omp_oacc (ctx->stmt)) return; /* SIMD reductions are handled in lower_rec_input_clauses. */ if (gimple_code (ctx->stmt) == GIMPLE_OMP_FOR && gimple_omp_for_kind (ctx->stmt) & GF_OMP_FOR_SIMD) return; /* First see if there is exactly one reduction clause. Use OMP_ATOMIC update in that case, otherwise use a lock. */ for (c = clauses; c && count < 2; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION) { if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) || TREE_CODE (OMP_CLAUSE_DECL (c)) == MEM_REF) { /* Never use OMP_ATOMIC for array reductions or UDRs. */ count = -1; break; } count++; } if (count == 0) return; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree var, ref, new_var, orig_var; enum tree_code code; location_t clause_loc = OMP_CLAUSE_LOCATION (c); if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_REDUCTION) continue; enum omp_clause_code ccode = OMP_CLAUSE_REDUCTION; orig_var = var = OMP_CLAUSE_DECL (c); if (TREE_CODE (var) == MEM_REF) { var = TREE_OPERAND (var, 0); if (TREE_CODE (var) == POINTER_PLUS_EXPR) var = TREE_OPERAND (var, 0); if (TREE_CODE (var) == ADDR_EXPR) var = TREE_OPERAND (var, 0); else { /* If this is a pointer or referenced based array section, the var could be private in the outer context e.g. on orphaned loop construct. Pretend this is private variable's outer reference. */ ccode = OMP_CLAUSE_PRIVATE; if (TREE_CODE (var) == INDIRECT_REF) var = TREE_OPERAND (var, 0); } orig_var = var; if (is_variable_sized (var)) { gcc_assert (DECL_HAS_VALUE_EXPR_P (var)); var = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (var) == INDIRECT_REF); var = TREE_OPERAND (var, 0); gcc_assert (DECL_P (var)); } } new_var = lookup_decl (var, ctx); if (var == OMP_CLAUSE_DECL (c) && omp_is_reference (var)) new_var = build_simple_mem_ref_loc (clause_loc, new_var); ref = build_outer_var_ref (var, ctx, ccode); code = OMP_CLAUSE_REDUCTION_CODE (c); /* reduction(-:var) sums up the partial results, so it acts identically to reduction(+:var). */ if (code == MINUS_EXPR) code = PLUS_EXPR; if (count == 1) { tree addr = build_fold_addr_expr_loc (clause_loc, ref); addr = save_expr (addr); ref = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (addr)), addr); x = fold_build2_loc (clause_loc, code, TREE_TYPE (ref), ref, new_var); x = build2 (OMP_ATOMIC, void_type_node, addr, x); gimplify_and_add (x, stmt_seqp); return; } else if (TREE_CODE (OMP_CLAUSE_DECL (c)) == MEM_REF) { tree d = OMP_CLAUSE_DECL (c); tree type = TREE_TYPE (d); tree v = TYPE_MAX_VALUE (TYPE_DOMAIN (type)); tree i = create_tmp_var (TREE_TYPE (v), NULL); tree ptype = build_pointer_type (TREE_TYPE (type)); tree bias = TREE_OPERAND (d, 1); d = TREE_OPERAND (d, 0); if (TREE_CODE (d) == POINTER_PLUS_EXPR) { tree b = TREE_OPERAND (d, 1); b = maybe_lookup_decl (b, ctx); if (b == NULL) { b = TREE_OPERAND (d, 1); b = maybe_lookup_decl_in_outer_ctx (b, ctx); } if (integer_zerop (bias)) bias = b; else { bias = fold_convert_loc (clause_loc, TREE_TYPE (b), bias); bias = fold_build2_loc (clause_loc, PLUS_EXPR, TREE_TYPE (b), b, bias); } d = TREE_OPERAND (d, 0); } /* For ref build_outer_var_ref already performs this, so only new_var needs a dereference. */ if (TREE_CODE (d) == INDIRECT_REF) { new_var = build_simple_mem_ref_loc (clause_loc, new_var); gcc_assert (omp_is_reference (var) && var == orig_var); } else if (TREE_CODE (d) == ADDR_EXPR) { if (orig_var == var) { new_var = build_fold_addr_expr (new_var); ref = build_fold_addr_expr (ref); } } else { gcc_assert (orig_var == var); if (omp_is_reference (var)) ref = build_fold_addr_expr (ref); } if (DECL_P (v)) { tree t = maybe_lookup_decl (v, ctx); if (t) v = t; else v = maybe_lookup_decl_in_outer_ctx (v, ctx); gimplify_expr (&v, stmt_seqp, NULL, is_gimple_val, fb_rvalue); } if (!integer_zerop (bias)) { bias = fold_convert_loc (clause_loc, sizetype, bias); new_var = fold_build2_loc (clause_loc, POINTER_PLUS_EXPR, TREE_TYPE (new_var), new_var, unshare_expr (bias)); ref = fold_build2_loc (clause_loc, POINTER_PLUS_EXPR, TREE_TYPE (ref), ref, bias); } new_var = fold_convert_loc (clause_loc, ptype, new_var); ref = fold_convert_loc (clause_loc, ptype, ref); tree m = create_tmp_var (ptype, NULL); gimplify_assign (m, new_var, stmt_seqp); new_var = m; m = create_tmp_var (ptype, NULL); gimplify_assign (m, ref, stmt_seqp); ref = m; gimplify_assign (i, build_int_cst (TREE_TYPE (v), 0), stmt_seqp); tree body = create_artificial_label (UNKNOWN_LOCATION); tree end = create_artificial_label (UNKNOWN_LOCATION); gimple_seq_add_stmt (&sub_seq, gimple_build_label (body)); tree priv = build_simple_mem_ref_loc (clause_loc, new_var); tree out = build_simple_mem_ref_loc (clause_loc, ref); if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); tree decl_placeholder = OMP_CLAUSE_REDUCTION_DECL_PLACEHOLDER (c); SET_DECL_VALUE_EXPR (placeholder, out); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; SET_DECL_VALUE_EXPR (decl_placeholder, priv); DECL_HAS_VALUE_EXPR_P (decl_placeholder) = 1; lower_omp (&OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c), ctx); gimple_seq_add_seq (&sub_seq, OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c)); OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = NULL; OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = NULL; OMP_CLAUSE_REDUCTION_DECL_PLACEHOLDER (c) = NULL; } else { x = build2 (code, TREE_TYPE (out), out, priv); out = unshare_expr (out); gimplify_assign (out, x, &sub_seq); } gimple *g = gimple_build_assign (new_var, POINTER_PLUS_EXPR, new_var, TYPE_SIZE_UNIT (TREE_TYPE (type))); gimple_seq_add_stmt (&sub_seq, g); g = gimple_build_assign (ref, POINTER_PLUS_EXPR, ref, TYPE_SIZE_UNIT (TREE_TYPE (type))); gimple_seq_add_stmt (&sub_seq, g); g = gimple_build_assign (i, PLUS_EXPR, i, build_int_cst (TREE_TYPE (i), 1)); gimple_seq_add_stmt (&sub_seq, g); g = gimple_build_cond (LE_EXPR, i, v, body, end); gimple_seq_add_stmt (&sub_seq, g); gimple_seq_add_stmt (&sub_seq, gimple_build_label (end)); } else if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); if (omp_is_reference (var) && !useless_type_conversion_p (TREE_TYPE (placeholder), TREE_TYPE (ref))) ref = build_fold_addr_expr_loc (clause_loc, ref); SET_DECL_VALUE_EXPR (placeholder, ref); DECL_HAS_VALUE_EXPR_P (placeholder) = 1; lower_omp (&OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c), ctx); gimple_seq_add_seq (&sub_seq, OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c)); OMP_CLAUSE_REDUCTION_GIMPLE_MERGE (c) = NULL; OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = NULL; } else { x = build2 (code, TREE_TYPE (ref), ref, new_var); ref = build_outer_var_ref (var, ctx); gimplify_assign (ref, x, &sub_seq); } } stmt = gimple_build_call (builtin_decl_explicit (BUILT_IN_GOMP_ATOMIC_START), 0); gimple_seq_add_stmt (stmt_seqp, stmt); gimple_seq_add_seq (stmt_seqp, sub_seq); stmt = gimple_build_call (builtin_decl_explicit (BUILT_IN_GOMP_ATOMIC_END), 0); gimple_seq_add_stmt (stmt_seqp, stmt); } /* Generate code to implement the COPYPRIVATE clauses. */ static void lower_copyprivate_clauses (tree clauses, gimple_seq *slist, gimple_seq *rlist, omp_context *ctx) { tree c; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree var, new_var, ref, x; bool by_ref; location_t clause_loc = OMP_CLAUSE_LOCATION (c); if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_COPYPRIVATE) continue; var = OMP_CLAUSE_DECL (c); by_ref = use_pointer_for_field (var, NULL); ref = build_sender_ref (var, ctx); x = new_var = lookup_decl_in_outer_ctx (var, ctx); if (by_ref) { x = build_fold_addr_expr_loc (clause_loc, new_var); x = fold_convert_loc (clause_loc, TREE_TYPE (ref), x); } gimplify_assign (ref, x, slist); ref = build_receiver_ref (var, false, ctx); if (by_ref) { ref = fold_convert_loc (clause_loc, build_pointer_type (TREE_TYPE (new_var)), ref); ref = build_fold_indirect_ref_loc (clause_loc, ref); } if (omp_is_reference (var)) { ref = fold_convert_loc (clause_loc, TREE_TYPE (new_var), ref); ref = build_simple_mem_ref_loc (clause_loc, ref); new_var = build_simple_mem_ref_loc (clause_loc, new_var); } x = lang_hooks.decls.omp_clause_assign_op (c, new_var, ref); gimplify_and_add (x, rlist); } } /* Generate code to implement the clauses, FIRSTPRIVATE, COPYIN, LASTPRIVATE, and REDUCTION from the sender (aka parent) side. */ static void lower_send_clauses (tree clauses, gimple_seq *ilist, gimple_seq *olist, omp_context *ctx) { tree c, t; int ignored_looptemp = 0; bool is_taskloop = false; /* For taskloop, ignore first two _looptemp_ clauses, those are initialized by GOMP_taskloop. */ if (is_task_ctx (ctx) && gimple_omp_task_taskloop_p (ctx->stmt)) { ignored_looptemp = 2; is_taskloop = true; } for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) { tree val, ref, x, var; bool by_ref, do_in = false, do_out = false; location_t clause_loc = OMP_CLAUSE_LOCATION (c); switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_PRIVATE: if (OMP_CLAUSE_PRIVATE_OUTER_REF (c)) break; continue; case OMP_CLAUSE_FIRSTPRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE_LASTPRIVATE: case OMP_CLAUSE_REDUCTION: break; case OMP_CLAUSE_SHARED: if (OMP_CLAUSE_SHARED_FIRSTPRIVATE (c)) break; continue; case OMP_CLAUSE__LOOPTEMP_: if (ignored_looptemp) { ignored_looptemp--; continue; } break; default: continue; } val = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && TREE_CODE (val) == MEM_REF) { val = TREE_OPERAND (val, 0); if (TREE_CODE (val) == POINTER_PLUS_EXPR) val = TREE_OPERAND (val, 0); if (TREE_CODE (val) == INDIRECT_REF || TREE_CODE (val) == ADDR_EXPR) val = TREE_OPERAND (val, 0); if (is_variable_sized (val)) continue; } /* For OMP_CLAUSE_SHARED_FIRSTPRIVATE, look beyond the outer taskloop region. */ omp_context *ctx_for_o = ctx; if (is_taskloop && OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED && OMP_CLAUSE_SHARED_FIRSTPRIVATE (c)) ctx_for_o = ctx->outer; var = lookup_decl_in_outer_ctx (val, ctx_for_o); if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_COPYIN && is_global_var (var)) continue; t = omp_member_access_dummy_var (var); if (t) { var = DECL_VALUE_EXPR (var); tree o = maybe_lookup_decl_in_outer_ctx (t, ctx_for_o); if (o != t) var = unshare_and_remap (var, t, o); else var = unshare_expr (var); } if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED) { /* Handle taskloop firstprivate/lastprivate, where the lastprivate on GIMPLE_OMP_TASK is represented as OMP_CLAUSE_SHARED_FIRSTPRIVATE. */ tree f = lookup_sfield ((splay_tree_key) &DECL_UID (val), ctx); x = omp_build_component_ref (ctx->sender_decl, f); if (use_pointer_for_field (val, ctx)) var = build_fold_addr_expr (var); gimplify_assign (x, var, ilist); DECL_ABSTRACT_ORIGIN (f) = NULL; continue; } if ((OMP_CLAUSE_CODE (c) != OMP_CLAUSE_REDUCTION || val == OMP_CLAUSE_DECL (c)) && is_variable_sized (val)) continue; by_ref = use_pointer_for_field (val, NULL); switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_FIRSTPRIVATE: if (OMP_CLAUSE_FIRSTPRIVATE_IMPLICIT (c) && !by_ref && is_task_ctx (ctx)) TREE_NO_WARNING (var) = 1; do_in = true; break; case OMP_CLAUSE_PRIVATE: case OMP_CLAUSE_COPYIN: case OMP_CLAUSE__LOOPTEMP_: do_in = true; break; case OMP_CLAUSE_LASTPRIVATE: if (by_ref || omp_is_reference (val)) { if (OMP_CLAUSE_LASTPRIVATE_FIRSTPRIVATE (c)) continue; do_in = true; } else { do_out = true; if (lang_hooks.decls.omp_private_outer_ref (val)) do_in = true; } break; case OMP_CLAUSE_REDUCTION: do_in = true; if (val == OMP_CLAUSE_DECL (c)) do_out = !(by_ref || omp_is_reference (val)); else by_ref = TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE; break; default: gcc_unreachable (); } if (do_in) { ref = build_sender_ref (val, ctx); x = by_ref ? build_fold_addr_expr_loc (clause_loc, var) : var; gimplify_assign (ref, x, ilist); if (is_task_ctx (ctx)) DECL_ABSTRACT_ORIGIN (TREE_OPERAND (ref, 1)) = NULL; } if (do_out) { ref = build_sender_ref (val, ctx); gimplify_assign (var, ref, olist); } } } /* Generate code to implement SHARED from the sender (aka parent) side. This is trickier, since GIMPLE_OMP_PARALLEL_CLAUSES doesn't list things that got automatically shared. */ static void lower_send_shared_vars (gimple_seq *ilist, gimple_seq *olist, omp_context *ctx) { tree var, ovar, nvar, t, f, x, record_type; if (ctx->record_type == NULL) return; record_type = ctx->srecord_type ? ctx->srecord_type : ctx->record_type; for (f = TYPE_FIELDS (record_type); f ; f = DECL_CHAIN (f)) { ovar = DECL_ABSTRACT_ORIGIN (f); if (!ovar || TREE_CODE (ovar) == FIELD_DECL) continue; nvar = maybe_lookup_decl (ovar, ctx); if (!nvar || !DECL_HAS_VALUE_EXPR_P (nvar)) continue; /* If CTX is a nested parallel directive. Find the immediately enclosing parallel or workshare construct that contains a mapping for OVAR. */ var = lookup_decl_in_outer_ctx (ovar, ctx); t = omp_member_access_dummy_var (var); if (t) { var = DECL_VALUE_EXPR (var); tree o = maybe_lookup_decl_in_outer_ctx (t, ctx); if (o != t) var = unshare_and_remap (var, t, o); else var = unshare_expr (var); } if (use_pointer_for_field (ovar, ctx)) { x = build_sender_ref (ovar, ctx); var = build_fold_addr_expr (var); gimplify_assign (x, var, ilist); } else { x = build_sender_ref (ovar, ctx); gimplify_assign (x, var, ilist); if (!TREE_READONLY (var) /* We don't need to receive a new reference to a result or parm decl. In fact we may not store to it as we will invalidate any pending RSO and generate wrong gimple during inlining. */ && !((TREE_CODE (var) == RESULT_DECL || TREE_CODE (var) == PARM_DECL) && DECL_BY_REFERENCE (var))) { x = build_sender_ref (ovar, ctx); gimplify_assign (var, x, olist); } } } } /* Emit an OpenACC head marker call, encapulating the partitioning and other information that must be processed by the target compiler. Return the maximum number of dimensions the associated loop might be partitioned over. */ static unsigned lower_oacc_head_mark (location_t loc, tree ddvar, tree clauses, gimple_seq *seq, omp_context *ctx) { unsigned levels = 0; unsigned tag = 0; tree gang_static = NULL_TREE; auto_vec<tree, 5> args; args.quick_push (build_int_cst (integer_type_node, IFN_UNIQUE_OACC_HEAD_MARK)); args.quick_push (ddvar); for (tree c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) { switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_GANG: tag |= OLF_DIM_GANG; gang_static = OMP_CLAUSE_GANG_STATIC_EXPR (c); /* static:* is represented by -1, and we can ignore it, as scheduling is always static. */ if (gang_static && integer_minus_onep (gang_static)) gang_static = NULL_TREE; levels++; break; case OMP_CLAUSE_WORKER: tag |= OLF_DIM_WORKER; levels++; break; case OMP_CLAUSE_VECTOR: tag |= OLF_DIM_VECTOR; levels++; break; case OMP_CLAUSE_SEQ: tag |= OLF_SEQ; break; case OMP_CLAUSE_AUTO: tag |= OLF_AUTO; break; case OMP_CLAUSE_INDEPENDENT: tag |= OLF_INDEPENDENT; break; case OMP_CLAUSE_TILE: tag |= OLF_TILE; break; default: continue; } } if (gang_static) { if (DECL_P (gang_static)) gang_static = build_outer_var_ref (gang_static, ctx); tag |= OLF_GANG_STATIC; } /* In a parallel region, loops are implicitly INDEPENDENT. */ omp_context *tgt = enclosing_target_ctx (ctx); if (!tgt || is_oacc_parallel (tgt)) tag |= OLF_INDEPENDENT; if (tag & OLF_TILE) /* Tiling could use all 3 levels. */ levels = 3; else { /* A loop lacking SEQ, GANG, WORKER and/or VECTOR could be AUTO. Ensure at least one level, or 2 for possible auto partitioning */ bool maybe_auto = !(tag & (((GOMP_DIM_MASK (GOMP_DIM_MAX) - 1) << OLF_DIM_BASE) | OLF_SEQ)); if (levels < 1u + maybe_auto) levels = 1u + maybe_auto; } args.quick_push (build_int_cst (integer_type_node, levels)); args.quick_push (build_int_cst (integer_type_node, tag)); if (gang_static) args.quick_push (gang_static); gcall *call = gimple_build_call_internal_vec (IFN_UNIQUE, args); gimple_set_location (call, loc); gimple_set_lhs (call, ddvar); gimple_seq_add_stmt (seq, call); return levels; } /* Emit an OpenACC lopp head or tail marker to SEQ. LEVEL is the partitioning level of the enclosed region. */ static void lower_oacc_loop_marker (location_t loc, tree ddvar, bool head, tree tofollow, gimple_seq *seq) { int marker_kind = (head ? IFN_UNIQUE_OACC_HEAD_MARK : IFN_UNIQUE_OACC_TAIL_MARK); tree marker = build_int_cst (integer_type_node, marker_kind); int nargs = 2 + (tofollow != NULL_TREE); gcall *call = gimple_build_call_internal (IFN_UNIQUE, nargs, marker, ddvar, tofollow); gimple_set_location (call, loc); gimple_set_lhs (call, ddvar); gimple_seq_add_stmt (seq, call); } /* Generate the before and after OpenACC loop sequences. CLAUSES are the loop clauses, from which we extract reductions. Initialize HEAD and TAIL. */ static void lower_oacc_head_tail (location_t loc, tree clauses, gimple_seq *head, gimple_seq *tail, omp_context *ctx) { bool inner = false; tree ddvar = create_tmp_var (integer_type_node, ".data_dep"); gimple_seq_add_stmt (head, gimple_build_assign (ddvar, integer_zero_node)); unsigned count = lower_oacc_head_mark (loc, ddvar, clauses, head, ctx); tree fork_kind = build_int_cst (unsigned_type_node, IFN_UNIQUE_OACC_FORK); tree join_kind = build_int_cst (unsigned_type_node, IFN_UNIQUE_OACC_JOIN); gcc_assert (count); for (unsigned done = 1; count; count--, done++) { gimple_seq fork_seq = NULL; gimple_seq join_seq = NULL; tree place = build_int_cst (integer_type_node, -1); gcall *fork = gimple_build_call_internal (IFN_UNIQUE, 3, fork_kind, ddvar, place); gimple_set_location (fork, loc); gimple_set_lhs (fork, ddvar); gcall *join = gimple_build_call_internal (IFN_UNIQUE, 3, join_kind, ddvar, place); gimple_set_location (join, loc); gimple_set_lhs (join, ddvar); /* Mark the beginning of this level sequence. */ if (inner) lower_oacc_loop_marker (loc, ddvar, true, build_int_cst (integer_type_node, count), &fork_seq); lower_oacc_loop_marker (loc, ddvar, false, build_int_cst (integer_type_node, done), &join_seq); lower_oacc_reductions (loc, clauses, place, inner, fork, join, &fork_seq, &join_seq, ctx); /* Append this level to head. */ gimple_seq_add_seq (head, fork_seq); /* Prepend it to tail. */ gimple_seq_add_seq (&join_seq, *tail); *tail = join_seq; inner = true; } /* Mark the end of the sequence. */ lower_oacc_loop_marker (loc, ddvar, true, NULL_TREE, head); lower_oacc_loop_marker (loc, ddvar, false, NULL_TREE, tail); } /* If exceptions are enabled, wrap the statements in BODY in a MUST_NOT_THROW catch handler and return it. This prevents programs from violating the structured block semantics with throws. */ static gimple_seq maybe_catch_exception (gimple_seq body) { gimple *g; tree decl; if (!flag_exceptions) return body; if (lang_hooks.eh_protect_cleanup_actions != NULL) decl = lang_hooks.eh_protect_cleanup_actions (); else decl = builtin_decl_explicit (BUILT_IN_TRAP); g = gimple_build_eh_must_not_throw (decl); g = gimple_build_try (body, gimple_seq_alloc_with_stmt (g), GIMPLE_TRY_CATCH); return gimple_seq_alloc_with_stmt (g); } /* Routines to lower OMP directives into OMP-GIMPLE. */ /* If ctx is a worksharing context inside of a cancellable parallel region and it isn't nowait, add lhs to its GIMPLE_OMP_RETURN and conditional branch to parallel's cancel_label to handle cancellation in the implicit barrier. */ static void maybe_add_implicit_barrier_cancel (omp_context *ctx, gimple_seq *body) { gimple *omp_return = gimple_seq_last_stmt (*body); gcc_assert (gimple_code (omp_return) == GIMPLE_OMP_RETURN); if (gimple_omp_return_nowait_p (omp_return)) return; if (ctx->outer && gimple_code (ctx->outer->stmt) == GIMPLE_OMP_PARALLEL && ctx->outer->cancellable) { tree fndecl = builtin_decl_explicit (BUILT_IN_GOMP_CANCEL); tree c_bool_type = TREE_TYPE (TREE_TYPE (fndecl)); tree lhs = create_tmp_var (c_bool_type); gimple_omp_return_set_lhs (omp_return, lhs); tree fallthru_label = create_artificial_label (UNKNOWN_LOCATION); gimple *g = gimple_build_cond (NE_EXPR, lhs, fold_convert (c_bool_type, boolean_false_node), ctx->outer->cancel_label, fallthru_label); gimple_seq_add_stmt (body, g); gimple_seq_add_stmt (body, gimple_build_label (fallthru_label)); } } /* Lower the OpenMP sections directive in the current statement in GSI_P. CTX is the enclosing OMP context for the current statement. */ static void lower_omp_sections (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree block, control; gimple_stmt_iterator tgsi; gomp_sections *stmt; gimple *t; gbind *new_stmt, *bind; gimple_seq ilist, dlist, olist, new_body; stmt = as_a <gomp_sections *> (gsi_stmt (*gsi_p)); push_gimplify_context (); dlist = NULL; ilist = NULL; lower_rec_input_clauses (gimple_omp_sections_clauses (stmt), &ilist, &dlist, ctx, NULL); new_body = gimple_omp_body (stmt); gimple_omp_set_body (stmt, NULL); tgsi = gsi_start (new_body); for (; !gsi_end_p (tgsi); gsi_next (&tgsi)) { omp_context *sctx; gimple *sec_start; sec_start = gsi_stmt (tgsi); sctx = maybe_lookup_ctx (sec_start); gcc_assert (sctx); lower_omp (gimple_omp_body_ptr (sec_start), sctx); gsi_insert_seq_after (&tgsi, gimple_omp_body (sec_start), GSI_CONTINUE_LINKING); gimple_omp_set_body (sec_start, NULL); if (gsi_one_before_end_p (tgsi)) { gimple_seq l = NULL; lower_lastprivate_clauses (gimple_omp_sections_clauses (stmt), NULL, &l, ctx); gsi_insert_seq_after (&tgsi, l, GSI_CONTINUE_LINKING); gimple_omp_section_set_last (sec_start); } gsi_insert_after (&tgsi, gimple_build_omp_return (false), GSI_CONTINUE_LINKING); } block = make_node (BLOCK); bind = gimple_build_bind (NULL, new_body, block); olist = NULL; lower_reduction_clauses (gimple_omp_sections_clauses (stmt), &olist, ctx); block = make_node (BLOCK); new_stmt = gimple_build_bind (NULL, NULL, block); gsi_replace (gsi_p, new_stmt, true); pop_gimplify_context (new_stmt); gimple_bind_append_vars (new_stmt, ctx->block_vars); BLOCK_VARS (block) = gimple_bind_vars (bind); if (BLOCK_VARS (block)) TREE_USED (block) = 1; new_body = NULL; gimple_seq_add_seq (&new_body, ilist); gimple_seq_add_stmt (&new_body, stmt); gimple_seq_add_stmt (&new_body, gimple_build_omp_sections_switch ()); gimple_seq_add_stmt (&new_body, bind); control = create_tmp_var (unsigned_type_node, ".section"); t = gimple_build_omp_continue (control, control); gimple_omp_sections_set_control (stmt, control); gimple_seq_add_stmt (&new_body, t); gimple_seq_add_seq (&new_body, olist); if (ctx->cancellable) gimple_seq_add_stmt (&new_body, gimple_build_label (ctx->cancel_label)); gimple_seq_add_seq (&new_body, dlist); new_body = maybe_catch_exception (new_body); bool nowait = omp_find_clause (gimple_omp_sections_clauses (stmt), OMP_CLAUSE_NOWAIT) != NULL_TREE; t = gimple_build_omp_return (nowait); gimple_seq_add_stmt (&new_body, t); maybe_add_implicit_barrier_cancel (ctx, &new_body); gimple_bind_set_body (new_stmt, new_body); } /* A subroutine of lower_omp_single. Expand the simple form of a GIMPLE_OMP_SINGLE, without a copyprivate clause: if (GOMP_single_start ()) BODY; [ GOMP_barrier (); ] -> unless 'nowait' is present. FIXME. It may be better to delay expanding the logic of this until pass_expand_omp. The expanded logic may make the job more difficult to a synchronization analysis pass. */ static void lower_omp_single_simple (gomp_single *single_stmt, gimple_seq *pre_p) { location_t loc = gimple_location (single_stmt); tree tlabel = create_artificial_label (loc); tree flabel = create_artificial_label (loc); gimple *call, *cond; tree lhs, decl; decl = builtin_decl_explicit (BUILT_IN_GOMP_SINGLE_START); lhs = create_tmp_var (TREE_TYPE (TREE_TYPE (decl))); call = gimple_build_call (decl, 0); gimple_call_set_lhs (call, lhs); gimple_seq_add_stmt (pre_p, call); cond = gimple_build_cond (EQ_EXPR, lhs, fold_convert_loc (loc, TREE_TYPE (lhs), boolean_true_node), tlabel, flabel); gimple_seq_add_stmt (pre_p, cond); gimple_seq_add_stmt (pre_p, gimple_build_label (tlabel)); gimple_seq_add_seq (pre_p, gimple_omp_body (single_stmt)); gimple_seq_add_stmt (pre_p, gimple_build_label (flabel)); } /* A subroutine of lower_omp_single. Expand the simple form of a GIMPLE_OMP_SINGLE, with a copyprivate clause: #pragma omp single copyprivate (a, b, c) Create a new structure to hold copies of 'a', 'b' and 'c' and emit: { if ((copyout_p = GOMP_single_copy_start ()) == NULL) { BODY; copyout.a = a; copyout.b = b; copyout.c = c; GOMP_single_copy_end (&copyout); } else { a = copyout_p->a; b = copyout_p->b; c = copyout_p->c; } GOMP_barrier (); } FIXME. It may be better to delay expanding the logic of this until pass_expand_omp. The expanded logic may make the job more difficult to a synchronization analysis pass. */ static void lower_omp_single_copy (gomp_single *single_stmt, gimple_seq *pre_p, omp_context *ctx) { tree ptr_type, t, l0, l1, l2, bfn_decl; gimple_seq copyin_seq; location_t loc = gimple_location (single_stmt); ctx->sender_decl = create_tmp_var (ctx->record_type, ".omp_copy_o"); ptr_type = build_pointer_type (ctx->record_type); ctx->receiver_decl = create_tmp_var (ptr_type, ".omp_copy_i"); l0 = create_artificial_label (loc); l1 = create_artificial_label (loc); l2 = create_artificial_label (loc); bfn_decl = builtin_decl_explicit (BUILT_IN_GOMP_SINGLE_COPY_START); t = build_call_expr_loc (loc, bfn_decl, 0); t = fold_convert_loc (loc, ptr_type, t); gimplify_assign (ctx->receiver_decl, t, pre_p); t = build2 (EQ_EXPR, boolean_type_node, ctx->receiver_decl, build_int_cst (ptr_type, 0)); t = build3 (COND_EXPR, void_type_node, t, build_and_jump (&l0), build_and_jump (&l1)); gimplify_and_add (t, pre_p); gimple_seq_add_stmt (pre_p, gimple_build_label (l0)); gimple_seq_add_seq (pre_p, gimple_omp_body (single_stmt)); copyin_seq = NULL; lower_copyprivate_clauses (gimple_omp_single_clauses (single_stmt), pre_p, &copyin_seq, ctx); t = build_fold_addr_expr_loc (loc, ctx->sender_decl); bfn_decl = builtin_decl_explicit (BUILT_IN_GOMP_SINGLE_COPY_END); t = build_call_expr_loc (loc, bfn_decl, 1, t); gimplify_and_add (t, pre_p); t = build_and_jump (&l2); gimplify_and_add (t, pre_p); gimple_seq_add_stmt (pre_p, gimple_build_label (l1)); gimple_seq_add_seq (pre_p, copyin_seq); gimple_seq_add_stmt (pre_p, gimple_build_label (l2)); } /* Expand code for an OpenMP single directive. */ static void lower_omp_single (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree block; gomp_single *single_stmt = as_a <gomp_single *> (gsi_stmt (*gsi_p)); gbind *bind; gimple_seq bind_body, bind_body_tail = NULL, dlist; push_gimplify_context (); block = make_node (BLOCK); bind = gimple_build_bind (NULL, NULL, block); gsi_replace (gsi_p, bind, true); bind_body = NULL; dlist = NULL; lower_rec_input_clauses (gimple_omp_single_clauses (single_stmt), &bind_body, &dlist, ctx, NULL); lower_omp (gimple_omp_body_ptr (single_stmt), ctx); gimple_seq_add_stmt (&bind_body, single_stmt); if (ctx->record_type) lower_omp_single_copy (single_stmt, &bind_body, ctx); else lower_omp_single_simple (single_stmt, &bind_body); gimple_omp_set_body (single_stmt, NULL); gimple_seq_add_seq (&bind_body, dlist); bind_body = maybe_catch_exception (bind_body); bool nowait = omp_find_clause (gimple_omp_single_clauses (single_stmt), OMP_CLAUSE_NOWAIT) != NULL_TREE; gimple *g = gimple_build_omp_return (nowait); gimple_seq_add_stmt (&bind_body_tail, g); maybe_add_implicit_barrier_cancel (ctx, &bind_body_tail); if (ctx->record_type) { gimple_stmt_iterator gsi = gsi_start (bind_body_tail); tree clobber = build_constructor (ctx->record_type, NULL); TREE_THIS_VOLATILE (clobber) = 1; gsi_insert_after (&gsi, gimple_build_assign (ctx->sender_decl, clobber), GSI_SAME_STMT); } gimple_seq_add_seq (&bind_body, bind_body_tail); gimple_bind_set_body (bind, bind_body); pop_gimplify_context (bind); gimple_bind_append_vars (bind, ctx->block_vars); BLOCK_VARS (block) = ctx->block_vars; if (BLOCK_VARS (block)) TREE_USED (block) = 1; } /* Expand code for an OpenMP master directive. */ static void lower_omp_master (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree block, lab = NULL, x, bfn_decl; gimple *stmt = gsi_stmt (*gsi_p); gbind *bind; location_t loc = gimple_location (stmt); gimple_seq tseq; push_gimplify_context (); block = make_node (BLOCK); bind = gimple_build_bind (NULL, NULL, block); gsi_replace (gsi_p, bind, true); gimple_bind_add_stmt (bind, stmt); bfn_decl = builtin_decl_explicit (BUILT_IN_OMP_GET_THREAD_NUM); x = build_call_expr_loc (loc, bfn_decl, 0); x = build2 (EQ_EXPR, boolean_type_node, x, integer_zero_node); x = build3 (COND_EXPR, void_type_node, x, NULL, build_and_jump (&lab)); tseq = NULL; gimplify_and_add (x, &tseq); gimple_bind_add_seq (bind, tseq); lower_omp (gimple_omp_body_ptr (stmt), ctx); gimple_omp_set_body (stmt, maybe_catch_exception (gimple_omp_body (stmt))); gimple_bind_add_seq (bind, gimple_omp_body (stmt)); gimple_omp_set_body (stmt, NULL); gimple_bind_add_stmt (bind, gimple_build_label (lab)); gimple_bind_add_stmt (bind, gimple_build_omp_return (true)); pop_gimplify_context (bind); gimple_bind_append_vars (bind, ctx->block_vars); BLOCK_VARS (block) = ctx->block_vars; } /* Expand code for an OpenMP taskgroup directive. */ static void lower_omp_taskgroup (gimple_stmt_iterator *gsi_p, omp_context *ctx) { gimple *stmt = gsi_stmt (*gsi_p); gcall *x; gbind *bind; tree block = make_node (BLOCK); bind = gimple_build_bind (NULL, NULL, block); gsi_replace (gsi_p, bind, true); gimple_bind_add_stmt (bind, stmt); x = gimple_build_call (builtin_decl_explicit (BUILT_IN_GOMP_TASKGROUP_START), 0); gimple_bind_add_stmt (bind, x); lower_omp (gimple_omp_body_ptr (stmt), ctx); gimple_bind_add_seq (bind, gimple_omp_body (stmt)); gimple_omp_set_body (stmt, NULL); gimple_bind_add_stmt (bind, gimple_build_omp_return (true)); gimple_bind_append_vars (bind, ctx->block_vars); BLOCK_VARS (block) = ctx->block_vars; } /* Fold the OMP_ORDERED_CLAUSES for the OMP_ORDERED in STMT if possible. */ static void lower_omp_ordered_clauses (gimple_stmt_iterator *gsi_p, gomp_ordered *ord_stmt, omp_context *ctx) { struct omp_for_data fd; if (!ctx->outer || gimple_code (ctx->outer->stmt) != GIMPLE_OMP_FOR) return; unsigned int len = gimple_omp_for_collapse (ctx->outer->stmt); struct omp_for_data_loop *loops = XALLOCAVEC (struct omp_for_data_loop, len); omp_extract_for_data (as_a <gomp_for *> (ctx->outer->stmt), &fd, loops); if (!fd.ordered) return; tree *list_p = gimple_omp_ordered_clauses_ptr (ord_stmt); tree c = gimple_omp_ordered_clauses (ord_stmt); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND && OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_SINK) { /* Merge depend clauses from multiple adjacent #pragma omp ordered depend(sink:...) constructs into one #pragma omp ordered depend(sink:...), so that we can optimize them together. */ gimple_stmt_iterator gsi = *gsi_p; gsi_next (&gsi); while (!gsi_end_p (gsi)) { gimple *stmt = gsi_stmt (gsi); if (is_gimple_debug (stmt) || gimple_code (stmt) == GIMPLE_NOP) { gsi_next (&gsi); continue; } if (gimple_code (stmt) != GIMPLE_OMP_ORDERED) break; gomp_ordered *ord_stmt2 = as_a <gomp_ordered *> (stmt); c = gimple_omp_ordered_clauses (ord_stmt2); if (c == NULL_TREE || OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND || OMP_CLAUSE_DEPEND_KIND (c) != OMP_CLAUSE_DEPEND_SINK) break; while (*list_p) list_p = &OMP_CLAUSE_CHAIN (*list_p); *list_p = c; gsi_remove (&gsi, true); } } /* Canonicalize sink dependence clauses into one folded clause if possible. The basic algorithm is to create a sink vector whose first element is the GCD of all the first elements, and whose remaining elements are the minimum of the subsequent columns. We ignore dependence vectors whose first element is zero because such dependencies are known to be executed by the same thread. We take into account the direction of the loop, so a minimum becomes a maximum if the loop is iterating forwards. We also ignore sink clauses where the loop direction is unknown, or where the offsets are clearly invalid because they are not a multiple of the loop increment. For example: #pragma omp for ordered(2) for (i=0; i < N; ++i) for (j=0; j < M; ++j) { #pragma omp ordered \ depend(sink:i-8,j-2) \ depend(sink:i,j-1) \ // Completely ignored because i+0. depend(sink:i-4,j-3) \ depend(sink:i-6,j-4) #pragma omp ordered depend(source) } Folded clause is: depend(sink:-gcd(8,4,6),-min(2,3,4)) -or- depend(sink:-2,-2) */ /* FIXME: Computing GCD's where the first element is zero is non-trivial in the presence of collapsed loops. Do this later. */ if (fd.collapse > 1) return; wide_int *folded_deps = XALLOCAVEC (wide_int, 2 * len - 1); /* wide_int is not a POD so it must be default-constructed. */ for (unsigned i = 0; i != 2 * len - 1; ++i) new (static_cast<void*>(folded_deps + i)) wide_int (); tree folded_dep = NULL_TREE; /* TRUE if the first dimension's offset is negative. */ bool neg_offset_p = false; list_p = gimple_omp_ordered_clauses_ptr (ord_stmt); unsigned int i; while ((c = *list_p) != NULL) { bool remove = false; gcc_assert (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND); if (OMP_CLAUSE_DEPEND_KIND (c) != OMP_CLAUSE_DEPEND_SINK) goto next_ordered_clause; tree vec; for (vec = OMP_CLAUSE_DECL (c), i = 0; vec && TREE_CODE (vec) == TREE_LIST; vec = TREE_CHAIN (vec), ++i) { gcc_assert (i < len); /* omp_extract_for_data has canonicalized the condition. */ gcc_assert (fd.loops[i].cond_code == LT_EXPR || fd.loops[i].cond_code == GT_EXPR); bool forward = fd.loops[i].cond_code == LT_EXPR; bool maybe_lexically_later = true; /* While the committee makes up its mind, bail if we have any non-constant steps. */ if (TREE_CODE (fd.loops[i].step) != INTEGER_CST) goto lower_omp_ordered_ret; tree itype = TREE_TYPE (TREE_VALUE (vec)); if (POINTER_TYPE_P (itype)) itype = sizetype; wide_int offset = wide_int::from (wi::to_wide (TREE_PURPOSE (vec)), TYPE_PRECISION (itype), TYPE_SIGN (itype)); /* Ignore invalid offsets that are not multiples of the step. */ if (!wi::multiple_of_p (wi::abs (offset), wi::abs (wi::to_wide (fd.loops[i].step)), UNSIGNED)) { warning_at (OMP_CLAUSE_LOCATION (c), 0, "ignoring sink clause with offset that is not " "a multiple of the loop step"); remove = true; goto next_ordered_clause; } /* Calculate the first dimension. The first dimension of the folded dependency vector is the GCD of the first elements, while ignoring any first elements whose offset is 0. */ if (i == 0) { /* Ignore dependence vectors whose first dimension is 0. */ if (offset == 0) { remove = true; goto next_ordered_clause; } else { if (!TYPE_UNSIGNED (itype) && (forward ^ wi::neg_p (offset))) { error_at (OMP_CLAUSE_LOCATION (c), "first offset must be in opposite direction " "of loop iterations"); goto lower_omp_ordered_ret; } if (forward) offset = -offset; neg_offset_p = forward; /* Initialize the first time around. */ if (folded_dep == NULL_TREE) { folded_dep = c; folded_deps[0] = offset; } else folded_deps[0] = wi::gcd (folded_deps[0], offset, UNSIGNED); } } /* Calculate minimum for the remaining dimensions. */ else { folded_deps[len + i - 1] = offset; if (folded_dep == c) folded_deps[i] = offset; else if (maybe_lexically_later && !wi::eq_p (folded_deps[i], offset)) { if (forward ^ wi::gts_p (folded_deps[i], offset)) { unsigned int j; folded_dep = c; for (j = 1; j <= i; j++) folded_deps[j] = folded_deps[len + j - 1]; } else maybe_lexically_later = false; } } } gcc_assert (i == len); remove = true; next_ordered_clause: if (remove) *list_p = OMP_CLAUSE_CHAIN (c); else list_p = &OMP_CLAUSE_CHAIN (c); } if (folded_dep) { if (neg_offset_p) folded_deps[0] = -folded_deps[0]; tree itype = TREE_TYPE (TREE_VALUE (OMP_CLAUSE_DECL (folded_dep))); if (POINTER_TYPE_P (itype)) itype = sizetype; TREE_PURPOSE (OMP_CLAUSE_DECL (folded_dep)) = wide_int_to_tree (itype, folded_deps[0]); OMP_CLAUSE_CHAIN (folded_dep) = gimple_omp_ordered_clauses (ord_stmt); *gimple_omp_ordered_clauses_ptr (ord_stmt) = folded_dep; } lower_omp_ordered_ret: /* Ordered without clauses is #pragma omp threads, while we want a nop instead if we remove all clauses. */ if (gimple_omp_ordered_clauses (ord_stmt) == NULL_TREE) gsi_replace (gsi_p, gimple_build_nop (), true); } /* Expand code for an OpenMP ordered directive. */ static void lower_omp_ordered (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree block; gimple *stmt = gsi_stmt (*gsi_p), *g; gomp_ordered *ord_stmt = as_a <gomp_ordered *> (stmt); gcall *x; gbind *bind; bool simd = omp_find_clause (gimple_omp_ordered_clauses (ord_stmt), OMP_CLAUSE_SIMD); /* FIXME: this should check presence of OMP_CLAUSE__SIMT_ on the enclosing loop. */ bool maybe_simt = simd && omp_maybe_offloaded_ctx (ctx) && omp_max_simt_vf () > 1; bool threads = omp_find_clause (gimple_omp_ordered_clauses (ord_stmt), OMP_CLAUSE_THREADS); if (omp_find_clause (gimple_omp_ordered_clauses (ord_stmt), OMP_CLAUSE_DEPEND)) { /* FIXME: This is needs to be moved to the expansion to verify various conditions only testable on cfg with dominators computed, and also all the depend clauses to be merged still might need to be available for the runtime checks. */ if (0) lower_omp_ordered_clauses (gsi_p, ord_stmt, ctx); return; } push_gimplify_context (); block = make_node (BLOCK); bind = gimple_build_bind (NULL, NULL, block); gsi_replace (gsi_p, bind, true); gimple_bind_add_stmt (bind, stmt); if (simd) { x = gimple_build_call_internal (IFN_GOMP_SIMD_ORDERED_START, 1, build_int_cst (NULL_TREE, threads)); cfun->has_simduid_loops = true; } else x = gimple_build_call (builtin_decl_explicit (BUILT_IN_GOMP_ORDERED_START), 0); gimple_bind_add_stmt (bind, x); tree counter = NULL_TREE, test = NULL_TREE, body = NULL_TREE; if (maybe_simt) { counter = create_tmp_var (integer_type_node); g = gimple_build_call_internal (IFN_GOMP_SIMT_LANE, 0); gimple_call_set_lhs (g, counter); gimple_bind_add_stmt (bind, g); body = create_artificial_label (UNKNOWN_LOCATION); test = create_artificial_label (UNKNOWN_LOCATION); gimple_bind_add_stmt (bind, gimple_build_label (body)); tree simt_pred = create_tmp_var (integer_type_node); g = gimple_build_call_internal (IFN_GOMP_SIMT_ORDERED_PRED, 1, counter); gimple_call_set_lhs (g, simt_pred); gimple_bind_add_stmt (bind, g); tree t = create_artificial_label (UNKNOWN_LOCATION); g = gimple_build_cond (EQ_EXPR, simt_pred, integer_zero_node, t, test); gimple_bind_add_stmt (bind, g); gimple_bind_add_stmt (bind, gimple_build_label (t)); } lower_omp (gimple_omp_body_ptr (stmt), ctx); gimple_omp_set_body (stmt, maybe_catch_exception (gimple_omp_body (stmt))); gimple_bind_add_seq (bind, gimple_omp_body (stmt)); gimple_omp_set_body (stmt, NULL); if (maybe_simt) { gimple_bind_add_stmt (bind, gimple_build_label (test)); g = gimple_build_assign (counter, MINUS_EXPR, counter, integer_one_node); gimple_bind_add_stmt (bind, g); tree c = build2 (GE_EXPR, boolean_type_node, counter, integer_zero_node); tree nonneg = create_tmp_var (integer_type_node); gimple_seq tseq = NULL; gimplify_assign (nonneg, fold_convert (integer_type_node, c), &tseq); gimple_bind_add_seq (bind, tseq); g = gimple_build_call_internal (IFN_GOMP_SIMT_VOTE_ANY, 1, nonneg); gimple_call_set_lhs (g, nonneg); gimple_bind_add_stmt (bind, g); tree end = create_artificial_label (UNKNOWN_LOCATION); g = gimple_build_cond (NE_EXPR, nonneg, integer_zero_node, body, end); gimple_bind_add_stmt (bind, g); gimple_bind_add_stmt (bind, gimple_build_label (end)); } if (simd) x = gimple_build_call_internal (IFN_GOMP_SIMD_ORDERED_END, 1, build_int_cst (NULL_TREE, threads)); else x = gimple_build_call (builtin_decl_explicit (BUILT_IN_GOMP_ORDERED_END), 0); gimple_bind_add_stmt (bind, x); gimple_bind_add_stmt (bind, gimple_build_omp_return (true)); pop_gimplify_context (bind); gimple_bind_append_vars (bind, ctx->block_vars); BLOCK_VARS (block) = gimple_bind_vars (bind); } /* Gimplify a GIMPLE_OMP_CRITICAL statement. This is a relatively simple substitution of a couple of function calls. But in the NAMED case, requires that languages coordinate a symbol name. It is therefore best put here in common code. */ static GTY(()) hash_map<tree, tree> *critical_name_mutexes; static void lower_omp_critical (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree block; tree name, lock, unlock; gomp_critical *stmt = as_a <gomp_critical *> (gsi_stmt (*gsi_p)); gbind *bind; location_t loc = gimple_location (stmt); gimple_seq tbody; name = gimple_omp_critical_name (stmt); if (name) { tree decl; if (!critical_name_mutexes) critical_name_mutexes = hash_map<tree, tree>::create_ggc (10); tree *n = critical_name_mutexes->get (name); if (n == NULL) { char *new_str; decl = create_tmp_var_raw (ptr_type_node); new_str = ACONCAT ((".gomp_critical_user_", IDENTIFIER_POINTER (name), NULL)); DECL_NAME (decl) = get_identifier (new_str); TREE_PUBLIC (decl) = 1; TREE_STATIC (decl) = 1; DECL_COMMON (decl) = 1; DECL_ARTIFICIAL (decl) = 1; DECL_IGNORED_P (decl) = 1; varpool_node::finalize_decl (decl); critical_name_mutexes->put (name, decl); } else decl = *n; /* If '#pragma omp critical' is inside offloaded region or inside function marked as offloadable, the symbol must be marked as offloadable too. */ omp_context *octx; if (cgraph_node::get (current_function_decl)->offloadable) varpool_node::get_create (decl)->offloadable = 1; else for (octx = ctx->outer; octx; octx = octx->outer) if (is_gimple_omp_offloaded (octx->stmt)) { varpool_node::get_create (decl)->offloadable = 1; break; } lock = builtin_decl_explicit (BUILT_IN_GOMP_CRITICAL_NAME_START); lock = build_call_expr_loc (loc, lock, 1, build_fold_addr_expr_loc (loc, decl)); unlock = builtin_decl_explicit (BUILT_IN_GOMP_CRITICAL_NAME_END); unlock = build_call_expr_loc (loc, unlock, 1, build_fold_addr_expr_loc (loc, decl)); } else { lock = builtin_decl_explicit (BUILT_IN_GOMP_CRITICAL_START); lock = build_call_expr_loc (loc, lock, 0); unlock = builtin_decl_explicit (BUILT_IN_GOMP_CRITICAL_END); unlock = build_call_expr_loc (loc, unlock, 0); } push_gimplify_context (); block = make_node (BLOCK); bind = gimple_build_bind (NULL, NULL, block); gsi_replace (gsi_p, bind, true); gimple_bind_add_stmt (bind, stmt); tbody = gimple_bind_body (bind); gimplify_and_add (lock, &tbody); gimple_bind_set_body (bind, tbody); lower_omp (gimple_omp_body_ptr (stmt), ctx); gimple_omp_set_body (stmt, maybe_catch_exception (gimple_omp_body (stmt))); gimple_bind_add_seq (bind, gimple_omp_body (stmt)); gimple_omp_set_body (stmt, NULL); tbody = gimple_bind_body (bind); gimplify_and_add (unlock, &tbody); gimple_bind_set_body (bind, tbody); gimple_bind_add_stmt (bind, gimple_build_omp_return (true)); pop_gimplify_context (bind); gimple_bind_append_vars (bind, ctx->block_vars); BLOCK_VARS (block) = gimple_bind_vars (bind); } /* A subroutine of lower_omp_for. Generate code to emit the predicate for a lastprivate clause. Given a loop control predicate of (V cond N2), we gate the clause on (!(V cond N2)). The lowered form is appended to *DLIST, iterator initialization is appended to *BODY_P. */ static void lower_omp_for_lastprivate (struct omp_for_data *fd, gimple_seq *body_p, gimple_seq *dlist, struct omp_context *ctx) { tree clauses, cond, vinit; enum tree_code cond_code; gimple_seq stmts; cond_code = fd->loop.cond_code; cond_code = cond_code == LT_EXPR ? GE_EXPR : LE_EXPR; /* When possible, use a strict equality expression. This can let VRP type optimizations deduce the value and remove a copy. */ if (tree_fits_shwi_p (fd->loop.step)) { HOST_WIDE_INT step = tree_to_shwi (fd->loop.step); if (step == 1 || step == -1) cond_code = EQ_EXPR; } if (gimple_omp_for_kind (fd->for_stmt) == GF_OMP_FOR_KIND_GRID_LOOP || gimple_omp_for_grid_phony (fd->for_stmt)) cond = omp_grid_lastprivate_predicate (fd); else { tree n2 = fd->loop.n2; if (fd->collapse > 1 && TREE_CODE (n2) != INTEGER_CST && gimple_omp_for_combined_into_p (fd->for_stmt)) { struct omp_context *taskreg_ctx = NULL; if (gimple_code (ctx->outer->stmt) == GIMPLE_OMP_FOR) { gomp_for *gfor = as_a <gomp_for *> (ctx->outer->stmt); if (gimple_omp_for_kind (gfor) == GF_OMP_FOR_KIND_FOR || gimple_omp_for_kind (gfor) == GF_OMP_FOR_KIND_DISTRIBUTE) { if (gimple_omp_for_combined_into_p (gfor)) { gcc_assert (ctx->outer->outer && is_parallel_ctx (ctx->outer->outer)); taskreg_ctx = ctx->outer->outer; } else { struct omp_for_data outer_fd; omp_extract_for_data (gfor, &outer_fd, NULL); n2 = fold_convert (TREE_TYPE (n2), outer_fd.loop.n2); } } else if (gimple_omp_for_kind (gfor) == GF_OMP_FOR_KIND_TASKLOOP) taskreg_ctx = ctx->outer->outer; } else if (is_taskreg_ctx (ctx->outer)) taskreg_ctx = ctx->outer; if (taskreg_ctx) { int i; tree taskreg_clauses = gimple_omp_taskreg_clauses (taskreg_ctx->stmt); tree innerc = omp_find_clause (taskreg_clauses, OMP_CLAUSE__LOOPTEMP_); gcc_assert (innerc); for (i = 0; i < fd->collapse; i++) { innerc = omp_find_clause (OMP_CLAUSE_CHAIN (innerc), OMP_CLAUSE__LOOPTEMP_); gcc_assert (innerc); } innerc = omp_find_clause (OMP_CLAUSE_CHAIN (innerc), OMP_CLAUSE__LOOPTEMP_); if (innerc) n2 = fold_convert (TREE_TYPE (n2), lookup_decl (OMP_CLAUSE_DECL (innerc), taskreg_ctx)); } } cond = build2 (cond_code, boolean_type_node, fd->loop.v, n2); } clauses = gimple_omp_for_clauses (fd->for_stmt); stmts = NULL; lower_lastprivate_clauses (clauses, cond, &stmts, ctx); if (!gimple_seq_empty_p (stmts)) { gimple_seq_add_seq (&stmts, *dlist); *dlist = stmts; /* Optimize: v = 0; is usually cheaper than v = some_other_constant. */ vinit = fd->loop.n1; if (cond_code == EQ_EXPR && tree_fits_shwi_p (fd->loop.n2) && ! integer_zerop (fd->loop.n2)) vinit = build_int_cst (TREE_TYPE (fd->loop.v), 0); else vinit = unshare_expr (vinit); /* Initialize the iterator variable, so that threads that don't execute any iterations don't execute the lastprivate clauses by accident. */ gimplify_assign (fd->loop.v, vinit, body_p); } } /* Lower code for an OMP loop directive. */ static void lower_omp_for (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree *rhs_p, block; struct omp_for_data fd, *fdp = NULL; gomp_for *stmt = as_a <gomp_for *> (gsi_stmt (*gsi_p)); gbind *new_stmt; gimple_seq omp_for_body, body, dlist; gimple_seq oacc_head = NULL, oacc_tail = NULL; size_t i; push_gimplify_context (); lower_omp (gimple_omp_for_pre_body_ptr (stmt), ctx); block = make_node (BLOCK); new_stmt = gimple_build_bind (NULL, NULL, block); /* Replace at gsi right away, so that 'stmt' is no member of a sequence anymore as we're going to add to a different one below. */ gsi_replace (gsi_p, new_stmt, true); /* Move declaration of temporaries in the loop body before we make it go away. */ omp_for_body = gimple_omp_body (stmt); if (!gimple_seq_empty_p (omp_for_body) && gimple_code (gimple_seq_first_stmt (omp_for_body)) == GIMPLE_BIND) { gbind *inner_bind = as_a <gbind *> (gimple_seq_first_stmt (omp_for_body)); tree vars = gimple_bind_vars (inner_bind); gimple_bind_append_vars (new_stmt, vars); /* bind_vars/BLOCK_VARS are being moved to new_stmt/block, don't keep them on the inner_bind and it's block. */ gimple_bind_set_vars (inner_bind, NULL_TREE); if (gimple_bind_block (inner_bind)) BLOCK_VARS (gimple_bind_block (inner_bind)) = NULL_TREE; } if (gimple_omp_for_combined_into_p (stmt)) { omp_extract_for_data (stmt, &fd, NULL); fdp = &fd; /* We need two temporaries with fd.loop.v type (istart/iend) and then (fd.collapse - 1) temporaries with the same type for count2 ... countN-1 vars if not constant. */ size_t count = 2; tree type = fd.iter_type; if (fd.collapse > 1 && TREE_CODE (fd.loop.n2) != INTEGER_CST) count += fd.collapse - 1; bool taskreg_for = (gimple_omp_for_kind (stmt) == GF_OMP_FOR_KIND_FOR || gimple_omp_for_kind (stmt) == GF_OMP_FOR_KIND_TASKLOOP); tree outerc = NULL, *pc = gimple_omp_for_clauses_ptr (stmt); tree simtc = NULL; tree clauses = *pc; if (taskreg_for) outerc = omp_find_clause (gimple_omp_taskreg_clauses (ctx->outer->stmt), OMP_CLAUSE__LOOPTEMP_); if (ctx->simt_stmt) simtc = omp_find_clause (gimple_omp_for_clauses (ctx->simt_stmt), OMP_CLAUSE__LOOPTEMP_); for (i = 0; i < count; i++) { tree temp; if (taskreg_for) { gcc_assert (outerc); temp = lookup_decl (OMP_CLAUSE_DECL (outerc), ctx->outer); outerc = omp_find_clause (OMP_CLAUSE_CHAIN (outerc), OMP_CLAUSE__LOOPTEMP_); } else { /* If there are 2 adjacent SIMD stmts, one with _simt_ clause, another without, make sure they have the same decls in _looptemp_ clauses, because the outer stmt they are combined into will look up just one inner_stmt. */ if (ctx->simt_stmt) temp = OMP_CLAUSE_DECL (simtc); else temp = create_tmp_var (type); insert_decl_map (&ctx->outer->cb, temp, temp); } *pc = build_omp_clause (UNKNOWN_LOCATION, OMP_CLAUSE__LOOPTEMP_); OMP_CLAUSE_DECL (*pc) = temp; pc = &OMP_CLAUSE_CHAIN (*pc); if (ctx->simt_stmt) simtc = omp_find_clause (OMP_CLAUSE_CHAIN (simtc), OMP_CLAUSE__LOOPTEMP_); } *pc = clauses; } /* The pre-body and input clauses go before the lowered GIMPLE_OMP_FOR. */ dlist = NULL; body = NULL; lower_rec_input_clauses (gimple_omp_for_clauses (stmt), &body, &dlist, ctx, fdp); gimple_seq_add_seq (&body, gimple_omp_for_pre_body (stmt)); lower_omp (gimple_omp_body_ptr (stmt), ctx); /* Lower the header expressions. At this point, we can assume that the header is of the form: #pragma omp for (V = VAL1; V {<|>|<=|>=} VAL2; V = V [+-] VAL3) We just need to make sure that VAL1, VAL2 and VAL3 are lowered using the .omp_data_s mapping, if needed. */ for (i = 0; i < gimple_omp_for_collapse (stmt); i++) { rhs_p = gimple_omp_for_initial_ptr (stmt, i); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, &body); else if (TREE_CODE (*rhs_p) == ADDR_EXPR) recompute_tree_invariant_for_addr_expr (*rhs_p); rhs_p = gimple_omp_for_final_ptr (stmt, i); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, &body); else if (TREE_CODE (*rhs_p) == ADDR_EXPR) recompute_tree_invariant_for_addr_expr (*rhs_p); rhs_p = &TREE_OPERAND (gimple_omp_for_incr (stmt, i), 1); if (!is_gimple_min_invariant (*rhs_p)) *rhs_p = get_formal_tmp_var (*rhs_p, &body); } /* Once lowered, extract the bounds and clauses. */ omp_extract_for_data (stmt, &fd, NULL); if (is_gimple_omp_oacc (ctx->stmt) && !ctx_in_oacc_kernels_region (ctx)) lower_oacc_head_tail (gimple_location (stmt), gimple_omp_for_clauses (stmt), &oacc_head, &oacc_tail, ctx); /* Add OpenACC partitioning and reduction markers just before the loop. */ if (oacc_head) gimple_seq_add_seq (&body, oacc_head); lower_omp_for_lastprivate (&fd, &body, &dlist, ctx); if (gimple_omp_for_kind (stmt) == GF_OMP_FOR_KIND_FOR) for (tree c = gimple_omp_for_clauses (stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR && !OMP_CLAUSE_LINEAR_NO_COPYIN (c)) { OMP_CLAUSE_DECL (c) = lookup_decl (OMP_CLAUSE_DECL (c), ctx); if (DECL_P (OMP_CLAUSE_LINEAR_STEP (c))) OMP_CLAUSE_LINEAR_STEP (c) = maybe_lookup_decl_in_outer_ctx (OMP_CLAUSE_LINEAR_STEP (c), ctx); } bool phony_loop = (gimple_omp_for_kind (stmt) != GF_OMP_FOR_KIND_GRID_LOOP && gimple_omp_for_grid_phony (stmt)); if (!phony_loop) gimple_seq_add_stmt (&body, stmt); gimple_seq_add_seq (&body, gimple_omp_body (stmt)); if (!phony_loop) gimple_seq_add_stmt (&body, gimple_build_omp_continue (fd.loop.v, fd.loop.v)); /* After the loop, add exit clauses. */ lower_reduction_clauses (gimple_omp_for_clauses (stmt), &body, ctx); if (ctx->cancellable) gimple_seq_add_stmt (&body, gimple_build_label (ctx->cancel_label)); gimple_seq_add_seq (&body, dlist); body = maybe_catch_exception (body); if (!phony_loop) { /* Region exit marker goes at the end of the loop body. */ gimple_seq_add_stmt (&body, gimple_build_omp_return (fd.have_nowait)); maybe_add_implicit_barrier_cancel (ctx, &body); } /* Add OpenACC joining and reduction markers just after the loop. */ if (oacc_tail) gimple_seq_add_seq (&body, oacc_tail); pop_gimplify_context (new_stmt); gimple_bind_append_vars (new_stmt, ctx->block_vars); maybe_remove_omp_member_access_dummy_vars (new_stmt); BLOCK_VARS (block) = gimple_bind_vars (new_stmt); if (BLOCK_VARS (block)) TREE_USED (block) = 1; gimple_bind_set_body (new_stmt, body); gimple_omp_set_body (stmt, NULL); gimple_omp_for_set_pre_body (stmt, NULL); } /* Callback for walk_stmts. Check if the current statement only contains GIMPLE_OMP_FOR or GIMPLE_OMP_SECTIONS. */ static tree check_combined_parallel (gimple_stmt_iterator *gsi_p, bool *handled_ops_p, struct walk_stmt_info *wi) { int *info = (int *) wi->info; gimple *stmt = gsi_stmt (*gsi_p); *handled_ops_p = true; switch (gimple_code (stmt)) { WALK_SUBSTMTS; case GIMPLE_DEBUG: break; case GIMPLE_OMP_FOR: case GIMPLE_OMP_SECTIONS: *info = *info == 0 ? 1 : -1; break; default: *info = -1; break; } return NULL; } struct omp_taskcopy_context { /* This field must be at the beginning, as we do "inheritance": Some callback functions for tree-inline.c (e.g., omp_copy_decl) receive a copy_body_data pointer that is up-casted to an omp_context pointer. */ copy_body_data cb; omp_context *ctx; }; static tree task_copyfn_copy_decl (tree var, copy_body_data *cb) { struct omp_taskcopy_context *tcctx = (struct omp_taskcopy_context *) cb; if (splay_tree_lookup (tcctx->ctx->sfield_map, (splay_tree_key) var)) return create_tmp_var (TREE_TYPE (var)); return var; } static tree task_copyfn_remap_type (struct omp_taskcopy_context *tcctx, tree orig_type) { tree name, new_fields = NULL, type, f; type = lang_hooks.types.make_type (RECORD_TYPE); name = DECL_NAME (TYPE_NAME (orig_type)); name = build_decl (gimple_location (tcctx->ctx->stmt), TYPE_DECL, name, type); TYPE_NAME (type) = name; for (f = TYPE_FIELDS (orig_type); f ; f = TREE_CHAIN (f)) { tree new_f = copy_node (f); DECL_CONTEXT (new_f) = type; TREE_TYPE (new_f) = remap_type (TREE_TYPE (f), &tcctx->cb); TREE_CHAIN (new_f) = new_fields; walk_tree (&DECL_SIZE (new_f), copy_tree_body_r, &tcctx->cb, NULL); walk_tree (&DECL_SIZE_UNIT (new_f), copy_tree_body_r, &tcctx->cb, NULL); walk_tree (&DECL_FIELD_OFFSET (new_f), copy_tree_body_r, &tcctx->cb, NULL); new_fields = new_f; tcctx->cb.decl_map->put (f, new_f); } TYPE_FIELDS (type) = nreverse (new_fields); layout_type (type); return type; } /* Create task copyfn. */ static void create_task_copyfn (gomp_task *task_stmt, omp_context *ctx) { struct function *child_cfun; tree child_fn, t, c, src, dst, f, sf, arg, sarg, decl; tree record_type, srecord_type, bind, list; bool record_needs_remap = false, srecord_needs_remap = false; splay_tree_node n; struct omp_taskcopy_context tcctx; location_t loc = gimple_location (task_stmt); child_fn = gimple_omp_task_copy_fn (task_stmt); child_cfun = DECL_STRUCT_FUNCTION (child_fn); gcc_assert (child_cfun->cfg == NULL); DECL_SAVED_TREE (child_fn) = alloc_stmt_list (); /* Reset DECL_CONTEXT on function arguments. */ for (t = DECL_ARGUMENTS (child_fn); t; t = DECL_CHAIN (t)) DECL_CONTEXT (t) = child_fn; /* Populate the function. */ push_gimplify_context (); push_cfun (child_cfun); bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL); TREE_SIDE_EFFECTS (bind) = 1; list = NULL; DECL_SAVED_TREE (child_fn) = bind; DECL_SOURCE_LOCATION (child_fn) = gimple_location (task_stmt); /* Remap src and dst argument types if needed. */ record_type = ctx->record_type; srecord_type = ctx->srecord_type; for (f = TYPE_FIELDS (record_type); f ; f = DECL_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) { record_needs_remap = true; break; } for (f = TYPE_FIELDS (srecord_type); f ; f = DECL_CHAIN (f)) if (variably_modified_type_p (TREE_TYPE (f), ctx->cb.src_fn)) { srecord_needs_remap = true; break; } if (record_needs_remap || srecord_needs_remap) { memset (&tcctx, '\0', sizeof (tcctx)); tcctx.cb.src_fn = ctx->cb.src_fn; tcctx.cb.dst_fn = child_fn; tcctx.cb.src_node = cgraph_node::get (tcctx.cb.src_fn); gcc_checking_assert (tcctx.cb.src_node); tcctx.cb.dst_node = tcctx.cb.src_node; tcctx.cb.src_cfun = ctx->cb.src_cfun; tcctx.cb.copy_decl = task_copyfn_copy_decl; tcctx.cb.eh_lp_nr = 0; tcctx.cb.transform_call_graph_edges = CB_CGE_MOVE; tcctx.cb.decl_map = new hash_map<tree, tree>; tcctx.ctx = ctx; if (record_needs_remap) record_type = task_copyfn_remap_type (&tcctx, record_type); if (srecord_needs_remap) srecord_type = task_copyfn_remap_type (&tcctx, srecord_type); } else tcctx.cb.decl_map = NULL; arg = DECL_ARGUMENTS (child_fn); TREE_TYPE (arg) = build_pointer_type (record_type); sarg = DECL_CHAIN (arg); TREE_TYPE (sarg) = build_pointer_type (srecord_type); /* First pass: initialize temporaries used in record_type and srecord_type sizes and field offsets. */ if (tcctx.cb.decl_map) for (c = gimple_omp_task_clauses (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { tree *p; decl = OMP_CLAUSE_DECL (c); p = tcctx.cb.decl_map->get (decl); if (p == NULL) continue; n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); sf = (tree) n->value; sf = *tcctx.cb.decl_map->get (sf); src = build_simple_mem_ref_loc (loc, sarg); src = omp_build_component_ref (src, sf); t = build2 (MODIFY_EXPR, TREE_TYPE (*p), *p, src); append_to_statement_list (t, &list); } /* Second pass: copy shared var pointers and copy construct non-VLA firstprivate vars. */ for (c = gimple_omp_task_clauses (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { splay_tree_key key; case OMP_CLAUSE_SHARED: decl = OMP_CLAUSE_DECL (c); key = (splay_tree_key) decl; if (OMP_CLAUSE_SHARED_FIRSTPRIVATE (c)) key = (splay_tree_key) &DECL_UID (decl); n = splay_tree_lookup (ctx->field_map, key); if (n == NULL) break; f = (tree) n->value; if (tcctx.cb.decl_map) f = *tcctx.cb.decl_map->get (f); n = splay_tree_lookup (ctx->sfield_map, key); sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *tcctx.cb.decl_map->get (sf); src = build_simple_mem_ref_loc (loc, sarg); src = omp_build_component_ref (src, sf); dst = build_simple_mem_ref_loc (loc, arg); dst = omp_build_component_ref (dst, f); t = build2 (MODIFY_EXPR, TREE_TYPE (dst), dst, src); append_to_statement_list (t, &list); break; case OMP_CLAUSE_FIRSTPRIVATE: decl = OMP_CLAUSE_DECL (c); if (is_variable_sized (decl)) break; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) break; f = (tree) n->value; if (tcctx.cb.decl_map) f = *tcctx.cb.decl_map->get (f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); if (n != NULL) { sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *tcctx.cb.decl_map->get (sf); src = build_simple_mem_ref_loc (loc, sarg); src = omp_build_component_ref (src, sf); if (use_pointer_for_field (decl, NULL) || omp_is_reference (decl)) src = build_simple_mem_ref_loc (loc, src); } else src = decl; dst = build_simple_mem_ref_loc (loc, arg); dst = omp_build_component_ref (dst, f); t = lang_hooks.decls.omp_clause_copy_ctor (c, dst, src); append_to_statement_list (t, &list); break; case OMP_CLAUSE_PRIVATE: if (! OMP_CLAUSE_PRIVATE_OUTER_REF (c)) break; decl = OMP_CLAUSE_DECL (c); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); f = (tree) n->value; if (tcctx.cb.decl_map) f = *tcctx.cb.decl_map->get (f); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) decl); if (n != NULL) { sf = (tree) n->value; if (tcctx.cb.decl_map) sf = *tcctx.cb.decl_map->get (sf); src = build_simple_mem_ref_loc (loc, sarg); src = omp_build_component_ref (src, sf); if (use_pointer_for_field (decl, NULL)) src = build_simple_mem_ref_loc (loc, src); } else src = decl; dst = build_simple_mem_ref_loc (loc, arg); dst = omp_build_component_ref (dst, f); t = build2 (MODIFY_EXPR, TREE_TYPE (dst), dst, src); append_to_statement_list (t, &list); break; default: break; } /* Last pass: handle VLA firstprivates. */ if (tcctx.cb.decl_map) for (c = gimple_omp_task_clauses (task_stmt); c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { tree ind, ptr, df; decl = OMP_CLAUSE_DECL (c); if (!is_variable_sized (decl)) continue; n = splay_tree_lookup (ctx->field_map, (splay_tree_key) decl); if (n == NULL) continue; f = (tree) n->value; f = *tcctx.cb.decl_map->get (f); gcc_assert (DECL_HAS_VALUE_EXPR_P (decl)); ind = DECL_VALUE_EXPR (decl); gcc_assert (TREE_CODE (ind) == INDIRECT_REF); gcc_assert (DECL_P (TREE_OPERAND (ind, 0))); n = splay_tree_lookup (ctx->sfield_map, (splay_tree_key) TREE_OPERAND (ind, 0)); sf = (tree) n->value; sf = *tcctx.cb.decl_map->get (sf); src = build_simple_mem_ref_loc (loc, sarg); src = omp_build_component_ref (src, sf); src = build_simple_mem_ref_loc (loc, src); dst = build_simple_mem_ref_loc (loc, arg); dst = omp_build_component_ref (dst, f); t = lang_hooks.decls.omp_clause_copy_ctor (c, dst, src); append_to_statement_list (t, &list); n = splay_tree_lookup (ctx->field_map, (splay_tree_key) TREE_OPERAND (ind, 0)); df = (tree) n->value; df = *tcctx.cb.decl_map->get (df); ptr = build_simple_mem_ref_loc (loc, arg); ptr = omp_build_component_ref (ptr, df); t = build2 (MODIFY_EXPR, TREE_TYPE (ptr), ptr, build_fold_addr_expr_loc (loc, dst)); append_to_statement_list (t, &list); } t = build1 (RETURN_EXPR, void_type_node, NULL); append_to_statement_list (t, &list); if (tcctx.cb.decl_map) delete tcctx.cb.decl_map; pop_gimplify_context (NULL); BIND_EXPR_BODY (bind) = list; pop_cfun (); } static void lower_depend_clauses (tree *pclauses, gimple_seq *iseq, gimple_seq *oseq) { tree c, clauses; gimple *g; size_t n_in = 0, n_out = 0, idx = 2, i; clauses = omp_find_clause (*pclauses, OMP_CLAUSE_DEPEND); gcc_assert (clauses); for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND) switch (OMP_CLAUSE_DEPEND_KIND (c)) { case OMP_CLAUSE_DEPEND_IN: n_in++; break; case OMP_CLAUSE_DEPEND_OUT: case OMP_CLAUSE_DEPEND_INOUT: n_out++; break; case OMP_CLAUSE_DEPEND_SOURCE: case OMP_CLAUSE_DEPEND_SINK: /* FALLTHRU */ default: gcc_unreachable (); } tree type = build_array_type_nelts (ptr_type_node, n_in + n_out + 2); tree array = create_tmp_var (type); TREE_ADDRESSABLE (array) = 1; tree r = build4 (ARRAY_REF, ptr_type_node, array, size_int (0), NULL_TREE, NULL_TREE); g = gimple_build_assign (r, build_int_cst (ptr_type_node, n_in + n_out)); gimple_seq_add_stmt (iseq, g); r = build4 (ARRAY_REF, ptr_type_node, array, size_int (1), NULL_TREE, NULL_TREE); g = gimple_build_assign (r, build_int_cst (ptr_type_node, n_out)); gimple_seq_add_stmt (iseq, g); for (i = 0; i < 2; i++) { if ((i ? n_in : n_out) == 0) continue; for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND && ((OMP_CLAUSE_DEPEND_KIND (c) != OMP_CLAUSE_DEPEND_IN) ^ i)) { tree t = OMP_CLAUSE_DECL (c); t = fold_convert (ptr_type_node, t); gimplify_expr (&t, iseq, NULL, is_gimple_val, fb_rvalue); r = build4 (ARRAY_REF, ptr_type_node, array, size_int (idx++), NULL_TREE, NULL_TREE); g = gimple_build_assign (r, t); gimple_seq_add_stmt (iseq, g); } } c = build_omp_clause (UNKNOWN_LOCATION, OMP_CLAUSE_DEPEND); OMP_CLAUSE_DECL (c) = build_fold_addr_expr (array); OMP_CLAUSE_CHAIN (c) = *pclauses; *pclauses = c; tree clobber = build_constructor (type, NULL); TREE_THIS_VOLATILE (clobber) = 1; g = gimple_build_assign (array, clobber); gimple_seq_add_stmt (oseq, g); } /* Lower the OpenMP parallel or task directive in the current statement in GSI_P. CTX holds context information for the directive. */ static void lower_omp_taskreg (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree clauses; tree child_fn, t; gimple *stmt = gsi_stmt (*gsi_p); gbind *par_bind, *bind, *dep_bind = NULL; gimple_seq par_body, olist, ilist, par_olist, par_rlist, par_ilist, new_body; location_t loc = gimple_location (stmt); clauses = gimple_omp_taskreg_clauses (stmt); par_bind = as_a <gbind *> (gimple_seq_first_stmt (gimple_omp_body (stmt))); par_body = gimple_bind_body (par_bind); child_fn = ctx->cb.dst_fn; if (gimple_code (stmt) == GIMPLE_OMP_PARALLEL && !gimple_omp_parallel_combined_p (stmt)) { struct walk_stmt_info wi; int ws_num = 0; memset (&wi, 0, sizeof (wi)); wi.info = &ws_num; wi.val_only = true; walk_gimple_seq (par_body, check_combined_parallel, NULL, &wi); if (ws_num == 1) gimple_omp_parallel_set_combined_p (stmt, true); } gimple_seq dep_ilist = NULL; gimple_seq dep_olist = NULL; if (gimple_code (stmt) == GIMPLE_OMP_TASK && omp_find_clause (clauses, OMP_CLAUSE_DEPEND)) { push_gimplify_context (); dep_bind = gimple_build_bind (NULL, NULL, make_node (BLOCK)); lower_depend_clauses (gimple_omp_task_clauses_ptr (stmt), &dep_ilist, &dep_olist); } if (ctx->srecord_type) create_task_copyfn (as_a <gomp_task *> (stmt), ctx); push_gimplify_context (); par_olist = NULL; par_ilist = NULL; par_rlist = NULL; bool phony_construct = gimple_code (stmt) == GIMPLE_OMP_PARALLEL && gimple_omp_parallel_grid_phony (as_a <gomp_parallel *> (stmt)); if (phony_construct && ctx->record_type) { gcc_checking_assert (!ctx->receiver_decl); ctx->receiver_decl = create_tmp_var (build_reference_type (ctx->record_type), ".omp_rec"); } lower_rec_input_clauses (clauses, &par_ilist, &par_olist, ctx, NULL); lower_omp (&par_body, ctx); if (gimple_code (stmt) == GIMPLE_OMP_PARALLEL) lower_reduction_clauses (clauses, &par_rlist, ctx); /* Declare all the variables created by mapping and the variables declared in the scope of the parallel body. */ record_vars_into (ctx->block_vars, child_fn); maybe_remove_omp_member_access_dummy_vars (par_bind); record_vars_into (gimple_bind_vars (par_bind), child_fn); if (ctx->record_type) { ctx->sender_decl = create_tmp_var (ctx->srecord_type ? ctx->srecord_type : ctx->record_type, ".omp_data_o"); DECL_NAMELESS (ctx->sender_decl) = 1; TREE_ADDRESSABLE (ctx->sender_decl) = 1; gimple_omp_taskreg_set_data_arg (stmt, ctx->sender_decl); } olist = NULL; ilist = NULL; lower_send_clauses (clauses, &ilist, &olist, ctx); lower_send_shared_vars (&ilist, &olist, ctx); if (ctx->record_type) { tree clobber = build_constructor (TREE_TYPE (ctx->sender_decl), NULL); TREE_THIS_VOLATILE (clobber) = 1; gimple_seq_add_stmt (&olist, gimple_build_assign (ctx->sender_decl, clobber)); } /* Once all the expansions are done, sequence all the different fragments inside gimple_omp_body. */ new_body = NULL; if (ctx->record_type) { t = build_fold_addr_expr_loc (loc, ctx->sender_decl); /* fixup_child_record_type might have changed receiver_decl's type. */ t = fold_convert_loc (loc, TREE_TYPE (ctx->receiver_decl), t); gimple_seq_add_stmt (&new_body, gimple_build_assign (ctx->receiver_decl, t)); } gimple_seq_add_seq (&new_body, par_ilist); gimple_seq_add_seq (&new_body, par_body); gimple_seq_add_seq (&new_body, par_rlist); if (ctx->cancellable) gimple_seq_add_stmt (&new_body, gimple_build_label (ctx->cancel_label)); gimple_seq_add_seq (&new_body, par_olist); new_body = maybe_catch_exception (new_body); if (gimple_code (stmt) == GIMPLE_OMP_TASK) gimple_seq_add_stmt (&new_body, gimple_build_omp_continue (integer_zero_node, integer_zero_node)); if (!phony_construct) { gimple_seq_add_stmt (&new_body, gimple_build_omp_return (false)); gimple_omp_set_body (stmt, new_body); } bind = gimple_build_bind (NULL, NULL, gimple_bind_block (par_bind)); gsi_replace (gsi_p, dep_bind ? dep_bind : bind, true); gimple_bind_add_seq (bind, ilist); if (!phony_construct) gimple_bind_add_stmt (bind, stmt); else gimple_bind_add_seq (bind, new_body); gimple_bind_add_seq (bind, olist); pop_gimplify_context (NULL); if (dep_bind) { gimple_bind_add_seq (dep_bind, dep_ilist); gimple_bind_add_stmt (dep_bind, bind); gimple_bind_add_seq (dep_bind, dep_olist); pop_gimplify_context (dep_bind); } } /* Lower the GIMPLE_OMP_TARGET in the current statement in GSI_P. CTX holds context information for the directive. */ static void lower_omp_target (gimple_stmt_iterator *gsi_p, omp_context *ctx) { tree clauses; tree child_fn, t, c; gomp_target *stmt = as_a <gomp_target *> (gsi_stmt (*gsi_p)); gbind *tgt_bind, *bind, *dep_bind = NULL; gimple_seq tgt_body, olist, ilist, fplist, new_body; location_t loc = gimple_location (stmt); bool offloaded, data_region; unsigned int map_cnt = 0; offloaded = is_gimple_omp_offloaded (stmt); switch (gimple_omp_target_kind (stmt)) { case GF_OMP_TARGET_KIND_REGION: case GF_OMP_TARGET_KIND_UPDATE: case GF_OMP_TARGET_KIND_ENTER_DATA: case GF_OMP_TARGET_KIND_EXIT_DATA: case GF_OMP_TARGET_KIND_OACC_PARALLEL: case GF_OMP_TARGET_KIND_OACC_KERNELS: case GF_OMP_TARGET_KIND_OACC_UPDATE: case GF_OMP_TARGET_KIND_OACC_ENTER_EXIT_DATA: case GF_OMP_TARGET_KIND_OACC_DECLARE: data_region = false; break; case GF_OMP_TARGET_KIND_DATA: case GF_OMP_TARGET_KIND_OACC_DATA: case GF_OMP_TARGET_KIND_OACC_HOST_DATA: data_region = true; break; default: gcc_unreachable (); } clauses = gimple_omp_target_clauses (stmt); gimple_seq dep_ilist = NULL; gimple_seq dep_olist = NULL; if (omp_find_clause (clauses, OMP_CLAUSE_DEPEND)) { push_gimplify_context (); dep_bind = gimple_build_bind (NULL, NULL, make_node (BLOCK)); lower_depend_clauses (gimple_omp_target_clauses_ptr (stmt), &dep_ilist, &dep_olist); } tgt_bind = NULL; tgt_body = NULL; if (offloaded) { tgt_bind = gimple_seq_first_stmt_as_a_bind (gimple_omp_body (stmt)); tgt_body = gimple_bind_body (tgt_bind); } else if (data_region) tgt_body = gimple_omp_body (stmt); child_fn = ctx->cb.dst_fn; push_gimplify_context (); fplist = NULL; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { tree var, x; default: break; case OMP_CLAUSE_MAP: #if CHECKING_P /* First check what we're prepared to handle in the following. */ switch (OMP_CLAUSE_MAP_KIND (c)) { case GOMP_MAP_ALLOC: case GOMP_MAP_TO: case GOMP_MAP_FROM: case GOMP_MAP_TOFROM: case GOMP_MAP_POINTER: case GOMP_MAP_TO_PSET: case GOMP_MAP_DELETE: case GOMP_MAP_RELEASE: case GOMP_MAP_ALWAYS_TO: case GOMP_MAP_ALWAYS_FROM: case GOMP_MAP_ALWAYS_TOFROM: case GOMP_MAP_FIRSTPRIVATE_POINTER: case GOMP_MAP_FIRSTPRIVATE_REFERENCE: case GOMP_MAP_STRUCT: case GOMP_MAP_ALWAYS_POINTER: break; case GOMP_MAP_FORCE_ALLOC: case GOMP_MAP_FORCE_TO: case GOMP_MAP_FORCE_FROM: case GOMP_MAP_FORCE_TOFROM: case GOMP_MAP_FORCE_PRESENT: case GOMP_MAP_FORCE_DEVICEPTR: case GOMP_MAP_DEVICE_RESIDENT: case GOMP_MAP_LINK: gcc_assert (is_gimple_omp_oacc (stmt)); break; default: gcc_unreachable (); } #endif /* FALLTHRU */ case OMP_CLAUSE_TO: case OMP_CLAUSE_FROM: oacc_firstprivate: var = OMP_CLAUSE_DECL (c); if (!DECL_P (var)) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP || (!OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (c) && (OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FIRSTPRIVATE_POINTER))) map_cnt++; continue; } if (DECL_SIZE (var) && TREE_CODE (DECL_SIZE (var)) != INTEGER_CST) { tree var2 = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (var2) == INDIRECT_REF); var2 = TREE_OPERAND (var2, 0); gcc_assert (DECL_P (var2)); var = var2; } if (offloaded && OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_POINTER || OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_REFERENCE)) { if (TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE) { if (is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx)) && varpool_node::get_create (var)->offloadable) continue; tree type = build_pointer_type (TREE_TYPE (var)); tree new_var = lookup_decl (var, ctx); x = create_tmp_var_raw (type, get_name (new_var)); gimple_add_tmp_var (x); x = build_simple_mem_ref (x); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } continue; } if (!maybe_lookup_field (var, ctx)) continue; /* Don't remap oacc parallel reduction variables, because the intermediate result must be local to each gang. */ if (offloaded && !(OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_IN_REDUCTION (c))) { x = build_receiver_ref (var, true, ctx); tree new_var = lookup_decl (var, ctx); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER && !OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (c) && TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE) x = build_simple_mem_ref (x); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { gcc_assert (is_gimple_omp_oacc (ctx->stmt)); if (omp_is_reference (new_var)) { /* Create a local object to hold the instance value. */ tree type = TREE_TYPE (TREE_TYPE (new_var)); const char *id = IDENTIFIER_POINTER (DECL_NAME (new_var)); tree inst = create_tmp_var (type, id); gimplify_assign (inst, fold_indirect_ref (x), &fplist); x = build_fold_addr_expr (inst); } gimplify_assign (new_var, x, &fplist); } else if (DECL_P (new_var)) { SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } else gcc_unreachable (); } map_cnt++; break; case OMP_CLAUSE_FIRSTPRIVATE: if (is_oacc_parallel (ctx)) goto oacc_firstprivate; map_cnt++; var = OMP_CLAUSE_DECL (c); if (!omp_is_reference (var) && !is_gimple_reg_type (TREE_TYPE (var))) { tree new_var = lookup_decl (var, ctx); if (is_variable_sized (var)) { tree pvar = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (pvar) == INDIRECT_REF); pvar = TREE_OPERAND (pvar, 0); gcc_assert (DECL_P (pvar)); tree new_pvar = lookup_decl (pvar, ctx); x = build_fold_indirect_ref (new_pvar); TREE_THIS_NOTRAP (x) = 1; } else x = build_receiver_ref (var, true, ctx); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } break; case OMP_CLAUSE_PRIVATE: if (is_gimple_omp_oacc (ctx->stmt)) break; var = OMP_CLAUSE_DECL (c); if (is_variable_sized (var)) { tree new_var = lookup_decl (var, ctx); tree pvar = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (pvar) == INDIRECT_REF); pvar = TREE_OPERAND (pvar, 0); gcc_assert (DECL_P (pvar)); tree new_pvar = lookup_decl (pvar, ctx); x = build_fold_indirect_ref (new_pvar); TREE_THIS_NOTRAP (x) = 1; SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } break; case OMP_CLAUSE_USE_DEVICE_PTR: case OMP_CLAUSE_IS_DEVICE_PTR: var = OMP_CLAUSE_DECL (c); map_cnt++; if (is_variable_sized (var)) { tree new_var = lookup_decl (var, ctx); tree pvar = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (pvar) == INDIRECT_REF); pvar = TREE_OPERAND (pvar, 0); gcc_assert (DECL_P (pvar)); tree new_pvar = lookup_decl (pvar, ctx); x = build_fold_indirect_ref (new_pvar); TREE_THIS_NOTRAP (x) = 1; SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } else if (TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE) { tree new_var = lookup_decl (var, ctx); tree type = build_pointer_type (TREE_TYPE (var)); x = create_tmp_var_raw (type, get_name (new_var)); gimple_add_tmp_var (x); x = build_simple_mem_ref (x); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } else { tree new_var = lookup_decl (var, ctx); x = create_tmp_var_raw (TREE_TYPE (new_var), get_name (new_var)); gimple_add_tmp_var (x); SET_DECL_VALUE_EXPR (new_var, x); DECL_HAS_VALUE_EXPR_P (new_var) = 1; } break; } if (offloaded) { target_nesting_level++; lower_omp (&tgt_body, ctx); target_nesting_level--; } else if (data_region) lower_omp (&tgt_body, ctx); if (offloaded) { /* Declare all the variables created by mapping and the variables declared in the scope of the target body. */ record_vars_into (ctx->block_vars, child_fn); maybe_remove_omp_member_access_dummy_vars (tgt_bind); record_vars_into (gimple_bind_vars (tgt_bind), child_fn); } olist = NULL; ilist = NULL; if (ctx->record_type) { ctx->sender_decl = create_tmp_var (ctx->record_type, ".omp_data_arr"); DECL_NAMELESS (ctx->sender_decl) = 1; TREE_ADDRESSABLE (ctx->sender_decl) = 1; t = make_tree_vec (3); TREE_VEC_ELT (t, 0) = ctx->sender_decl; TREE_VEC_ELT (t, 1) = create_tmp_var (build_array_type_nelts (size_type_node, map_cnt), ".omp_data_sizes"); DECL_NAMELESS (TREE_VEC_ELT (t, 1)) = 1; TREE_ADDRESSABLE (TREE_VEC_ELT (t, 1)) = 1; TREE_STATIC (TREE_VEC_ELT (t, 1)) = 1; tree tkind_type = short_unsigned_type_node; int talign_shift = 8; TREE_VEC_ELT (t, 2) = create_tmp_var (build_array_type_nelts (tkind_type, map_cnt), ".omp_data_kinds"); DECL_NAMELESS (TREE_VEC_ELT (t, 2)) = 1; TREE_ADDRESSABLE (TREE_VEC_ELT (t, 2)) = 1; TREE_STATIC (TREE_VEC_ELT (t, 2)) = 1; gimple_omp_target_set_data_arg (stmt, t); vec<constructor_elt, va_gc> *vsize; vec<constructor_elt, va_gc> *vkind; vec_alloc (vsize, map_cnt); vec_alloc (vkind, map_cnt); unsigned int map_idx = 0; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { tree ovar, nc, s, purpose, var, x, type; unsigned int talign; default: break; case OMP_CLAUSE_MAP: case OMP_CLAUSE_TO: case OMP_CLAUSE_FROM: oacc_firstprivate_map: nc = c; ovar = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_POINTER || (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_REFERENCE))) break; if (!DECL_P (ovar)) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (c)) { gcc_checking_assert (OMP_CLAUSE_DECL (OMP_CLAUSE_CHAIN (c)) == get_base_address (ovar)); nc = OMP_CLAUSE_CHAIN (c); ovar = OMP_CLAUSE_DECL (nc); } else { tree x = build_sender_ref (ovar, ctx); tree v = build_fold_addr_expr_with_type (ovar, ptr_type_node); gimplify_assign (x, v, &ilist); nc = NULL_TREE; } } else { if (DECL_SIZE (ovar) && TREE_CODE (DECL_SIZE (ovar)) != INTEGER_CST) { tree ovar2 = DECL_VALUE_EXPR (ovar); gcc_assert (TREE_CODE (ovar2) == INDIRECT_REF); ovar2 = TREE_OPERAND (ovar2, 0); gcc_assert (DECL_P (ovar2)); ovar = ovar2; } if (!maybe_lookup_field (ovar, ctx)) continue; } talign = TYPE_ALIGN_UNIT (TREE_TYPE (ovar)); if (DECL_P (ovar) && DECL_ALIGN_UNIT (ovar) > talign) talign = DECL_ALIGN_UNIT (ovar); if (nc) { var = lookup_decl_in_outer_ctx (ovar, ctx); x = build_sender_ref (ovar, ctx); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER && !OMP_CLAUSE_MAP_ZERO_BIAS_ARRAY_SECTION (c) && TREE_CODE (TREE_TYPE (ovar)) == ARRAY_TYPE) { gcc_assert (offloaded); tree avar = create_tmp_var (TREE_TYPE (TREE_TYPE (x))); mark_addressable (avar); gimplify_assign (avar, build_fold_addr_expr (var), &ilist); talign = DECL_ALIGN_UNIT (avar); avar = build_fold_addr_expr (avar); gimplify_assign (x, avar, &ilist); } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { gcc_assert (is_gimple_omp_oacc (ctx->stmt)); if (!omp_is_reference (var)) { if (is_gimple_reg (var) && OMP_CLAUSE_FIRSTPRIVATE_IMPLICIT (c)) TREE_NO_WARNING (var) = 1; var = build_fold_addr_expr (var); } else talign = TYPE_ALIGN_UNIT (TREE_TYPE (TREE_TYPE (ovar))); gimplify_assign (x, var, &ilist); } else if (is_gimple_reg (var)) { gcc_assert (offloaded); tree avar = create_tmp_var (TREE_TYPE (var)); mark_addressable (avar); enum gomp_map_kind map_kind = OMP_CLAUSE_MAP_KIND (c); if (GOMP_MAP_COPY_TO_P (map_kind) || map_kind == GOMP_MAP_POINTER || map_kind == GOMP_MAP_TO_PSET || map_kind == GOMP_MAP_FORCE_DEVICEPTR) { /* If we need to initialize a temporary with VAR because it is not addressable, and the variable hasn't been initialized yet, then we'll get a warning for the store to avar. Don't warn in that case, the mapping might be implicit. */ TREE_NO_WARNING (var) = 1; gimplify_assign (avar, var, &ilist); } avar = build_fold_addr_expr (avar); gimplify_assign (x, avar, &ilist); if ((GOMP_MAP_COPY_FROM_P (map_kind) || map_kind == GOMP_MAP_FORCE_DEVICEPTR) && !TYPE_READONLY (TREE_TYPE (var))) { x = unshare_expr (x); x = build_simple_mem_ref (x); gimplify_assign (var, x, &olist); } } else { var = build_fold_addr_expr (var); gimplify_assign (x, var, &ilist); } } s = NULL_TREE; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) { gcc_checking_assert (is_gimple_omp_oacc (ctx->stmt)); s = TREE_TYPE (ovar); if (TREE_CODE (s) == REFERENCE_TYPE) s = TREE_TYPE (s); s = TYPE_SIZE_UNIT (s); } else s = OMP_CLAUSE_SIZE (c); if (s == NULL_TREE) s = TYPE_SIZE_UNIT (TREE_TYPE (ovar)); s = fold_convert (size_type_node, s); purpose = size_int (map_idx++); CONSTRUCTOR_APPEND_ELT (vsize, purpose, s); if (TREE_CODE (s) != INTEGER_CST) TREE_STATIC (TREE_VEC_ELT (t, 1)) = 0; unsigned HOST_WIDE_INT tkind, tkind_zero; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_MAP: tkind = OMP_CLAUSE_MAP_KIND (c); tkind_zero = tkind; if (OMP_CLAUSE_MAP_MAYBE_ZERO_LENGTH_ARRAY_SECTION (c)) switch (tkind) { case GOMP_MAP_ALLOC: case GOMP_MAP_TO: case GOMP_MAP_FROM: case GOMP_MAP_TOFROM: case GOMP_MAP_ALWAYS_TO: case GOMP_MAP_ALWAYS_FROM: case GOMP_MAP_ALWAYS_TOFROM: case GOMP_MAP_RELEASE: case GOMP_MAP_FORCE_TO: case GOMP_MAP_FORCE_FROM: case GOMP_MAP_FORCE_TOFROM: case GOMP_MAP_FORCE_PRESENT: tkind_zero = GOMP_MAP_ZERO_LEN_ARRAY_SECTION; break; case GOMP_MAP_DELETE: tkind_zero = GOMP_MAP_DELETE_ZERO_LEN_ARRAY_SECTION; default: break; } if (tkind_zero != tkind) { if (integer_zerop (s)) tkind = tkind_zero; else if (integer_nonzerop (s)) tkind_zero = tkind; } break; case OMP_CLAUSE_FIRSTPRIVATE: gcc_checking_assert (is_gimple_omp_oacc (ctx->stmt)); tkind = GOMP_MAP_TO; tkind_zero = tkind; break; case OMP_CLAUSE_TO: tkind = GOMP_MAP_TO; tkind_zero = tkind; break; case OMP_CLAUSE_FROM: tkind = GOMP_MAP_FROM; tkind_zero = tkind; break; default: gcc_unreachable (); } gcc_checking_assert (tkind < (HOST_WIDE_INT_C (1U) << talign_shift)); gcc_checking_assert (tkind_zero < (HOST_WIDE_INT_C (1U) << talign_shift)); talign = ceil_log2 (talign); tkind |= talign << talign_shift; tkind_zero |= talign << talign_shift; gcc_checking_assert (tkind <= tree_to_uhwi (TYPE_MAX_VALUE (tkind_type))); gcc_checking_assert (tkind_zero <= tree_to_uhwi (TYPE_MAX_VALUE (tkind_type))); if (tkind == tkind_zero) x = build_int_cstu (tkind_type, tkind); else { TREE_STATIC (TREE_VEC_ELT (t, 2)) = 0; x = build3 (COND_EXPR, tkind_type, fold_build2 (EQ_EXPR, boolean_type_node, unshare_expr (s), size_zero_node), build_int_cstu (tkind_type, tkind_zero), build_int_cstu (tkind_type, tkind)); } CONSTRUCTOR_APPEND_ELT (vkind, purpose, x); if (nc && nc != c) c = nc; break; case OMP_CLAUSE_FIRSTPRIVATE: if (is_oacc_parallel (ctx)) goto oacc_firstprivate_map; ovar = OMP_CLAUSE_DECL (c); if (omp_is_reference (ovar)) talign = TYPE_ALIGN_UNIT (TREE_TYPE (TREE_TYPE (ovar))); else talign = DECL_ALIGN_UNIT (ovar); var = lookup_decl_in_outer_ctx (ovar, ctx); x = build_sender_ref (ovar, ctx); tkind = GOMP_MAP_FIRSTPRIVATE; type = TREE_TYPE (ovar); if (omp_is_reference (ovar)) type = TREE_TYPE (type); if ((INTEGRAL_TYPE_P (type) && TYPE_PRECISION (type) <= POINTER_SIZE) || TREE_CODE (type) == POINTER_TYPE) { tkind = GOMP_MAP_FIRSTPRIVATE_INT; tree t = var; if (omp_is_reference (var)) t = build_simple_mem_ref (var); else if (OMP_CLAUSE_FIRSTPRIVATE_IMPLICIT (c)) TREE_NO_WARNING (var) = 1; if (TREE_CODE (type) != POINTER_TYPE) t = fold_convert (pointer_sized_int_node, t); t = fold_convert (TREE_TYPE (x), t); gimplify_assign (x, t, &ilist); } else if (omp_is_reference (var)) gimplify_assign (x, var, &ilist); else if (is_gimple_reg (var)) { tree avar = create_tmp_var (TREE_TYPE (var)); mark_addressable (avar); if (OMP_CLAUSE_FIRSTPRIVATE_IMPLICIT (c)) TREE_NO_WARNING (var) = 1; gimplify_assign (avar, var, &ilist); avar = build_fold_addr_expr (avar); gimplify_assign (x, avar, &ilist); } else { var = build_fold_addr_expr (var); gimplify_assign (x, var, &ilist); } if (tkind == GOMP_MAP_FIRSTPRIVATE_INT) s = size_int (0); else if (omp_is_reference (ovar)) s = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (ovar))); else s = TYPE_SIZE_UNIT (TREE_TYPE (ovar)); s = fold_convert (size_type_node, s); purpose = size_int (map_idx++); CONSTRUCTOR_APPEND_ELT (vsize, purpose, s); if (TREE_CODE (s) != INTEGER_CST) TREE_STATIC (TREE_VEC_ELT (t, 1)) = 0; gcc_checking_assert (tkind < (HOST_WIDE_INT_C (1U) << talign_shift)); talign = ceil_log2 (talign); tkind |= talign << talign_shift; gcc_checking_assert (tkind <= tree_to_uhwi (TYPE_MAX_VALUE (tkind_type))); CONSTRUCTOR_APPEND_ELT (vkind, purpose, build_int_cstu (tkind_type, tkind)); break; case OMP_CLAUSE_USE_DEVICE_PTR: case OMP_CLAUSE_IS_DEVICE_PTR: ovar = OMP_CLAUSE_DECL (c); var = lookup_decl_in_outer_ctx (ovar, ctx); x = build_sender_ref (ovar, ctx); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_USE_DEVICE_PTR) tkind = GOMP_MAP_USE_DEVICE_PTR; else tkind = GOMP_MAP_FIRSTPRIVATE_INT; type = TREE_TYPE (ovar); if (TREE_CODE (type) == ARRAY_TYPE) var = build_fold_addr_expr (var); else { if (omp_is_reference (ovar)) { type = TREE_TYPE (type); if (TREE_CODE (type) != ARRAY_TYPE) var = build_simple_mem_ref (var); var = fold_convert (TREE_TYPE (x), var); } } gimplify_assign (x, var, &ilist); s = size_int (0); purpose = size_int (map_idx++); CONSTRUCTOR_APPEND_ELT (vsize, purpose, s); gcc_checking_assert (tkind < (HOST_WIDE_INT_C (1U) << talign_shift)); gcc_checking_assert (tkind <= tree_to_uhwi (TYPE_MAX_VALUE (tkind_type))); CONSTRUCTOR_APPEND_ELT (vkind, purpose, build_int_cstu (tkind_type, tkind)); break; } gcc_assert (map_idx == map_cnt); DECL_INITIAL (TREE_VEC_ELT (t, 1)) = build_constructor (TREE_TYPE (TREE_VEC_ELT (t, 1)), vsize); DECL_INITIAL (TREE_VEC_ELT (t, 2)) = build_constructor (TREE_TYPE (TREE_VEC_ELT (t, 2)), vkind); for (int i = 1; i <= 2; i++) if (!TREE_STATIC (TREE_VEC_ELT (t, i))) { gimple_seq initlist = NULL; force_gimple_operand (build1 (DECL_EXPR, void_type_node, TREE_VEC_ELT (t, i)), &initlist, true, NULL_TREE); gimple_seq_add_seq (&ilist, initlist); tree clobber = build_constructor (TREE_TYPE (TREE_VEC_ELT (t, i)), NULL); TREE_THIS_VOLATILE (clobber) = 1; gimple_seq_add_stmt (&olist, gimple_build_assign (TREE_VEC_ELT (t, i), clobber)); } tree clobber = build_constructor (ctx->record_type, NULL); TREE_THIS_VOLATILE (clobber) = 1; gimple_seq_add_stmt (&olist, gimple_build_assign (ctx->sender_decl, clobber)); } /* Once all the expansions are done, sequence all the different fragments inside gimple_omp_body. */ new_body = NULL; if (offloaded && ctx->record_type) { t = build_fold_addr_expr_loc (loc, ctx->sender_decl); /* fixup_child_record_type might have changed receiver_decl's type. */ t = fold_convert_loc (loc, TREE_TYPE (ctx->receiver_decl), t); gimple_seq_add_stmt (&new_body, gimple_build_assign (ctx->receiver_decl, t)); } gimple_seq_add_seq (&new_body, fplist); if (offloaded || data_region) { tree prev = NULL_TREE; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { tree var, x; default: break; case OMP_CLAUSE_FIRSTPRIVATE: if (is_gimple_omp_oacc (ctx->stmt)) break; var = OMP_CLAUSE_DECL (c); if (omp_is_reference (var) || is_gimple_reg_type (TREE_TYPE (var))) { tree new_var = lookup_decl (var, ctx); tree type; type = TREE_TYPE (var); if (omp_is_reference (var)) type = TREE_TYPE (type); if ((INTEGRAL_TYPE_P (type) && TYPE_PRECISION (type) <= POINTER_SIZE) || TREE_CODE (type) == POINTER_TYPE) { x = build_receiver_ref (var, false, ctx); if (TREE_CODE (type) != POINTER_TYPE) x = fold_convert (pointer_sized_int_node, x); x = fold_convert (type, x); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); if (omp_is_reference (var)) { tree v = create_tmp_var_raw (type, get_name (var)); gimple_add_tmp_var (v); TREE_ADDRESSABLE (v) = 1; gimple_seq_add_stmt (&new_body, gimple_build_assign (v, x)); x = build_fold_addr_expr (v); } gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } else { x = build_receiver_ref (var, !omp_is_reference (var), ctx); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } } else if (is_variable_sized (var)) { tree pvar = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (pvar) == INDIRECT_REF); pvar = TREE_OPERAND (pvar, 0); gcc_assert (DECL_P (pvar)); tree new_var = lookup_decl (pvar, ctx); x = build_receiver_ref (var, false, ctx); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } break; case OMP_CLAUSE_PRIVATE: if (is_gimple_omp_oacc (ctx->stmt)) break; var = OMP_CLAUSE_DECL (c); if (omp_is_reference (var)) { location_t clause_loc = OMP_CLAUSE_LOCATION (c); tree new_var = lookup_decl (var, ctx); x = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (new_var))); if (TREE_CONSTANT (x)) { x = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (new_var)), get_name (var)); gimple_add_tmp_var (x); TREE_ADDRESSABLE (x) = 1; x = build_fold_addr_expr_loc (clause_loc, x); } else break; x = fold_convert_loc (clause_loc, TREE_TYPE (new_var), x); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } break; case OMP_CLAUSE_USE_DEVICE_PTR: case OMP_CLAUSE_IS_DEVICE_PTR: var = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_USE_DEVICE_PTR) x = build_sender_ref (var, ctx); else x = build_receiver_ref (var, false, ctx); if (is_variable_sized (var)) { tree pvar = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (pvar) == INDIRECT_REF); pvar = TREE_OPERAND (pvar, 0); gcc_assert (DECL_P (pvar)); tree new_var = lookup_decl (pvar, ctx); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } else if (TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE) { tree new_var = lookup_decl (var, ctx); new_var = DECL_VALUE_EXPR (new_var); gcc_assert (TREE_CODE (new_var) == MEM_REF); new_var = TREE_OPERAND (new_var, 0); gcc_assert (DECL_P (new_var)); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } else { tree type = TREE_TYPE (var); tree new_var = lookup_decl (var, ctx); if (omp_is_reference (var)) { type = TREE_TYPE (type); if (TREE_CODE (type) != ARRAY_TYPE) { tree v = create_tmp_var_raw (type, get_name (var)); gimple_add_tmp_var (v); TREE_ADDRESSABLE (v) = 1; x = fold_convert (type, x); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (v, x)); x = build_fold_addr_expr (v); } } new_var = DECL_VALUE_EXPR (new_var); x = fold_convert (TREE_TYPE (new_var), x); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } break; } /* Handle GOMP_MAP_FIRSTPRIVATE_{POINTER,REFERENCE} in second pass, so that firstprivate vars holding OMP_CLAUSE_SIZE if needed are already handled. Similarly OMP_CLAUSE_PRIVATE for VLAs or references to VLAs. */ for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) switch (OMP_CLAUSE_CODE (c)) { tree var; default: break; case OMP_CLAUSE_MAP: if (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_POINTER || OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_REFERENCE) { location_t clause_loc = OMP_CLAUSE_LOCATION (c); poly_int64 offset = 0; gcc_assert (prev); var = OMP_CLAUSE_DECL (c); if (DECL_P (var) && TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE && is_global_var (maybe_lookup_decl_in_outer_ctx (var, ctx)) && varpool_node::get_create (var)->offloadable) break; if (TREE_CODE (var) == INDIRECT_REF && TREE_CODE (TREE_OPERAND (var, 0)) == COMPONENT_REF) var = TREE_OPERAND (var, 0); if (TREE_CODE (var) == COMPONENT_REF) { var = get_addr_base_and_unit_offset (var, &offset); gcc_assert (var != NULL_TREE && DECL_P (var)); } else if (DECL_SIZE (var) && TREE_CODE (DECL_SIZE (var)) != INTEGER_CST) { tree var2 = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (var2) == INDIRECT_REF); var2 = TREE_OPERAND (var2, 0); gcc_assert (DECL_P (var2)); var = var2; } tree new_var = lookup_decl (var, ctx), x; tree type = TREE_TYPE (new_var); bool is_ref; if (TREE_CODE (OMP_CLAUSE_DECL (c)) == INDIRECT_REF && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (c), 0)) == COMPONENT_REF)) { type = TREE_TYPE (TREE_OPERAND (OMP_CLAUSE_DECL (c), 0)); is_ref = true; new_var = build2 (MEM_REF, type, build_fold_addr_expr (new_var), build_int_cst (build_pointer_type (type), offset)); } else if (TREE_CODE (OMP_CLAUSE_DECL (c)) == COMPONENT_REF) { type = TREE_TYPE (OMP_CLAUSE_DECL (c)); is_ref = TREE_CODE (type) == REFERENCE_TYPE; new_var = build2 (MEM_REF, type, build_fold_addr_expr (new_var), build_int_cst (build_pointer_type (type), offset)); } else is_ref = omp_is_reference (var); if (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_REFERENCE) is_ref = false; bool ref_to_array = false; if (is_ref) { type = TREE_TYPE (type); if (TREE_CODE (type) == ARRAY_TYPE) { type = build_pointer_type (type); ref_to_array = true; } } else if (TREE_CODE (type) == ARRAY_TYPE) { tree decl2 = DECL_VALUE_EXPR (new_var); gcc_assert (TREE_CODE (decl2) == MEM_REF); decl2 = TREE_OPERAND (decl2, 0); gcc_assert (DECL_P (decl2)); new_var = decl2; type = TREE_TYPE (new_var); } x = build_receiver_ref (OMP_CLAUSE_DECL (prev), false, ctx); x = fold_convert_loc (clause_loc, type, x); if (!integer_zerop (OMP_CLAUSE_SIZE (c))) { tree bias = OMP_CLAUSE_SIZE (c); if (DECL_P (bias)) bias = lookup_decl (bias, ctx); bias = fold_convert_loc (clause_loc, sizetype, bias); bias = fold_build1_loc (clause_loc, NEGATE_EXPR, sizetype, bias); x = fold_build2_loc (clause_loc, POINTER_PLUS_EXPR, TREE_TYPE (x), x, bias); } if (ref_to_array) x = fold_convert_loc (clause_loc, TREE_TYPE (new_var), x); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); if (is_ref && !ref_to_array) { tree t = create_tmp_var_raw (type, get_name (var)); gimple_add_tmp_var (t); TREE_ADDRESSABLE (t) = 1; gimple_seq_add_stmt (&new_body, gimple_build_assign (t, x)); x = build_fold_addr_expr_loc (clause_loc, t); } gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); prev = NULL_TREE; } else if (OMP_CLAUSE_CHAIN (c) && OMP_CLAUSE_CODE (OMP_CLAUSE_CHAIN (c)) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (OMP_CLAUSE_CHAIN (c)) == GOMP_MAP_FIRSTPRIVATE_POINTER || (OMP_CLAUSE_MAP_KIND (OMP_CLAUSE_CHAIN (c)) == GOMP_MAP_FIRSTPRIVATE_REFERENCE))) prev = c; break; case OMP_CLAUSE_PRIVATE: var = OMP_CLAUSE_DECL (c); if (is_variable_sized (var)) { location_t clause_loc = OMP_CLAUSE_LOCATION (c); tree new_var = lookup_decl (var, ctx); tree pvar = DECL_VALUE_EXPR (var); gcc_assert (TREE_CODE (pvar) == INDIRECT_REF); pvar = TREE_OPERAND (pvar, 0); gcc_assert (DECL_P (pvar)); tree new_pvar = lookup_decl (pvar, ctx); tree atmp = builtin_decl_explicit (BUILT_IN_ALLOCA_WITH_ALIGN); tree al = size_int (DECL_ALIGN (var)); tree x = TYPE_SIZE_UNIT (TREE_TYPE (new_var)); x = build_call_expr_loc (clause_loc, atmp, 2, x, al); x = fold_convert_loc (clause_loc, TREE_TYPE (new_pvar), x); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_pvar, x)); } else if (omp_is_reference (var) && !is_gimple_omp_oacc (ctx->stmt)) { location_t clause_loc = OMP_CLAUSE_LOCATION (c); tree new_var = lookup_decl (var, ctx); tree x = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (new_var))); if (TREE_CONSTANT (x)) break; else { tree atmp = builtin_decl_explicit (BUILT_IN_ALLOCA_WITH_ALIGN); tree rtype = TREE_TYPE (TREE_TYPE (new_var)); tree al = size_int (TYPE_ALIGN (rtype)); x = build_call_expr_loc (clause_loc, atmp, 2, x, al); } x = fold_convert_loc (clause_loc, TREE_TYPE (new_var), x); gimplify_expr (&x, &new_body, NULL, is_gimple_val, fb_rvalue); gimple_seq_add_stmt (&new_body, gimple_build_assign (new_var, x)); } break; } gimple_seq fork_seq = NULL; gimple_seq join_seq = NULL; if (is_oacc_parallel (ctx)) { /* If there are reductions on the offloaded region itself, treat them as a dummy GANG loop. */ tree level = build_int_cst (integer_type_node, GOMP_DIM_GANG); lower_oacc_reductions (gimple_location (ctx->stmt), clauses, level, false, NULL, NULL, &fork_seq, &join_seq, ctx); } gimple_seq_add_seq (&new_body, fork_seq); gimple_seq_add_seq (&new_body, tgt_body); gimple_seq_add_seq (&new_body, join_seq); if (offloaded) new_body = maybe_catch_exception (new_body); gimple_seq_add_stmt (&new_body, gimple_build_omp_return (false)); gimple_omp_set_body (stmt, new_body); } bind = gimple_build_bind (NULL, NULL, tgt_bind ? gimple_bind_block (tgt_bind) : NULL_TREE); gsi_replace (gsi_p, dep_bind ? dep_bind : bind, true); gimple_bind_add_seq (bind, ilist); gimple_bind_add_stmt (bind, stmt); gimple_bind_add_seq (bind, olist); pop_gimplify_context (NULL); if (dep_bind) { gimple_bind_add_seq (dep_bind, dep_ilist); gimple_bind_add_stmt (dep_bind, bind); gimple_bind_add_seq (dep_bind, dep_olist); pop_gimplify_context (dep_bind); } } /* Expand code for an OpenMP teams directive. */ static void lower_omp_teams (gimple_stmt_iterator *gsi_p, omp_context *ctx) { gomp_teams *teams_stmt = as_a <gomp_teams *> (gsi_stmt (*gsi_p)); push_gimplify_context (); tree block = make_node (BLOCK); gbind *bind = gimple_build_bind (NULL, NULL, block); gsi_replace (gsi_p, bind, true); gimple_seq bind_body = NULL; gimple_seq dlist = NULL; gimple_seq olist = NULL; tree num_teams = omp_find_clause (gimple_omp_teams_clauses (teams_stmt), OMP_CLAUSE_NUM_TEAMS); if (num_teams == NULL_TREE) num_teams = build_int_cst (unsigned_type_node, 0); else { num_teams = OMP_CLAUSE_NUM_TEAMS_EXPR (num_teams); num_teams = fold_convert (unsigned_type_node, num_teams); gimplify_expr (&num_teams, &bind_body, NULL, is_gimple_val, fb_rvalue); } tree thread_limit = omp_find_clause (gimple_omp_teams_clauses (teams_stmt), OMP_CLAUSE_THREAD_LIMIT); if (thread_limit == NULL_TREE) thread_limit = build_int_cst (unsigned_type_node, 0); else { thread_limit = OMP_CLAUSE_THREAD_LIMIT_EXPR (thread_limit); thread_limit = fold_convert (unsigned_type_node, thread_limit); gimplify_expr (&thread_limit, &bind_body, NULL, is_gimple_val, fb_rvalue); } lower_rec_input_clauses (gimple_omp_teams_clauses (teams_stmt), &bind_body, &dlist, ctx, NULL); lower_omp (gimple_omp_body_ptr (teams_stmt), ctx); lower_reduction_clauses (gimple_omp_teams_clauses (teams_stmt), &olist, ctx); if (!gimple_omp_teams_grid_phony (teams_stmt)) { gimple_seq_add_stmt (&bind_body, teams_stmt); location_t loc = gimple_location (teams_stmt); tree decl = builtin_decl_explicit (BUILT_IN_GOMP_TEAMS); gimple *call = gimple_build_call (decl, 2, num_teams, thread_limit); gimple_set_location (call, loc); gimple_seq_add_stmt (&bind_body, call); } gimple_seq_add_seq (&bind_body, gimple_omp_body (teams_stmt)); gimple_omp_set_body (teams_stmt, NULL); gimple_seq_add_seq (&bind_body, olist); gimple_seq_add_seq (&bind_body, dlist); if (!gimple_omp_teams_grid_phony (teams_stmt)) gimple_seq_add_stmt (&bind_body, gimple_build_omp_return (true)); gimple_bind_set_body (bind, bind_body); pop_gimplify_context (bind); gimple_bind_append_vars (bind, ctx->block_vars); BLOCK_VARS (block) = ctx->block_vars; if (BLOCK_VARS (block)) TREE_USED (block) = 1; } /* Expand code within an artificial GIMPLE_OMP_GRID_BODY OMP construct. */ static void lower_omp_grid_body (gimple_stmt_iterator *gsi_p, omp_context *ctx) { gimple *stmt = gsi_stmt (*gsi_p); lower_omp (gimple_omp_body_ptr (stmt), ctx); gimple_seq_add_stmt (gimple_omp_body_ptr (stmt), gimple_build_omp_return (false)); } /* Callback for lower_omp_1. Return non-NULL if *tp needs to be regimplified. If DATA is non-NULL, lower_omp_1 is outside of OMP context, but with task_shared_vars set. */ static tree lower_omp_regimplify_p (tree *tp, int *walk_subtrees, void *data) { tree t = *tp; /* Any variable with DECL_VALUE_EXPR needs to be regimplified. */ if (VAR_P (t) && data == NULL && DECL_HAS_VALUE_EXPR_P (t)) return t; if (task_shared_vars && DECL_P (t) && bitmap_bit_p (task_shared_vars, DECL_UID (t))) return t; /* If a global variable has been privatized, TREE_CONSTANT on ADDR_EXPR might be wrong. */ if (data == NULL && TREE_CODE (t) == ADDR_EXPR) recompute_tree_invariant_for_addr_expr (t); *walk_subtrees = !IS_TYPE_OR_DECL_P (t); return NULL_TREE; } /* Data to be communicated between lower_omp_regimplify_operands and lower_omp_regimplify_operands_p. */ struct lower_omp_regimplify_operands_data { omp_context *ctx; vec<tree> *decls; }; /* Helper function for lower_omp_regimplify_operands. Find omp_member_access_dummy_var vars and adjust temporarily their DECL_VALUE_EXPRs if needed. */ static tree lower_omp_regimplify_operands_p (tree *tp, int *walk_subtrees, void *data) { tree t = omp_member_access_dummy_var (*tp); if (t) { struct walk_stmt_info *wi = (struct walk_stmt_info *) data; lower_omp_regimplify_operands_data *ldata = (lower_omp_regimplify_operands_data *) wi->info; tree o = maybe_lookup_decl (t, ldata->ctx); if (o != t) { ldata->decls->safe_push (DECL_VALUE_EXPR (*tp)); ldata->decls->safe_push (*tp); tree v = unshare_and_remap (DECL_VALUE_EXPR (*tp), t, o); SET_DECL_VALUE_EXPR (*tp, v); } } *walk_subtrees = !IS_TYPE_OR_DECL_P (*tp); return NULL_TREE; } /* Wrapper around gimple_regimplify_operands that adjusts DECL_VALUE_EXPRs of omp_member_access_dummy_var vars during regimplification. */ static void lower_omp_regimplify_operands (omp_context *ctx, gimple *stmt, gimple_stmt_iterator *gsi_p) { auto_vec<tree, 10> decls; if (ctx) { struct walk_stmt_info wi; memset (&wi, '\0', sizeof (wi)); struct lower_omp_regimplify_operands_data data; data.ctx = ctx; data.decls = &decls; wi.info = &data; walk_gimple_op (stmt, lower_omp_regimplify_operands_p, &wi); } gimple_regimplify_operands (stmt, gsi_p); while (!decls.is_empty ()) { tree t = decls.pop (); tree v = decls.pop (); SET_DECL_VALUE_EXPR (t, v); } } static void lower_omp_1 (gimple_stmt_iterator *gsi_p, omp_context *ctx) { gimple *stmt = gsi_stmt (*gsi_p); struct walk_stmt_info wi; gcall *call_stmt; if (gimple_has_location (stmt)) input_location = gimple_location (stmt); if (task_shared_vars) memset (&wi, '\0', sizeof (wi)); /* If we have issued syntax errors, avoid doing any heavy lifting. Just replace the OMP directives with a NOP to avoid confusing RTL expansion. */ if (seen_error () && is_gimple_omp (stmt)) { gsi_replace (gsi_p, gimple_build_nop (), true); return; } switch (gimple_code (stmt)) { case GIMPLE_COND: { gcond *cond_stmt = as_a <gcond *> (stmt); if ((ctx || task_shared_vars) && (walk_tree (gimple_cond_lhs_ptr (cond_stmt), lower_omp_regimplify_p, ctx ? NULL : &wi, NULL) || walk_tree (gimple_cond_rhs_ptr (cond_stmt), lower_omp_regimplify_p, ctx ? NULL : &wi, NULL))) lower_omp_regimplify_operands (ctx, cond_stmt, gsi_p); } break; case GIMPLE_CATCH: lower_omp (gimple_catch_handler_ptr (as_a <gcatch *> (stmt)), ctx); break; case GIMPLE_EH_FILTER: lower_omp (gimple_eh_filter_failure_ptr (stmt), ctx); break; case GIMPLE_TRY: lower_omp (gimple_try_eval_ptr (stmt), ctx); lower_omp (gimple_try_cleanup_ptr (stmt), ctx); break; case GIMPLE_TRANSACTION: lower_omp (gimple_transaction_body_ptr (as_a <gtransaction *> (stmt)), ctx); break; case GIMPLE_BIND: lower_omp (gimple_bind_body_ptr (as_a <gbind *> (stmt)), ctx); maybe_remove_omp_member_access_dummy_vars (as_a <gbind *> (stmt)); break; case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TASK: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); if (ctx->cancellable) ctx->cancel_label = create_artificial_label (UNKNOWN_LOCATION); lower_omp_taskreg (gsi_p, ctx); break; case GIMPLE_OMP_FOR: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); if (ctx->cancellable) ctx->cancel_label = create_artificial_label (UNKNOWN_LOCATION); lower_omp_for (gsi_p, ctx); break; case GIMPLE_OMP_SECTIONS: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); if (ctx->cancellable) ctx->cancel_label = create_artificial_label (UNKNOWN_LOCATION); lower_omp_sections (gsi_p, ctx); break; case GIMPLE_OMP_SINGLE: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_single (gsi_p, ctx); break; case GIMPLE_OMP_MASTER: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_master (gsi_p, ctx); break; case GIMPLE_OMP_TASKGROUP: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_taskgroup (gsi_p, ctx); break; case GIMPLE_OMP_ORDERED: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_ordered (gsi_p, ctx); break; case GIMPLE_OMP_CRITICAL: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_critical (gsi_p, ctx); break; case GIMPLE_OMP_ATOMIC_LOAD: if ((ctx || task_shared_vars) && walk_tree (gimple_omp_atomic_load_rhs_ptr ( as_a <gomp_atomic_load *> (stmt)), lower_omp_regimplify_p, ctx ? NULL : &wi, NULL)) lower_omp_regimplify_operands (ctx, stmt, gsi_p); break; case GIMPLE_OMP_TARGET: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_target (gsi_p, ctx); break; case GIMPLE_OMP_TEAMS: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_teams (gsi_p, ctx); break; case GIMPLE_OMP_GRID_BODY: ctx = maybe_lookup_ctx (stmt); gcc_assert (ctx); lower_omp_grid_body (gsi_p, ctx); break; case GIMPLE_CALL: tree fndecl; call_stmt = as_a <gcall *> (stmt); fndecl = gimple_call_fndecl (call_stmt); if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL) switch (DECL_FUNCTION_CODE (fndecl)) { case BUILT_IN_GOMP_BARRIER: if (ctx == NULL) break; /* FALLTHRU */ case BUILT_IN_GOMP_CANCEL: case BUILT_IN_GOMP_CANCELLATION_POINT: omp_context *cctx; cctx = ctx; if (gimple_code (cctx->stmt) == GIMPLE_OMP_SECTION) cctx = cctx->outer; gcc_assert (gimple_call_lhs (call_stmt) == NULL_TREE); if (!cctx->cancellable) { if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_GOMP_CANCELLATION_POINT) { stmt = gimple_build_nop (); gsi_replace (gsi_p, stmt, false); } break; } if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_GOMP_BARRIER) { fndecl = builtin_decl_explicit (BUILT_IN_GOMP_BARRIER_CANCEL); gimple_call_set_fndecl (call_stmt, fndecl); gimple_call_set_fntype (call_stmt, TREE_TYPE (fndecl)); } tree lhs; lhs = create_tmp_var (TREE_TYPE (TREE_TYPE (fndecl))); gimple_call_set_lhs (call_stmt, lhs); tree fallthru_label; fallthru_label = create_artificial_label (UNKNOWN_LOCATION); gimple *g; g = gimple_build_label (fallthru_label); gsi_insert_after (gsi_p, g, GSI_SAME_STMT); g = gimple_build_cond (NE_EXPR, lhs, fold_convert (TREE_TYPE (lhs), boolean_false_node), cctx->cancel_label, fallthru_label); gsi_insert_after (gsi_p, g, GSI_SAME_STMT); break; default: break; } /* FALLTHRU */ default: if ((ctx || task_shared_vars) && walk_gimple_op (stmt, lower_omp_regimplify_p, ctx ? NULL : &wi)) { /* Just remove clobbers, this should happen only if we have "privatized" local addressable variables in SIMD regions, the clobber isn't needed in that case and gimplifying address of the ARRAY_REF into a pointer and creating MEM_REF based clobber would create worse code than we get with the clobber dropped. */ if (gimple_clobber_p (stmt)) { gsi_replace (gsi_p, gimple_build_nop (), true); break; } lower_omp_regimplify_operands (ctx, stmt, gsi_p); } break; } } static void lower_omp (gimple_seq *body, omp_context *ctx) { location_t saved_location = input_location; gimple_stmt_iterator gsi; for (gsi = gsi_start (*body); !gsi_end_p (gsi); gsi_next (&gsi)) lower_omp_1 (&gsi, ctx); /* During gimplification, we haven't folded statments inside offloading or taskreg regions (gimplify.c:maybe_fold_stmt); do that now. */ if (target_nesting_level || taskreg_nesting_level) for (gsi = gsi_start (*body); !gsi_end_p (gsi); gsi_next (&gsi)) fold_stmt (&gsi); input_location = saved_location; } /* Main entry point. */ static unsigned int execute_lower_omp (void) { gimple_seq body; int i; omp_context *ctx; /* This pass always runs, to provide PROP_gimple_lomp. But often, there is nothing to do. */ if (flag_openacc == 0 && flag_openmp == 0 && flag_openmp_simd == 0) return 0; all_contexts = splay_tree_new (splay_tree_compare_pointers, 0, delete_omp_context); body = gimple_body (current_function_decl); if (hsa_gen_requested_p ()) omp_grid_gridify_all_targets (&body); scan_omp (&body, NULL); gcc_assert (taskreg_nesting_level == 0); FOR_EACH_VEC_ELT (taskreg_contexts, i, ctx) finish_taskreg_scan (ctx); taskreg_contexts.release (); if (all_contexts->root) { if (task_shared_vars) push_gimplify_context (); lower_omp (&body, NULL); if (task_shared_vars) pop_gimplify_context (NULL); } if (all_contexts) { splay_tree_delete (all_contexts); all_contexts = NULL; } BITMAP_FREE (task_shared_vars); /* If current function is a method, remove artificial dummy VAR_DECL created for non-static data member privatization, they aren't needed for debuginfo nor anything else, have been already replaced everywhere in the IL and cause problems with LTO. */ if (DECL_ARGUMENTS (current_function_decl) && DECL_ARTIFICIAL (DECL_ARGUMENTS (current_function_decl)) && (TREE_CODE (TREE_TYPE (DECL_ARGUMENTS (current_function_decl))) == POINTER_TYPE)) remove_member_access_dummy_vars (DECL_INITIAL (current_function_decl)); return 0; } namespace { const pass_data pass_data_lower_omp = { GIMPLE_PASS, /* type */ "omplower", /* name */ OPTGROUP_OMP, /* optinfo_flags */ TV_NONE, /* tv_id */ PROP_gimple_any, /* properties_required */ PROP_gimple_lomp | PROP_gimple_lomp_dev, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ 0, /* todo_flags_finish */ }; class pass_lower_omp : public gimple_opt_pass { public: pass_lower_omp (gcc::context *ctxt) : gimple_opt_pass (pass_data_lower_omp, ctxt) {} /* opt_pass methods: */ virtual unsigned int execute (function *) { return execute_lower_omp (); } }; // class pass_lower_omp } // anon namespace gimple_opt_pass * make_pass_lower_omp (gcc::context *ctxt) { return new pass_lower_omp (ctxt); } /* The following is a utility to diagnose structured block violations. It is not part of the "omplower" pass, as that's invoked too late. It should be invoked by the respective front ends after gimplification. */ static splay_tree all_labels; /* Check for mismatched contexts and generate an error if needed. Return true if an error is detected. */ static bool diagnose_sb_0 (gimple_stmt_iterator *gsi_p, gimple *branch_ctx, gimple *label_ctx) { gcc_checking_assert (!branch_ctx || is_gimple_omp (branch_ctx)); gcc_checking_assert (!label_ctx || is_gimple_omp (label_ctx)); if (label_ctx == branch_ctx) return false; const char* kind = NULL; if (flag_openacc) { if ((branch_ctx && is_gimple_omp_oacc (branch_ctx)) || (label_ctx && is_gimple_omp_oacc (label_ctx))) { gcc_checking_assert (kind == NULL); kind = "OpenACC"; } } if (kind == NULL) { gcc_checking_assert (flag_openmp || flag_openmp_simd); kind = "OpenMP"; } /* Previously we kept track of the label's entire context in diagnose_sb_[12] so we could traverse it and issue a correct "exit" or "enter" error message upon a structured block violation. We built the context by building a list with tree_cons'ing, but there is no easy counterpart in gimple tuples. It seems like far too much work for issuing exit/enter error messages. If someone really misses the distinct error message... patches welcome. */ #if 0 /* Try to avoid confusing the user by producing and error message with correct "exit" or "enter" verbiage. We prefer "exit" unless we can show that LABEL_CTX is nested within BRANCH_CTX. */ if (branch_ctx == NULL) exit_p = false; else { while (label_ctx) { if (TREE_VALUE (label_ctx) == branch_ctx) { exit_p = false; break; } label_ctx = TREE_CHAIN (label_ctx); } } if (exit_p) error ("invalid exit from %s structured block", kind); else error ("invalid entry to %s structured block", kind); #endif /* If it's obvious we have an invalid entry, be specific about the error. */ if (branch_ctx == NULL) error ("invalid entry to %s structured block", kind); else { /* Otherwise, be vague and lazy, but efficient. */ error ("invalid branch to/from %s structured block", kind); } gsi_replace (gsi_p, gimple_build_nop (), false); return true; } /* Pass 1: Create a minimal tree of structured blocks, and record where each label is found. */ static tree diagnose_sb_1 (gimple_stmt_iterator *gsi_p, bool *handled_ops_p, struct walk_stmt_info *wi) { gimple *context = (gimple *) wi->info; gimple *inner_context; gimple *stmt = gsi_stmt (*gsi_p); *handled_ops_p = true; switch (gimple_code (stmt)) { WALK_SUBSTMTS; case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TASK: case GIMPLE_OMP_SECTIONS: case GIMPLE_OMP_SINGLE: case GIMPLE_OMP_SECTION: case GIMPLE_OMP_MASTER: case GIMPLE_OMP_ORDERED: case GIMPLE_OMP_CRITICAL: case GIMPLE_OMP_TARGET: case GIMPLE_OMP_TEAMS: case GIMPLE_OMP_TASKGROUP: /* The minimal context here is just the current OMP construct. */ inner_context = stmt; wi->info = inner_context; walk_gimple_seq (gimple_omp_body (stmt), diagnose_sb_1, NULL, wi); wi->info = context; break; case GIMPLE_OMP_FOR: inner_context = stmt; wi->info = inner_context; /* gimple_omp_for_{index,initial,final} are all DECLs; no need to walk them. */ walk_gimple_seq (gimple_omp_for_pre_body (stmt), diagnose_sb_1, NULL, wi); walk_gimple_seq (gimple_omp_body (stmt), diagnose_sb_1, NULL, wi); wi->info = context; break; case GIMPLE_LABEL: splay_tree_insert (all_labels, (splay_tree_key) gimple_label_label ( as_a <glabel *> (stmt)), (splay_tree_value) context); break; default: break; } return NULL_TREE; } /* Pass 2: Check each branch and see if its context differs from that of the destination label's context. */ static tree diagnose_sb_2 (gimple_stmt_iterator *gsi_p, bool *handled_ops_p, struct walk_stmt_info *wi) { gimple *context = (gimple *) wi->info; splay_tree_node n; gimple *stmt = gsi_stmt (*gsi_p); *handled_ops_p = true; switch (gimple_code (stmt)) { WALK_SUBSTMTS; case GIMPLE_OMP_PARALLEL: case GIMPLE_OMP_TASK: case GIMPLE_OMP_SECTIONS: case GIMPLE_OMP_SINGLE: case GIMPLE_OMP_SECTION: case GIMPLE_OMP_MASTER: case GIMPLE_OMP_ORDERED: case GIMPLE_OMP_CRITICAL: case GIMPLE_OMP_TARGET: case GIMPLE_OMP_TEAMS: case GIMPLE_OMP_TASKGROUP: wi->info = stmt; walk_gimple_seq_mod (gimple_omp_body_ptr (stmt), diagnose_sb_2, NULL, wi); wi->info = context; break; case GIMPLE_OMP_FOR: wi->info = stmt; /* gimple_omp_for_{index,initial,final} are all DECLs; no need to walk them. */ walk_gimple_seq_mod (gimple_omp_for_pre_body_ptr (stmt), diagnose_sb_2, NULL, wi); walk_gimple_seq_mod (gimple_omp_body_ptr (stmt), diagnose_sb_2, NULL, wi); wi->info = context; break; case GIMPLE_COND: { gcond *cond_stmt = as_a <gcond *> (stmt); tree lab = gimple_cond_true_label (cond_stmt); if (lab) { n = splay_tree_lookup (all_labels, (splay_tree_key) lab); diagnose_sb_0 (gsi_p, context, n ? (gimple *) n->value : NULL); } lab = gimple_cond_false_label (cond_stmt); if (lab) { n = splay_tree_lookup (all_labels, (splay_tree_key) lab); diagnose_sb_0 (gsi_p, context, n ? (gimple *) n->value : NULL); } } break; case GIMPLE_GOTO: { tree lab = gimple_goto_dest (stmt); if (TREE_CODE (lab) != LABEL_DECL) break; n = splay_tree_lookup (all_labels, (splay_tree_key) lab); diagnose_sb_0 (gsi_p, context, n ? (gimple *) n->value : NULL); } break; case GIMPLE_SWITCH: { gswitch *switch_stmt = as_a <gswitch *> (stmt); unsigned int i; for (i = 0; i < gimple_switch_num_labels (switch_stmt); ++i) { tree lab = CASE_LABEL (gimple_switch_label (switch_stmt, i)); n = splay_tree_lookup (all_labels, (splay_tree_key) lab); if (n && diagnose_sb_0 (gsi_p, context, (gimple *) n->value)) break; } } break; case GIMPLE_RETURN: diagnose_sb_0 (gsi_p, context, NULL); break; default: break; } return NULL_TREE; } static unsigned int diagnose_omp_structured_block_errors (void) { struct walk_stmt_info wi; gimple_seq body = gimple_body (current_function_decl); all_labels = splay_tree_new (splay_tree_compare_pointers, 0, 0); memset (&wi, 0, sizeof (wi)); walk_gimple_seq (body, diagnose_sb_1, NULL, &wi); memset (&wi, 0, sizeof (wi)); wi.want_locations = true; walk_gimple_seq_mod (&body, diagnose_sb_2, NULL, &wi); gimple_set_body (current_function_decl, body); splay_tree_delete (all_labels); all_labels = NULL; return 0; } namespace { const pass_data pass_data_diagnose_omp_blocks = { GIMPLE_PASS, /* type */ "*diagnose_omp_blocks", /* name */ OPTGROUP_OMP, /* optinfo_flags */ TV_NONE, /* tv_id */ PROP_gimple_any, /* properties_required */ 0, /* properties_provided */ 0, /* properties_destroyed */ 0, /* todo_flags_start */ 0, /* todo_flags_finish */ }; class pass_diagnose_omp_blocks : public gimple_opt_pass { public: pass_diagnose_omp_blocks (gcc::context *ctxt) : gimple_opt_pass (pass_data_diagnose_omp_blocks, ctxt) {} /* opt_pass methods: */ virtual bool gate (function *) { return flag_openacc || flag_openmp || flag_openmp_simd; } virtual unsigned int execute (function *) { return diagnose_omp_structured_block_errors (); } }; // class pass_diagnose_omp_blocks } // anon namespace gimple_opt_pass * make_pass_diagnose_omp_blocks (gcc::context *ctxt) { return new pass_diagnose_omp_blocks (ctxt); } #include "gt-omp-low.h"
DFS.c
// ----------------------------------------------------------------------------- // // "00_AccelGraph" // // ----------------------------------------------------------------------------- // Copyright (c) 2014-2019 All rights reserved // ----------------------------------------------------------------------------- // Author : Abdullah Mughrabi // Email : atmughra@ncsu.edu||atmughrabi@gmail.com // File : DFS.c // Create : 2019-06-21 17:15:17 // Revise : 2019-09-28 15:34:11 // Editor : Abdullah Mughrabi // ----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <omp.h> #include "timer.h" #include "myMalloc.h" #include "boolean.h" #include "arrayStack.h" #include "bitmap.h" #include "graphConfig.h" #include "reorder.h" #include "graphCSR.h" #include "graphGrid.h" #include "graphAdjArrayList.h" #include "graphAdjLinkedList.h" #include "DFS.h" // ******************************************************************************************** // *************** Stats DataStructure ************** // ******************************************************************************************** struct DFSStats *newDFSStatsGraphCSR(struct GraphCSR *graph) { uint32_t vertex_id; struct DFSStats *stats = (struct DFSStats *) my_malloc(sizeof(struct DFSStats)); stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; // optimization for DFS implentaion instead of -1 we use -out degree to for hybrid approach counter #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; stats->parents[vertex_id] = -1; } return stats; } struct DFSStats *newDFSStatsGraphGrid(struct GraphGrid *graph) { uint32_t vertex_id; struct DFSStats *stats = (struct DFSStats *) my_malloc(sizeof(struct DFSStats)); stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; stats->parents[vertex_id] = -1; } return stats; } struct DFSStats *newDFSStatsGraphAdjArrayList(struct GraphAdjArrayList *graph) { uint32_t vertex_id; struct DFSStats *stats = (struct DFSStats *) my_malloc(sizeof(struct DFSStats)); stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; stats->parents[vertex_id] = -1; } return stats; } struct DFSStats *newDFSStatsGraphAdjLinkedList(struct GraphAdjLinkedList *graph) { uint32_t vertex_id; struct DFSStats *stats = (struct DFSStats *) my_malloc(sizeof(struct DFSStats)); stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (int *) my_malloc(graph->num_vertices * sizeof(int)); stats->processed_nodes = 0; stats->num_vertices = graph->num_vertices; stats->time_total = 0.0f; #pragma omp parallel for default(none) private(vertex_id) shared(stats,graph) for(vertex_id = 0; vertex_id < graph->num_vertices ; vertex_id++) { stats->distances[vertex_id] = 0; stats->parents[vertex_id] = -1; } return stats; } void freeDFSStats(struct DFSStats *stats) { if(stats) { if(stats->distances) free(stats->distances); if(stats->parents) free(stats->parents); free(stats); } } // ******************************************************************************************** // *************** CSR DataStructure ************** // ******************************************************************************************** struct DFSStats *depthFirstSearchGraphCSRBase(struct Arguments *arguments, struct GraphCSR *graph) { struct DFSStats *stats = newDFSStatsGraphCSR(graph); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayStack *sharedFrontierStack = newArrayStack(graph->num_vertices); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting Depth First Search (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } pushArrayStack(sharedFrontierStack, arguments->source); stats->parents[arguments->source] = arguments->source; Start(timer); while(!isEmptyArrayStackCurr(sharedFrontierStack)) // start while { uint32_t v = popArrayStack(sharedFrontierStack); stats->processed_nodes++; uint32_t edge_idx = graph->vertices->edges_idx[v]; uint32_t j; for(j = edge_idx ; j < (edge_idx + graph->vertices->out_degree[v]) ; j++) { uint32_t u = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[j]); int u_parent = stats->parents[u]; if(u_parent < 0 ) { stats->parents[u] = v; stats->distances[u] = stats->distances[v] + 1; pushArrayStack(sharedFrontierStack, u); } } } // end while Stop(timer); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayStack(sharedFrontierStack); free(timer); return stats; } struct DFSStats *depthFirstSearchGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct DFSStats *stats = newDFSStatsGraphCSR(graph); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct ArrayStack *sharedFrontierStack = newArrayStack(graph->num_vertices); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting Depth First Search (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } pushArrayStack(sharedFrontierStack, arguments->source); stats->parents[arguments->source] = arguments->source; Start(timer); while(!isEmptyArrayStackCurr(sharedFrontierStack)) // start while { uint32_t v = popArrayStack(sharedFrontierStack); stats->processed_nodes++; uint32_t edge_idx = graph->vertices->edges_idx[v]; uint32_t j; for(j = edge_idx ; j < (edge_idx + graph->vertices->out_degree[v]) ; j++) { uint32_t u = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[j]); int u_parent = stats->parents[u]; if(u_parent < 0 ) { stats->parents[u] = v; stats->distances[u] = stats->distances[v] + 1; pushArrayStack(sharedFrontierStack, u); } } } // end while Stop(timer); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); freeArrayStack(sharedFrontierStack); free(timer); return stats; } struct DFSStats *pDepthFirstSearchGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct DFSStats *stats = newDFSStatsGraphCSR(graph); struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting P-Depth First Search (SOURCE NODE)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Nodes", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } stats->parents[arguments->source] = arguments->source; Start(timer); parallelDepthFirstSearchGraphCSRTask(arguments, graph, stats); Stop(timer); stats->time_total = Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "No OverHead", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, Seconds(timer)); printf(" -----------------------------------------------------\n"); free(timer); return stats; } void parallelDepthFirstSearchGraphCSRTask(struct Arguments *arguments, struct GraphCSR *graph, struct DFSStats *stats) { uint32_t v = arguments->source; #pragma omp atomic update stats->processed_nodes++; // printf("%u \n", stats->processed_nodes); uint32_t edge_idx = graph->vertices->edges_idx[v]; uint32_t j; for(j = edge_idx ; j < (edge_idx + graph->vertices->out_degree[v]) ; j++) { uint32_t u = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[j]); int u_parent = stats->parents[u]; if(u_parent < 0 ) { if(__sync_bool_compare_and_swap(&(stats->parents[u]), u_parent, v)) { arguments->source = u; stats->distances[u] = stats->distances[v] + 1; // #pragma omp task parallelDepthFirstSearchGraphCSRTask( arguments, graph, stats); } } } }
GB_unaryop__abs_uint32_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint32_uint32 // op(A') function: GB_tran__abs_uint32_uint32 // C type: uint32_t // A type: uint32_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ 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_ABS || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint32_uint32 ( uint32_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint32_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
AlloyVector.h
/* * Copyright(C) 2015, Blake C. Lucas, Ph.D. (img.science@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef ALLOYLINEARALGEBRA_H_ #define ALLOYLINEARALGEBRA_H_ #include "AlloyMath.h" #include <vector> #include <functional> #include <iomanip> #include <limits> #include <algorithm> #include <fstream> #include "cereal/types/vector.hpp" #include "cereal/types/string.hpp" namespace aly { bool SANITY_CHECK_LINALG(); template<class T, int C> struct Vector { public: std::vector<vec<T, C>> data; const int channels = C; typedef vec<T, C> ValueType; typedef typename std::vector<ValueType>::iterator iterator; typedef typename std::vector<ValueType>::const_iterator const_iterator; typedef typename std::vector<ValueType>::reverse_iterator reverse_iterator; iterator begin() { return data.begin(); } iterator end() { return data.end(); } const_iterator cbegin() const { return data.cbegin(); } const_iterator cend() const { return data.cend(); } reverse_iterator rbegin() { return data.rbegin(); } reverse_iterator rend() { return data.rend(); } reverse_iterator rbegin() const { return data.rbegin(); } reverse_iterator rend() const { return data.rend(); } template<class Archive> void save(Archive & archive) const { archive(cereal::make_nvp(MakeString() << "vector" << C, data)); } template<class Archive> void load(Archive & archive) { archive(cereal::make_nvp(MakeString() << "vector" << C, data)); } void set(const T& val) { data.assign(data.size(), vec<T, C>(val)); } void set(const vec<T, C>& val) { data.assign(data.size(), val); } void set(const std::vector<vec<T, C>>& val) { data = val; } void set(T* val) { if (val == nullptr) return; size_t offset = 0; for (vec<T, C>& x : data) { for (int c = 0; c < C; c++) { x[c] = val[offset++]; } } } void set(vec<T, C>* val) { if (val == nullptr) return; size_t offset = 0; for (vec<T, C>& x : data) { x = val[offset++]; } } template<class F> void apply(F f) { size_t sz = size(); #pragma omp parallel for for (int offset = 0; offset < (int) sz; offset++) { f(offset, data[offset]); } } Vector(size_t sz) : data(sz) { } Vector(const Vector<T, C>& img) : Vector(img.size()) { set(img.data); } Vector<T, C>& operator=(const Vector<T, C>& rhs) { if (this == &rhs) return *this; if (rhs.size() > 0) { this->set(rhs.data); } else { this->clear(); } return *this; } Vector() { } Vector(T* ptr, size_t sz) : Vector(sz) { set(ptr); } Vector(vec<T, C>* ptr, size_t sz) : Vector(sz) { set(ptr); } Vector(const std::vector<vec<T, C>>& ref) : data(ref) { } size_t size() const { return data.size(); } size_t typeSize() const { return sizeof(vec<T, C> ); } void resize(size_t sz) { data.resize(sz); data.shrink_to_fit(); } void resize(size_t sz, const vec<T, C>& val) { data.resize(sz, val); data.shrink_to_fit(); } void append(const vec<T, C>& val) { data.push_back(val); } void push_back(const vec<T, C>& val) { data.push_back(val); } T* ptr() { if (data.size() == 0) return nullptr; return &(data.front()[0]); } const T* ptr() const { if (data.size() == 0) return nullptr; return &(data.front()[0]); } void setZero() { data.assign(data.size(), vec<T, C>((T) 0)); } const vec<T, C>& operator[](const size_t i) const { if (i >= data.size()) throw std::runtime_error( MakeString() << "Vector index out of bounds " << i << "/" << data.size()); return data[i]; } vec<T, C>& operator[](const size_t i) { if (i >= data.size()) throw std::runtime_error( MakeString() << "Vector index out of bounds " << i << "/" << data.size()); return data[i]; } inline void clear() { data.clear(); data.shrink_to_fit(); } vec<T, C> min() const { vec<T, C> minVal(std::numeric_limits<T>::max()); for (const vec<T, C>& val : data) { minVal = aly::minVec(val, minVal); } return minVal; } vec<T, C> max() const { vec<T, C> maxVal(std::numeric_limits<T>::min()); for (const vec<T, C>& val : data) { maxVal = aly::maxVec(val, maxVal); } return maxVal; } std::pair<vec<T, C>, vec<T, C>> range() const { vec<T, C> maxVal(std::numeric_limits<T>::min()); vec<T, C> minVal(std::numeric_limits<T>::max()); for (const vec<T, C>& val : data) { maxVal = aly::maxVec(val, maxVal); minVal = aly::minVec(val, minVal); } return std::pair<vec<T, C>, vec<T, C>>(minVal, maxVal); } vec<T, C> mean() const { vec<double, C> mean(0.0); for (const vec<T, C>& val : data) { mean += vec<double, C>(val); } mean = mean / (double) data.size(); return vec<T, C>(mean); } vec<T, C> median() const { std::vector<T> bands[C]; for (int c = 0; c < C; c++) { bands[c].resize(data.size()); } size_t index = 0; for (const vec<T, C>& val : data) { for (int c = 0; c < C; c++) { bands[c][index] = val[c]; } index++; } #pragma omp parallel for for (int c = 0; c < C; c++) { std::sort(bands[c].begin(), bands[c].end()); } vec<T, C> med; if (data.size() % 2 == 0) { for (int c = 0; c < C; c++) { med[c] = T( ((double) bands[c][data.size() / 2] + (double) bands[c][data.size() / 2 - 1]) * 0.5f); } } else { for (int c = 0; c < C; c++) { med[c] = bands[c][data.size() / 2]; } } return med; } vec<T, C> mad() const { if (data.size() <= 2) return vec<T, C>(T(0)); vec<T, C> med = median(); std::vector<T> bands[C]; for (int c = 0; c < C; c++) { bands[c].resize(data.size()); } size_t index = 0; for (const vec<T, C>& val : data) { vec<T, C> e = aly::abs(val - med); for (int c = 0; c < C; c++) { bands[c][index] = e[c]; } index++; } #pragma omp parallel for for (int c = 0; c < C; c++) { std::sort(bands[c].begin(), bands[c].end()); } vec<T, C> mad; if (data.size() % 2 == 0) { for (int c = 0; c < C; c++) { mad[c] = T( ((double) bands[c][data.size() / 2] + (double) bands[c][data.size() / 2 - 1]) * 0.5f); } } else { for (int c = 0; c < C; c++) { mad[c] = bands[c][data.size() / 2]; } } return mad; } vec<T, C> madStdDev() const { return vec<T, C>(1.4826 * vec<double, C>(mad())); } vec<T, C> stdDev() const { if (data.size() < 2) { return vec<T, C>(T(0)); } vec<T, C> avg = mean(); vec<double, C> var(0.0); for (const vec<T, C>& val : data) { vec<double, C> e = vec<double, C>(val - avg); var += e * e; } var = var / (double) (data.size() - 1); return vec<T, C>(aly::sqrt(var)); } }; template<class T, int C> void Transform(Vector<T, C>& im1, Vector<T, C>& im2, const std::function<void(vec<T, C>&, vec<T, C>&)>& func) { if (im1.size() != im2.size()) throw std::runtime_error( MakeString() << "Vector dimensions do not match. " << im1.size() << "!=" << im2.size()); size_t sz = im1.size(); #pragma omp parallel for for (size_t offset = 0; offset < sz; offset++) { func(im1.data[offset], im2.data[offset]); } } template<class T, int C> void Transform(Vector<T, C>& im1, const std::function<void(vec<T, C>&)>& func) { size_t sz = im1.size(); #pragma omp parallel for for (int offset = 0; offset < (int) sz; offset++) { func(im1.data[offset]); } } template<class T, int C> void Transform(Vector<T, C>& im1, const Vector<T, C>& im2, const std::function<void(vec<T, C>&, const vec<T, C>&)>& func) { if (im1.size() != im2.size()) throw std::runtime_error( MakeString() << "Vector dimensions do not match. " << im1.size() << "!=" << im2.size()); size_t sz = im1.size(); #pragma omp parallel for for (int offset = 0; offset < (int) sz; offset++) { func(im1.data[offset], im2.data[offset]); } } template<class T, int C> void Transform(Vector<T, C>& im1, const Vector<T, C>& im2, const Vector<T, C>& im3, const Vector<T, C>& im4, const std::function< void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&, const vec<T, C>&)>& func) { if (im1.size() != im2.size()) throw std::runtime_error( MakeString() << "Vector dimensions do not match. " << im1.size() << "!=" << im2.size()); size_t sz = im1.size(); #pragma omp parallel for for (int offset = 0; offset < (int) sz; offset++) { func(im1.data[offset], im2.data[offset], im3.data[offset], im4.data[offset]); } } template<class T, int C> void Transform(Vector<T, C>& im1, const Vector<T, C>& im2, const Vector<T, C>& im3, const std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)>& func) { if (im1.size() != im2.size()) throw std::runtime_error( MakeString() << "Vector dimensions do not match. " << im1.size() << "!=" << im2.size()); size_t sz = im1.size(); #pragma omp parallel for for (int offset = 0; offset < (int) sz; offset++) { func(im1.data[offset], im2.data[offset], im3.data[offset]); } } template<class T, int C> void Transform(Vector<T, C>& im1, Vector<T, C>& im2, const std::function< void(size_t offset, vec<T, C>& val1, vec<T, C>& val2)>& func) { if (im1.size() != im2.size()) throw std::runtime_error( MakeString() << "Vector dimensions do not match. " << im1.size() << "!=" << im2.size()); size_t sz = im1.size(); #pragma omp parallel for for (size_t offset = 0; offset < sz; offset++) { func(offset, im1.data[offset], im2.data[offset]); } } template<class T, class L, class R, int C> std::basic_ostream<L, R> & operator <<( std::basic_ostream<L, R> & ss, const Vector<T, C> & A) { size_t index = 0; for (const vec<T, C>& val : A.data) { ss << std::setw(5) << index++ << ": " << val << std::endl; } return ss; } template<class T, int C> Vector<T, C> operator+(const vec<T, C>& scalar, const Vector<T, C>& img) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = scalar + val2;}; Transform(out, img, f); return out; } template<class T, int C> void ScaleAdd(Vector<T, C>& out, const vec<T, C>& scalar, const Vector<T, C>& in) { out.resize(in.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 += scalar * val2;}; Transform(out, in, f); } template<class T, int C> void ScaleAdd(Vector<T, C>& out, const T& scalar, const Vector<T, C>& in) { out.resize(in.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 += scalar * val2;}; Transform(out, in, f); } template<class T, int C> void ScaleAdd(Vector<T, C>& out, const Vector<T, C>& in1, const vec<T, C>& scalar, const Vector<T, C>& in2) { out.resize(in1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2+scalar * val3;}; Transform(out, in1, in2, f); } template<class T, int C> void ScaleAdd(Vector<T, C>& out, const Vector<T, C>& in1, const vec<T, C>& scalar2, const Vector<T, C>& in2, const vec<T, C>& scalar3, const Vector<T, C>& in3) { out.resize(in1.size()); std::function< void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& out, const vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) { out = val1+scalar2*val2+scalar3 * val3;}; Transform(out, in1, in2, in3, f); } template<class T, int C> void ScaleSubtract(Vector<T, C>& out, const vec<T, C>& scalar, const Vector<T, C>& in) { out.resize(in.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 -= scalar * val2;}; Transform(out, in, f); } template<class T, int C> void ScaleSubtract(Vector<T, C>& out, const Vector<T, C>& in1, const vec<T, C>& scalar, const Vector<T, C>& in2) { out.resize(in1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2 - scalar * val3;}; Transform(out, in1, in2, f); } template<class T, int C> void Subtract(Vector<T, C>& out, const Vector<T, C>& v1, const Vector<T, C>& v2) { out.resize(v1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2-val3;}; Transform(out, v1, v2, f); } template<class T, int C> void Add(Vector<T, C>& out, const Vector<T, C>& v1, const Vector<T, C>& v2) { out.resize(v1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2 + val3;}; Transform(out, v1, v2, f); } template<class T, int C> Vector<T, C> operator-(const vec<T, C>& scalar, const Vector<T, C>& img) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = scalar - val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator*(const vec<T, C>& scalar, const Vector<T, C>& img) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = scalar*val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator*(const T& scalar, const Vector<T, C>& img) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = scalar*val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator/(const vec<T, C>& scalar, const Vector<T, C>& img) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = scalar / val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator+(const Vector<T, C>& img, const vec<T, C>& scalar) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = val2 + scalar;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator-(const Vector<T, C>& img, const vec<T, C>& scalar) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = val2 - scalar;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator*(const Vector<T, C>& img, const vec<T, C>& scalar) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = val2*scalar;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator/(const Vector<T, C>& img, const vec<T, C>& scalar) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = val2 / scalar;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator-(const Vector<T, C>& img) { Vector<T, C> out(img.size()); std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 = -val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator+=(Vector<T, C>& out, const Vector<T, C>& img) { std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 += val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator-=(Vector<T, C>& out, const Vector<T, C>& img) { std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 -= val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator*=(Vector<T, C>& out, const Vector<T, C>& img) { std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 *= val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator/=(Vector<T, C>& out, const Vector<T, C>& img) { std::function<void(vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2) {val1 /= val2;}; Transform(out, img, f); return out; } template<class T, int C> Vector<T, C> operator+=(Vector<T, C>& out, const vec<T, C>& scalar) { std::function<void(vec<T, C>&)> f = [=](vec<T, C>& val1) {val1 += scalar;}; Transform(out, f); return out; } template<class T, int C> Vector<T, C> operator-=(Vector<T, C>& out, const vec<T, C>& scalar) { std::function<void(vec<T, C>&)> f = [=](vec<T, C>& val1) {val1 -= scalar;}; Transform(out, f); return out; } template<class T, int C> Vector<T, C> operator*=(Vector<T, C>& out, const vec<T, C>& scalar) { std::function<void(vec<T, C>&)> f = [=](vec<T, C>& val1) {val1 *= scalar;}; Transform(out, f); return out; } template<class T, int C> Vector<T, C> operator/=(Vector<T, C>& out, const vec<T, C>& scalar) { std::function<void(vec<T, C>&)> f = [=](vec<T, C>& val1) {val1 /= scalar;}; Transform(out, f); return out; } template<class T, int C> Vector<T, C> operator+(const Vector<T, C>& img1, const Vector<T, C>& img2) { Vector<T, C> out(img1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2 + val3;}; Transform(out, img1, img2, f); return out; } template<class T, int C> Vector<T, C> operator-(const Vector<T, C>& img1, const Vector<T, C>& img2) { Vector<T, C> out(img1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2 - val3;}; Transform(out, img1, img2, f); return out; } template<class T, int C> Vector<T, C> operator*(const Vector<T, C>& img1, const Vector<T, C>& img2) { Vector<T, C> out(img1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2*val3;}; Transform(out, img1, img2, f); return out; } template<class T, int C> Vector<T, C> operator/(const Vector<T, C>& img1, const Vector<T, C>& img2) { Vector<T, C> out(img1.size()); std::function<void(vec<T, C>&, const vec<T, C>&, const vec<T, C>&)> f = [=](vec<T, C>& val1, const vec<T, C>& val2, const vec<T, C>& val3) {val1 = val2 / val3;}; Transform(out, img1, img2, f); return out; } template<class T, int C> vec<double, C> dotVec(const Vector<T, C>& a, const Vector<T, C>& b) { vec<double, C> ans(0.0); if (a.size() != b.size()) throw std::runtime_error( MakeString() << "Vector dimensions do not match. " << a.size() << "!=" << b.size()); size_t sz = a.size(); #pragma omp parallel for for (int c = 0; c < C; c++) { double cans = 0; #pragma omp parallel for reduction(+:cans) for (int i = 0; i < (int) sz; i++) { cans += (double) a[i][c] * (double) b[i][c]; } ans[c] = cans; } return ans; } template<class T, int C> double dot(const Vector<T, C>& a, const Vector<T, C>& b) { double ans = 0.0; if (a.size() != b.size()) throw std::runtime_error( MakeString() << "Vector dimensions do not match. " << a.size() << "!=" << b.size()); size_t sz = a.size(); #pragma omp parallel for reduction(+:ans) for (int i = 0; i < (int) sz; i++) { ans += dot(vec<double, C>(a[i]), vec<double, C>(b[i])); } return ans; } template<class T, int C> T lengthSqr(const Vector<T, C>& a) { T ans(0); size_t sz = a.size(); #pragma omp parallel for reduction(+:ans) for (int i = 0; i < (int) sz; i++) { ans += dot(a[i], a[i]); } return ans; } template<class T, int C> T lengthL1(const Vector<T, C>& a) { T ans(0); size_t sz = a.size(); #pragma omp parallel for reduction(+:ans) for (int i = 0; i < (int) sz; i++) { for (int c = 0; c < C; c++) { ans += std::abs(a[i][c]); } } return ans; } template<class T, int C> vec<T, C> lengthVecL1(const Vector<T, C>& a) { vec<T, C> ans((T) 0); size_t sz = a.size(); #pragma omp parallel for for (int c = 0; c < C; c++) { T cans = 0; #pragma omp parallel for reduction(+:cans) for (int i = 0; i < (int) sz; i++) { cans += std::abs(a[i][c]); } ans[c] = cans; } return ans; } template<class T, int C> vec<T, C> maxVec(const Vector<T, C>& a) { vec<T, C> ans((T) 0); size_t sz = a.size(); #pragma omp parallel for for (int c = 0; c < C; c++) { T tmp(std::numeric_limits<T>::min()); //#pragma omp parallel for reduction(max:tmp) for (int i = 0; i < (int) sz; i++) { if (a[i][c] > tmp) tmp = a[i][c]; } ans[c] = tmp; } return ans; } template<class T, int C> vec<T, C> minVec(const Vector<T, C>& a) { vec<T, C> ans((T) 0); size_t sz = a.size(); #pragma omp parallel for for (int c = 0; c < C; c++) { T tmp(std::numeric_limits<T>::max()); //#pragma omp parallel for reduction(min:tmp) for (int i = 0; i < (int) sz; i++) { if (a[i][c] < tmp) tmp = a[i][c]; } ans[c] = tmp; } return ans; } template<class T, int C> T max(const Vector<T, C>& a) { size_t sz = a.size(); T tmp(std::numeric_limits<T>::min()); //#pragma omp parallel for reduction(max:tmp) for (int i = 0; i < (int) sz; i++) { for (int c = 0; c < C; c++) { if (a[i][c] > tmp) tmp = a[i][c]; } } return tmp; } template<class T, int C> T min(const Vector<T, C>& a) { size_t sz = a.size(); T tmp(std::numeric_limits<T>::max()); //#pragma omp parallel for reduction(min:tmp) for (int i = 0; i < (int) sz; i++) { for (int c = 0; c < C; c++) { if (a[i][c] < tmp) tmp = a[i][c]; } } return tmp; } template<class T, int C> T length(const Vector<T, C>& a) { return std::sqrt(lengthSqr(a)); } template<class T, int C> vec<double, C> lengthVecSqr(const Vector<T, C>& a) { vec<double, C> ans(0.0); size_t sz = a.size(); #pragma omp parallel for for (int c = 0; c < C; c++) { double cans = 0; #pragma omp parallel for reduction(+:cans) for (int i = 0; i < (int) sz; i++) { double val = a[i][c]; cans += val * val; } ans[c] = cans; } return ans; } template<class T, int C> vec<double, C> lengthVec(const Vector<T, C>& a) { return aly::sqrt(lengthVecSqr(a)); } template<class T, int C> void WriteVectorToFile(const std::string& file,const Vector<T,C>& vector) { uint64_t sz = vector.size(); std::ofstream os(file, std::ios::binary); os.write((const char*)&sz, sizeof(uint64_t)); os.write((const char*)vector.ptr(), (std::streamsize)(sz*vector.typeSize())); } template<class T, int C> void ReadVectorFromFile(const std::string& file, Vector<T, C>& vector) { std::ifstream os(file, std::ios::binary); uint64_t sz=0; os.read((char*)&sz,sizeof(uint64_t)); vector.resize(sz); os.read((char*)vector.ptr(),(std::streamsize)sz); } typedef Vector<uint8_t, 4> VectorRGBA; typedef Vector<int, 4> VectorRGBAi; typedef Vector<float, 4> VectorRGBAf; typedef Vector<uint8_t, 3> VectorRGB; typedef Vector<int, 3> VectorRGBi; typedef Vector<float, 3> VectorRGBf; typedef Vector<uint8_t, 1> VectorA; typedef Vector<int, 1> VectorAi; typedef Vector<float, 1> VectorAf; typedef Vector<uint8_t, 4> Vector4b; typedef Vector<uint16_t, 4> Vector4us; typedef Vector<int16_t, 4> Vector4s; typedef Vector<int, 4> Vector4i; typedef Vector<uint32_t, 4> Vector4ui; typedef Vector<float, 4> Vector4f; typedef Vector<double, 4> Vector4d; typedef Vector<uint8_t, 3> Vector3b; typedef Vector<uint16_t, 3> Vector3us; typedef Vector<int16_t, 3> Vector3s; typedef Vector<int, 3> Vector3i; typedef Vector<uint32_t, 3> Vector3ui; typedef Vector<float, 3> Vector3f; typedef Vector<double, 3> Vector3d; typedef Vector<uint8_t, 2> Vector2b; typedef Vector<uint16_t, 2> Vector2us; typedef Vector<int16_t, 2> Vector2s; typedef Vector<int, 2> Vector2i; typedef Vector<uint32_t, 2> Vector2ui; typedef Vector<float, 2> Vector2f; typedef Vector<double, 2> Vector2d; typedef Vector<uint8_t, 1> Vector1b; typedef Vector<uint16_t, 1> Vector1us; typedef Vector<int16_t, 1> Vector1s; typedef Vector<int, 1> Vector1i; typedef Vector<uint32_t, 1> Vector1ui; typedef Vector<float, 1> Vector1f; typedef Vector<double, 1> Vector1d; } ; #endif /* ALLOYLINEARALGEBRA_H_ */
LSBasics.h
#include "graph.h" #pragma once struct DFSData { int *id2dfs; //maps vertex ids to post-order numbers int *dfs2id; //maps post-order numbers to vertex ids int *id2parc; //maps vertex ids to parent arcs in the dfs tree DFSData(int n) { id2dfs = new int [n+1]; dfs2id = new int [n+1]; id2parc = new int [n+1]; } ~DFSData() { delete [] id2parc; delete [] dfs2id; delete [] id2dfs; //fprintf (stderr, "Deleted DFS data.\n"); //fflush(stderr); } }; class GlobalInfo { EdgeCost bestfound; int solved; public: int bbpruned; //true iff bb pruned at a node that was not yet solved EdgeCost fixed; //hack because bb cannot handle fixed costs // EdgeCost UpdateBestFound(EdgeCost bf) { double answer = bestfound; if (bf != answer) { #pragma omp critical { if (bf < bestfound) { bestfound = bf; fprintf (stderr, "[[[ %.2f ]]] ", bestfound); } answer = bestfound; } } return answer; } inline bool IsSolved() { return (solved!=0); } void MakeSolved() { solved = 1; } GlobalInfo() { bestfound = INFINITE_COST; fixed = 0; solved = 0; bbpruned = 0; } }; class CutRecorder { public: vector<int> cutlist; void Reset() { cutlist.clear(); } void Reset(int size) { cutlist.reserve(size); cutlist.clear(); } inline void AddArc(int alabel) { cutlist.push_back(alabel); } inline void CloseCut() { cutlist.push_back(-1); } }; class GraphMapper { private: void Init() { oldn = oldm = 0; v2new = e2new = NULL; } public: int *v2new; int *e2new; int oldn, oldm; GraphMapper() { Init(); } void Reset(int _oldn, int _oldm) { oldn = _oldn; oldm = _oldm; v2new = new int [oldn+1]; e2new = new int [oldm+1]; for (int e=1; e<=oldm; e++) e2new[e] = -1; for (int v=1; v<=oldn; v++) v2new[v] = -1; } ~GraphMapper() { if (v2new) delete [] v2new; if (e2new) delete [] e2new; } void Destroy() { if (v2new) delete [] v2new; if (e2new) delete [] e2new; Init(); } }; class Basics { public: static void ReportResults (FILE *file, const string &prefix, double seconds, EdgeCost solvalue, EdgeCost bestknown) { fprintf (file, "%ssolution %.20f\n", prefix.c_str(), (double)solvalue); fprintf(file, "%stimeus %.3f\n", prefix.c_str(), 1000000.0 * seconds); fprintf(file, "%stimems %.6f\n", prefix.c_str(), 1000.0 * seconds); fprintf(file, "%stimes %.9f\n", prefix.c_str(), seconds); double ratio = (double)solvalue / (double)bestknown; double error = ratio - 1; fprintf(file, "%sratio %.20f\n", prefix.c_str(), ratio); fprintf(file, "%serror %.20f\n", prefix.c_str(), error); fprintf(file, "%spcterror %.20f\n", prefix.c_str(), 100.0 * error); } static void fatal (const string &msg) { fprintf (stderr, "ERROR: %s.\n", msg.c_str()); fflush(stderr); exit(-1); } // this is old; the terminal is not random static int WrongPickRandomTerminal(Graph &g) { //fprintf (stderr, "r"); int n = g.VertexCount(); for (int v=1; v<=n; v++) if (g.IsTerminal(v)) return v; fatal ("could not find terminal"); return 0; } static int PickRandomTerminal(Graph &g) { //fprintf (stderr, "r"); int n = g.VertexCount(); int count = 0; int target = RFWRandom::getInteger(1,g.TerminalCount()); for (int v=1; v<=n; v++) { if (g.IsTerminal(v)) { if (++count == target) return v; } } fatal ("could not find terminal"); return 0; } static int PickRandomTerminal(Graph &g, RFWLocalRandom &random) { static bool first = true; if (first) { // fprintf (stderr, "PICKRANDOMTERMINAL IS NOT PROPERLY SET.\n"); first = false; } int n = g.VertexCount(); int count = 0; int target = random.GetInteger(1,g.TerminalCount()); for (int v=1; v<=n; v++) { if (g.IsTerminal(v)) { if (++count == target) return v; } } fatal ("could not find terminal"); return 0; } /// <summary> /// Perform DFS on the solution, numbering vertices in reverse post-order. /// Returns the number of vertices visited. /// </summary> /// <param name="r">Root of DFS.</param> /// <param name="solution">Current solution.</param> /// <param name="dfs2id">Output: map from dfs number to id (-1 if not visited)</param> /// <param name="id2dfs">Output: map from id to dfs number (-1 if not visited)</param> /// <param name="id2parc">Output: map from it to parent arc (0 if not visited)</param> static int DFS (Graph &g, int r, SteinerSolution &solution, DFSData &dfsdata, RFWStack<int> &stack) { // this is a funny implementation of dfs: when we first scan a vertex, we simply add to the stack // every nonscanned neighbor---even those that are already in the stack. This requires a stack of size m. // WARNING! IF WE ARE ONLY SCANNING EDGES OF THE SOLUTION, THE SIZE IS N int *id2dfs = dfsdata.id2dfs; int *dfs2id = dfsdata.dfs2id; int *id2parc = dfsdata.id2parc; int n = g.VertexCount(); int m = g.EdgeCount(); stack.reset(); //id2dfs: -1:unreached 0:scanned >0:processed for (int v=0; v<=n; v++) { id2dfs[v] = -1; //everybody unreached, initially dfs2id[v] = -1; id2parc[v] = 0; } stack.push(r); int nextdfs = 1; while (!stack.isEmpty()) { int v = stack.pop(); int vdfs = id2dfs[v]; if (vdfs > 0) {continue;} //vertex already processed: nothing else to do //vertex already scanned, but with no label; we assign it a label now if (vdfs == 0) { id2dfs[v] = nextdfs; dfs2id[nextdfs] = v; nextdfs++; continue; } //vertex not yet scanned: scan it, put it back on the stack (a label will be assigned later) stack.push(v); id2dfs[v] = 0; //foreach (WeightedGraph.Arc arc in g.ArcEnumerator(v)) { SPGArc *a, *end; //for (int pa=g.GetStart(v); pa<g.GetEnd(v); pa++) { for (g.GetBounds(v,a,end); a<end; a++) { int alabel = a->label; //g.GetArcLabel(pa); if (!solution.Contains(alabel)) continue; int w = a->head; //g.GetArcHead(pa);//arc.head; if (id2dfs[w] >= 0) continue; //w already scanned: no need to go there again id2parc[w] = alabel; stack.push(w); } } return nextdfs - 1; } // add all vertices in the current solution to solnodes // (vertices with incident edges) static void MarkSolutionNodes(Graph &g, SteinerSolution &solution, UniverseSet &solnodes) { int n = g.VertexCount(); for (int v=1; v<=n; v++) { if (solution.GetDegree(v)>0) solnodes.Insert(v); } } //mark the components containing the elements of the stack static void MarkComponent(Graph &g, RFWStack<int> &stack, int *id2parc, UniverseSet &marked) { //Console.Error.Write("+"); //Invariant: a vertex becomes marked when it is inserted into the stack //A marked vertex is or was on the stack. bool verbose = false; if (verbose) fprintf (stderr, "Marking component from %d vertices; marked has %d.", stack.getNElements(), marked.Count()); //make invariants true for original vertices for (int i = stack.getNElements(); i >= 1; i--) { int v = stack.peek(i); if (marked.Contains(v)) fprintf (stderr, "BAD"); marked.Insert(v); } int mcount = marked.Count(); //add all relevant tree children to the stack while (!stack.isEmpty()) { int v = stack.pop(); SPGArc *a, *end; for (g.GetBounds(v,a,end); a<end; a++) { //for (int pa=g.GetStart(v); pa<g.GetEnd(v); pa++) { int w = a->head; //g.GetArcHead(pa); if (id2parc[w]==a->label) { //g.GetArcLabel(pa)) { if (marked.Insert(w)) { //mcount ++; stack.push(w); } } } /* foreach (WeightedGraph.Arc arc in g.ArcEnumerator(v)) { int w = arc.head; if (id2parc[w]==arc.label) { if (marked.Insert(w)) stack.Push(w); } }*/ } mcount = marked.Count() - mcount; if (verbose) fprintf(stderr, "%d elements marked", mcount); /* if (verbose) {Console.Error.WriteLine(" {0} elements marked.", marked.Count()); foreach (int e in marked.ElementEnumerator()) {Console.Error.Write("+{0} ", e);}}*/ } static void CheckSolution(Graph &g, SteinerSolution &solution) { if (!InnerCheck(g, solution, false)) { fatal ("Invalid solution"); } } static bool InnerCheck(Graph &g, SteinerSolution &solution, bool verbose) { int n = g.VertexCount(); UniverseSet svertices(n); UnionFind uf(n); Basics::MarkSolutionNodes(g, solution, svertices); int ncomp = svertices.Count(); UniverseSet terminals(n); for (int t=1; t<=g.VertexCount(); t++) { if (g.IsTerminal(t)) terminals.Insert(t); } //Console.Error.WriteLine("Term //foreach (int e in solution.ElementEnumerator()) int m = g.EdgeCount(); int ecount = 0; for (int e=1; e<=m; e++) { if (!solution.Contains(e)) continue; ecount ++; int v, w; g.GetEndpoints(e, v, w); if (!svertices.Contains(v) || !svertices.Contains(w)) { fprintf (stderr, "Edge %d=(%d,%d), membership %d %d.\n", e, v, w, svertices.Contains(v), svertices.Contains(w)); fatal ("Inconsistent vertex membership in solution"); } terminals.Remove(v); terminals.Remove(w); if (uf.Find(v) == uf.Find(w)) { fprintf (stderr, "Vertices %d, %d already in the same component.", v, w); fatal ("Solution has a cycle."); } else { uf.Union(v, w); ncomp --; } } if (terminals.Count() > 0) { fprintf (stderr, "Terminals not in solution: %d.", terminals.Count()); fatal ("Missing terminals in solution."); } fprintf (stderr, "[CHECKING:n=%d:m=%d:%d components]", svertices.Count(), ecount, ncomp); if (verbose) { for (int v=1; v<=n; v++) { if (svertices.Contains(v)) { fprintf (stderr, "%d:%d ", v, uf.Find(v)); } } fprintf (stderr, "\n"); } if (ecount != svertices.Count() - 1) return false; else return true; } /// <summary> /// Compute the Voronoi diagram of the current graph, given a set of bases /// and maybe the perturbed cost of the edges. /// </summary> /// <param name="voronoi">Output: description of the Voronoi diagram</param> /// <param name="baselist">List of bases.</param> /// <param name="heap">Preallocated heap to be used in the computation (will be reset)</param> /// <param name="pertcost">Edge costs (use original costs if null).</param> static void ComputeVoronoi(Graph &g, VoronoiData &voronoi, UniverseSet &baselist, BinaryHeap<EdgeCost> &heap, EdgeCost *pertcost) { const bool GLOBAL_USE_VORONOI_TIE_BREAKER = false; // NOT CLEAR WHERE THIS THING IS SUPPOSED TO BE DEFINED const bool verbose = false; voronoi.Reset(); int nbases = 0; heap.Reset(); // initialize with all bases int p, pend; for (baselist.GetBounds(p,pend); p<pend; p++) { int b = baselist.PickPos(p); nbases ++; voronoi.MakeBase(b); heap.Insert(b, 0); } if (verbose) fprintf (stderr, "%d vertices marked as bases.\n", nbases); int count = 0; //WARNING: RANDOMIZING THE CHOICE SEEMS TO BE A GOOD IDEA bool randomize = false; bool PREFER_TERMINALS = true; bool USE_TIEBREAKERS = GLOBAL_USE_VORONOI_TIE_BREAKER && (randomize || PREFER_TERMINALS); //perform multisource Dijkstra while (!heap.IsEmpty()) { unsigned int v; EdgeCost dist; heap.RemoveFirst(v, dist); count++; if (verbose) fprintf (stderr, "%d ", dist); //foreach (WeightedGraph.Arc arc in g.ArcEnumerator(v)) { SPGArc *a, *end; for (g.GetBounds(v,a,end); a<end; a++) { int w = a->head; //g.GetArcHead(pa); EdgeCost newdist = dist; if (pertcost == NULL) newdist += a->cost; //g.GetArcCost(pa); else newdist += pertcost[a->label]; bool improve = false; if (voronoi.GetBase(w) == 0) improve = true; else if (newdist <= voronoi.GetDistance(w)) improve = true; //using leq here to prefer shorter edges... else if (USE_TIEBREAKERS && newdist == voronoi.GetDistance(w)) { if (randomize) { fatal ("randomization not implemented!\n"); //(stderr, "NOT IMPLEMENTED!\n //improve = (random.GetInteger(0, 1) == 0); //(arc.cost < g.GetCost(voronoi.GetParentArc(w))); } else if (PREFER_TERMINALS) { improve = g.IsTerminal(voronoi.GetBase(v)); } //improve = (arc.cost < g.GetCost(voronoi.GetParentArc(w))); } if (improve) { //make w a tentative child of v heap.Insert(w, newdist); voronoi.Update(w, voronoi.GetBase(v), a->label, newdist); } } } } /// Iteratively removes all degree-one vertices in the solution. /// Takes O(1) if there are no such vertices. If there are, takes /// O(n) + degree of all vertices removed. /// <param name="solution">Original solution (will be modified).</param> static void Prune(Graph &g, SteinerSolution &solution) { if (solution.LeafCount()==0) return; //WARNING: THIS SHOULD BE THERE! int n = g.VertexCount(); for (int v=1; v<=n; v++) { int t = v; while (solution.GetDegree(t)==1 && !g.IsTerminal(t)) { //find the unique incident solution edge SPGArc *a, *end; for (g.GetBounds(t,a,end); a<end; a++) { int alabel = a->label; if (!solution.Contains(alabel)) continue; solution.Remove(alabel); t = g.GetOther(alabel,t); //process the other endpoint next break; } } } } };
8342.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 */ #define EXTRALARGE_DATASET #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "correlation.h" /* Array initialization. */ static void init_array (int m, int n, DATA_TYPE *float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n)) { int i, j; *float_n = 1.2; for (i = 0; i < m; i++) for (j = 0; j < n; j++) data[i][j] = ((DATA_TYPE) i*j) / M; } /* 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 m, DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m)) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < m; j++) { fprintf (stderr, DATA_PRINTF_MODIFIER, symmat[i][j]); if ((i * m + 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_correlation(int m, int n, DATA_TYPE float_n, DATA_TYPE POLYBENCH_2D(data,M,N,m,n), DATA_TYPE POLYBENCH_2D(symmat,M,M,m,m), DATA_TYPE POLYBENCH_1D(mean,M,m), DATA_TYPE POLYBENCH_1D(stddev,M,m)) { int i, j, j1, j2; DATA_TYPE eps = 0.1f; #define sqrt_of_array_cell(x,j) sqrt(x[j]) #pragma scop /* Determine mean of column vectors of input data matrix */ #pragma omp parallel private(i, j, j2) num_threads(4) { #pragma omp for schedule(dynamic, 16) for (j = 0; j < _PB_M; j++) { mean[j] = 0.0; for (i = 0; i < _PB_N; i++) mean[j] += data[i][j]; mean[j] /= float_n; } /* Determine standard deviations of column vectors of data matrix. */ #pragma omp for schedule(dynamic, 16) for (j = 0; j < _PB_M; j++) { stddev[j] = 0.0; for (i = 0; i < _PB_N; i++) stddev[j] += (data[i][j] - mean[j]) * (data[i][j] - mean[j]); stddev[j] /= float_n; stddev[j] = sqrt_of_array_cell(stddev, j); /* The following in an inelegant but usual way to handle near-zero std. dev. values, which below would cause a zero- divide. */ stddev[j] = stddev[j] <= eps ? 1.0 : stddev[j]; } /* Center and reduce the column vectors. */ #pragma omp for schedule(dynamic, 16) for (i = 0; i < _PB_N; i++) for (j = 0; j < _PB_M; j++) { data[i][j] -= mean[j]; data[i][j] /= sqrt(float_n) * stddev[j]; } /* Calculate the m * m correlation matrix. */ #pragma omp for schedule(dynamic, 16) for (j1 = 0; j1 < _PB_M-1; j1++) { symmat[j1][j1] = 1.0; for (j2 = j1+1; j2 < _PB_M; j2++) { symmat[j1][j2] = 0.0; for (i = 0; i < _PB_N; i++) symmat[j1][j2] += (data[i][j1] * data[i][j2]); symmat[j2][j1] = symmat[j1][j2]; } } } #pragma endscop symmat[_PB_M-1][_PB_M-1] = 1.0; } int main(int argc, char** argv) { /* Retrieve problem size. */ int n = N; int m = M; /* Variable declaration/allocation. */ DATA_TYPE float_n; POLYBENCH_2D_ARRAY_DECL(data,DATA_TYPE,M,N,m,n); POLYBENCH_2D_ARRAY_DECL(symmat,DATA_TYPE,M,M,m,m); POLYBENCH_1D_ARRAY_DECL(mean,DATA_TYPE,M,m); POLYBENCH_1D_ARRAY_DECL(stddev,DATA_TYPE,M,m); /* Initialize array(s). */ init_array (m, n, &float_n, POLYBENCH_ARRAY(data)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_correlation (m, n, float_n, POLYBENCH_ARRAY(data), POLYBENCH_ARRAY(symmat), POLYBENCH_ARRAY(mean), POLYBENCH_ARRAY(stddev)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(m, POLYBENCH_ARRAY(symmat))); /* Be clean. */ POLYBENCH_FREE_ARRAY(data); POLYBENCH_FREE_ARRAY(symmat); POLYBENCH_FREE_ARRAY(mean); POLYBENCH_FREE_ARRAY(stddev); return 0; }
matrix.h
/** * @file matrix.h This code provide a templated matrix implementation * @author TPOC: contact@palisade-crypto.org * * @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. THIS SOFTWARE IS * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef LBCRYPTO_MATH_MATRIX_H #define LBCRYPTO_MATH_MATRIX_H #include <iostream> #include <functional> #include <cmath> #include "../math/backend.h" #include "../lattice/backend.h" #include "../math/nbtheory.h" #include "../math/distrgen.h" #include "../encoding/encodings.h" #include "../utils/inttypes.h" #include "../utils/utilities.h" #include "../utils/memory.h" using std::invalid_argument; namespace lbcrypto { template <class Element> class Matrix : public Serializable { public: typedef vector<vector<Element>> data_t; typedef vector<Element> data_row_t; typedef std::function<Element(void)> alloc_func; /** * Constructor that initializes matrix values using a zero allocator * * @param &allocZero lambda function for zero initialization. * @param &rows number of rows. * @param &rows number of columns. */ Matrix(alloc_func allocZero, size_t rows, size_t cols) : data(), rows(rows), cols(cols), allocZero(allocZero) { data.resize(rows); for (auto row = data.begin(); row != data.end(); ++row) { for (size_t col = 0; col < cols; ++col) { row->push_back(allocZero()); } } } // TODO: add Clear(); /** * Constructor that initializes matrix values using a distribution generation * allocator * * @param &allocZero lambda function for zero initialization (used for * initializing derived matrix objects) * @param &rows number of rows. * @param &rows number of columns. * @param &allocGen lambda function for initialization using a distribution * generator. */ Matrix(alloc_func allocZero, size_t rows, size_t cols, alloc_func allocGen); /** * Constructor of an empty matrix. * SetSize must be called on this matrix to use it * SetAlloc needs to be called if 0 passed to constructor * This mostly exists to support deserializing * * @param &allocZero lambda function for zero initialization. */ Matrix(alloc_func allocZero = 0) : data(), rows(0), cols(0), allocZero(allocZero) {} /** * Set the size of a matrix, elements are zeroed out * * @param rows number of rows * @param cols number of colums */ void SetSize(size_t rows, size_t cols) { if (this->rows != 0 || this->cols != 0) { PALISADE_THROW(not_available_error, "You cannot SetSize on a non-empty matrix"); } this->rows = rows; this->cols = cols; data.resize(rows); for (auto row = data.begin(); row != data.end(); ++row) { for (size_t col = 0; col < cols; ++col) { row->push_back(allocZero()); } } } /** * SetAllocator - set the function to allocate a zero; * basically only required for deserializer * * @param allocZero */ void SetAllocator(alloc_func allocZero) { this->allocZero = allocZero; } /** * Copy constructor * * @param &other the matrix object to be copied */ Matrix(const Matrix<Element>& other) : data(), rows(other.rows), cols(other.cols), allocZero(other.allocZero) { deepCopyData(other.data); } /** * Assignment operator * * @param &other the matrix object whose values are to be copied * @return the resulting matrix */ Matrix<Element>& operator=(const Matrix<Element>& other); /** * In-place change of the current matrix to a matrix of all ones * * @return the resulting matrix */ Matrix<Element>& Ones(); // Macro for convenient definitions of class implementations of special // functions #define ONES_FOR_TYPE(T) \ template <> \ Matrix<T>& Matrix<T>::Ones() { \ for (size_t row = 0; row < rows; ++row) { \ for (size_t col = 0; col < cols; ++col) { \ data[row][col] = 1; \ } \ } \ return *this; \ } /** * In-place modulo reduction * * @return the resulting matrix */ Matrix<Element>& ModEq(const Element& modulus); /** * modular subtraction * * @return the resulting matrix */ Matrix<Element>& ModSubEq(Matrix<Element> const& b, const Element& modulus); /** * Fill matrix using the same element * * @param &val the element the matrix is filled by * * @return the resulting matrix */ Matrix<Element>& Fill(const Element& val); /** * In-place change of the current matrix to Identity matrix * * @return the resulting matrix */ Matrix<Element>& Identity(); #define IDENTITY_FOR_TYPE(T) \ template <> \ Matrix<T>& Matrix<T>::Identity() { \ for (size_t row = 0; row < rows; ++row) { \ for (size_t col = 0; col < cols; ++col) { \ if (row == col) { \ data[row][col] = 1; \ } else { \ data[row][col] = 0; \ } \ } \ } \ return *this; \ } /** * Sets the first row to be powers of two for when the base is two * * @param base is the base the digits of the matrix are represented in * @return the resulting matrix */ Matrix<Element> GadgetVector(int64_t base = 2) const; #define GADGET_FOR_TYPE(T) \ template <> \ Matrix<T> Matrix<T>::GadgetVector(int64_t base) const { \ Matrix<T> g(allocZero, rows, cols); \ auto base_matrix = allocZero(); \ size_t k = cols / rows; \ base_matrix = base; \ g(0, 0) = 1; \ for (size_t i = 1; i < k; i++) { \ g(0, i) = g(0, i - 1) * base_matrix; \ } \ for (size_t row = 1; row < rows; row++) { \ for (size_t i = 0; i < k; i++) { \ g(row, i + row * k) = g(0, i); \ } \ } \ return g; \ } #define GADGET_FOR_TYPE_DCRT(T) \ template <> \ Matrix<T> Matrix<T>::GadgetVector(int64_t base) const { \ Matrix<T> g(allocZero, rows, cols); \ auto base_matrix = allocZero(); \ base_matrix = base; \ size_t bk = 1; \ \ auto params = g(0, 0).GetParams()->GetParams(); \ \ uint64_t digitCount = (long)ceil( \ log2(params[0]->GetModulus().ConvertToDouble()) / log2(base)); \ \ for (size_t k = 0; k < digitCount; k++) { \ for (size_t i = 0; i < params.size(); i++) { \ NativePoly temp(params[i]); \ temp = bk; \ g(0, k + i * digitCount).SetElementAtIndex(i, temp); \ } \ bk *= base; \ } \ \ size_t kCols = cols / rows; \ for (size_t row = 1; row < rows; row++) { \ for (size_t i = 0; i < kCols; i++) { \ g(row, i + row * kCols) = g(0, i); \ } \ } \ return g; \ } /** * Computes the infinity norm * * @return the norm in double format */ double Norm() const; #define NORM_FOR_TYPE(T) \ template <> \ double Matrix<T>::Norm() const { \ double retVal = 0.0; \ double locVal = 0.0; \ for (size_t row = 0; row < rows; ++row) { \ for (size_t col = 0; col < cols; ++col) { \ locVal = data[row][col].Norm(); \ if (locVal > retVal) { \ retVal = locVal; \ } \ } \ } \ return retVal; \ } /** * Matrix multiplication * * @param &other the multiplier matrix * @return the result of multiplication */ Matrix<Element> Mult(Matrix<Element> const& other) const; /** * Operator for matrix multiplication * * @param &other the multiplier matrix * @return the result of multiplication */ Matrix<Element> operator*(Matrix<Element> const& other) const { return Mult(other); } /** * Multiplication of matrix by a scalar * * @param &other the multiplier element * @return the result of multiplication */ Matrix<Element> ScalarMult(Element const& other) const { Matrix<Element> result(*this); #pragma omp parallel for for (size_t col = 0; col < result.cols; ++col) { for (size_t row = 0; row < result.rows; ++row) { result.data[row][col] = result.data[row][col] * other; } } return result; } /** * Operator for scalar multiplication * * @param &other the multiplier element * @return the result of multiplication */ Matrix<Element> operator*(Element const& other) const { return ScalarMult(other); } /** * Equality check * * @param &other the matrix object to compare to * @return the boolean result */ bool Equal(Matrix<Element> const& other) const { if (rows != other.rows || cols != other.cols) { return false; } for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < cols; ++j) { if (data[i][j] != other.data[i][j]) { return false; } } } return true; } /** * Operator for equality check * * @param &other the matrix object to compare to * @return the boolean result */ bool operator==(Matrix<Element> const& other) const { return Equal(other); } /** * Operator for non-equality check * * @param &other the matrix object to compare to * @return the boolean result */ bool operator!=(Matrix<Element> const& other) const { return !Equal(other); } /** * Get property to access the data as a vector of vectors * * @return the data as vector of vectors */ const data_t& GetData() const { return data; } /** * Get property to access the number of rows in the matrix * * @return the number of rows */ size_t GetRows() const { return rows; } /** * Get property to access the number of columns in the matrix * * @return the number of columns */ size_t GetCols() const { return cols; } /** * Get property to access the zero allocator for the matrix * * @return the lambda function corresponding to the element zero allocator */ alloc_func GetAllocator() const { return allocZero; } /** * Sets the evaluation or coefficient representation for all ring elements * that support the SetFormat method * * @param &format the enum value corresponding to coefficient or evaluation * representation */ void SetFormat(Format format); /** * Matrix addition * * @param &other the matrix to be added * @return the resulting matrix */ Matrix<Element> Add(Matrix<Element> const& other) const { if (rows != other.rows || cols != other.cols) { PALISADE_THROW(math_error, "Addition operands have incompatible dimensions"); } Matrix<Element> result(*this); #pragma omp parallel for for (size_t j = 0; j < cols; ++j) { for (size_t i = 0; i < rows; ++i) { result.data[i][j] += other.data[i][j]; } } return result; } /** * Operator for matrix addition * * @param &other the matrix to be added * @return the resulting matrix */ Matrix<Element> operator+(Matrix<Element> const& other) const { return this->Add(other); } /** * Operator for in-place addition * * @param &other the matrix to be added * @return the resulting matrix (same object) */ Matrix<Element>& operator+=(Matrix<Element> const& other); /** * Matrix substraction * * @param &other the matrix to be substracted * @return the resulting matrix */ Matrix<Element> Sub(Matrix<Element> const& other) const { if (rows != other.rows || cols != other.cols) { PALISADE_THROW(math_error, "Subtraction operands have incompatible dimensions"); } Matrix<Element> result(allocZero, rows, other.cols); #pragma omp parallel for for (size_t j = 0; j < cols; ++j) { for (size_t i = 0; i < rows; ++i) { result.data[i][j] = data[i][j] - other.data[i][j]; } } return result; } /** * Operator for matrix substraction * * @param &other the matrix to be substracted * @return the resulting matrix */ Matrix<Element> operator-(Matrix<Element> const& other) const { return this->Sub(other); } /** * Operator for in-place matrix substraction * * @param &other the matrix to be substracted * @return the resulting matrix (same object) */ Matrix<Element>& operator-=(Matrix<Element> const& other); /** * Matrix transposition * * @return the resulting matrix */ Matrix<Element> Transpose() const; // YSP The signature of this method needs to be changed in the future /** * Matrix determinant - found using Laplace formula with complexity O(d!), * where d is the dimension * * @param *result where the result is stored */ void Determinant(Element* result) const; // Element Determinant() const; /** * Cofactor matrix - the matrix of determinants of the minors A_{ij} * multiplied by -1^{i+j} * * @return the cofactor matrix for the given matrix */ Matrix<Element> CofactorMatrix() const; /** * Add rows to bottom of the matrix * * @param &other the matrix to be added to the bottom of current matrix * @return the resulting matrix */ Matrix<Element>& VStack(Matrix<Element> const& other); /** * Add columns the right of the matrix * * @param &other the matrix to be added to the right of current matrix * @return the resulting matrix */ Matrix<Element>& HStack(Matrix<Element> const& other); /** * Matrix indexing operator - writeable instance of the element * * @param &row row index * @param &col column index * @return the element at the index */ Element& operator()(size_t row, size_t col) { return data[row][col]; } /** * Matrix indexing operator - read-only instance of the element * * @param &row row index * @param &col column index * @return the element at the index */ Element const& operator()(size_t row, size_t col) const { return data[row][col]; } /** * Matrix row extractor * * @param &row row index * @return the row at the index */ Matrix<Element> ExtractRow(size_t row) const { Matrix<Element> result(this->allocZero, 1, this->cols); int i = 0; for (auto elem = this->GetData()[row].begin(); elem != this->GetData()[row].end(); ++elem) { result(0, i) = *elem; i++; } return result; // return *this; } /** * Matrix column extractor * * @param &col col index * @return the col at the index */ Matrix<Element> ExtractCol(size_t col) const { Matrix<Element> result(this->allocZero, this->rows, 1); for (size_t i = 0; i < this->rows; i++) { result(i, 0) = data[i][col]; } return result; // return *this; } /** * Matrix rows extractor in a range from row_start to row_and; inclusive * * @param &row_start &row_end row indices * @return the rows in the range delimited by indices inclusive */ inline Matrix<Element> ExtractRows(size_t row_start, size_t row_end) const { Matrix<Element> result(this->allocZero, row_end - row_start + 1, this->cols); for (usint row = row_start; row < row_end + 1; row++) { int i = 0; for (auto elem = this->GetData()[row].begin(); elem != this->GetData()[row].end(); ++elem) { result(row - row_start, i) = *elem; i++; } } return result; } friend std::ostream& operator<<(std::ostream& os, const Matrix<Element>& m) { os << "[ "; for (size_t row = 0; row < m.GetRows(); ++row) { os << "[ "; for (size_t col = 0; col < m.GetCols(); ++col) { os << m(row, col) << " "; } os << "]\n"; } os << " ]\n"; return os; } /** * Call switch format for each (ring) element * */ void SwitchFormat(); #define NOT_AN_ELEMENT_MATRIX(T) \ template <> \ void Matrix<T>::SwitchFormat() { \ PALISADE_THROW(not_available_error, "Not a matrix of Elements"); \ } /* * Multiply the matrix by a vector whose elements are all 1's. This causes * the elements of each row of the matrix to be added and placed into the * corresponding position in the output vector. */ Matrix<Element> MultByUnityVector() const; /* * Multiply the matrix by a vector of random 1's and 0's, which is the same as * adding select elements in each row together. Return a vector that is a rows * x 1 matrix. */ Matrix<Element> MultByRandomVector(std::vector<int> ranvec) const; template <class Archive> void save(Archive& ar, std::uint32_t const version) const { ar(::cereal::make_nvp("d", data)); ar(::cereal::make_nvp("r", rows)); ar(::cereal::make_nvp("c", cols)); } template <class Archive> void load(Archive& ar, std::uint32_t const version) { if (version > SerializedVersion()) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar(::cereal::make_nvp("d", data)); ar(::cereal::make_nvp("r", rows)); ar(::cereal::make_nvp("c", cols)); // users will need to SetAllocator for any newly deserialized matrix } std::string SerializedObjectName() const { return "Matrix"; } static uint32_t SerializedVersion() { return 1; } private: data_t data; size_t rows; size_t cols; alloc_func allocZero; // mutable int NUM_THREADS = 1; // deep copy of data - used for copy constructor void deepCopyData(data_t const& src) { data.clear(); data.resize(src.size()); for (size_t row = 0; row < src.size(); ++row) { for (auto elem = src[row].begin(); elem != src[row].end(); ++elem) { data[row].push_back(*elem); } } } }; /** * Operator for scalar multiplication of matrix * * @param &e element * @param &M matrix * @return the resulting matrix */ template <class Element> Matrix<Element> operator*(Element const& e, Matrix<Element> const& M) { return M.ScalarMult(e); } /** * Generates a matrix of rotations. See pages 7-8 of * https://eprint.iacr.org/2013/297 * * @param &inMat the matrix of power-of-2 cyclotomic ring elements to be rotated * @return the resulting matrix of big binary integers */ template <typename Element> Matrix<typename Element::Integer> Rotate(Matrix<Element> const& inMat); /** * Each element becomes a square matrix with columns of that element's * rotations in coefficient form. See pages 7-8 of * https://eprint.iacr.org/2013/297 * * @param &inMat the matrix of power-of-2 cyclotomic ring elements to be rotated * @return the resulting matrix of big binary integers */ template <typename Element> Matrix<typename Element::Vector> RotateVecResult(Matrix<Element> const& inMat); /** * Stream output operator * * @param &os stream * @param &m matrix to be outputted * @return the chained stream */ template <class Element> std::ostream& operator<<(std::ostream& os, const Matrix<Element>& m); /** * Gives the Choleshky decomposition of the input matrix. * The assumption is that covariance matrix does not have large coefficients * because it is formed by discrete gaussians e and s; this implies int32_t can * be used This algorithm can be further improved - see the Darmstadt paper * section 4.4 http://eprint.iacr.org/2013/297.pdf * * @param &input the matrix for which the Cholesky decomposition is to be * computed * @return the resulting matrix of floating-point numbers */ Matrix<double> Cholesky(const Matrix<int32_t>& input); void Cholesky(const Matrix<int32_t>& input, Matrix<double>& result); /** * Convert a matrix of integers from BigInteger to int32_t * Convert from Z_q to [-q/2, q/2] * * @param &input the input matrix * @param &modulus the ring modulus * @return the resulting matrix of int32_t */ Matrix<int32_t> ConvertToInt32(const Matrix<BigInteger>& input, const BigInteger& modulus); /** * Convert a matrix of BigVector to int32_t * Convert from Z_q to [-q/2, q/2] * * @param &input the input matrix * @param &modulus the ring modulus * @return the resulting matrix of int32_t */ Matrix<int32_t> ConvertToInt32(const Matrix<BigVector>& input, const BigInteger& modulus); /** * Split a vector of int32_t into a vector of ring elements with ring dimension * n * * @param &other the input matrix * @param &n the ring dimension * @param &params Poly element params * @return the resulting matrix of Poly */ template <typename Element> Matrix<Element> SplitInt64IntoElements( Matrix<int64_t> const& other, size_t n, const shared_ptr<typename Element::Params> params); #define SPLIT64_FOR_TYPE(T) \ template <> \ Matrix<T> SplitInt64IntoElements( \ Matrix<int64_t> const& other, size_t n, \ const shared_ptr<typename T::Params> params) { \ auto zero_alloc = T::Allocator(params, COEFFICIENT); \ size_t rows = other.GetRows() / n; \ Matrix<T> result(zero_alloc, rows, 1); \ for (size_t row = 0; row < rows; ++row) { \ std::vector<int64_t> values(n); \ for (size_t i = 0; i < n; ++i) values[i] = other(row * n + i, 0); \ result(row, 0) = values; \ } \ return result; \ } /** * Another method for splitting a vector of int32_t into a vector of ring * elements with ring dimension n * * @param &other the input matrix * @param &n the ring dimension * @param &params Poly element params * @return the resulting matrix of Poly */ template <typename Element> Matrix<Element> SplitInt32AltIntoElements( Matrix<int32_t> const& other, size_t n, const shared_ptr<typename Element::Params> params); #define SPLIT32ALT_FOR_TYPE(T) \ template <> \ Matrix<T> SplitInt32AltIntoElements( \ Matrix<int32_t> const& other, size_t n, \ const shared_ptr<typename T::Params> params) { \ auto zero_alloc = T::Allocator(params, COEFFICIENT); \ size_t rows = other.GetRows(); \ Matrix<T> result(zero_alloc, rows, 1); \ for (size_t row = 0; row < rows; ++row) { \ std::vector<int32_t> values(n); \ for (size_t i = 0; i < n; ++i) values[i] = other(row, i); \ result(row, 0) = values; \ } \ return result; \ } /** * Split a vector of int64_t into a vector of ring elements with ring dimension * n * * @param &other the input matrix * @param &n the ring dimension * @param &params Poly element params * @return the resulting matrix of Poly */ template <typename Element> Matrix<Element> SplitInt64AltIntoElements( Matrix<int64_t> const& other, size_t n, const shared_ptr<typename Element::Params> params); #define SPLIT64ALT_FOR_TYPE(T) \ template <> \ Matrix<T> SplitInt64AltIntoElements( \ Matrix<int64_t> const& other, size_t n, \ const shared_ptr<typename T::Params> params) { \ auto zero_alloc = T::Allocator(params, COEFFICIENT); \ size_t rows = other.GetRows(); \ Matrix<T> result(zero_alloc, rows, 1); \ for (size_t row = 0; row < rows; ++row) { \ std::vector<int64_t> values(n); \ for (size_t i = 0; i < n; ++i) values[i] = other(row, i); \ result(row, 0) = values; \ } \ return result; \ } } // namespace lbcrypto #endif // LBCRYPTO_MATH_MATRIX_H
evolve_cc.c
/* * The Connected Components Hamiltonian split uses a connected component search * on the time step graph of the system to find isolated subsystems with fast * interactions. These subsystems are then evolved at greater accuracy compared * to the rest system. * Equation numbers in comments refer to: J\"anes, Pelupessy, Portegies Zwart, A&A 2014 (doi:10.1051/0004-6361/201423831) */ #include <tgmath.h> #include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #endif #include "evolve.h" #include "evolve_kepler.h" #include "evolve_bs.h" //#define CC_DEBUG // perform (time-consuming, but thorough) CC sanity checks #define IS_ZEROSYS(SYS) (((SYS)->n == 0) && ((SYS)->part == NULL) && ((SYS)->last == NULL) && ((SYS)->next_cc == NULL)) #define IS_ZEROSYSs(SYS) (((SYS).n == 0) && ((SYS).part == NULL) && ((SYS).last == NULL) && ((SYS).next_cc == NULL)) #define LOG_CC_SPLIT(C, R) \ { \ LOG("clevel = %d s.n = %d c.n = {", clevel, s.n); \ for (struct sys *_ci = (C); !IS_ZEROSYS(_ci); _ci = _ci->next_cc) printf(" %d ", _ci->n ); \ printf("} r.n = %d\n", (R)->n); \ }; #define LOGSYS_ID(SYS) for (UINT i = 0; i < (SYS).n; i++) { printf("%u ", (SYS).part[i].id); } printf("\n"); #define LOGSYSp_ID(SYS) for (UINT i = 0; i < (SYS)->n; i++) { printf("%u ", (SYS)->part[i].id); } printf("\n"); #define LOGSYSC_ID(SYS) for (struct sys *_ci = &(SYS); !IS_ZEROSYS(_ci); _ci = _ci->next_cc) {printf("{"); for (UINT i = 0; i < _ci->n; i++) {printf("%u ", _ci->part[i].id); } printf("}\t");} printf("\n"); void split_cc(int clevel,struct sys s, struct sys *c, struct sys *r, DOUBLE dt) { /* * split_cc: run a connected component search on sys s with threshold dt, * creates a singly-linked list of connected components c and a rest system r * c or r is set to zerosys if no connected components/rest is found */ int dir=SIGN(dt); dt=fabs(dt); diag->tstep[clevel]++; // not directly comparable to corresponding SF-split statistics struct sys *c_next; c_next = c; *c_next = zerosys; UINT processed = 0; // increase if something is added from the stack to the cc UINT comp_next = 0; // increase to move a particle from stack to cc; points to the first element of the stack UINT comp_size = 0; // amount of particles added to the current cc UINT stack_next = 1; // swap this with s[i] to increase the stack UINT stack_size = 1; // first element of the stack is s[comp_next] // last element of the stack is s[comp_next + stack_size - 1] UINT rest_next = s.n - 1; // swap this to add to the rest-system // find connected components while (processed < s.n) { //LOG("split_cc: searching for connected components: %d / %d\n", processed, s.n); // search for the next connected component while (stack_size > 0) { // iterate over all unvisited elements for (UINT i = stack_next; i <= rest_next; i++) { // if element is connected to the first element of the stack DOUBLE timestep = (DOUBLE) timestep_ij(s.part+comp_next, s.part+i,dir); diag->tcount[clevel]++; if ( timestep <= dt) { // add i to the end of the stack by swapping stack_next and i SWAP( s.part[ stack_next ], s.part[i], struct particle ); stack_next++; stack_size++; } } // pop the stack; add to the connected component comp_size++; comp_next++; stack_size--; } processed += comp_size; // new component is non-trivial: create a new sys if (comp_size > 1) { //LOG("split_cc: found component with size: %d\n", comp_size); // create new component c from u[0] to u[cc_visited - 1] // remove components from u (u.n, u.part) c_next->n = comp_size; c_next->part = &( s.part[ comp_next - comp_size ]); c_next->last = &( s.part[ comp_next - 1 ]); c_next->next_cc = (struct sys*) malloc( sizeof(struct sys) ); c_next = c_next->next_cc; *c_next = zerosys; comp_next = stack_next; comp_size = 0; stack_next = stack_next + 1; stack_size = 1; // new component is trivial: add to rest } else { //LOG("found trivial component; adding to rest\n"); SWAP(s.part[ comp_next - 1 ], s.part[ rest_next ], struct particle ); rest_next--; comp_next = comp_next - 1; comp_size = 0; stack_next = comp_next + 1; stack_size = 1; } } if (processed != s.n) { ENDRUN("split_cc particle count mismatch: processed=%u s.n=%u r->n=%u\n", processed, s.n, r->n); } // create the rest system r->n = (s.n - 1) - rest_next; if (r->n > 0) { r->part = &( s.part[rest_next + 1] ); r->last = s.last; } else { r->part = NULL; r->last = NULL; } //LOG("split_cc: rest system size: %d\n", r->n); } void split_cc_verify(int clevel,struct sys s, struct sys *c, struct sys *r) { /* * split_cc_verify: explicit verification if connected components c and rest system r form a correct * connected components decomposition of the system. */ //LOG("split_cc_verify ping s.n=%d r->n=%d\n", s.n, r->n); //LOG_CC_SPLIT(c, r); UINT pcount_check = 0; for (UINT i = 0; i < s.n; i++) { pcount_check = 0; UINT particle_found = 0; struct particle *p = &( s.part[i] ); for (struct sys *cj = c; !IS_ZEROSYS(cj); cj = cj->next_cc) { pcount_check += cj->n; //LOG("%d\n", pcount_check); // search for p in connected components for (UINT k = 0; k < cj->n; k++) { struct particle * pk = &( cj->part[k] ); // is pk equal to p if (p->id == pk->id) { particle_found += 1; //LOG("split_cc_verify: found in a cc\n"); } } if (& ( cj->part[cj->n - 1] ) != cj->last) { LOG("split_cc_verify: last pointer for c is not set correctly!"); LOG_CC_SPLIT(c, r); ENDRUN("data structure corrupted\n"); } } // search for p in rest for (UINT k = 0; k < r->n; k++) { struct particle * pk = &( r->part[k] ); // is pk equal to p if (p->id == pk->id) { particle_found += 1; } } if (particle_found != 1) { LOG("split_cc_verify: particle %d particle_found=%d ", i, particle_found); LOG_CC_SPLIT(c, r); ENDRUN("data structure corrupted\n"); } } //if (& ( r->part[r->n - 1] ) != r->last) { // LOG("split_cc_verify: last pointer for r is not set correctly! %d %d",&( r->part[r->n - 1] ), r->last); // LOG_CC_SPLIT(c, r); // ENDRUN("data structure corrupted\n"); //} if (pcount_check + r->n != s.n) { LOG("split_cc_verify: particle count mismatch (%d %d)\n", pcount_check + r->n, s.n); LOG_CC_SPLIT(c, r); ENDRUN("data structure corrupted\n"); //ENDRUN("split_cc_verify: particle count mismatch\n"); } else { //LOG("split_cc_verify pong\n"); } //ENDRUN("Fin.\n"); } void split_cc_verify_ts(int clevel,struct sys *c, struct sys *r, DOUBLE dt) { DOUBLE ts_ij; int dir=SIGN(dt); dt=fabs(dt); // verify C-C interactions for (struct sys *ci = c; !IS_ZEROSYS(ci); ci = ci->next_cc) { for (UINT i = 0; i < ci->n; i++) { for (struct sys *cj = c; !IS_ZEROSYS(cj); cj = cj->next_cc) { if (ci == cj) { continue; } for (UINT j = 0; j < cj->n; j++) { ts_ij = (DOUBLE) timestep_ij((*ci).part+i, (*cj).part+j, dir); //LOG("comparing %d %d\n", ci->part[i].id, cj->part[j].id); //LOG("%f %f \n", ts_ij, dt); if (dt > ts_ij) { ENDRUN("split_cc_verify_ts C-C timestep underflow\n"); } } } } } // verify C-R interactions for (struct sys *ci = c; !IS_ZEROSYS(ci); ci = ci->next_cc) { for (UINT i = 0; i < ci->n; i++) { for (UINT j = 0; j < r->n; j++) { ts_ij = (DOUBLE) timestep_ij( (*ci).part+ i, (*r).part+ j,dir); if (ts_ij < dt) { ENDRUN("split_cc_verify_ts C-R timestep underflow\n"); } } } } // verify R interactions for (UINT i = 0; i < r->n; i++) { for (UINT j = 0; j < r->n; j++) { if (i == j) continue; ts_ij = (DOUBLE) timestep_ij( (*r).part+ i, (*r).part+j,dir); if (ts_ij < dt) { ENDRUN("split_cc_verify_ts R-R timestep underflow\n"); } } } } // TODO rename to cc_free_sys? void free_sys(struct sys * s) { if (s==NULL) return; if (s->next_cc != NULL) { free_sys(s->next_cc); } free(s); } DOUBLE sys_forces_max_timestep(struct sys s,int dir) { DOUBLE ts = 0.0; DOUBLE ts_ij; for (UINT i = 0; i < s.n-1; i++) { for (UINT j = i+1; j < s.n; j++) { ts_ij = (DOUBLE) timestep_ij(s.part+ i, s.part+j,dir); // check symm. if (ts_ij >= ts) { ts = ts_ij; }; } } return ts; } #define BS_SUBSYS_SIZE 10 #define TASKCONDITION (nc > 1 && s.n>BS_SUBSYS_SIZE) void evolve_cc2(int clevel,struct sys s, DOUBLE stime, DOUBLE etime, DOUBLE dt, int inttype, int recenter) { DOUBLE cmpos[3],cmvel[3]; int recentersub=0; struct sys c = zerosys, r = zerosys; CHECK_TIMESTEP(etime,stime,dt,clevel); if (s.n == 2 && (inttype==CCC_KEPLER || inttype==CC_KEPLER)) { evolve_kepler(clevel,s, stime, etime, dt); return; } if (s.n <= BS_SUBSYS_SIZE && (inttype==CCC_BS ||inttype==CC_BS)) { evolve_bs(clevel,s, stime, etime, dt); return; } if (s.n <= BS_SUBSYS_SIZE && (inttype==CCC_BSA ||inttype==CC_BSA)) { evolve_bs_adaptive(clevel,s, stime, etime, dt,1); return; } if(recenter && (inttype==CCC || inttype==CCC_KEPLER || inttype==CCC_BS || inttype==CCC_BSA)) { system_center_of_mass(s,cmpos,cmvel); move_system(s,cmpos,cmvel,-1); } // not actually helpful I think; needs testing #ifdef CC2_SPLIT_SHORTCUTS int dir=SIGN(dt); DOUBLE initial_timestep = sys_forces_max_timestep(s, dir); if(fabs(dt) > initial_timestep) { DOUBLE dt_step = dt; while (fabs(dt_step) > initial_timestep) { dt_step = dt_step / 2; clevel++; } LOG("CC2_SPLIT_SHORTCUTS clevel=%d dt/dt_step=%Le\n", clevel,(long double) (dt / dt_step)); for (DOUBLE dt_now = 0; dir*dt_now < dir*(dt-dt_step/2); dt_now += dt_step) evolve_cc2(clevel,s, dt_now, dt_now + dt_step, dt_step,inttype,0); return; } #endif #ifdef CC2_SPLIT_CONSISTENCY_CHECKS if (clevel == 0) { printf("consistency_checks: ", s.n, clevel); } #endif #ifdef CC2_SPLIT_CONSISTENCY_CHECKS // debug: make a copy of s to verify that the split has been done properly struct sys s_before_split; s_before_split.n = s.n; s_before_split.part = (struct particle*) malloc(s.n*sizeof(struct particle)); s_before_split.last = &( s_before_split.part[s.n - 1] ); s_before_split.next_cc = NULL; memcpy(s_before_split.part, s.part, s.n*sizeof(struct particle)); #endif /* split_cc() decomposes particles in H (eq 25) into: 1) K non-trivial connected components C_1..C_K 2) Rest set R */ split_cc(clevel,s, &c, &r, dt); //if (s.n != c.n) LOG_CC_SPLIT(&c, &r); // print out non-trivial splits #ifdef CC2_SPLIT_CONSISTENCY_CHECKS /* if (s.n != r.n) { LOG("s: "); LOGSYS_ID(s_before_split); LOG("c: "); LOGSYSC_ID(c); LOG("r: "); LOGSYS_ID(r); } */ // verify the split split_cc_verify(clevel,s_before_split, &c, &r); split_cc_verify_ts(clevel,&c, &r, dt); free(s_before_split.part); if (clevel == 0) { printf("ok "); } #endif if (IS_ZEROSYSs(c)) { diag->deepsteps++; diag->simtime+=dt; } // Independently integrate every C_i at reduced pivot time step h/2 (1st time) int nc=0; for (struct sys *ci = &c; !IS_ZEROSYS(ci); ci = ci->next_cc) nc++; if(nc>1 || r.n>0) recentersub=1; for (struct sys *ci = &c; !IS_ZEROSYS(ci); ci = ci->next_cc) { #ifdef _OPENMP if( TASKCONDITION ) { diag->ntasks[clevel]++; diag->taskcount[clevel]+=ci->n; #pragma omp task firstprivate(clevel,ci,stime,dt,recentersub) untied { struct sys lsys; lsys.n=ci->n; struct particle* lpart=(struct particle*) malloc(lsys.n*sizeof(struct particle)); lsys.part=lpart;lsys.last=lpart+lsys.n-1; for(UINT i=0;i<lsys.n;i++) lsys.part[i]=ci->part[i]; evolve_cc2(clevel+1,lsys, stime, stime+dt/2, dt/2,inttype,recentersub); for(UINT i=0;i<lsys.n;i++) ci->part[i]=lpart[i]; free(lpart); } } else #endif { evolve_cc2(clevel+1,*ci, stime, stime+dt/2, dt/2,inttype,recentersub); } } #pragma omp taskwait // Apply drifts and kicks at current pivot time step (eq 30) if(r.n>0) drift(clevel,r, stime+dt/2, dt/2); // drift r, 1st time // kick ci <-> cj (eq 23) for (struct sys *ci = &c; !IS_ZEROSYS(ci); ci = ci->next_cc) { for (struct sys *cj = &c; !IS_ZEROSYS(cj); cj = cj->next_cc) { if (ci != cj) { kick(clevel,*ci, *cj, dt); //kick(*cj, *ci, dt); } } } // kick c <-> rest (eq 24) if(r.n>0) for (struct sys *ci = &c; !IS_ZEROSYS(ci); ci = ci->next_cc) { kick(clevel,r, *ci, dt); kick(clevel,*ci, r, dt); } if(r.n>0) kick(clevel,r, r, dt); // kick rest (V_RR) if(r.n>0) drift(clevel,r, etime, dt/2); // drift r, 2nd time // Independently integrate every C_i at reduced pivot time step h/2 (2nd time, eq 27) for (struct sys *ci = &c; !IS_ZEROSYS(ci); ci = ci->next_cc) { #ifdef _OPENMP if (TASKCONDITION) { diag->ntasks[clevel]++; diag->taskcount[clevel]+=ci->n; #pragma omp task firstprivate(clevel,ci,stime,etime,dt,recentersub) untied { struct sys lsys; lsys.n=ci->n; struct particle* lpart=(struct particle*) malloc(lsys.n*sizeof(struct particle)); lsys.part=lpart;lsys.last=lpart+lsys.n-1; for(UINT i=0;i<lsys.n;i++) lsys.part[i]=ci->part[i]; evolve_cc2(clevel+1,lsys, stime+dt/2, etime, dt/2,inttype,recentersub); for(UINT i=0;i<lsys.n;i++) ci->part[i]=lpart[i]; free(lpart); } } else #endif { evolve_cc2(clevel+1,*ci, stime, stime+dt/2, dt/2,inttype,recentersub); } } #pragma omp taskwait if(recenter && (inttype==CCC || inttype==CCC_KEPLER || inttype==CCC_BS || inttype==CCC_BSA)) { for(int i=0;i<3;i++) cmpos[i]+=cmvel[i]*dt; move_system(s,cmpos,cmvel,1); } free_sys(c.next_cc); } #undef TASKCONDITION
calculate_signed_distance_to_3d_skin_process.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Daniel Baumgaertner // Johannes Wolf // #if !defined(KRATOS_CALCULATE_DISTANCE_PROCESS_H_INCLUDED ) #define KRATOS_CALCULATE_DISTANCE_PROCESS_H_INCLUDED // System includes #include <string> #include <iostream> #include <ctime> // External includes // Project includes #include "includes/define.h" #include "processes/process.h" #include "includes/model_part.h" #include "includes/deprecated_variables.h" #include "spatial_containers/octree_binary.h" #include "utilities/spatial_containers_configure.h" #include "utilities/timer.h" #include "utilities/math_utils.h" #include "utilities/geometry_utilities.h" #include "geometries/triangle_3d_3.h" #include "geometries/quadrilateral_3d_4.h" #include "utilities/body_normal_calculation_utils.h" #include "includes/kratos_flags.h" #include "utilities/binbased_fast_point_locator.h" #include "utilities/binbased_nodes_in_element_locator.h" #include "processes/calculate_distance_to_skin_process.h" #ifdef _OPENMP #include "omp.h" #endif using namespace boost::numeric::ublas; namespace Kratos { class DistanceSpatialContainersConfigure { public: class CellNodeData { double mDistance; double mCoordinates[3]; std::size_t mId; public: double& Distance(){return mDistance;} double& X() {return mCoordinates[0];} double& Y() {return mCoordinates[1];} double& Z() {return mCoordinates[2];} double& operator[](int i) {return mCoordinates[i];} std::size_t& Id(){return mId;} }; ///@name Type Definitions ///@{ enum { Dimension = 3, DIMENSION = 3, MAX_LEVEL = 12, MIN_LEVEL = 2 // this cannot be less than 2!!! }; typedef Point PointType; /// always the point 3D typedef std::vector<double>::iterator DistanceIteratorType; typedef ModelPart::ElementsContainerType::ContainerType ContainerType; typedef ContainerType::value_type PointerType; typedef ContainerType::iterator IteratorType; typedef ModelPart::ElementsContainerType::ContainerType ResultContainerType; typedef ResultContainerType::value_type ResultPointerType; typedef ResultContainerType::iterator ResultIteratorType; typedef Element::Pointer pointer_type; typedef CellNodeData cell_node_data_type; typedef std::vector<CellNodeData*> data_type; typedef std::vector<PointerType>::iterator PointerTypeIterator; /// Pointer definition of DistanceSpatialContainersConfigure KRATOS_CLASS_POINTER_DEFINITION(DistanceSpatialContainersConfigure); ///@} ///@name Life Cycle ///@{ /// Default constructor. DistanceSpatialContainersConfigure() {} /// Destructor. virtual ~DistanceSpatialContainersConfigure() {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ static data_type* AllocateData() { return new data_type(27, (CellNodeData*)NULL); } static void CopyData(data_type* source, data_type* destination) { *destination = *source; } static void DeleteData(data_type* data) { delete data; } static inline void CalculateBoundingBox(const PointerType& rObject, PointType& rLowPoint, PointType& rHighPoint) { rHighPoint = rObject->GetGeometry().GetPoint(0); rLowPoint = rObject->GetGeometry().GetPoint(0); for (unsigned int point = 0; point<rObject->GetGeometry().PointsNumber(); point++) { for(std::size_t i = 0; i<3; i++) { rLowPoint[i] = (rLowPoint[i] > rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rLowPoint[i]; rHighPoint[i] = (rHighPoint[i] < rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rHighPoint[i]; } } } static inline void GetBoundingBox(const PointerType rObject, double* rLowPoint, double* rHighPoint) { for(std::size_t i = 0; i<3; i++) { rLowPoint[i] = rObject->GetGeometry().GetPoint(0)[i]; rHighPoint[i] = rObject->GetGeometry().GetPoint(0)[i]; } for (unsigned int point = 0; point<rObject->GetGeometry().PointsNumber(); point++) { for(std::size_t i = 0; i<3; i++) { rLowPoint[i] = (rLowPoint[i] > rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rLowPoint[i]; rHighPoint[i] = (rHighPoint[i] < rObject->GetGeometry().GetPoint(point)[i] ) ? rObject->GetGeometry().GetPoint(point)[i] : rHighPoint[i]; } } } static inline bool Intersection(const PointerType& rObj_1, const PointerType& rObj_2) { Element::GeometryType& geom_1 = rObj_1->GetGeometry(); Element::GeometryType& geom_2 = rObj_2->GetGeometry(); return geom_1.HasIntersection(geom_2); } static inline bool IntersectionBox(const PointerType& rObject, const PointType& rLowPoint, const PointType& rHighPoint) { return rObject->GetGeometry().HasIntersection(rLowPoint, rHighPoint); } static inline bool IsIntersected(const Element::Pointer rObject, double Tolerance, const double* rLowPoint, const double* rHighPoint) { Point low_point(rLowPoint[0] - Tolerance, rLowPoint[1] - Tolerance, rLowPoint[2] - Tolerance); Point high_point(rHighPoint[0] + Tolerance, rHighPoint[1] + Tolerance, rHighPoint[2] + Tolerance); KRATOS_THROW_ERROR(std::logic_error, "Not Implemented method", "") //return HasIntersection(rObject->GetGeometry(), low_point, high_point); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const { return " Spatial Containers Configure"; } /// 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. DistanceSpatialContainersConfigure& operator=(DistanceSpatialContainersConfigure const& rOther); /// Copy constructor. DistanceSpatialContainersConfigure(DistanceSpatialContainersConfigure const& rOther); }; // Class DistanceSpatialContainersConfigure ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ class CalculateSignedDistanceTo3DSkinProcess : public Process { public: ///@name Type Definitions ///@{ /// Pointer definition of CalculateSignedDistanceTo3DSkinProcess KRATOS_CLASS_POINTER_DEFINITION(CalculateSignedDistanceTo3DSkinProcess); typedef DistanceSpatialContainersConfigure ConfigurationType; typedef OctreeBinaryCell<ConfigurationType> CellType; typedef OctreeBinary<CellType> OctreeType; typedef ConfigurationType::cell_node_data_type CellNodeDataType; typedef Point PointType; /// always the point 3D typedef OctreeType::cell_type::object_container_type object_container_type; typedef struct{ array_1d<double,3> Coordinates; array_1d<double,3> StructElemNormal; unsigned int EdgeNode1; unsigned int EdgeNode2; }IntersectionNodeStruct; typedef struct{ std::vector<IntersectionNodeStruct> IntNodes; }TetEdgeStruct; ///@} ///@name Life Cycle ///@{ /// Constructor. CalculateSignedDistanceTo3DSkinProcess(ModelPart& rThisModelPartStruc, ModelPart& rThisModelPartFluid) : mrSkinModelPart(rThisModelPartStruc), mrBodyModelPart(rThisModelPartStruc), mrFluidModelPart(rThisModelPartFluid) { } /// Destructor. ~CalculateSignedDistanceTo3DSkinProcess() override { } ///@} ///@name Operators ///@{ void operator()() { Execute(); } ///@} ///@name Operations ///@{ ///****************************************************************************************************************** ///****************************************************************************************************************** void Execute() override { KRATOS_TRY; GenerateOctree(); //DistanceFluidStructure(); CalculateDistanceToSkinProcess<3> distance_process(mrFluidModelPart, mrBodyModelPart); distance_process.Execute(); // ------------------------------------------------------------------ // GenerateNodes(); CalculateDistance2(); // I have to change this. Pooyan. //mrSkinModelPart.GetCommunicator().AssembleCurrentData(DISTANCE); // std::ofstream mesh_file1("octree1.post.msh"); // std::ofstream res_file("octree1.post.res"); // Timer::Start("Writing Gid conform Mesh"); // PrintGiDMesh(mesh_file1); // PrintGiDResults(res_file); // octree.PrintGiDMeshNew(mesh_file2); // Timer::Stop("Writing Gid conform Mesh"); // delete octree. TODO: Carlos // ------------------------------------------------------------------ KRATOS_CATCH(""); } ///****************************************************************************************************************** ///****************************************************************************************************************** /** * This function maps the nodal pressure values computed in the CFD analysis to the respective * structural nodes, i.e. for each structural node inside a fluid tetrahedra positive and negative * face pressure is computed by mapping between the nodal values of the tetrahedra. Afterwards * the resulting delta is applied as new nodal pressure. */ void MappingPressureToStructure(BinBasedFastPointLocator<3>& node_locator) { //loop over nodes and find the tetra in which it falls, than do interpolation Vector N; const int max_results = 10000; BinBasedFastPointLocator<3>::ResultContainerType results(max_results); const int n_structure_nodes = mrSkinModelPart.Nodes().size(); #pragma omp parallel for firstprivate(results,N) //MY NEW LOOP: reset the viisted flaf for (int i = 0; i < n_structure_nodes; i++) { ModelPart::NodesContainerType::iterator iparticle = mrSkinModelPart.NodesBegin() + i; Node < 3 > ::Pointer p_structure_node = *(iparticle.base()); p_structure_node->Set(VISITED, false); } for (int i = 0; i < n_structure_nodes; i++) { ModelPart::NodesContainerType::iterator iparticle = mrSkinModelPart.NodesBegin() + i; Node < 3 > ::Pointer p_structure_node = *(iparticle.base()); BinBasedFastPointLocator<3>::ResultIteratorType result_begin = results.begin(); Element::Pointer pElement; bool is_found = node_locator.FindPointOnMesh(p_structure_node->Coordinates(), N, pElement, result_begin, max_results); if (is_found == true) { array_1d<double,4> nodalPressures; const Vector& ElementalDistances = pElement->GetValue(ELEMENTAL_DISTANCES); Geometry<Node<3> >& geom = pElement->GetGeometry(); for(unsigned int j=0; j<geom.size(); j++) { nodalPressures[j] = geom[j].FastGetSolutionStepValue(PRESSURE); } if(pElement->GetValue(SPLIT_ELEMENT)==true) { array_1d<double,4> Npos,Nneg; // Do mapping ComputeDiscontinuousInterpolation((*p_structure_node),pElement->GetGeometry(),ElementalDistances,Npos,Nneg); // Compute face pressure double p_positive_structure = inner_prod(nodalPressures,Npos); double p_negative_structure = inner_prod(nodalPressures,Nneg); // Assign ModelPart::ElementIteratorface pressure to structure node p_structure_node->FastGetSolutionStepValue(POSITIVE_FACE_PRESSURE) = p_positive_structure; p_structure_node->FastGetSolutionStepValue(NEGATIVE_FACE_PRESSURE) = p_negative_structure; p_structure_node->Set(VISITED); } else { double p = inner_prod(nodalPressures,N); p_structure_node->FastGetSolutionStepValue(POSITIVE_FACE_PRESSURE) = p; p_structure_node->FastGetSolutionStepValue(NEGATIVE_FACE_PRESSURE) = p; p_structure_node->Set(VISITED); } } } //AND NOW WE "TREAT" the bad nodes, the ones that belong to the structural faces that by some chance did not cross the fluid elements //to such nodes we simply extrapolate the pressure from the neighbors int n_bad_nodes=0; for (int i = 0; i < n_structure_nodes; i++) { ModelPart::NodesContainerType::iterator iparticle = mrSkinModelPart.NodesBegin() + i; Node < 3 > ::Pointer p_structure_node = *(iparticle.base()); if (p_structure_node->IsNot(VISITED)) n_bad_nodes++; } //KRATOS_WATCH("THERE WERE THIS MANY BAD NODES ORIGINALLY") //KRATOS_WATCH(n_bad_nodes) while (n_bad_nodes >= 1.0) { int n_bad_nodes_backup = n_bad_nodes; for (int i = 0; i < n_structure_nodes; i++) { ModelPart::NodesContainerType::iterator iparticle = mrSkinModelPart.NodesBegin() + i; Node < 3 > ::Pointer p_structure_node = *(iparticle.base()); //here we store the number of neigbor nodes that were given the pressure in the previous loop (i.e. were found) if (p_structure_node->IsNot(VISITED)) { int n_good_neighbors = 0; double pos_pres = 0.0; double neg_pres = 0.0; WeakPointerVector< Node < 3 > >& neighours = p_structure_node->GetValue(NEIGHBOUR_NODES); for (WeakPointerVector< Node < 3 > >::iterator j = neighours.begin(); j != neighours.end(); j++) { if (j->Is(VISITED)) { n_good_neighbors++; pos_pres += j->FastGetSolutionStepValue(POSITIVE_FACE_PRESSURE); neg_pres += j->FastGetSolutionStepValue(NEGATIVE_FACE_PRESSURE); //KRATOS_WATCH("Good neighbor found") } } if (n_good_neighbors != 0) { pos_pres /= n_good_neighbors; neg_pres /= n_good_neighbors; p_structure_node->FastGetSolutionStepValue(POSITIVE_FACE_PRESSURE) = pos_pres; p_structure_node->FastGetSolutionStepValue(NEGATIVE_FACE_PRESSURE) = neg_pres; p_structure_node->Set(VISITED); n_bad_nodes--; } //KRATOS_WATCH(pos_pres) //KRATOS_WATCH(neg_pres) } } if(n_bad_nodes == n_bad_nodes_backup) break; //WE BREAK THE WHILE HERE, OTHERWISE THE CODE HANGS (it was not able to remove any other node) /*int n_bad_nodes=0; for (int i = 0; i < n_structure_nodes; i++) { ModelPart::NodesContainerType::iterator iparticle = mrSkinModelPart.NodesBegin() + i; Node < 3 > ::Pointer p_structure_node = *(iparticle.base()); if (p_structure_node->IsNot(VISITED)) n_bad_nodes++; } */ //KRATOS_WATCH(n_bad_nodes) } //THE BELOW ONE IS A "CHEAT".. THERE IS A PROBLEM OF INCORRECT PROJECTION BETWEEN THE MESHES AT SOME POINTS //FOR NODES WITH PRESSURE VERY DIFFERENT FROM THAT OF THE NEIGHBORS, I JUST TAKE THE NEIGHBOR PRESSURE AVERAGED for (int i = 0; i < n_structure_nodes; i++) { ModelPart::NodesContainerType::iterator iparticle = mrSkinModelPart.NodesBegin() + i; Node < 3 > ::Pointer p_structure_node = *(iparticle.base()); double pos_pressure=p_structure_node->FastGetSolutionStepValue(POSITIVE_FACE_PRESSURE); double neg_pressure=p_structure_node->FastGetSolutionStepValue(NEGATIVE_FACE_PRESSURE); WeakPointerVector< Node < 3 > >& neighours = p_structure_node->GetValue(NEIGHBOUR_NODES); if (neighours.size()>=1.0) { double av_pos_pres=0.0; double av_neg_pres=0.0; for( WeakPointerVector< Node<3> >::iterator j = neighours.begin(); j != neighours.end(); j++) { av_pos_pres+=j->FastGetSolutionStepValue(POSITIVE_FACE_PRESSURE); av_neg_pres+=j->FastGetSolutionStepValue(NEGATIVE_FACE_PRESSURE); } av_pos_pres/=neighours.size(); av_neg_pres/=neighours.size(); //IF the average pressure of the neighbors is 10 times lower than of the given node, something is bad and we reset its value if (fabs(pos_pressure)>3.0*fabs(av_pos_pres)) { p_structure_node->FastGetSolutionStepValue(POSITIVE_FACE_PRESSURE) = av_pos_pres; //KRATOS_WATCH("BAD NODE") } if (fabs(neg_pressure)>3.0*fabs(av_neg_pres)) { p_structure_node->FastGetSolutionStepValue(NEGATIVE_FACE_PRESSURE) = av_neg_pres; //KRATOS_WATCH("BAD NODE") } } } } ///****************************************************************************************************************** ///****************************************************************************************************************** void ComputeDiscontinuousInterpolation( const Node<3>& pNode, Geometry< Node<3> >& geom, const array_1d<double,4>& distances, array_1d<double,4>& Npos, array_1d<double,4>& Nneg) { //count positives int n_positives = 0; for(unsigned int i=0; i<distances.size(); i++) if(distances[i]>0) n_positives++; //generate the points on the edges at the zero of the distance function //generate "father nodes", defined as the end nodes of the edge on which the local point is located std::vector< Point > edge_points; edge_points.reserve(4); array_1d<unsigned int, 4> positive_fathers, negative_fathers; //there are at most 4 cut edges unsigned int k=0; unsigned int l=0; for(unsigned int i=0; i<3; i++) { for(unsigned int j=i+1; j<4; j++) // go through the edges 01, 02, 03, 12, 13, 23 { double di = distances[i]; double dj = distances[j]; if(di*dj < 0) //edge is cut { //generate point on edge by linear interpolation double Ni = fabs(dj) / ( fabs(di) + fabs(dj) ); double Nj = 1.0 - Ni; Point edge_point(Ni * geom[i] + Nj * geom[j]); edge_points.push_back(edge_point); //store the id of the positive and negative fathers if(di > 0.0) { positive_fathers[k++] = i; negative_fathers[l++] = j; } else { positive_fathers[k++] = j; negative_fathers[l++] = i; } } } } if(edge_points.size() == 3) { //compute local shape functions (tell how to interpolate from the edge nodes) Vector Nlocal(3); //form a triangle with the edge nodes Triangle3D3< Point > triangle(Point::Pointer(new Point(edge_points[0])), Point::Pointer(new Point(edge_points[1])), Point::Pointer(new Point(edge_points[2])) ); array_1d<double,3> local_coords; local_coords = triangle.PointLocalCoordinates(local_coords, pNode); for(unsigned int i=0; i<3;i++) Nlocal[i] = triangle.ShapeFunctionValue(i, local_coords ); noalias(Npos) = ZeroVector(4); noalias(Nneg) = ZeroVector(4); for(unsigned int i=0; i<3; i++) { Npos[ positive_fathers[i] ] += Nlocal[i]; Nneg[ negative_fathers[i] ] += Nlocal[i]; } } if(edge_points.size() == 4) { //compute local shape functions (tell how to interpolate from the edge nodes) Vector Nlocal(4); //form a quadrilatera with the 4 cut nodes array_1d<double,3> x21 = edge_points[1] - edge_points[0]; array_1d<double,3> x31 = edge_points[2] - edge_points[0]; array_1d<double,3> x41 = edge_points[3] - edge_points[0]; //define a vector oriented as x21 array_1d<double,3> v1 = x21 / norm_2(x21); BoundedMatrix<double,4,3> DN_DX; array_1d<double,4> msN; double Area; GeometryUtils::CalculateGeometryData( geom, DN_DX, msN, Area ); array_1d<double,3> n = prod(trans(DN_DX),distances); n /= norm_2(n); array_1d<double,3> v2; MathUtils<double>::CrossProduct(v2,v1,n); // v2 = v1 x n array_1d<double,3> angles; angles[0] = 0.0; //angle between x21 and v1 angles[1] = atan2( inner_prod(x31,v2), inner_prod(x31,v1) ); //angle between x31 and v1 angles[2] = atan2( inner_prod(x41,v2), inner_prod(x41,v1) ); //angle between x31 and v1 double max_angle = 0.0; double min_angle = 0.0; unsigned int min_pos = 1; unsigned int max_pos = 1; for(unsigned int i=1; i<3; i++) { if(angles[i] < min_angle) { min_pos = i+1; //this is the local index of the edge point which forms the minimal angle min_angle = angles[i]; } else if(angles[i] > max_angle) { max_pos = i+1; //this is the local index of the edge point which forms the maximal angle max_angle = angles[i]; } } //find the pos of the center node unsigned int center_pos = 0; for(unsigned int i=1; i<4; i++) { if((i!= min_pos) && (i!=max_pos)) { center_pos = i; } } //form a quadrilateral with the edge nodes Quadrilateral3D4< Point > quad = Quadrilateral3D4< Point >( Point::Pointer(new Point(edge_points[0])), Point::Pointer(new Point(edge_points[min_pos])), Point::Pointer(new Point(edge_points[center_pos])), Point::Pointer(new Point(edge_points[max_pos])) ); array_1d<double,3> local_coords; local_coords = quad.PointLocalCoordinates(local_coords, pNode); array_1d<unsigned int, 4> indices; indices[0] = 0; indices[1] = min_pos; indices[2] = center_pos; indices[3] = max_pos; for(unsigned int i=0; i<4;i++) Nlocal[ i ] = quad.ShapeFunctionValue(i, local_coords ); noalias(Npos) = ZeroVector(4); noalias(Nneg) = ZeroVector(4); for(unsigned int i=0; i<4; i++) { Npos[ positive_fathers[i] ] += Nlocal[indices[i]]; Nneg[ negative_fathers[i] ] += Nlocal[indices[i]]; } } } ///****************************************************************************************************************** ///****************************************************************************************************************** void AveragePressureToNode(BinBasedFastPointLocator<3>& node_locator, Node<3>& node) { //loop over nodes and find the tetra in which it falls, than do interpolation Vector N; const int max_results = 10000; BinBasedFastPointLocator<3>::ResultContainerType results(max_results); BinBasedFastPointLocator<3>::ResultIteratorType result_begin = results.begin(); Element::Pointer pElement; bool is_found = node_locator.FindPointOnMesh(node.Coordinates(), N, pElement, result_begin, max_results); if (is_found == true) { array_1d<double,4> nodalPressures; const Vector& ElementalDistances = pElement->GetValue(ELEMENTAL_DISTANCES); Geometry<Node<3> >& geom = pElement->GetGeometry(); for(unsigned int i=0; i<4; i++) nodalPressures[i] = geom[i].GetSolutionStepValue(PRESSURE); if(pElement->GetValue(SPLIT_ELEMENT)==true) { // Compute average of all positive and all negative values double positiveAverage = 0; double negativeAverage = 0; unsigned int nPos = 0; unsigned int nNeg = 0; for(unsigned int i=0 ; i<4 ; i++) { if(ElementalDistances[i]>=0) { positiveAverage += nodalPressures[i]; nPos++; } else { negativeAverage += nodalPressures[i]; nNeg++; } } positiveAverage /= nPos; negativeAverage /= nNeg; // Assign Pressures node.GetSolutionStepValue(POSITIVE_FACE_PRESSURE,0) = positiveAverage; node.GetSolutionStepValue(NEGATIVE_FACE_PRESSURE,0) = negativeAverage; } else { // Compute average of all positive and all negative values double Average = 0; // for output of for(unsigned int i = 0 ; i<4 ; i++) Average += nodalPressures[i]; Average /= 4; // Assign Pressures node.GetSolutionStepValue(POSITIVE_FACE_PRESSURE,0) = Average; node.GetSolutionStepValue(NEGATIVE_FACE_PRESSURE,0) = Average; } } } ///****************************************************************************************************************** ///****************************************************************************************************************** void DistanceFluidStructure() { //std::cout << "Start calculating Elemental distances..." << std::endl; // Initialize Elemental distances in the domain Initialize(); // Initialize index table that defines line Edges of fluid Element BoundedMatrix<unsigned int,6,2> TetEdgeIndexTable; SetIndexTable(TetEdgeIndexTable); // loop over all fluid Elements // this loop is parallelized using openmp #ifdef _OPENMP int number_of_threads = omp_get_max_threads(); #else int number_of_threads = 1; #endif ModelPart::ElementsContainerType& pElements = mrFluidModelPart.Elements(); DenseVector<unsigned int> Element_partition; CreatePartition(number_of_threads, pElements.size(), Element_partition); #pragma omp parallel for for (int k = 0; k < number_of_threads; k++) { ModelPart::ElementsContainerType::iterator it_begin = pElements.ptr_begin() + Element_partition[k]; ModelPart::ElementsContainerType::iterator it_end = pElements.ptr_begin() + Element_partition[k+1]; // assemble all Elements for (ModelPart::ElementIterator it = it_begin; it != it_end; ++it) { CalcElementDistances( it , TetEdgeIndexTable ); } } // Finally, each tetrahedral Element has 4 distance values. But each node belongs to // several Elements, such that it is assigned several distance values // --> now synchronize these values by finding the minimal distance and assign to each node a minimal nodal distance AssignMinimalNodalDistance(); //std::cout << "Finished calculating Elemental distances..." << std::endl; } ///****************************************************************************************************************** ///****************************************************************************************************************** void Initialize() { const double initial_distance = 1.0; ModelPart::NodesContainerType::ContainerType& nodes = mrFluidModelPart.NodesArray(); // reset the node distance to 1.0 which is the maximum distance in our normalized space. int nodesSize = nodes.size(); #pragma omp parallel for firstprivate(nodesSize) for(int i = 0 ; i < nodesSize ; i++) nodes[i]->GetSolutionStepValue(DISTANCE) = initial_distance; ModelPart::ElementsContainerType::ContainerType& fluid_Elements = mrFluidModelPart.ElementsArray(); array_1d<double,4> ElementalDistances; ElementalDistances[0] = initial_distance; ElementalDistances[1] = initial_distance; ElementalDistances[2] = initial_distance; ElementalDistances[3] = initial_distance; // reset the Elemental distance to 1.0 which is the maximum distance in our normalized space. // also initialize the embedded velocity of the fluid Element int ElementsSize = fluid_Elements.size(); #pragma omp parallel for firstprivate(ElementsSize) for(int i = 0 ; i < ElementsSize ; i++) { fluid_Elements[i]->GetValue(ELEMENTAL_DISTANCES) = ElementalDistances; fluid_Elements[i]->GetValue(SPLIT_ELEMENT) = false; fluid_Elements[i]->GetValue(EMBEDDED_VELOCITY)=ZeroVector(3); } } ///****************************************************************************************************************** ///****************************************************************************************************************** void SetIndexTable( BoundedMatrix<unsigned int,6,2>& TetEdgeIndexTable ) { // Initialize index table to define line Edges of fluid Element TetEdgeIndexTable(0,0) = 0; TetEdgeIndexTable(0,1) = 1; TetEdgeIndexTable(1,0) = 0; TetEdgeIndexTable(1,1) = 2; TetEdgeIndexTable(2,0) = 0; TetEdgeIndexTable(2,1) = 3; TetEdgeIndexTable(3,0) = 1; TetEdgeIndexTable(3,1) = 2; TetEdgeIndexTable(4,0) = 1; TetEdgeIndexTable(4,1) = 3; TetEdgeIndexTable(5,0) = 2; TetEdgeIndexTable(5,1) = 3; } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalcElementDistances( ModelPart::ElementsContainerType::iterator& i_fluidElement, BoundedMatrix<unsigned int,6,2> TetEdgeIndexTable ) { std::vector<OctreeType::cell_type*> leaves; std::vector<TetEdgeStruct> IntersectedTetEdges; unsigned int NumberIntersectionsOnTetCorner = 0; // Get leaves of octree intersecting with fluid Element mpOctree->GetIntersectedLeaves(*(i_fluidElement).base(),leaves); int intersection_counter = 0; // Loop over all 6 line Edges of the tetrahedra for(unsigned int i_tetEdge = 0; i_tetEdge < 6; i_tetEdge++) { IdentifyIntersectionNodes( i_fluidElement, i_tetEdge, leaves, IntersectedTetEdges, NumberIntersectionsOnTetCorner, TetEdgeIndexTable, intersection_counter ); } if (intersection_counter!=0) { i_fluidElement->GetValue(EMBEDDED_VELOCITY) /= intersection_counter; } if(IntersectedTetEdges.size() > 0) CalcDistanceTo3DSkin( IntersectedTetEdges , i_fluidElement , NumberIntersectionsOnTetCorner ); } ///****************************************************************************************************************** ///****************************************************************************************************************** void IdentifyIntersectionNodes( ModelPart::ElementsContainerType::iterator& i_fluidElement, unsigned int i_tetEdge, std::vector<OctreeType::cell_type*>& leaves, std::vector<TetEdgeStruct>& IntersectedTetEdges, unsigned int& NumberIntersectionsOnTetCorner, BoundedMatrix<unsigned int,6,2> TetEdgeIndexTable, int& intersection_counter ) { std::vector<unsigned int> IntersectingStructElemID; TetEdgeStruct NewTetEdge; unsigned int NumberIntersectionsOnTetCornerCurrentEdge = 0; // Get nodes of line Edge unsigned int EdgeStartIndex = TetEdgeIndexTable(i_tetEdge,0); unsigned int EdgeEndIndex = TetEdgeIndexTable(i_tetEdge,1); PointType& P1 = i_fluidElement->GetGeometry()[EdgeStartIndex]; PointType& P2 = i_fluidElement->GetGeometry()[EdgeEndIndex]; double EdgeNode1[3] = {P1.X() , P1.Y() , P1.Z()}; double EdgeNode2[3] = {P2.X() , P2.Y() , P2.Z()}; // loop over all octree cells which are intersected by the fluid Element for(unsigned int i_cell = 0 ; i_cell < leaves.size() ; i_cell++) { // Structural Element contained in one cell of the octree object_container_type* struct_elem = (leaves[i_cell]->pGetObjects()); // loop over all structural Elements within each octree cell for(object_container_type::iterator i_StructElement = struct_elem->begin(); i_StructElement != struct_elem->end(); i_StructElement++) { if( StructuralElementNotYetConsidered( (*i_StructElement)->Id() , IntersectingStructElemID ) ) { // Calculate and associate intersection point to the current fluid Element double IntersectionPoint[3] = {0.0 , 0.0 , 0.0}; int TetEdgeHasIntersections = IntersectionTriangleSegment( (*i_StructElement)->GetGeometry() , EdgeNode1 , EdgeNode2 , IntersectionPoint ); if( TetEdgeHasIntersections == 1 ) { IntersectionNodeStruct NewIntersectionNode; // Assign information to the intersection node NewIntersectionNode.Coordinates[0] = IntersectionPoint[0]; NewIntersectionNode.Coordinates[1] = IntersectionPoint[1]; NewIntersectionNode.Coordinates[2] = IntersectionPoint[2]; if( IsIntersectionNodeOnTetEdge( IntersectionPoint , EdgeNode1 , EdgeNode2 ) ) { if ( IsNewIntersectionNode( NewIntersectionNode , IntersectedTetEdges ) ) { // Calculate normal of the structural Element at the position of the intersection point CalculateNormal3D((*i_StructElement)->GetGeometry()[0], (*i_StructElement)->GetGeometry()[1], (*i_StructElement)->GetGeometry()[2], NewIntersectionNode.StructElemNormal); // check, how many intersection nodes are located on corner points of the tetrahedra if ( IsIntersectionOnCorner( NewIntersectionNode , EdgeNode1 , EdgeNode2) ) { NumberIntersectionsOnTetCornerCurrentEdge++; // only allow one intersection node on a tet edge if(NumberIntersectionsOnTetCornerCurrentEdge < 2) { // add the new intersection point to the list of intersection points of the fluid Element NewIntersectionNode.EdgeNode1 = EdgeStartIndex; NewIntersectionNode.EdgeNode2 = EdgeEndIndex; NewTetEdge.IntNodes.push_back(NewIntersectionNode); // if tet edge belonging to this intersection point is not already marked as "IntersectedTetEdge" --> put it into the respective container // when a second intersection node is found, then it is not necessary to push_back again if( NewTetEdge.IntNodes.size() == 1 ) IntersectedTetEdges.push_back(NewTetEdge); } // this corner intersection node is only considered once for each tet edge if(NumberIntersectionsOnTetCornerCurrentEdge==1) { NumberIntersectionsOnTetCorner++; } } else { // add the new intersection point to the list of intersection points of the fluid Element NewIntersectionNode.EdgeNode1 = EdgeStartIndex; NewIntersectionNode.EdgeNode2 = EdgeEndIndex; NewTetEdge.IntNodes.push_back(NewIntersectionNode); // velocity mapping structure --> fluid array_1d<double,3> emb_vel = (*i_StructElement)->GetGeometry()[0].GetSolutionStepValue(VELOCITY); emb_vel += (*i_StructElement)->GetGeometry()[1].GetSolutionStepValue(VELOCITY); emb_vel += (*i_StructElement)->GetGeometry()[2].GetSolutionStepValue(VELOCITY); i_fluidElement->GetValue(EMBEDDED_VELOCITY) += emb_vel/3; intersection_counter++; } } } } } } } // Finally put the found intersection nodes into the container if( NewTetEdge.IntNodes.size() > 0 ) { if(NumberIntersectionsOnTetCornerCurrentEdge == 0) IntersectedTetEdges.push_back(NewTetEdge); } } ///****************************************************************************************************************** ///****************************************************************************************************************** bool StructuralElementNotYetConsidered( unsigned int IDCurrentStructElem, std::vector<unsigned int>& IntersectingStructElemID ) { // check if the structural Element was already considered as intersecting Element for(unsigned int k = 0 ; k < IntersectingStructElemID.size() ; k++) { if( IDCurrentStructElem == IntersectingStructElemID[k] ) return false; } // if structural Element has not been considered in another octree, which also intersects the fluid Element // add the new object ID to the vector IntersectingStructElemID.push_back( IDCurrentStructElem ); return true; } ///****************************************************************************************************************** ///****************************************************************************************************************** bool IsIntersectionNodeOnTetEdge( double* IntersectionPoint, double* EdgeNode1, double* EdgeNode2 ) { // check, if intersection point is located on any edge of the fluid Element array_1d<double,3> ConnectVectTetNodeIntNode1; array_1d<double,3> ConnectVectTetNodeIntNode2; array_1d<double,3> EdgeVector; ConnectVectTetNodeIntNode1[0] = IntersectionPoint[0] - EdgeNode1[0]; ConnectVectTetNodeIntNode1[1] = IntersectionPoint[1] - EdgeNode1[1]; ConnectVectTetNodeIntNode1[2] = IntersectionPoint[2] - EdgeNode1[2]; ConnectVectTetNodeIntNode2[0] = IntersectionPoint[0] - EdgeNode2[0]; ConnectVectTetNodeIntNode2[1] = IntersectionPoint[1] - EdgeNode2[1]; ConnectVectTetNodeIntNode2[2] = IntersectionPoint[2] - EdgeNode2[2]; double LengthConnectVect1 = norm_2( ConnectVectTetNodeIntNode1 ); double LengthConnectVect2 = norm_2( ConnectVectTetNodeIntNode2 ); EdgeVector[0] = EdgeNode2[0] - EdgeNode1[0]; EdgeVector[1] = EdgeNode2[1] - EdgeNode1[1]; EdgeVector[2] = EdgeNode2[2] - EdgeNode1[2]; double MaxEdgeLength = norm_2( EdgeVector ); // if both connection vectors (corner point --> intersection point) // are smaller or equal to the edge length of tetrahedra, // then intersection point is located on the edge if( (LengthConnectVect1 <= (MaxEdgeLength)) && (LengthConnectVect2 <= (MaxEdgeLength)) ) return true; else return false; } ///****************************************************************************************************************** ///****************************************************************************************************************** bool IsNewIntersectionNode( IntersectionNodeStruct& NewIntersectionNode, std::vector<TetEdgeStruct>& IntersectedTetEdges ) { array_1d<double,3> DiffVector; double NormDiffVector = 0; unsigned int NumberIntNodes = 0; for( unsigned int i_TetEdge = 0 ; i_TetEdge < IntersectedTetEdges.size() ; i_TetEdge++ ) { NumberIntNodes = IntersectedTetEdges[i_TetEdge].IntNodes.size(); for( unsigned int i_IntNode = 0 ; i_IntNode < NumberIntNodes ; i_IntNode++ ) { DiffVector[0] = NewIntersectionNode.Coordinates[0] - IntersectedTetEdges[i_TetEdge].IntNodes[i_IntNode].Coordinates[0]; DiffVector[1] = NewIntersectionNode.Coordinates[1] - IntersectedTetEdges[i_TetEdge].IntNodes[i_IntNode].Coordinates[1]; DiffVector[2] = NewIntersectionNode.Coordinates[2] - IntersectedTetEdges[i_TetEdge].IntNodes[i_IntNode].Coordinates[2]; NormDiffVector = norm_2(DiffVector); if( NormDiffVector < epsilon ) return false; } } // if the new intersection node is not existing (as intersection with a corner point), then return false return true; } ///****************************************************************************************************************** ///****************************************************************************************************************** bool IsIntersectionOnCorner( IntersectionNodeStruct& NewIntersectionNode, double* EdgeNode1, double* EdgeNode2 ) { array_1d<double,3> DiffVector; double NormDiffVector; DiffVector[0] = EdgeNode1[0] - NewIntersectionNode.Coordinates[0]; DiffVector[1] = EdgeNode1[1] - NewIntersectionNode.Coordinates[1]; DiffVector[2] = EdgeNode1[2] - NewIntersectionNode.Coordinates[2]; NormDiffVector = norm_2(DiffVector); if( NormDiffVector < epsilon ) return true; DiffVector[0] = EdgeNode2[0] - NewIntersectionNode.Coordinates[0]; DiffVector[1] = EdgeNode2[1] - NewIntersectionNode.Coordinates[1]; DiffVector[2] = EdgeNode2[2] - NewIntersectionNode.Coordinates[2]; NormDiffVector = norm_2(DiffVector); if( NormDiffVector < epsilon ) return true; else return false; } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalculateNormal3D( Point& Point1, Point& Point2, Point& Point3, array_1d<double,3>& rResultNormal ) { array_1d<double,3> v1 = Point2 - Point1; array_1d<double,3> v2 = Point3 - Point1; MathUtils<double>::CrossProduct(rResultNormal,v1,v2); rResultNormal *= 0.5; } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalcDistanceTo3DSkin( std::vector<TetEdgeStruct>& IntersectedTetEdges, ModelPart::ElementsContainerType::iterator& i_fluid_Element, unsigned int NumberIntersectionsOnTetCorner ) { std::vector<IntersectionNodeStruct> NodesOfApproximatedStructure; array_1d<double,4> ElementalDistances; FillIntNodesContainer(IntersectedTetEdges,NodesOfApproximatedStructure); // Intersection with one corner point if( NodesOfApproximatedStructure.size() == 1 && NumberIntersectionsOnTetCorner == 1 ) { CalcSignedDistancesToOneIntNode(i_fluid_Element,NodesOfApproximatedStructure,ElementalDistances); i_fluid_Element->GetValue(SPLIT_ELEMENT) = true; } // Intersection with two corner points / one tetrahedra edge if( NodesOfApproximatedStructure.size() == 2 && NumberIntersectionsOnTetCorner == 2 ) { CalcSignedDistancesToTwoIntNodes(i_fluid_Element,NodesOfApproximatedStructure,ElementalDistances); i_fluid_Element->GetValue(SPLIT_ELEMENT) = true; } // Intersection with three tetrahedra edges if( NodesOfApproximatedStructure.size() == 3 ) { CalcSignedDistancesToThreeIntNodes(i_fluid_Element,NodesOfApproximatedStructure,ElementalDistances); i_fluid_Element->GetValue(SPLIT_ELEMENT) = true; } // Intersection with more than three tetrahedra edges if( NodesOfApproximatedStructure.size() > 3 ) { CalcSignedDistancesToMoreThanThreeIntNodes(i_fluid_Element,NodesOfApproximatedStructure,ElementalDistances,IntersectedTetEdges); i_fluid_Element->GetValue(SPLIT_ELEMENT) = true; } // Postprocessing treatment of Elemental distances if( i_fluid_Element->GetValue(SPLIT_ELEMENT) == true ) AvoidZeroDistances(i_fluid_Element, ElementalDistances); // In case there is intersection with fluid Element: assign distances to the Element if( i_fluid_Element->GetValue(SPLIT_ELEMENT) == true ) i_fluid_Element->GetValue(ELEMENTAL_DISTANCES) = ElementalDistances; } ///****************************************************************************************************************** ///****************************************************************************************************************** void FillIntNodesContainer( std::vector<TetEdgeStruct>& IntersectedTetEdges, std::vector<IntersectionNodeStruct>& NodesOfApproximatedStructure ) { const unsigned int NumberCutEdges = IntersectedTetEdges.size(); for(unsigned int i_TetEdge = 0 ; i_TetEdge < NumberCutEdges ; i_TetEdge++) { unsigned int NumberIntNodes = IntersectedTetEdges[i_TetEdge].IntNodes.size(); for( unsigned int i_IntNode = 0 ; i_IntNode < NumberIntNodes ; i_IntNode++ ) { NodesOfApproximatedStructure.push_back(IntersectedTetEdges[i_TetEdge].IntNodes[i_IntNode]); } } } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalcSignedDistancesToOneIntNode( ModelPart::ElementsContainerType::iterator& i_fluid_Element, std::vector<IntersectionNodeStruct> NodesOfApproximatedStructure, array_1d<double,4>& ElementalDistances ) { Geometry< Node<3> >& rFluidGeom = i_fluid_Element->GetGeometry(); Point P1; P1.Coordinates() = NodesOfApproximatedStructure[0].Coordinates; array_1d<double,3>& Normal = NodesOfApproximatedStructure[0].StructElemNormal; // Compute distance values for all tet-nodes for(unsigned int i_TetNode = 0 ; i_TetNode < 4 ; i_TetNode++) { ElementalDistances[i_TetNode] = PointDistanceToPlane(P1, Normal, rFluidGeom[i_TetNode]); } } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalcSignedDistancesToTwoIntNodes( ModelPart::ElementsContainerType::iterator& i_fluid_Element, std::vector<IntersectionNodeStruct> NodesOfApproximatedStructure, array_1d<double,4>& ElementalDistances ) { Geometry< Node<3> >& rFluidGeom = i_fluid_Element->GetGeometry(); Point P1; P1.Coordinates() = NodesOfApproximatedStructure[0].Coordinates; // Get normal at intersections, average them and check direction of distances array_1d<double,3> NormalAtIntersectionNode1 = NodesOfApproximatedStructure[0].StructElemNormal; array_1d<double,3> NormalAtIntersectionNode2 = NodesOfApproximatedStructure[1].StructElemNormal; // Compute normal of surface plane array_1d<double,3> Normal; Normal[0] = 0.5*(NormalAtIntersectionNode1[0] + NormalAtIntersectionNode2[0]); Normal[1] = 0.5*(NormalAtIntersectionNode1[1] + NormalAtIntersectionNode2[1]); Normal[2] = 0.5*(NormalAtIntersectionNode1[2] + NormalAtIntersectionNode2[2]); // Check whether orientation of normal is in direction of the normal of the intersecting structure // Note: The normal of the approx. surface can be max. 90deg to every surrounding normal of the structure at the intersection nodes const array_1d<double,3> NormalAtOneIntersectionNode = NodesOfApproximatedStructure[0].StructElemNormal; bool NormalWrongOriented = false; if(inner_prod(NormalAtOneIntersectionNode,Normal)<0) NormalWrongOriented = true; // switch direction of normal if(NormalWrongOriented) Normal *=-1; // Compute distance values for all tet-nodes for(unsigned int i_TetNode = 0 ; i_TetNode < 4 ; i_TetNode++) { ElementalDistances[i_TetNode] = PointDistanceToPlane(P1, Normal, rFluidGeom[i_TetNode]); } } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalcSignedDistancesToThreeIntNodes( ModelPart::ElementsContainerType::iterator& i_fluid_Element, std::vector<IntersectionNodeStruct>& NodesOfApproximatedStructure, array_1d<double,4>& ElementalDistances ) { Geometry< Node<3> >& rFluidGeom = i_fluid_Element->GetGeometry(); Point P1; Point P2; Point P3; P1.Coordinates() = NodesOfApproximatedStructure[0].Coordinates; P2.Coordinates() = NodesOfApproximatedStructure[1].Coordinates; P3.Coordinates() = NodesOfApproximatedStructure[2].Coordinates; array_1d<double,3> Normal; CalculateNormal3D(P1,P2,P3,Normal); // Check whether orientation of normal is in direction of the normal of the intersecting structure // Note: The normal of the approx. surface can be max. 90deg to every surrounding normal of the structure at the intersection nodes const array_1d<double,3> NormalAtOneIntersectionNode = NodesOfApproximatedStructure[0].StructElemNormal; bool NormalWrongOriented = false; if(inner_prod(NormalAtOneIntersectionNode,Normal)<0) NormalWrongOriented = true; // switch direction of normal if(NormalWrongOriented) Normal *=-1; // Compute distance values for all tet-nodes for(unsigned int i_TetNode = 0 ; i_TetNode < 4 ; i_TetNode++) { ElementalDistances[i_TetNode] = PointDistanceToPlane(P1, Normal, rFluidGeom[i_TetNode] ); } } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalcSignedDistancesToMoreThanThreeIntNodes( ModelPart::ElementsContainerType::iterator& i_fluid_Element, std::vector<IntersectionNodeStruct> NodesOfApproximatedStructure, array_1d<double,4>& ElementalDistances, std::vector<TetEdgeStruct>& IntersectedTetEdges ) { unsigned int numberCutEdges = NodesOfApproximatedStructure.size(); // Compute average of the intersection nodes which is a node on the plane we look for Point P_mean; for(unsigned int k=0; k<numberCutEdges; k++) for(unsigned int i=0; i<3; i++) P_mean.Coordinates()[i] += NodesOfApproximatedStructure[k].Coordinates[i]; for(unsigned int i=0; i<3; i++) P_mean.Coordinates()[i] /= numberCutEdges; // Compute normal for the best-fitted plane array_1d<double,3> N_mean; Matrix coordinates(numberCutEdges,3); for(unsigned int i=0; i<numberCutEdges; i++) for(unsigned int j=0; j<3; j++) coordinates(i,j) = NodesOfApproximatedStructure[i].Coordinates[j] - P_mean[j]; Matrix A = prod(trans(coordinates),coordinates); Matrix V(3,3); Vector lambda(3); // Calculate the eigenvectors V and the corresponding eigenvalues lambda EigenVectors(A, V, lambda); // Look for the minimal eigenvalue all lambdas unsigned int min_pos = 0; double min_lambda = lambda[min_pos]; for(unsigned int i=1;i<3; i++) if(min_lambda > lambda[i]) { min_lambda = lambda[i]; min_pos = i; } // the normal equals to the eigenvector which corresponds to the minimal eigenvalue for(unsigned int i=0;i<3; i++) N_mean[i] = V(min_pos,i); N_mean /= norm_2(N_mean); // Check whether orientation of normal is in direction of the normal of the intersecting structure // Note: The normal of the approx. surface can be max. 90deg to every surrounding normal of the structure at the intersection nodes array_1d<double,3> NormalAtOneIntersectionNode; NormalAtOneIntersectionNode = NodesOfApproximatedStructure[0].StructElemNormal; bool NormalWrongOriented = false; if(inner_prod(NormalAtOneIntersectionNode,N_mean)<0) NormalWrongOriented = true; // switch direction of normal if(NormalWrongOriented) N_mean *=-1; // Determine about the minimal distance by considering the distances to both triangles for(unsigned int i_TetNode = 0 ; i_TetNode < 4 ; i_TetNode++) { ElementalDistances[i_TetNode] = PointDistanceToPlane(P_mean, N_mean, i_fluid_Element->GetGeometry()[i_TetNode] ); } // ################################################# unsigned int numberDoubleCutEdges = 0; unsigned int indexDoubleCutEdge = 0; // figure out the edges which are cut more than once for(unsigned int i_TetEdge = 0 ; i_TetEdge < IntersectedTetEdges.size() ; i_TetEdge++) { unsigned int NumberIntNodes = IntersectedTetEdges[i_TetEdge].IntNodes.size(); if(NumberIntNodes == 2) { numberDoubleCutEdges++; indexDoubleCutEdge = i_TetEdge; } } if((numberDoubleCutEdges >= 1)) { array_1d<double,3> normal_1 = IntersectedTetEdges[indexDoubleCutEdge].IntNodes[0].StructElemNormal; array_1d<double,3> normal_2 = IntersectedTetEdges[indexDoubleCutEdge].IntNodes[1].StructElemNormal; // normalize normals normal_1 /= norm_2(normal_1); normal_2 /= norm_2(normal_2); const double pi = 3.1415926; // compute angle between normals double angle_n1n2 = acos( inner_prod(normal_1,normal_2) ); // rad --> degree angle_n1n2 *= 180 / pi; // if angle between -60º and 120º, take the mean if( (angle_n1n2 > -60) && (angle_n1n2 < 120) ) { // take the mean of the normals N_mean = 0.5 * (normal_1 + normal_2); } else { N_mean = 0.5 * (normal_1 - normal_2); } // Based on N_mean and P_mean compute the distances to that plane for(unsigned int i_TetNode = 0 ; i_TetNode < 4 ; i_TetNode++) { ElementalDistances[i_TetNode] = PointDistanceToPlane(P_mean, N_mean, i_fluid_Element->GetGeometry()[i_TetNode] ); } } } ///****************************************************************************************************************** ///****************************************************************************************************************** /** * This function calculates the distance of a 3D point to a plane spanned by a 3D triangle * @param Plane base point * @param planeNormal * @param ToPoint The point which distance is required * @return The distance between the point and the plane spanned by the 3D triangle */ double PointDistanceToPlane( Point& planeBasePoint, array_1d<double, 3>& planeNormal, Point& ToPoint) { // calculate vector pointing from a node in the plane (e.g. triangle point 1) to the considered node ToPoint array_1d<double,3> planeToPointVec = ToPoint - planeBasePoint; // projection of node on the plane const double sn = inner_prod(planeToPointVec,planeNormal); const double sd = inner_prod(planeNormal,planeNormal); double DistanceToPlane = sn / sqrt(sd); if( fabs(DistanceToPlane) < epsilon ) DistanceToPlane = 0; return DistanceToPlane; } ///****************************************************************************************************************** ///****************************************************************************************************************** void AssignMinimalNodalDistance() { // loop over all fluid Elements for( ModelPart::ElementIterator i_fluid_Element = mrFluidModelPart.ElementsBegin(); i_fluid_Element != mrFluidModelPart.ElementsEnd(); i_fluid_Element++) { Geometry< Node<3> >& geom = i_fluid_Element->GetGeometry(); const Vector& ElementalDistances = i_fluid_Element->GetValue(ELEMENTAL_DISTANCES); // Assign distances to the single nodes, if a smaller value is found for( unsigned int i_TetNode = 0; i_TetNode < 4; i_TetNode++ ) { double currentNodeDist = geom[i_TetNode].GetSolutionStepValue(DISTANCE); double nodeInElemDist = ElementalDistances[i_TetNode]; if( fabs( nodeInElemDist ) < fabs( currentNodeDist ) ) geom[i_TetNode].GetSolutionStepValue(DISTANCE) = nodeInElemDist; // overwrite nodal distance (which is global) } // loop i_TetNode } // loop i_fluidElement } ///****************************************************************************************************************** ///****************************************************************************************************************** /** * If structure directly passes through the corner point of a tetrahedra (leading to zero distances * in the respective node), then a small distance value (different from zero) will be stored for * that point. This is necessary since the embedded solver cannot handle zero distances. * @param Element current Element which was cut by the structure (flag SPLIT_ELEMENT is set to one) * @param ElementalDistances Elemental distances calculated by the intersection pattern */ void AvoidZeroDistances( ModelPart::ElementsContainerType::iterator& Element, array_1d<double,4>& ElementalDistances) { // Assign a distance limit double dist_limit = 1e-5; // bool distChangedToLimit = false; //variable to indicate that a distance value < tolerance is set to a limit distance = tolerance // // for(unsigned int i_node = 0; i_node < 4; i_node++) // { // if(fabs(ElementalDistances[i_node]) < dist_limit) // { // ElementalDistances[i_node] = dist_limit; // distChangedToLimit = true; // } // } // // // Check, if this approach changes the split-flag (might be, that Element is not cut anymore if node with zero distance gets a positive limit distance value // unsigned int numberNodesPositiveDistance = 0; // for(unsigned int i_node = 0; i_node < 4; i_node++) // { // if((ElementalDistances[i_node]) > 0) // numberNodesPositiveDistance++; // } for(unsigned int i_node = 0; i_node < 4; i_node++) { double & di = ElementalDistances[i_node]; if(fabs(di) < dist_limit) { if(di >= 0) di = dist_limit; else di = -dist_limit; } } // Element is not set // if(numberNodesPositiveDistance == 4 && distChangedToLimit == true) // Element->GetValue(SPLIT_ELEMENT) = false; } ///****************************************************************************************************************** ///****************************************************************************************************************** void GenerateSkinModelPart( ModelPart& mrNewSkinModelPart ) { unsigned int id_node = mrFluidModelPart.NumberOfNodes() + 1; unsigned int id_condition = mrFluidModelPart.NumberOfConditions() + 1; mrNewSkinModelPart.Nodes().reserve(mrFluidModelPart.Nodes().size()); mrNewSkinModelPart.Conditions().reserve(mrFluidModelPart.Elements().size()); for(ModelPart::ElementIterator i_fluid_element = mrFluidModelPart.ElementsBegin(); i_fluid_element != mrFluidModelPart.ElementsEnd(); i_fluid_element++) { bool is_split = i_fluid_element->Is(TO_SPLIT); if(is_split == true) { const Vector& distances = i_fluid_element->GetValue(ELEMENTAL_DISTANCES); Geometry< Node<3> >& geom = i_fluid_element->GetGeometry(); // generate the points on the edges at the zero of the distance function std::vector< Point > edge_points; edge_points.reserve(4); // loop over all 6 edges of the tetrahedra for(unsigned int i=0; i<3; i++) { for(unsigned int j=i+1; j<4; j++) // go through the edges 01, 02, 03, 12, 13, 23 { double di = distances[i]; double dj = distances[j]; if(di*dj < 0) //edge is cut { // generate point on edge by linear interpolation double Ni = fabs(dj) / ( fabs(di) + fabs(dj) ); double Nj = 1.0 - Ni; Point edge_point(Ni * geom[i] + Nj * geom[j]); edge_points.push_back(edge_point); } } } // three intersection nodes if(edge_points.size() == 3) { // ######## ADDING NEW NODE ######### Node < 3 >::Pointer pnode1 = mrNewSkinModelPart.CreateNewNode(id_node++,edge_points[0].X(),edge_points[0].Y(),edge_points[0].Z()); Node < 3 >::Pointer pnode2 = mrNewSkinModelPart.CreateNewNode(id_node++,edge_points[1].X(),edge_points[1].Y(),edge_points[1].Z()); Node < 3 >::Pointer pnode3 = mrNewSkinModelPart.CreateNewNode(id_node++,edge_points[2].X(),edge_points[2].Y(),edge_points[2].Z()); // ######## ADDING NEW CONDITION ######### //form a triangle Triangle3D3< Node<3> > triangle(pnode1, pnode2, pnode3); Condition const& rReferenceCondition = KratosComponents<Condition>::Get("Condition3D"); Properties::Pointer properties = mrNewSkinModelPart.rProperties()(0); Condition::Pointer p_condition = rReferenceCondition.Create(id_condition++, triangle, properties); mrNewSkinModelPart.Conditions().push_back(p_condition); } // four intersection nodes if(edge_points.size() == 4) { //form a quadrilatera with the 4 cut nodes array_1d<double,3> x21 = edge_points[1] - edge_points[0]; array_1d<double,3> x31 = edge_points[2] - edge_points[0]; array_1d<double,3> x41 = edge_points[3] - edge_points[0]; //define a vector oriented as x21 array_1d<double,3> v1 = x21 / norm_2(x21); BoundedMatrix<double,4,3> DN_DX; array_1d<double,4> msN; double Area; GeometryUtils::CalculateGeometryData( geom, DN_DX, msN, Area ); array_1d<double,3> n = prod(trans(DN_DX),distances); n /= norm_2(n); array_1d<double,3> v2; MathUtils<double>::CrossProduct(v2,v1,n); // v2 = v1 x n array_1d<double,3> angles; angles[0] = 0.0; //angle between x21 and v1 angles[1] = atan2( inner_prod(x31,v2), inner_prod(x31,v1) ); //angle between x31 and v1 angles[2] = atan2( inner_prod(x41,v2), inner_prod(x41,v1) ); //angle between x31 and v1 double max_angle = 0.0; double min_angle = 0.0; unsigned int min_pos = 1; unsigned int max_pos = 1; for(unsigned int i=1; i<3; i++) { if(angles[i] < min_angle) { min_pos = i+1; //this is the local index of the edge point which forms the minimal angle min_angle = angles[i]; } else if(angles[i] > max_angle) { max_pos = i+1; //this is the local index of the edge point which forms the maximal angle max_angle = angles[i]; } } //find the pos of the center node unsigned int center_pos = 0; for(unsigned int i=1; i<4; i++) { if((i!= min_pos) && (i!=max_pos)) { center_pos = i; } } // ######## ADDING NEW NODE ######### Node < 3 >::Pointer pnode1 = mrNewSkinModelPart.CreateNewNode(id_node++,edge_points[0].X(),edge_points[0].Y(),edge_points[0].Z()); Node < 3 >::Pointer pnode2 = mrNewSkinModelPart.CreateNewNode(id_node++,edge_points[min_pos].X(),edge_points[min_pos].Y(),edge_points[min_pos].Z()); Node < 3 >::Pointer pnode3 = mrNewSkinModelPart.CreateNewNode(id_node++,edge_points[center_pos].X(),edge_points[center_pos].Y(),edge_points[center_pos].Z()); Node < 3 >::Pointer pnode4 = mrNewSkinModelPart.CreateNewNode(id_node++,edge_points[max_pos].X(),edge_points[max_pos].Y(),edge_points[max_pos].Z()); // ######## ADDING NEW CONDITION ######### //form two triangles Triangle3D3< Node<3> > triangle1(pnode1, pnode2, pnode3); Triangle3D3< Node<3> > triangle2(pnode1, pnode3, pnode4); Condition const& rReferenceCondition = KratosComponents<Condition>::Get("Condition3D"); Properties::Pointer properties = mrNewSkinModelPart.rProperties()(0); Condition::Pointer p_condition1 = rReferenceCondition.Create(id_condition++, triangle1, properties); Condition::Pointer p_condition2 = rReferenceCondition.Create(id_condition++, triangle2, properties); mrNewSkinModelPart.Conditions().push_back(p_condition1); mrNewSkinModelPart.Conditions().push_back(p_condition2); } } } } ///****************************************************************************************************************** ///****************************************************************************************************************** void GenerateOctree() { Timer::Start("Generating Octree"); //std::cout << "Generating the Octree..." << std::endl; auto temp_octree = Kratos::make_shared<OctreeType>(); //OctreeType::Pointer temp_octree = OctreeType::Pointer(new OctreeType() ); mpOctree.swap(temp_octree); double low[3]; double high[3]; for (int i = 0 ; i < 3; i++) { low[i] = high[i] = mrFluidModelPart.NodesBegin()->Coordinates()[i]; } // loop over all nodes in the bounding box for(ModelPart::NodeIterator i_node = mrFluidModelPart.NodesBegin(); i_node != mrFluidModelPart.NodesEnd(); i_node++) { const array_1d<double,3>& r_coordinates = i_node->Coordinates(); for (int i = 0 ; i < 3; i++) { low[i] = r_coordinates[i] < low[i] ? r_coordinates[i] : low[i]; high[i] = r_coordinates[i] > high[i] ? r_coordinates[i] : high[i]; } } // loop over all skin nodes for(ModelPart::NodeIterator i_node = mrSkinModelPart.NodesBegin(); i_node != mrSkinModelPart.NodesEnd(); i_node++) { const array_1d<double,3>& r_coordinates = i_node->Coordinates(); for (int i = 0 ; i < 3; i++) { low[i] = r_coordinates[i] < low[i] ? r_coordinates[i] : low[i]; high[i] = r_coordinates[i] > high[i] ? r_coordinates[i] : high[i]; } } mpOctree->SetBoundingBox(low,high); //mpOctree->RefineWithUniformSize(0.0625); // loop over all structure nodes for(ModelPart::NodeIterator i_node = mrSkinModelPart.NodesBegin(); i_node != mrSkinModelPart.NodesEnd(); i_node++) { double temp_point[3]; temp_point[0] = i_node->X(); temp_point[1] = i_node->Y(); temp_point[2] = i_node->Z(); mpOctree->Insert(temp_point); } //mpOctree->Constrain2To1(); // To be removed. Pooyan. // loop over all structure elements for(ModelPart::ElementIterator i_element = mrSkinModelPart.ElementsBegin(); i_element != mrSkinModelPart.ElementsEnd(); i_element++) { mpOctree->Insert(*(i_element).base()); } Timer::Stop("Generating Octree"); // KRATOS_WATCH(mpOctree); // std::cout << "######## WRITING OCTREE MESH #########" << std::endl; // std::ofstream myfile; // myfile.open ("octree.post.msh"); // mpOctree.PrintGiDMesh(myfile); // myfile.close(); //std::cout << "Generating the Octree finished" << std::endl; } ///****************************************************************************************************************** ///****************************************************************************************************************** void GenerateNodes() { Timer::Start("Generating Nodes"); std::vector<OctreeType::cell_type*> all_leaves; mpOctree->GetAllLeavesVector(all_leaves); int leaves_size = all_leaves.size(); #pragma omp parallel for for (int i = 0; i < leaves_size; i++) { *(all_leaves[i]->pGetDataPointer()) = ConfigurationType::AllocateData(); } std::size_t last_id = mrBodyModelPart.NumberOfNodes() + 1; for (std::size_t i = 0; i < all_leaves.size(); i++) { CellType* cell = all_leaves[i]; GenerateCellNode(cell, last_id); } Timer::Stop("Generating Nodes"); } ///****************************************************************************************************************** ///****************************************************************************************************************** void GenerateCellNode(CellType* pCell, std::size_t& LastId) { for (int i_pos=0; i_pos < 8; i_pos++) // position 8 is for center { DistanceSpatialContainersConfigure::cell_node_data_type* p_node = (*(pCell->pGetData()))[i_pos]; if(p_node == 0) { (*(pCell->pGetData()))[i_pos] = new DistanceSpatialContainersConfigure::cell_node_data_type; (*(pCell->pGetData()))[i_pos]->Id() = LastId++; mOctreeNodes.push_back((*(pCell->pGetData()))[i_pos]); SetNodeInNeighbours(pCell,i_pos,(*(pCell->pGetData()))[i_pos]); } } } ///****************************************************************************************************************** ///****************************************************************************************************************** void SetNodeInNeighbours(CellType* pCell, int Position, CellNodeDataType* pNode) { CellType::key_type point_key[3]; pCell->GetKey(Position, point_key); for (std::size_t i_direction = 0; i_direction < 8; i_direction++) { CellType::key_type neighbour_key[3]; if (pCell->GetNeighbourKey(Position, i_direction, neighbour_key)) { CellType* neighbour_cell = mpOctree->pGetCell(neighbour_key); if (!neighbour_cell || (neighbour_cell == pCell)) continue; std::size_t position = neighbour_cell->GetLocalPosition(point_key); if((*neighbour_cell->pGetData())[position]) { std::cout << "ERROR!! Bad Position calculated!!!!!!!!!!! position :" << position << std::endl; continue; } (*neighbour_cell->pGetData())[position] = pNode; } } } ///****************************************************************************************************************** ///****************************************************************************************************************** void CalculateDistance2() { Timer::Start("Calculate Distances2"); ModelPart::NodesContainerType::ContainerType& nodes = mrFluidModelPart.NodesArray(); int nodes_size = nodes.size(); // // first of all we reset the node distance to 1.00 which is the maximum distnace in our normalized space. //#pragma omp parallel for firstprivate(nodes_size) // for(int i = 0 ; i < nodes_size ; i++) // nodes[i]->GetSolutionStepValue(DISTANCE) = 1.00; std::vector<CellType*> leaves; mpOctree->GetAllLeavesVector(leaves); //int leaves_size = leaves.size(); // for(int i = 0 ; i < leaves_size ; i++) // CalculateNotEmptyLeavesDistance(leaves[i]); #pragma omp parallel for firstprivate(nodes_size) for(int i = 0 ; i < nodes_size ; i++) { CalculateNodeDistance(*(nodes[i])); } Timer::Stop("Calculate Distances2"); } ///****************************************************************************************************************** ///****************************************************************************************************************** // void CalculateDistance3() // { // Timer::Start("Calculate Distances2"); // ModelPart::NodesContainerType::ContainerType& nodes = mrFluidModelPart.NodesArray(); // int nodes_size = nodes.size(); //// // first of all we reset the node distance to 1.00 which is the maximum distnace in our normalized space. //#pragma omp parallel for firstprivate(nodes_size) // for(int i = 0 ; i < nodes_size ; i++) // nodes[i]->GetSolutionStepValue(DISTANCE) = 1.00; // std::vector<CellType*> leaves; // mpOctree->GetAllLeavesVector(leaves); // int leaves_size = leaves.size(); // for(int i = 0 ; i < leaves_size ; i++) // CalculateNotEmptyLeavesDistance(leaves[i]); //#pragma omp parallel for firstprivate(nodes_size) // for(int i = 0 ; i < nodes_size ; i++) // { // CalculateNodeDistance(*(nodes[i])); // } // Timer::Stop("Calculate Distances2"); // } // void CalculateDistance4() // { // Timer::Start("Calculate Distances3"); // ModelPart::NodesContainerType::ContainerType& nodes = mrFluidModelPart.NodesArray(); // int nodes_size = nodes.size(); // std::vector<CellType*> leaves; // mpOctree->GetAllLeavesVector(leaves); // int leaves_size = leaves.size(); //#pragma omp parallel for firstprivate(nodes_size) // for(int i = 0 ; i < nodes_size ; i++) // { // CalculateNodeDistanceFromCell(*(nodes[i])); // } // Timer::Stop("Calculate Distances3"); // } void CalculateDistance() { Timer::Start("Calculate Distances"); DistanceSpatialContainersConfigure::data_type& nodes = mOctreeNodes; int nodes_size = nodes.size(); // first of all we reste the node distance to 1.00 which is the maximum distnace in our normalized space. #pragma omp parallel for firstprivate(nodes_size) for(int i = 0 ; i < nodes_size ; i++) nodes[i]->Distance() = 1.00; std::vector<CellType*> leaves; mpOctree->GetAllLeavesVector(leaves); int leaves_size = leaves.size(); for(int i = 0 ; i < leaves_size ; i++) CalculateNotEmptyLeavesDistance(leaves[i]); for(int i_direction = 0 ; i_direction < 1 ; i_direction++) { //#pragma omp parallel for firstprivate(nodes_size) for(int i = 0 ; i < nodes_size ; i++) { if(nodes[i]->X() < 1.00 && nodes[i]->Y() < 1.00 && nodes[i]->Z() < 1.00) // if((*nodes[i])[i_direction] == 0.00) CalculateDistance(*(nodes[i]), i_direction); } } Timer::Stop("Calculate Distances"); } void CalculateDistance(CellNodeDataType& rNode, int i_direction) { double coords[3] = {rNode.X(), rNode.Y(), rNode.Z()}; // KRATOS_WATCH_3(coords); //This function must color the positions in space defined by 'coords'. //coords is of dimension (3) normalized in (0,1)^3 space typedef Element::GeometryType triangle_type; typedef std::vector<std::pair<double, triangle_type*> > intersections_container_type; intersections_container_type intersections; DistanceSpatialContainersConfigure::data_type nodes_array; const double epsilon = 1e-12; double distance = 1.0; // Creating the ray double ray[3] = {coords[0], coords[1], coords[2]}; mpOctree->NormalizeCoordinates(ray); ray[i_direction] = 0; // starting from the lower extreme // KRATOS_WATCH_3(ray) GetIntersectionsAndNodes(ray, i_direction, intersections, nodes_array); // KRATOS_WATCH(nodes_array.size()) for (std::size_t i_node = 0; i_node < nodes_array.size() ; i_node++) { double coord = (*nodes_array[i_node])[i_direction]; // KRATOS_WATCH(intersections.size()); int ray_color= 1; std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin(); while (i_intersection != intersections.end()) { double d = coord - i_intersection->first; if (d > epsilon) { ray_color = -ray_color; distance = d; } else if (d > -epsilon) {//interface distance = 0.00; break; } else { if(distance > -d) distance = -d; break; } i_intersection++; } distance *= ray_color; double& node_distance = nodes_array[i_node]->Distance(); if(fabs(distance) < fabs(node_distance)) node_distance = distance; else if (distance*node_distance < 0.00) // assigning the correct sign node_distance = -node_distance; } } void CalculateNotEmptyLeavesDistance(CellType* pCell) { //typedef Element::GeometryType triangle_type; typedef OctreeType::cell_type::object_container_type object_container_type; object_container_type* objects = (pCell->pGetObjects()); // There are no intersection in empty cells if (objects->empty()) return; for (int i_pos=0; i_pos < 8; i_pos++) // position 8 is for center { double distance = 1.00; // maximum distance is 1.00 for(object_container_type::iterator i_object = objects->begin(); i_object != objects->end(); i_object++) { CellType::key_type keys[3]; pCell->GetKey(i_pos,keys); double cell_point[3]; mpOctree->CalculateCoordinates(keys,cell_point); double d = GeometryUtils::PointDistanceToTriangle3D((*i_object)->GetGeometry()[0], (*i_object)->GetGeometry()[1], (*i_object)->GetGeometry()[2], Point(cell_point[0], cell_point[1], cell_point[2])); if(d < distance) distance = d; } double& node_distance = (*(pCell->pGetData()))[i_pos]->Distance(); if(distance < node_distance) node_distance = distance; } } void CalculateNodeDistance(Node<3>& rNode) { double coord[3] = {rNode.X(), rNode.Y(), rNode.Z()}; double distance = DistancePositionInSpace(coord); double& node_distance = rNode.GetSolutionStepValue(DISTANCE); //const double epsilon = 1.00e-12; //if(fabs(node_distance) > fabs(distance)) // node_distance = distance; /*else*/ if (distance*node_distance < 0.00) // assigning the correct sign node_distance = -node_distance; } // void CalculateNodeDistanceFromCell(Node<3>& rNode) // { // OctreeType::key_type node_key[3] = {octree->CalcKeyNormalized(rNode.X()), octree->CalcKeyNormalized(rNode.Y()), octree->CalcKeyNormalized(rNode.Z())}; // OctreeType::cell_type* pcell = octree->pGetCell(node_key); // object_container_type* objects = (pCell->pGetObjects()); // // We interpolate the cell distances for the node in empty cells // if (objects->empty()) // { // } // double distance = DistancePositionInSpace(coord); // double& node_distance = rNode.GetSolutionStepValue(DISTANCE); // //const double epsilon = 1.00e-12; // if(fabs(node_distance) > fabs(distance)) // node_distance = distance; // else if (distance*node_distance < 0.00) // assigning the correct sign // node_distance = -node_distance; // } double DistancePositionInSpace(double* coords) { //This function must color the positions in space defined by 'coords'. //coords is of dimension (3) normalized in (0,1)^3 space typedef Element::GeometryType triangle_type; typedef std::vector<std::pair<double, triangle_type*> > intersections_container_type; intersections_container_type intersections; const int dimension = 3; const double epsilon = 1e-12; double distances[3] = {1.0, 1.0, 1.0}; for (int i_direction = 0; i_direction < dimension; i_direction++) { // Creating the ray double ray[3] = {coords[0], coords[1], coords[2]}; mpOctree->NormalizeCoordinates(ray); ray[i_direction] = 0; // starting from the lower extreme GetIntersections(ray, i_direction, intersections); // if(intersections.size() == 1) // KRATOS_WATCH_3(ray) // KRATOS_WATCH(intersections.size()); int ray_color= 1; std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin(); while (i_intersection != intersections.end()) { double d = coords[i_direction] - i_intersection->first; if (d > epsilon) { ray_color = -ray_color; distances[i_direction] = d; // if(distances[i_direction] > d) // I think this is redundunt. Pooyan. // { // if(ray_color > 0.00) // distances[i_direction] = d; // else // distances[i_direction] = -d; // } } else if (d > -epsilon) {//interface distances[i_direction] = 0.00; break; } else { if(distances[i_direction] > -d) distances[i_direction] = -d; break; } i_intersection++; } distances[i_direction] *= ray_color; } // if(distances[0]*distances[1] < 0.00 || distances[2]*distances[1] < 0.00) // KRATOS_WATCH_3(distances); //#ifdef _DEBUG // std::cout << "colors : " << colors[0] << ", " << colors[1] << ", " << colors[2] << std::endl; //#endif double distance = (fabs(distances[0]) > fabs(distances[1])) ? distances[1] : distances[0]; distance = (fabs(distance) > fabs(distances[2])) ? distances[2] : distance; return distance; } void GetIntersectionsAndNodes(double* ray, int direction, std::vector<std::pair<double,Element::GeometryType*> >& intersections, DistanceSpatialContainersConfigure::data_type& rNodesArray) { //This function passes the ray through the model and gives the hit point to all objects in its way //ray is of dimension (3) normalized in (0,1)^3 space // direction can be 0,1,2 which are x,y and z respectively const double epsilon = 1.00e-12; // first clearing the intersections points vector intersections.clear(); //OctreeType* octree = &mOctree; OctreeType* octree = mpOctree.get(); OctreeType::key_type ray_key[3] = {octree->CalcKeyNormalized(ray[0]), octree->CalcKeyNormalized(ray[1]), octree->CalcKeyNormalized(ray[2])}; OctreeType::key_type cell_key[3]; // getting the entrance cell from lower extreme ray_key[direction] = 0; OctreeType::cell_type* cell = octree->pGetCell(ray_key); while (cell) { std::size_t position = cell->GetLocalPosition(ray_key); // Is this the local position!?!?!?! OctreeType::key_type node_key[3]; cell->GetKey(position, node_key); if((node_key[0] == ray_key[0]) && (node_key[1] == ray_key[1]) && (node_key[2] == ray_key[2])) { if(cell->pGetData()) { if(cell->pGetData()->size() > position) { CellNodeDataType* p_node = (*cell->pGetData())[position]; if(p_node) { //KRATOS_WATCH(p_node->Id()) rNodesArray.push_back(p_node); } } else KRATOS_WATCH(cell->pGetData()->size()) } } // std::cout << "."; GetCellIntersections(cell, ray, ray_key, direction, intersections); // Add the cell's middle node if existed // cell->GetKey(8, cell_key); // 8 is the central position // ray_key[direction]=cell_key[direction]; // positioning the ray in the middle of cell in its direction // position = cell->GetLocalPosition(ray_key); // if(position < 27) // principal nodes // { // if(cell->pGetData()) // { // if(cell->pGetData()->size() > position) // { // Node<3>* p_node = (*cell->pGetData())[position]; // if(p_node) // { // //KRATOS_WATCH(p_node->Id()) // rNodesArray.push_back(p_node); // } // } // else // KRATOS_WATCH(cell->pGetData()->size()) // } // } // else // { // KRATOS_WATCH(position); // KRATOS_WATCH(*cell); // } // go to the next cell if (cell->GetNeighbourKey(1 + direction * 2, cell_key)) { ray_key[direction] = cell_key[direction]; cell = octree->pGetCell(ray_key); ray_key[direction] -= 1 ;//the key returned by GetNeighbourKey is inside the cell (minkey +1), to ensure that the corresponding //cell get in pGetCell is the right one. //#ifdef _DEBUG // Octree_Pooyan::key_type min_key[3]; // cell->GetMinKey(min_key[0],min_key[1],min_key[2]); // Octree_Pooyan::key_type tmp; // tmp= min_key[direction]; // assert(ray_key[direction]==tmp); //#endif } else cell = NULL; } // KRATOS_WATCH(rNodesArray.size()); // now eliminating the repeated objects if (!intersections.empty()) { //sort std::sort(intersections.begin(), intersections.end()); // unique std::vector<std::pair<double, Element::GeometryType*> >::iterator i_begin = intersections.begin(); std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin(); while (++i_begin != intersections.end()) { // considering the very near points as the same points if (fabs(i_begin->first - i_intersection->first) > epsilon) // if the hit points are far enough they are not the same *(++i_intersection) = *i_begin; } intersections.resize((++i_intersection) - intersections.begin()); } } void GetIntersections(double* ray, int direction, std::vector<std::pair<double,Element::GeometryType*> >& intersections) { //This function passes the ray through the model and gives the hit point to all objects in its way //ray is of dimension (3) normalized in (0,1)^3 space // direction can be 0,1,2 which are x,y and z respectively const double epsilon = 1.00e-12; // first clearing the intersections points vector intersections.clear(); //OctreeType* octree = &mOctree; OctreeType* octree = mpOctree.get(); OctreeType::key_type ray_key[3] = {octree->CalcKeyNormalized(ray[0]), octree->CalcKeyNormalized(ray[1]), octree->CalcKeyNormalized(ray[2])}; OctreeType::key_type cell_key[3]; // getting the entrance cell from lower extreme OctreeType::cell_type* cell = octree->pGetCell(ray_key); while (cell) { // std::cout << "."; GetCellIntersections(cell, ray, ray_key, direction, intersections); // go to the next cell if (cell->GetNeighbourKey(1 + direction * 2, cell_key)) { ray_key[direction] = cell_key[direction]; cell = octree->pGetCell(ray_key); ray_key[direction] -= 1 ;//the key returned by GetNeighbourKey is inside the cell (minkey +1), to ensure that the corresponding //cell get in pGetCell is the right one. //#ifdef _DEBUG // Octree_Pooyan::key_type min_key[3]; // cell->GetMinKey(min_key[0],min_key[1],min_key[2]); // Octree_Pooyan::key_type tmp; // tmp= min_key[direction]; // assert(ray_key[direction]==tmp); //#endif } else cell = NULL; } // now eliminating the repeated objects if (!intersections.empty()) { //sort std::sort(intersections.begin(), intersections.end()); // unique std::vector<std::pair<double, Element::GeometryType*> >::iterator i_begin = intersections.begin(); std::vector<std::pair<double, Element::GeometryType*> >::iterator i_intersection = intersections.begin(); while (++i_begin != intersections.end()) { // considering the very near points as the same points if (fabs(i_begin->first - i_intersection->first) > epsilon) // if the hit points are far enough they are not the same *(++i_intersection) = *i_begin; } intersections.resize((++i_intersection) - intersections.begin()); } } int GetCellIntersections(OctreeType::cell_type* cell, double* ray, OctreeType::key_type* ray_key, int direction, std::vector<std::pair<double, Element::GeometryType*> >& intersections) { //This function passes the ray through the cell and gives the hit point to all objects in its way //ray is of dimension (3) normalized in (0,1)^3 space // direction can be 0,1,2 which are x,y and z respectively //typedef Element::GeometryType triangle_type; typedef OctreeType::cell_type::object_container_type object_container_type; object_container_type* objects = (cell->pGetObjects()); // There are no intersection in empty cells if (objects->empty()) return 0; // std::cout << "X"; // calculating the two extreme of the ray segment inside the cell double ray_point1[3] = {ray[0], ray[1], ray[2]}; double ray_point2[3] = {ray[0], ray[1], ray[2]}; double normalized_coordinate; mpOctree->CalculateCoordinateNormalized(ray_key[direction], normalized_coordinate); ray_point1[direction] = normalized_coordinate; ray_point2[direction] = ray_point1[direction] + mpOctree->CalcSizeNormalized(cell); mpOctree->ScaleBackToOriginalCoordinate(ray_point1); mpOctree->ScaleBackToOriginalCoordinate(ray_point2); for (object_container_type::iterator i_object = objects->begin(); i_object != objects->end(); i_object++) { double intersection[3]={0.00,0.00,0.00}; int is_intersected = IntersectionTriangleSegment((*i_object)->GetGeometry(), ray_point1, ray_point2, intersection); // This intersection has to be optimized for axis aligned rays if (is_intersected == 1) // There is an intersection but not coplanar intersections.push_back(std::pair<double, Element::GeometryType*>(intersection[direction], &((*i_object)->GetGeometry()))); //else if(is_intersected == 2) // coplanar case } return 0; } int IntersectionTriangleSegment(Element::GeometryType& rGeometry, double* RayPoint1, double* RayPoint2, double* IntersectionPoint) { // This is the adaption of the implemnetation provided in: // http://www.softsurfer.com/Archive/algorithm_0105/algorithm_0105.htm#intersect_RayTriangle() const double epsilon = 1.00e-12; array_1d<double,3> u, v, n; // triangle vectors array_1d<double,3> dir, w0, w; // ray vectors double r, a, b; // params to calc ray-plane intersect // get triangle edge vectors and plane normal u = rGeometry[1] - rGeometry[0]; v = rGeometry[2] - rGeometry[0]; MathUtils<double>::CrossProduct(n, u, v); // cross product if (norm_2(n) == 0) // triangle is degenerate return -1; // do not deal with this case double triangle_origin_distance = -inner_prod(n, rGeometry[0]); Point ray_point_1, ray_point_2; for(int i = 0 ; i < 3 ; i++) { dir[i] = RayPoint2[i] - RayPoint1[i]; // ray direction vector w0[i] = RayPoint1[i] - rGeometry[0][i]; ray_point_1[i] = RayPoint1[i]; ray_point_2[i] = RayPoint2[i]; } double sign_distance_1 = inner_prod(n, ray_point_1) + triangle_origin_distance; double sign_distance_2 = inner_prod(n, ray_point_2) + triangle_origin_distance; if (sign_distance_1*sign_distance_2 > epsilon) // segment line point on the same side of plane return 0; a = -inner_prod(n,w0); b = inner_prod(n,dir); if (fabs(b) < epsilon) { // ray is parallel to triangle plane if (a == 0) // ray lies in triangle plane return 2; else return 0; // ray disjoint from plane } // get intersect point of ray with triangle plane r = a / b; if (r < 0.0) // ray goes away from triangle return 0; // => no intersect // for a segment, also test if (r > 1.0) => no intersect for(int i = 0 ; i < 3 ; i++) IntersectionPoint[i] = RayPoint1[i] + r * dir[i]; // intersect point of ray and plane // is I inside T? double uu, uv, vv, wu, wv, D; uu = inner_prod(u,u); uv = inner_prod(u,v); vv = inner_prod(v,v); for(int i = 0 ; i < 3 ; i++) w[i] = IntersectionPoint[i] - rGeometry[0][i]; wu = inner_prod(w,u); wv = inner_prod(w,v); D = uv * uv - uu * vv; // get and test parametric coords double s, t; s = (uv * wv - vv * wu) / D; if (s < 0.0 - epsilon || s > 1.0 + epsilon) // I is outside T return 0; t = (uv * wu - uu * wv) / D; if (t < 0.0 - epsilon || (s + t) > 1.0 + epsilon) // I is outside T return 0; return 1; // I is in T } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "CalculateSignedDistanceTo3DSkinProcess"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "CalculateSignedDistanceTo3DSkinProcess"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { } void PrintGiDMesh(std::ostream & rOStream) const { std::vector<CellType*> leaves; mpOctree->GetAllLeavesVector(leaves); std::cout << "writing " << leaves.size() << " leaves" << std::endl; rOStream << "MESH \"leaves\" dimension 3 ElemType Hexahedra Nnode 8" << std::endl; rOStream << "# color 96 96 96" << std::endl; rOStream << "Coordinates" << std::endl; rOStream << "# node number coordinate_x coordinate_y coordinate_z " << std::endl; for(DistanceSpatialContainersConfigure::data_type::const_iterator i_node = mOctreeNodes.begin() ; i_node != mOctreeNodes.end() ; i_node++) { rOStream << (*i_node)->Id() << " " << (*i_node)->X() << " " << (*i_node)->Y() << " " << (*i_node)->Z() << std::endl; //mpOctree->Insert(temp_point); } std::cout << "Nodes written..." << std::endl; rOStream << "end coordinates" << std::endl; rOStream << "Elements" << std::endl; rOStream << "# Element node_1 node_2 node_3 material_number" << std::endl; for (std::size_t i = 0; i < leaves.size(); i++) { if ((leaves[i]->pGetData())) { DistanceSpatialContainersConfigure::data_type& nodes = (*(leaves[i]->pGetData())); rOStream << i + 1; for(int j = 0 ; j < 8 ; j++) rOStream << " " << nodes[j]->Id(); rOStream << std::endl; } } rOStream << "end Elements" << std::endl; } void PrintGiDResults(std::ostream & rOStream) const { std::vector<CellType*> leaves; mpOctree->GetAllLeavesVector(leaves); rOStream << "GiD Post Results File 1.0" << std::endl << std::endl; rOStream << "Result \"Distance\" \"Kratos\" 1 Scalar OnNodes" << std::endl; rOStream << "Values" << std::endl; for(DistanceSpatialContainersConfigure::data_type::const_iterator i_node = mOctreeNodes.begin() ; i_node != mOctreeNodes.end() ; i_node++) { rOStream << (*i_node)->Id() << " " << (*i_node)->Distance() << std::endl; } rOStream << "End Values" << std::endl; } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ModelPart& mrSkinModelPart; ModelPart& mrBodyModelPart; ModelPart& mrFluidModelPart; DistanceSpatialContainersConfigure::data_type mOctreeNodes; Kratos::shared_ptr<OctreeType> mpOctree; static const double epsilon; /** * @} */ /** * calculates the eigenvectors and eigenvalues of given symmetric matrix A. * The eigenvectors and eigenvalues are calculated using the iterative * Gauss-Seidel-method * @param A the given symmetric matrix the eigenvectors are to be calculated. * :WARNING: Matrix A will be overwritten and has to be symmetric * @param V the result matrix (will be overwritten with the eigenvectors) * @param zero_tolerance the largest value considered to be zero */ static inline void EigenVectors(const Matrix& A, Matrix& vectors, Vector& lambda, double zero_tolerance =1e-9, int max_iterations = 10) { Matrix Help= A; for(int i=0; i<3; i++) for(int j=0; j<3; j++) Help(i,j)= Help(i,j); vectors.resize(Help.size1(),Help.size2(),false); lambda.resize(Help.size1(),false); Matrix HelpDummy(Help.size1(),Help.size2()); bool is_converged = false; Matrix unity=ZeroMatrix(Help.size1(),Help.size2()); for(unsigned int i=0; i< Help.size1(); i++) unity(i,i)= 1.0; Matrix V= unity; Matrix VDummy(Help.size1(),Help.size2()); Matrix Rotation(Help.size1(),Help.size2()); for(int iterations=0; iterations<max_iterations; iterations++) { is_converged= true; double a= 0.0; unsigned int index1= 0; unsigned int index2= 1; for(unsigned int i=0; i< Help.size1(); i++) { for(unsigned int j=(i+1); j< Help.size2(); j++) { if((fabs(Help(i,j)) > a ) && (fabs(Help(i,j)) > zero_tolerance)) { a= fabs(Help(i,j)); index1= i; index2= j; is_converged= false; } } } // KRATOS_WATCH(Help); if(is_converged) break; //Calculation of Rotationangle double gamma= (Help(index2,index2)-Help(index1,index1))/(2*Help(index1,index2)); double u=1.0; if(fabs(gamma) > zero_tolerance && fabs(gamma)< (1/zero_tolerance)) { u= gamma/fabs(gamma)*1.0/(fabs(gamma)+sqrt(1.0+gamma*gamma)); } else { if (fabs(gamma)>= (1.0/zero_tolerance)) u= 0.5/gamma; } double c= 1.0/(sqrt(1.0+u*u)); double s= c*u; double teta= s/(1.0+c); //Ratotion of the Matrix HelpDummy= Help; HelpDummy(index2,index2)= Help(index2,index2)+u*Help(index1,index2); HelpDummy(index1,index1)= Help(index1,index1)-u*Help(index1,index2); HelpDummy(index1,index2)= 0.0; HelpDummy(index2,index1)= 0.0; for(unsigned int i=0; i<Help.size1(); i++) { if((i!= index1) && (i!= index2)) { HelpDummy(index2,i)=Help(index2,i)+s*(Help(index1,i)- teta*Help(index2,i)); HelpDummy(i,index2)=Help(index2,i)+s*(Help(index1,i)- teta*Help(index2,i)); HelpDummy(index1,i)=Help(index1,i)-s*(Help(index2,i)+ teta*Help(index1,i)); HelpDummy(i,index1)=Help(index1,i)-s*(Help(index2,i)+ teta*Help(index1,i)); } } Help= HelpDummy; //Calculation of the eigenvectors V Rotation =unity; Rotation(index2,index1)=-s; Rotation(index1,index2)=s; Rotation(index1,index1)=c; Rotation(index2,index2)=c; // Help=ZeroMatrix(A.size1(),A.size1()); VDummy = ZeroMatrix(Help.size1(), Help.size2()); for(unsigned int i=0; i< Help.size1(); i++) { for(unsigned int j=0; j< Help.size1(); j++) { for(unsigned int k=0; k< Help.size1(); k++) { VDummy(i,j) += V(i,k)*Rotation(k,j); } } } V= VDummy; } if(!(is_converged)) { std::cout<<"########################################################"<<std::endl; std::cout<<"Max_Iterations exceed in Jacobi-Seidel-Iteration (eigenvectors)"<<std::endl; std::cout<<"########################################################"<<std::endl; } for(unsigned int i=0; i< Help.size1(); i++) { for(unsigned int j=0; j< Help.size1(); j++) { vectors(i,j)= V(j,i); } } for(unsigned int i=0; i<Help.size1(); i++) lambda(i)= Help(i,i); return; } inline void CreatePartition(unsigned int number_of_threads, const int number_of_rows, DenseVector<unsigned int>& partitions) { partitions.resize(number_of_threads + 1); int partition_size = number_of_rows / number_of_threads; partitions[0] = 0; partitions[number_of_threads] = number_of_rows; for (unsigned int i = 1; i < number_of_threads; i++) partitions[i] = partitions[i - 1] + partition_size; } ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. CalculateSignedDistanceTo3DSkinProcess& operator=(CalculateSignedDistanceTo3DSkinProcess const& rOther); /// Copy constructor. //CalculateSignedDistanceTo3DSkinProcess(CalculateSignedDistanceTo3DSkinProcess const& rOther); ///@} }; // Class CalculateSignedDistanceTo3DSkinProcess ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream& operator >> (std::istream& rIStream, CalculateSignedDistanceTo3DSkinProcess& rThis); /// output stream function inline std::ostream& operator << (std::ostream& rOStream, const CalculateSignedDistanceTo3DSkinProcess& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} const double CalculateSignedDistanceTo3DSkinProcess::epsilon = 1e-18; } // namespace Kratos. #endif // KRATOS_CALCULATE_DISTANCE_PROCESS_H_INCLUDED defined
openmp_reorder.h
#pragma once ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename _T, typename _TIndex> void openmp_reorder_gather_inplace(_T *_result, _T *_buffer, _TIndex *_indexes, size_t _size) { if(omp_in_parallel()) { #pragma _NEC ivdep #pragma _NEC vovertake #pragma _NEC novob #pragma _NEC vector #pragma omp for for(_TIndex i = 0; i < _size; i++) { _buffer[i] = _result[_indexes[i]]; } #pragma _NEC ivdep #pragma omp for for(_TIndex i = 0; i < _size; i++) { _result[i] = _buffer[i]; } } else { #pragma omp parallel { openmp_reorder_gather_inplace(_result, _buffer, _indexes, _size); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename _T, typename _TIndex> void openmp_reorder_gather_copy(_T *_gather_from, _T *_output, _TIndex *_indexes, size_t _size) { if(omp_in_parallel()) { #pragma _NEC ivdep #pragma _NEC vovertake #pragma _NEC novob #pragma _NEC vector #pragma omp for for (_TIndex i = 0; i < _size; i++) { _output[i] = _gather_from[_indexes[i]]; } } else { #pragma omp parallel { openmp_reorder_gather_copy(_gather_from, _output, _indexes, _size); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename _T, typename _TIndex> void openmp_reorder_scatter_inplace(_T *_result, _T *_buffer, _TIndex *_indexes, size_t _size) { if(omp_in_parallel()) { #pragma _NEC ivdep #pragma _NEC vovertake #pragma _NEC novob #pragma _NEC vector #pragma omp for for(_TIndex i = 0; i < _size; i++) { _buffer[_indexes[i]] = _result[i]; } #pragma _NEC ivdep #pragma omp for for(_TIndex i = 0; i < _size; i++) { _result[i] = _buffer[i]; } } else { #pragma omp parallel { openmp_reorder_scatter_inplace(_result, _buffer, _indexes, _size); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename _T, typename _TIndex> void openmp_reorder_scatter_copy(_T *_scatter_from, _T *_output, _TIndex *_indexes, size_t _size) { if(omp_in_parallel()) { #pragma _NEC ivdep #pragma _NEC vovertake #pragma _NEC novob #pragma _NEC vector #pragma omp for for(_TIndex i = 0; i < _size; i++) { _output[_indexes[i]] = _scatter_from[i]; } } else { #pragma omp parallel { openmp_reorder_scatter_inplace(_scatter_from, _output, _indexes, _size); } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
GB_unop.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) // op(A') function: GB (_unop_tran) // C type: GB_ctype // A type: GB_atype // cast: GB_cast(cij,aij) // unaryop: GB_unaryop(cij,aij) #define GB_ATYPE \ GB_atype #define GB_CTYPE \ GB_ctype // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GB_geta(aij,Ax,pA) #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ GB_unaryop(z, x) ; // casting #define GB_CAST(z, aij) \ GB_cast(z, aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_geta(aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_cast(z, aij) ; \ GB_unaryop(Cx [pC], z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ GB_op_is_identity_with_no_typecast // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ GB_disable //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply) ( GB_ctype *Cx, // Cx and Ax may be aliased const GB_atype *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 (GB_atype), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_geta(aij, Ax, p) ; GB_cast(z, aij) ; GB_unaryop(Cx [p], z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GB_geta(aij, Ax, p) ; GB_cast(z, aij) ; GB_unaryop(Cx [p], z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran) ( 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
sample.c
/* Andre Augusto Giannotti Scota (https://sites.google.com/view/a2gs/) */ /* From line 34 onwards comes from: */ /* File: omp_hello.c * * Purpose: A parallel hello, world program that uses OpenMP * * Compile: gcc -g -Wall -fopenmp -o omp_hello omp_hello.c * Run: ./omp_hello <number of threads> * * Input: none * Output: A message from each thread * * IPP: Section 5.1 (pp. 211 and ff.) */ #include <stdio.h> #include <stdlib.h> #include <omp.h> #include "openmp_util.h" int main(int argc, char *argv[]) { int i = 0; int nthreads = 0, tid = 0; /* #pragma omp parallel num_threads(3) */ /* omp_set_num_threads(2); */ dumpEnviroment(); #pragma omp parallel for for(i = 0; i < 4; ++i){ printf("Hello World parallel for!\n"); } /* Fork a team of threads giving them their own copies of variables */ #pragma omp parallel private(nthreads, tid) { /* Obtain thread number */ tid = omp_get_thread_num(); printf("Hello World from thread = %d\n", tid); /* Only master thread does this */ if (tid == 0){ nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); } } /* All threads join master thread and disband */ return(0); }
fft-cuda.c
/* Copyright 2013, 2015. The Regents of the University of California. * Copyright 2019. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2012-2019 Martin Uecker <martin.uecker@med.uni-goettingen.de> * * * Internal interface to the CUFFT library used in fft.c. */ #include <stdbool.h> #include <complex.h> #include <assert.h> #include "misc/misc.h" #include "num/multind.h" #include "fft-cuda.h" #ifdef USE_CUDA #include <cufft.h> #include "num/gpuops.h" #ifndef CFL_SIZE #define CFL_SIZE sizeof(complex float) #endif struct fft_cuda_plan_s { cufftHandle cufft; struct fft_cuda_plan_s* chain; bool backwards; long batch; long idist; long odist; }; struct iovec { long n; long is; long os; }; static struct fft_cuda_plan_s* fft_cuda_plan0(unsigned int D, const long dimensions[D], unsigned long flags, const long ostrides[D], const long istrides[D], bool backwards) { PTR_ALLOC(struct fft_cuda_plan_s, plan); unsigned int N = D; plan->batch = 1; plan->odist = 0; plan->idist = 0; plan->backwards = backwards; plan->chain = NULL; struct iovec dims[N]; struct iovec hmdims[N]; assert(0 != flags); // the cufft interface is strange, but we do our best... unsigned int k = 0; unsigned int l = 0; for (unsigned int i = 0; i < N; i++) { if (1 == dimensions[i]) continue; if (MD_IS_SET(flags, i)) { dims[k].n = dimensions[i]; dims[k].is = istrides[i] / CFL_SIZE; dims[k].os = ostrides[i] / CFL_SIZE; k++; } else { hmdims[l].n = dimensions[i]; hmdims[l].is = istrides[i] / CFL_SIZE; hmdims[l].os = ostrides[i] / CFL_SIZE; l++; } } assert(k > 0); int cudims[k]; int cuiemb[k]; int cuoemb[k]; long batchdims[l]; long batchistr[l]; long batchostr[l]; int lis = dims[0].is; int los = dims[0].os; if (k > 3) goto errout; for (unsigned int i = 0; i < k; i++) { // assert(dims[i].is == lis); // assert(dims[i].os == los); cudims[k - 1 - i] = dims[i].n; cuiemb[k - 1 - i] = dims[i].n; cuoemb[k - 1 - i] = dims[i].n; lis = dims[i].n * dims[i].is; los = dims[i].n * dims[i].os; } for (unsigned int i = 0; i < l; i++) { batchdims[i] = hmdims[i].n; batchistr[i] = hmdims[i].is; batchostr[i] = hmdims[i].os; } int istride = dims[0].is; int ostride = dims[0].os; int idist = lis; int odist = los; int cubs = 1; // check that batch dimensions can be collapsed to one unsigned int bi = md_calc_blockdim(l, batchdims, batchistr, hmdims[0].is); unsigned int bo = md_calc_blockdim(l, batchdims, batchostr, hmdims[0].os); if (bi != bo) goto errout; if (bi > 0) { idist = hmdims[0].is; odist = hmdims[0].os; cubs = md_calc_size(bi, batchdims); } if (l != bi) { // check that batch dimensions can be collapsed to one if (l - bi != md_calc_blockdim(l - bi, batchdims + bi, batchistr + bi, hmdims[bi].is)) goto errout; if (l - bo != md_calc_blockdim(l - bo, batchdims + bo, batchostr + bo, hmdims[bo].os)) goto errout; plan->idist = hmdims[bi].is; plan->odist = hmdims[bo].os; plan->batch = md_calc_size(l - bi, batchdims + bi); } assert(k <= 3); int err; #pragma omp critical err = cufftPlanMany(&plan->cufft, k, cudims, cuiemb, istride, idist, cuoemb, ostride, odist, CUFFT_C2C, cubs); if (CUFFT_SUCCESS != err) goto errout; return PTR_PASS(plan); errout: PTR_FREE(plan); return NULL; } struct fft_cuda_plan_s* fft_cuda_plan(unsigned int D, const long dimensions[D], unsigned long flags, const long ostrides[D], const long istrides[D], bool backwards) { struct fft_cuda_plan_s* plan = fft_cuda_plan0(D, dimensions, flags, ostrides, istrides, backwards); if (NULL != plan) return plan; int lsb = ffs(flags) - 1; if (flags & lsb) { // FIXME: this couldbe better... struct fft_cuda_plan_s* plan = fft_cuda_plan0(D, dimensions, lsb, ostrides, istrides, backwards); if (NULL == plan) return NULL; plan->chain = fft_cuda_plan(D, dimensions, MD_CLEAR(flags, lsb), ostrides, ostrides, backwards); if (NULL == plan->chain) { fft_cuda_free_plan(plan); return NULL; } return plan; } return NULL; } void fft_cuda_free_plan(struct fft_cuda_plan_s* cuplan) { if (NULL != cuplan->chain) fft_cuda_free_plan(cuplan->chain); cufftDestroy(cuplan->cufft); xfree(cuplan); } void fft_cuda_exec(struct fft_cuda_plan_s* cuplan, complex float* dst, const complex float* src) { assert(cuda_ondevice(src)); assert(cuda_ondevice(dst)); assert(NULL != cuplan); int err; for (int i = 0; i < cuplan->batch; i++) { if (CUFFT_SUCCESS != (err = cufftExecC2C(cuplan->cufft, (cufftComplex*)src + i * cuplan->idist, (cufftComplex*)dst + i * cuplan->odist, (!cuplan->backwards) ? CUFFT_FORWARD : CUFFT_INVERSE))) error("CUFFT: %d\n", err); } if (NULL != cuplan->chain) fft_cuda_exec(cuplan->chain, dst, dst); } #endif
irbuilder_for_unsigned_dynamic_chunked.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=45 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-LABEL: define {{.*}}@workshareloop_unsigned_dynamic_chunked( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8 // CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4 // CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LASTITER:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LOWERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_UPPERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_STRIDE:.+]] = alloca i32, align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8 // CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8 // CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8 // CHECK-NEXT: store i32 33, i32* %[[I]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0 // CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]]) // CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER]]: // CHECK-NEXT: store i32 1, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: store i32 %[[DOTCOUNT]], i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: store i32 1, i32* %[[P_STRIDE]], align 4 // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_dispatch_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 1073741859, i32 1, i32 %[[DOTCOUNT]], i32 1, i32 5) // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER_OUTER_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_HEADER:.*]]: // CHECK-NEXT: %[[OMP_LOOP_IV:.+]] = phi i32 [ %[[LB:.+]], %[[OMP_LOOP_PREHEADER_OUTER_COND]] ], [ %[[OMP_LOOP_NEXT:.+]], %[[OMP_LOOP_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_LOOP_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_COND]]: // CHECK-NEXT: %[[UB:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: %[[OMP_LOOP_CMP:.+]] = icmp ult i32 %[[OMP_LOOP_IV]], %[[UB]] // CHECK-NEXT: br i1 %[[OMP_LOOP_CMP]], label %[[OMP_LOOP_BODY:.+]], label %[[OMP_LOOP_PREHEADER_OUTER_COND]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[OMP_LOOP_IV]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP3:.+]] = load float*, float** %[[B_ADDR]], align 8 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = zext i32 %[[TMP4]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP3]], i64 %[[IDXPROM]] // CHECK-NEXT: %[[TMP5:.+]] = load float, float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: %[[TMP6:.+]] = load float*, float** %[[C_ADDR]], align 8 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM2:.+]] = zext i32 %[[TMP7]] to i64 // CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP6]], i64 %[[IDXPROM2]] // CHECK-NEXT: %[[TMP8:.+]] = load float, float* %[[ARRAYIDX3]], align 4 // CHECK-NEXT: %[[MUL:.+]] = fmul float %[[TMP5]], %[[TMP8]] // CHECK-NEXT: %[[TMP9:.+]] = load float*, float** %[[D_ADDR]], align 8 // CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM4:.+]] = zext i32 %[[TMP10]] to i64 // CHECK-NEXT: %[[ARRAYIDX5:.+]] = getelementptr inbounds float, float* %[[TMP9]], i64 %[[IDXPROM4]] // CHECK-NEXT: %[[TMP11:.+]] = load float, float* %[[ARRAYIDX5]], align 4 // CHECK-NEXT: %[[MUL6:.+]] = fmul float %[[MUL]], %[[TMP11]] // CHECK-NEXT: %[[TMP12:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP13:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM7:.+]] = zext i32 %[[TMP13]] to i64 // CHECK-NEXT: %[[ARRAYIDX8:.+]] = getelementptr inbounds float, float* %[[TMP12]], i64 %[[IDXPROM7]] // CHECK-NEXT: store float %[[MUL6]], float* %[[ARRAYIDX8]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_INC]]: // CHECK-NEXT: %[[OMP_LOOP_NEXT]] = add nuw i32 %[[OMP_LOOP_IV]], 1 // CHECK-NEXT: br label %[[OMP_LOOP_HEADER]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_EXIT:.*]]: // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM9:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @2, i32 %[[OMP_GLOBAL_THREAD_NUM9]]) // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER_OUTER_COND]]: // CHECK-NEXT: %[[TMP14:.+]] = call i32 @__kmpc_dispatch_next_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]]) // CHECK-NEXT: %[[TMP15:.+]] = icmp ne i32 %[[TMP14]], 0 // CHECK-NEXT: %[[TMP16:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[LB]] = sub i32 %[[TMP16]], 1 // CHECK-NEXT: br i1 %[[TMP15]], label %[[OMP_LOOP_HEADER]], label %[[OMP_LOOP_EXIT]] // CHECK-NEXT: } extern "C" void workshareloop_unsigned_dynamic_chunked(float *a, float *b, float *c, float *d) { #pragma omp for schedule(dynamic, 5) for (unsigned i = 33; i < 32000000; i += 7) { a[i] = b[i] * c[i] * d[i]; } } #endif // HEADER // CHECK-LABEL: define {{.*}}@__captured_stmt( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8 // CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4 // CHECK-NEXT: store i32 32000000, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 7, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp ult i32 %[[TMP4]], %[[TMP5]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub i32 %[[TMP6]], %[[TMP7]] // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP8]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]] // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP9]] // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ] // CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define {{.*}}@__captured_stmt.1( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8 // CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: %[[MUL:.+]] = mul i32 7, %[[TMP3]] // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]] // CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 45} // CHECK: ![[META2:[0-9]+]] =
laplace_acc-omp.c
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <sys/time.h> #include "globals.h" //contains array sizes and needed externs #ifndef _JUSTOMP_ #include "functions_acc.h" #endif #ifndef _JUSTACC_ #include "functions_omp.h" #endif #if defined (_UPDATE_INTERNAL_) || defined (_ALL_INTERNAL_) #if !defined (_PGI_) && !defined (_NVCPP_) #define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) #endif #endif // smallest permitted change in temperature #define MAX_TEMP_ERROR 0.02 // Global arrays //double *restrict T_new; // temperature grid //double *restrict T; // temperature grid from last iteration // initialisation routine void init(double *restrict T, double *restrict T_new); int main(int argc, char *argv[]) { int i, j; // grid indexes int max_iterations; // maximal number of iterations int iteration=1; // iteration double dt=100; // largest change in temperature struct timeval start_time, stop_time, elapsed_time; // timers double *restrict T_new=(double*)malloc(sizeof(double)*(GRIDX+2)*(GRIDY+2)); // temperature grid double *restrict T=(double*)malloc(sizeof(double)*(GRIDX+2)*(GRIDY+2)); // temperature grid from last iteration if(argc!=2) { printf("Usage: %s number_of_iterations\n",argv[0]); exit(1); } else { max_iterations=atoi(argv[1]); } gettimeofday(&start_time,NULL); init(T,T_new); #ifndef _NOPRELOAD_ #if defined(_JUSTOMP_) || defined(_PRELOADOMP_) //#pragma omp target data map(tofrom:T) map(alloc:T_new) //:gcc11:fails in runtime: illegal memory access #pragma omp target data map(tofrom:T[:(GRIDX+2)*(GRIDY+2)]) map(alloc:T_new[:(GRIDX+2)*(GRIDY+2)]) //:gcc11:works #else //#pragma acc data copy(T) create(T_new) //:pgi:fails in compilation: error says "cannot determine bounds" //:gcc11:fails in runtime: illegal memory access #pragma acc data copy(T[:(GRIDX+2)*(GRIDY+2)]) create(T_new[:(GRIDX+2)*(GRIDY+2)]) //:pgi:works //:gcc11:works #endif #endif // simulation iterations while ( dt > MAX_TEMP_ERROR && iteration <= max_iterations ) { /*for ( iteration=1; iteration <=max_iterations; iteration++){ if (dt > MAX_TEMP_ERROR) {*/ // main computational kernel, average over neighbours in the grid #if defined (_AVERAGE_INTERNAL_) || defined (_ALL_INTERNAL_) #ifndef _JUSTOMP_ //#pragma acc kernels // #pragma acc loop independent //together with kernels above //:pgi:justacc:(internal):works (fast:only copies data outside the while) //#pragma acc parallel loop collapse(2) //:pgi:justacc:(internal):works (fast:only copies data outside the while) //:gcc11:justacc:(internal):works (fast:only copies data outside the while) //#pragma acc parallel loop copyin(T) copyout(T_new) collapse(2) //:pgi:justacc:(internal):works (fast:only copies data outside the while) //:gcc11:justacc:(internal):fails at runtime:illegal memory access #pragma acc parallel loop copyin(T[:(GRIDX+2)*(GRIDY+2)]) copyout(T_new[:(GRIDX+2)*(GRIDY+2)]) collapse(2) //:pgi:justacc:(internal):works (fast:only copies data outside the while) //:gcc11:justacc:(internal):works (fast:only copies data outside the while) //#pragma acc parallel loop pcopyin(T[:(GRIDX+2)*(GRIDY+2)]) pcopyout(T_new[:(GRIDX+2)*(GRIDY+2)]) collapse(2) //:pgi:justacc:(internal):works (fast:only copies data outside the while) //:gcc11:justacc:(internal):works (fast:only copies data outside the while) //#pragma acc parallel loop present(T) present(T_new) collapse(2) //:pgi:justacc:(internal):works (fast:only copies data outside the while) //:gcc11:justacc:(internal):fails at runtime:present clause error //#pragma acc parallel loop present(T[:(GRIDX+2)*(GRIDY+2)]) present(T_new[:(GRIDX+2)*(GRIDY+2)]) collapse(2) //:pgi:justacc:(internal):works (fast:only copies data outside the while) //:gcc11:justacc:(internal):works (fast:only copies data outside the while) #else //#pragma omp target //:gcc11:justomp:(internal):works (fast:only copies data outside the while) //#pragma omp target map(to:T) map(from:T_new) //:gcc11:justomp:(internal):fails at execution time: illegal memory access #pragma omp target map(to:T[:(GRIDX+2)*(GRIDY+2)]) map(from:T_new[:(GRIDX+2)*(GRIDY+2)]) //:gcc11:justomp:(internal):works (fast:only copies data outside the while) #pragma omp teams distribute parallel for collapse(2) private(i,j) #endif for(i = 1; i <= GRIDX; i++) #ifndef _JUSTOMP_ // #pragma acc loop independent //together with kernels above #endif for(j = 1; j <= GRIDY; j++) T_new[OFFSET(i,j)] = 0.25 * (T[OFFSET(i+1,j)] + T[OFFSET(i-1,j)] + T[OFFSET(i,j+1)] + T[OFFSET(i,j-1)]); #else #ifndef _JUSTOMP_ getAverage_acc(T,T_new); #else getAverage_omp(T,T_new); #endif #endif // reset dt dt = 0.0; // compute the largest change and copy T_new to T #if defined (_UPDATE_INTERNAL_) || (_ALL_INTERNAL_) #ifndef _JUSTACC_ //#pragma omp target map(dt) //#pragma omp target map(tofrom:T,dt) map(to:T_new) #pragma omp target map(tofrom:T[:(GRIDX+2)*(GRIDY+2)],dt) map(to:T_new[:(GRIDX+2)*(GRIDY+2)]) #pragma omp teams distribute parallel for collapse(2) reduction(max:dt) private(i,j) #else //#pragma acc kernels // #pragma acc loop independent //together with kernels above //#pragma acc parallel loop reduction(max:dt) collapse(2) //#pragma acc parallel loop copy(T) copyin(T_new) reduction(max:dt) collapse(2) #pragma acc parallel loop copy(T[:(GRIDX+2)*(GRIDY+2)]) copyin(T_new[:(GRIDX+2)*(GRIDY+2)]) reduction(max:dt) collapse(2) //#pragma acc parallel loop pcopy(T[:(GRIDX+2)*(GRIDY+2)]) pcopyin(T_new[:(GRIDX+2)*(GRIDY+2)]) reduction(max:dt) collapse(2) //#pragma acc parallel loop present(T) present(T_new) reduction(max:dt) collapse(2) //#pragma acc parallel loop present(T[:(GRIDX+2)*(GRIDY+2)]) present(T_new[:(GRIDX+2)*(GRIDY+2)]) reduction(max:dt) collapse(2) #endif for(i = 1; i <= GRIDX; i++){ #ifndef _JUSTACC_ #define papa 0 #else // #pragma acc loop independent //together with kernels above #endif for(j = 1; j <= GRIDY; j++){ #if defined (_PGI_) || defined (_NVCPP_) dt = fmax( fabs(T_new[OFFSET(i,j)]-T[OFFSET(i,j)]), dt); #else dt = MAX( fabs(T_new[OFFSET(i,j)]-T[OFFSET(i,j)]), dt); #endif T[OFFSET(i,j)] = T_new[OFFSET(i,j)]; } } #else #ifndef _JUSTACC_ dt = updateT_omp(T,T_new,dt); #else //dt = updateT_acc(GRIDX,GRIDY,T,T_new,dt); dt = updateT_acc(T,T_new,dt); #endif #endif // periodically print largest change if((iteration % 100) == 0) printf("Iteration %4.0d, dt %f\n",iteration,dt); iteration++; /*}else { break; }*/ } gettimeofday(&stop_time,NULL); timersub(&stop_time, &start_time, &elapsed_time); // measure time printf("Total time was %f seconds.\n", elapsed_time.tv_sec+elapsed_time.tv_usec/1000000.0); return 0; } // initialize grid and boundary conditions void init(double *restrict T, double *restrict T_new){ int i,j; for(i = 0; i <= GRIDX+1; i++){ for (j = 0; j <= GRIDY+1; j++){ T[OFFSET(i,j)] = 0.0; } } // these boundary conditions never change throughout run // set left side to 0 and right to a linear increase for(i = 0; i <= GRIDX+1; i++) { T[OFFSET(i,0)] = 0.0; T[OFFSET(i,GRIDY+1)] = (128.0/GRIDX)*i; } // set top to 0 and bottom to linear increase for(j = 0; j <= GRIDY+1; j++) { T[OFFSET(0,j)] = 0.0; T[OFFSET(GRIDX+1,j)] = (128.0/GRIDY)*j; } }
pem_fmt_plug.c
/* * PEM (PKCS #8) cracker. * * This software is Copyright (c) 2015, Dhiru Kholia <kholia at kth.se>, * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without modification, * are permitted. * * This code may be freely used and modified for any purpose. * * Big thanks to Martin Kleppmann, and Lapo Luchini for making this format * possible. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_pem; #elif FMT_REGISTERS_H john_register_one(&fmt_pem); #else #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 64 #endif #endif #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "pem_common.h" #include "pbkdf2_hmac_sha1.h" #include "jumbo.h" #include "memdbg.h" #define FORMAT_LABEL "PEM" #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 3DES " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 3DES 32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 0 #define PLAINTEXT_LENGTH 125 #define SALT_SIZE sizeof(*cur_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN sizeof(int) #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked, cracked_count; static struct custom_salt *cur_salt; static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); if (omp_t > 1) { self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; } #endif saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt); cracked = mem_calloc(sizeof(*cracked), self->params.max_keys_per_crypt); cracked_count = self->params.max_keys_per_crypt; } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static void PEM_set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; memset(cracked, 0, sizeof(cracked[0])*cracked_count); #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { unsigned char master[MAX_KEYS_PER_CRYPT][32]; int i; #ifdef SIMD_COEF_32 int lens[MAX_KEYS_PER_CRYPT]; unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = strlen(saved_key[index+i]); pin[i] = (unsigned char*)saved_key[index+i]; pout[i] = master[i]; } pbkdf2_sha1_sse((const unsigned char**)pin, lens, cur_salt->salt, SALTLEN, cur_salt->iterations, pout, 24, 0); #else pbkdf2_sha1((unsigned char *)saved_key[index], strlen(saved_key[index]), cur_salt->salt, SALTLEN, cur_salt->iterations, master[0], 24, 0); #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { if (pem_decrypt(master[i], cur_salt->iv, cur_salt->ciphertext, cur_salt) == 0) cracked[index+i] = 1; else cracked[index+i] = 0; } } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (cracked[index]) return 1; return 0; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static unsigned int iteration_count(void *salt) { struct custom_salt *cs = salt; return (unsigned int) cs->iterations; } struct fmt_main fmt_pem = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT, { "iteration count", }, { FORMAT_TAG }, pem_tests }, { init, done, fmt_default_reset, fmt_default_prepare, pem_valid, fmt_default_split, fmt_default_binary, pem_get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, PEM_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
draw.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD RRRR AAA W W % % D D R R A A W W % % D D RRRR AAAAA W W W % % D D R RN A A WW WW % % DDDD R R A A W W % % % % % % MagickCore Image Drawing Methods % % % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon % rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion", % Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent % (www.appligent.com) contributed the dash pattern, linecap stroking % algorithm, and minor rendering improvements. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define BezierQuantum 200 #define DrawEpsilon (1.0e-10) /* Typedef declarations. */ typedef struct _EdgeInfo { SegmentInfo bounds; double scanline; PointInfo *points; size_t number_points; ssize_t direction; MagickBooleanType ghostline; size_t highwater; } EdgeInfo; typedef struct _ElementInfo { double cx, cy, major, minor, angle; } ElementInfo; typedef struct _PolygonInfo { EdgeInfo *edges; size_t number_edges; } PolygonInfo; typedef enum { MoveToCode, OpenCode, GhostlineCode, LineToCode, EndCode } PathInfoCode; typedef struct _PathInfo { PointInfo point; PathInfoCode code; } PathInfo; /* Forward declarations. */ static MagickBooleanType DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *, ExceptionInfo *); static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *); static size_t TracePath(PrimitiveInfo *,const char *); static void TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo), TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo, const double,const MagickBooleanType,const MagickBooleanType), TraceBezier(PrimitiveInfo *,const size_t), TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo, const PointInfo), TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo), TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo, PointInfo), TraceSquareLinecap(PrimitiveInfo *,const size_t,const double); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireDrawInfo() returns a DrawInfo structure properly initialized. % % The format of the AcquireDrawInfo method is: % % DrawInfo *AcquireDrawInfo(void) % */ MagickExport DrawInfo *AcquireDrawInfo(void) { DrawInfo *draw_info; draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info)); if (draw_info == (DrawInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetDrawInfo((ImageInfo *) NULL,draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneDrawInfo() makes a copy of the given draw_info structure. If NULL % is specified, a new DrawInfo structure is created initialized to default % values. % % The format of the CloneDrawInfo method is: % % DrawInfo *CloneDrawInfo(const ImageInfo *image_info, % const DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info. % % o draw_info: the draw info. % */ MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info, const DrawInfo *draw_info) { DrawInfo *clone_info; ExceptionInfo *exception; clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info)); if (clone_info == (DrawInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetDrawInfo(image_info,clone_info); if (draw_info == (DrawInfo *) NULL) return(clone_info); exception=AcquireExceptionInfo(); if (clone_info->primitive != (char *) NULL) (void) CloneString(&clone_info->primitive,draw_info->primitive); if (draw_info->geometry != (char *) NULL) (void) CloneString(&clone_info->geometry,draw_info->geometry); clone_info->viewbox=draw_info->viewbox; clone_info->affine=draw_info->affine; clone_info->gravity=draw_info->gravity; clone_info->fill=draw_info->fill; clone_info->stroke=draw_info->stroke; clone_info->stroke_width=draw_info->stroke_width; if (draw_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue, exception); if (draw_info->stroke_pattern != (Image *) NULL) clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke_antialias=draw_info->stroke_antialias; clone_info->text_antialias=draw_info->text_antialias; clone_info->fill_rule=draw_info->fill_rule; clone_info->linecap=draw_info->linecap; clone_info->linejoin=draw_info->linejoin; clone_info->miterlimit=draw_info->miterlimit; clone_info->dash_offset=draw_info->dash_offset; clone_info->decorate=draw_info->decorate; clone_info->compose=draw_info->compose; if (draw_info->text != (char *) NULL) (void) CloneString(&clone_info->text,draw_info->text); if (draw_info->font != (char *) NULL) (void) CloneString(&clone_info->font,draw_info->font); if (draw_info->metrics != (char *) NULL) (void) CloneString(&clone_info->metrics,draw_info->metrics); if (draw_info->family != (char *) NULL) (void) CloneString(&clone_info->family,draw_info->family); clone_info->style=draw_info->style; clone_info->stretch=draw_info->stretch; clone_info->weight=draw_info->weight; if (draw_info->encoding != (char *) NULL) (void) CloneString(&clone_info->encoding,draw_info->encoding); clone_info->pointsize=draw_info->pointsize; clone_info->kerning=draw_info->kerning; clone_info->interline_spacing=draw_info->interline_spacing; clone_info->interword_spacing=draw_info->interword_spacing; clone_info->direction=draw_info->direction; if (draw_info->density != (char *) NULL) (void) CloneString(&clone_info->density,draw_info->density); clone_info->align=draw_info->align; clone_info->undercolor=draw_info->undercolor; clone_info->border_color=draw_info->border_color; if (draw_info->server_name != (char *) NULL) (void) CloneString(&clone_info->server_name,draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) { register ssize_t x; for (x=0; fabs(draw_info->dash_pattern[x]) >= DrawEpsilon; x++) ; clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL, sizeof(*clone_info->dash_pattern)); if (clone_info->dash_pattern == (double *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern, (size_t) (x+1)*sizeof(*clone_info->dash_pattern)); } clone_info->gradient=draw_info->gradient; if (draw_info->gradient.stops != (StopInfo *) NULL) { size_t number_stops; number_stops=clone_info->gradient.number_stops; clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t) number_stops,sizeof(*clone_info->gradient.stops)); if (clone_info->gradient.stops == (StopInfo *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAllocateDashPattern"); (void) CopyMagickMemory(clone_info->gradient.stops, draw_info->gradient.stops,(size_t) number_stops* sizeof(*clone_info->gradient.stops)); } if (draw_info->clip_mask != (char *) NULL) (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask); clone_info->bounds=draw_info->bounds; clone_info->clip_units=draw_info->clip_units; clone_info->render=draw_info->render; clone_info->fill_alpha=draw_info->fill_alpha; clone_info->stroke_alpha=draw_info->stroke_alpha; clone_info->element_reference=draw_info->element_reference; clone_info->debug=IsEventLogging(); exception=DestroyExceptionInfo(exception); return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P a t h T o P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPathToPolygon() converts a path to the more efficient sorted % rendering form. % % The format of the ConvertPathToPolygon method is: % % PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info, % const PathInfo *path_info) % % A description of each parameter follows: % % o Method ConvertPathToPolygon returns the path in a more efficient sorted % rendering form of type PolygonInfo. % % o draw_info: Specifies a pointer to an DrawInfo structure. % % o path_info: Specifies a pointer to an PathInfo structure. % % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int CompareEdges(const void *x,const void *y) { register const EdgeInfo *p, *q; /* Compare two edges. */ p=(const EdgeInfo *) x; q=(const EdgeInfo *) y; if ((p->points[0].y-DrawEpsilon) > q->points[0].y) return(1); if ((p->points[0].y+DrawEpsilon) < q->points[0].y) return(-1); if ((p->points[0].x-DrawEpsilon) > q->points[0].x) return(1); if ((p->points[0].x+DrawEpsilon) < q->points[0].x) return(-1); if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)- (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0) return(1); return(-1); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static void LogPolygonInfo(const PolygonInfo *polygon_info) { register EdgeInfo *p; register ssize_t i, j; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge"); p=polygon_info->edges; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { (void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:", (double) i); (void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s", p->direction != MagickFalse ? "down" : "up"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s", p->ghostline != MagickFalse ? "transparent" : "opaque"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1, p->bounds.x2,p->bounds.y2); for (j=0; j < (ssize_t) p->number_points; j++) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g", p->points[j].x,p->points[j].y); p++; } (void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge"); } static void ReversePoints(PointInfo *points,const size_t number_points) { PointInfo point; register ssize_t i; for (i=0; i < (ssize_t) (number_points >> 1); i++) { point=points[i]; points[i]=points[number_points-(i+1)]; points[number_points-(i+1)]=point; } } static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info) { long direction, next_direction; PointInfo point, *points; PolygonInfo *polygon_info; SegmentInfo bounds; register ssize_t i, n; MagickBooleanType ghostline; size_t edge, number_edges, number_points; /* Convert a path to the more efficient sorted rendering form. */ polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info)); if (polygon_info == (PolygonInfo *) NULL) return((PolygonInfo *) NULL); number_edges=16; polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); (void) ResetMagickMemory(polygon_info->edges,0,number_edges* sizeof(*polygon_info->edges)); direction=0; edge=0; ghostline=MagickFalse; n=0; number_points=0; points=(PointInfo *) NULL; (void) ResetMagickMemory(&point,0,sizeof(point)); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); for (i=0; path_info[i].code != EndCode; i++) { if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) || (path_info[i].code == GhostlineCode)) { /* Move to. */ if ((points != (PointInfo *) NULL) && (n >= 2)) { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; points=(PointInfo *) NULL; ghostline=MagickFalse; edge++; } if (points == (PointInfo *) NULL) { number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse; point=path_info[i].point; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; direction=0; n=1; continue; } /* Line to. */ next_direction=((path_info[i].point.y > point.y) || ((fabs(path_info[i].point.y-point.y) < DrawEpsilon) && (path_info[i].point.x > point.x))) ? 1 : -1; if ((points != (PointInfo *) NULL) && (direction != 0) && (direction != next_direction)) { /* New edge. */ point=points[n-1]; if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; number_points=16; points=(PointInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); n=1; ghostline=MagickFalse; points[0]=point; bounds.x1=point.x; bounds.x2=point.x; edge++; } direction=next_direction; if (points == (PointInfo *) NULL) continue; if (n == (ssize_t) number_points) { number_points<<=1; points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points, sizeof(*points)); if (points == (PointInfo *) NULL) return((PolygonInfo *) NULL); } point=path_info[i].point; points[n]=point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.x > bounds.x2) bounds.x2=point.x; n++; } if (points != (PointInfo *) NULL) { if (n < 2) points=(PointInfo *) RelinquishMagickMemory(points); else { if (edge == number_edges) { number_edges<<=1; polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory( polygon_info->edges,(size_t) number_edges, sizeof(*polygon_info->edges)); if (polygon_info->edges == (EdgeInfo *) NULL) return((PolygonInfo *) NULL); } polygon_info->edges[edge].number_points=(size_t) n; polygon_info->edges[edge].scanline=(-1.0); polygon_info->edges[edge].highwater=0; polygon_info->edges[edge].ghostline=ghostline; polygon_info->edges[edge].direction=(ssize_t) (direction > 0); if (direction < 0) ReversePoints(points,(size_t) n); polygon_info->edges[edge].points=points; polygon_info->edges[edge].bounds=bounds; polygon_info->edges[edge].bounds.y1=points[0].y; polygon_info->edges[edge].bounds.y2=points[n-1].y; ghostline=MagickFalse; edge++; } } polygon_info->number_edges=edge; qsort(polygon_info->edges,(size_t) polygon_info->number_edges, sizeof(*polygon_info->edges),CompareEdges); if (IsEventLogging() != MagickFalse) LogPolygonInfo(polygon_info); return(polygon_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n v e r t P r i m i t i v e T o P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector % path structure. % % The format of the ConvertPrimitiveToPath method is: % % PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o Method ConvertPrimitiveToPath returns a vector path structure of type % PathInfo. % % o draw_info: a structure of type DrawInfo. % % o primitive_info: Specifies a pointer to an PrimitiveInfo structure. % % */ static void LogPathInfo(const PathInfo *path_info) { register const PathInfo *p; (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path"); for (p=path_info; p->code != EndCode; p++) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ? "moveto ghostline" : p->code == OpenCode ? "moveto open" : p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" : "?"); (void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path"); } static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info) { PathInfo *path_info; PathInfoCode code; PointInfo p, q; register ssize_t i, n; ssize_t coordinates, start; /* Converts a PrimitiveInfo structure into a vector path structure. */ switch (primitive_info->primitive) { case AlphaPrimitive: case ColorPrimitive: case ImagePrimitive: case PointPrimitive: case TextPrimitive: return((PathInfo *) NULL); default: break; } for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL), sizeof(*path_info)); if (path_info == (PathInfo *) NULL) return((PathInfo *) NULL); coordinates=0; n=0; p.x=(-1.0); p.y=(-1.0); q.x=(-1.0); q.y=(-1.0); start=0; for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { code=LineToCode; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; p=primitive_info[i].point; start=n; code=MoveToCode; } coordinates--; /* Eliminate duplicate points. */ if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= DrawEpsilon) || (fabs(q.y-primitive_info[i].point.y) >= DrawEpsilon)) { path_info[n].code=code; path_info[n].point=primitive_info[i].point; q=primitive_info[i].point; n++; } if (coordinates > 0) continue; if ((fabs(p.x-primitive_info[i].point.x) < DrawEpsilon) && (fabs(p.y-primitive_info[i].point.y) < DrawEpsilon)) continue; /* Mark the p point as open if it does not match the q. */ path_info[start].code=OpenCode; path_info[n].code=GhostlineCode; path_info[n].point=primitive_info[i].point; n++; path_info[n].code=LineToCode; path_info[n].point=p; n++; } path_info[n].code=EndCode; path_info[n].point.x=0.0; path_info[n].point.y=0.0; if (IsEventLogging() != MagickFalse) LogPathInfo(path_info); return(path_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyDrawInfo() deallocates memory associated with an DrawInfo % structure. % % The format of the DestroyDrawInfo method is: % % DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) % % A description of each parameter follows: % % o draw_info: the draw info. % */ MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info) { if (draw_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (draw_info->primitive != (char *) NULL) draw_info->primitive=DestroyString(draw_info->primitive); if (draw_info->text != (char *) NULL) draw_info->text=DestroyString(draw_info->text); if (draw_info->geometry != (char *) NULL) draw_info->geometry=DestroyString(draw_info->geometry); if (draw_info->fill_pattern != (Image *) NULL) draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern); if (draw_info->stroke_pattern != (Image *) NULL) draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern); if (draw_info->font != (char *) NULL) draw_info->font=DestroyString(draw_info->font); if (draw_info->metrics != (char *) NULL) draw_info->metrics=DestroyString(draw_info->metrics); if (draw_info->family != (char *) NULL) draw_info->family=DestroyString(draw_info->family); if (draw_info->encoding != (char *) NULL) draw_info->encoding=DestroyString(draw_info->encoding); if (draw_info->density != (char *) NULL) draw_info->density=DestroyString(draw_info->density); if (draw_info->server_name != (char *) NULL) draw_info->server_name=(char *) RelinquishMagickMemory(draw_info->server_name); if (draw_info->dash_pattern != (double *) NULL) draw_info->dash_pattern=(double *) RelinquishMagickMemory( draw_info->dash_pattern); if (draw_info->gradient.stops != (StopInfo *) NULL) draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory( draw_info->gradient.stops); if (draw_info->clip_mask != (char *) NULL) draw_info->clip_mask=DestroyString(draw_info->clip_mask); draw_info->signature=(~MagickCoreSignature); draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info); return(draw_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y E d g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyEdge() destroys the specified polygon edge. % % The format of the DestroyEdge method is: % % ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % % o edge: the polygon edge number to destroy. % */ static size_t DestroyEdge(PolygonInfo *polygon_info, const size_t edge) { assert(edge < polygon_info->number_edges); polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory( polygon_info->edges[edge].points); polygon_info->number_edges--; if (edge < polygon_info->number_edges) (void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1, (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges)); return(polygon_info->number_edges); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P o l y g o n I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPolygonInfo() destroys the PolygonInfo data structure. % % The format of the DestroyPolygonInfo method is: % % PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) % % A description of each parameter follows: % % o polygon_info: Specifies a pointer to an PolygonInfo structure. % */ static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info) { register ssize_t i; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) polygon_info->edges[i].points=(PointInfo *) RelinquishMagickMemory(polygon_info->edges[i].points); polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges); return((PolygonInfo *) RelinquishMagickMemory(polygon_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w A f f i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawAffineImage() composites the source over the destination image as % dictated by the affine transform. % % The format of the DrawAffineImage method is: % % MagickBooleanType DrawAffineImage(Image *image,const Image *source, % const AffineMatrix *affine,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o source: the source image. % % o affine: the affine transform. % % o exception: return any errors or warnings in this structure. % */ static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine, const double y,const SegmentInfo *edge) { double intercept, z; register double x; SegmentInfo inverse_edge; /* Determine left and right edges. */ inverse_edge.x1=edge->x1; inverse_edge.y1=edge->y1; inverse_edge.x2=edge->x2; inverse_edge.y2=edge->y2; z=affine->ry*y+affine->tx; if (affine->sx >= DrawEpsilon) { intercept=(-z/affine->sx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->sx < -DrawEpsilon) { intercept=(-z+(double) image->columns)/affine->sx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->sx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns)) { inverse_edge.x2=edge->x1; return(inverse_edge); } /* Determine top and bottom edges. */ z=affine->sy*y+affine->ty; if (affine->rx >= DrawEpsilon) { intercept=(-z/affine->rx); x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if (affine->rx < -DrawEpsilon) { intercept=(-z+(double) image->rows)/affine->rx; x=intercept; if (x > inverse_edge.x1) inverse_edge.x1=x; intercept=(-z/affine->rx); x=intercept; if (x < inverse_edge.x2) inverse_edge.x2=x; } else if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows)) { inverse_edge.x2=edge->x2; return(inverse_edge); } return(inverse_edge); } static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine) { AffineMatrix inverse_affine; double determinant; determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx* affine->ry); inverse_affine.sx=determinant*affine->sy; inverse_affine.rx=determinant*(-affine->rx); inverse_affine.ry=determinant*(-affine->ry); inverse_affine.sy=determinant*affine->sx; inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty* inverse_affine.ry; inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty* inverse_affine.sy; return(inverse_affine); } MagickExport MagickBooleanType DrawAffineImage(Image *image, const Image *source,const AffineMatrix *affine,ExceptionInfo *exception) { AffineMatrix inverse_affine; CacheView *image_view, *source_view; MagickBooleanType status; PixelInfo zero; PointInfo extent[4], min, max; register ssize_t i; SegmentInfo edge; ssize_t start, stop, y; /* Determine bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(source != (const Image *) NULL); assert(source->signature == MagickCoreSignature); assert(affine != (AffineMatrix *) NULL); extent[0].x=0.0; extent[0].y=0.0; extent[1].x=(double) source->columns-1.0; extent[1].y=0.0; extent[2].x=(double) source->columns-1.0; extent[2].y=(double) source->rows-1.0; extent[3].x=0.0; extent[3].y=(double) source->rows-1.0; for (i=0; i < 4; i++) { PointInfo point; point=extent[i]; extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx; extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty; } 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; } /* Affine transform image. */ if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; edge.x1=MagickMax(min.x,0.0); edge.y1=MagickMax(min.y,0.0); edge.x2=MagickMin(max.x,(double) image->columns-1.0); edge.y2=MagickMin(max.y,(double) image->rows-1.0); inverse_affine=InverseAffineMatrix(affine); GetPixelInfo(image,&zero); start=(ssize_t) ceil(edge.y1-0.5); stop=(ssize_t) floor(edge.y2+0.5); source_view=AcquireVirtualCacheView(source,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(source,image,1,1) #endif for (y=start; y <= stop; y++) { PixelInfo composite, pixel; PointInfo point; register ssize_t x; register Quantum *magick_restrict q; SegmentInfo inverse_edge; ssize_t x_offset; inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge); if (inverse_edge.x2 < inverse_edge.x1) continue; q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1- 0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1), 1,exception); if (q == (Quantum *) NULL) continue; pixel=zero; composite=zero; x_offset=0; for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++) { point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+ inverse_affine.tx; point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+ inverse_affine.ty; (void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel, point.x,point.y,&pixel,exception); GetPixelInfoPixel(image,q,&composite); CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha, &composite); SetPixelViaPixelInfo(image,&composite,q); x_offset++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w B o u n d i n g R e c t a n g l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawBoundingRectangles() draws the bounding rectangles on the image. This % is only useful for developers debugging the rendering algorithm. % % The format of the DrawBoundingRectangles method is: % % void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, % PolygonInfo *polygon_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o polygon_info: Specifies a pointer to a PolygonInfo structure. % % o exception: return any errors or warnings in this structure. % */ static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info, const PolygonInfo *polygon_info,ExceptionInfo *exception) { DrawInfo *clone_info; double mid; PointInfo end, resolution, start; PrimitiveInfo primitive_info[6]; register ssize_t i; SegmentInfo bounds; ssize_t coordinates; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) QueryColorCompliance("#000F",AllCompliance,&clone_info->fill, exception); resolution.x=96.0; resolution.y=96.0; if (clone_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(clone_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == MagickFalse) resolution.y=resolution.x; } mid=(resolution.x/96.0)*ExpandAffine(&clone_info->affine)* clone_info->stroke_width/2.0; bounds.x1=0.0; bounds.y1=0.0; bounds.x2=0.0; bounds.y2=0.0; if (polygon_info != (PolygonInfo *) NULL) { bounds=polygon_info->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1) bounds.x1=polygon_info->edges[i].bounds.x1; if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1) bounds.y1=polygon_info->edges[i].bounds.y1; if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2) bounds.x2=polygon_info->edges[i].bounds.x2; if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2) bounds.y2=polygon_info->edges[i].bounds.y2; } bounds.x1-=mid; bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=mid; bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=mid; bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=mid; bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows ? (double) image->rows-1 : bounds.y2; for (i=0; i < (ssize_t) polygon_info->number_edges; i++) { if (polygon_info->edges[i].direction != 0) (void) QueryColorCompliance("red",AllCompliance,&clone_info->stroke, exception); else (void) QueryColorCompliance("green",AllCompliance,&clone_info->stroke, exception); start.x=(double) (polygon_info->edges[i].bounds.x1-mid); start.y=(double) (polygon_info->edges[i].bounds.y1-mid); end.x=(double) (polygon_info->edges[i].bounds.x2+mid); end.y=(double) (polygon_info->edges[i].bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info,exception); } } (void) QueryColorCompliance("blue",AllCompliance,&clone_info->stroke, exception); start.x=(double) (bounds.x1-mid); start.y=(double) (bounds.y1-mid); end.x=(double) (bounds.x2+mid); end.y=(double) (bounds.y2+mid); primitive_info[0].primitive=RectanglePrimitive; TraceRectangle(primitive_info,start,end); primitive_info[0].method=ReplaceMethod; coordinates=(ssize_t) primitive_info[0].coordinates; primitive_info[coordinates].primitive=UndefinedPrimitive; (void) DrawPrimitive(image,clone_info,primitive_info,exception); clone_info=DestroyDrawInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w C l i p P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawClipPath() draws the clip path on the image mask. % % The format of the DrawClipPath method is: % % MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info, % const char *name,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the name of the clip path. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawClipPath(Image *image, const DrawInfo *draw_info,const char *name,ExceptionInfo *exception) { char filename[MagickPathExtent]; Image *clip_mask; const char *value; DrawInfo *clone_info; MagickStatusType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); (void) FormatLocaleString(filename,MagickPathExtent,"%s",name); value=GetImageArtifact(image,filename); if (value == (const char *) NULL) return(MagickFalse); clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (clip_mask == (Image *) NULL) return(MagickFalse); (void) QueryColorCompliance("#0000",AllCompliance, &clip_mask->background_color,exception); clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(clip_mask,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s", draw_info->clip_mask); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->primitive,value); (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill, exception); clone_info->clip_mask=(char *) NULL; status=NegateImage(clip_mask,MagickFalse,exception); (void) SetImageMask(image,ReadPixelMask,clip_mask,exception); clip_mask=DestroyImage(clip_mask); status&=DrawImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w D a s h P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the % image while respecting the dash offset and dash pattern attributes. % % The format of the DrawDashPolygon method is: % % MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, % const PrimitiveInfo *primitive_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception) { DrawInfo *clone_info; double length, maximum_length, offset, scale, total_length; MagickStatusType status; PrimitiveInfo *dash_polygon; register ssize_t i; register double dx, dy; size_t number_vertices; ssize_t j, n; assert(draw_info != (const DrawInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash"); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; number_vertices=(size_t) i; dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (2UL*number_vertices+1UL),sizeof(*dash_polygon)); if (dash_polygon == (PrimitiveInfo *) NULL) return(MagickFalse); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->miterlimit=0; dash_polygon[0]=primitive_info[0]; scale=ExpandAffine(&draw_info->affine); length=scale*(draw_info->dash_pattern[0]-0.5); offset=fabs(draw_info->dash_offset) >= DrawEpsilon ? scale*draw_info->dash_offset : 0.0; j=1; for (n=0; offset > 0.0; j=0) { if (draw_info->dash_pattern[n] <= 0.0) break; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); if (offset > length) { offset-=length; n++; length=scale*(draw_info->dash_pattern[n]+0.5); continue; } if (offset < length) { length-=offset; offset=0.0; break; } offset=0.0; n++; } status=MagickTrue; maximum_length=0.0; total_length=0.0; for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++) { dx=primitive_info[i].point.x-primitive_info[i-1].point.x; dy=primitive_info[i].point.y-primitive_info[i-1].point.y; maximum_length=hypot((double) dx,dy); if (fabs(length) < DrawEpsilon) { n++; if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); ) { total_length+=length; if ((n & 0x01) != 0) { dash_polygon[0]=primitive_info[0]; dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); j=1; } else { if ((j+1) > (ssize_t) (2*number_vertices)) break; dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx* total_length/maximum_length); dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy* total_length/maximum_length); dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } n++; if (fabs(draw_info->dash_pattern[n]) < DrawEpsilon) n=0; length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5)); } length-=(maximum_length-total_length); if ((n & 0x01) != 0) continue; dash_polygon[j]=primitive_info[i]; dash_polygon[j].coordinates=1; j++; } if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1)) { dash_polygon[j]=primitive_info[i-1]; dash_polygon[j].point.x+=DrawEpsilon; dash_polygon[j].point.y+=DrawEpsilon; dash_polygon[j].coordinates=1; j++; dash_polygon[0].coordinates=(size_t) j; dash_polygon[j].primitive=UndefinedPrimitive; status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception); } dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawImage() draws a graphic primitive on your image. The primitive % may be represented as a string or filename. Precede the filename with an % "at" sign (@) and the contents of the file are drawn on the image. You % can affect how text is drawn by setting one or more members of the draw % info structure. % % The format of the DrawImage method is: % % MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType IsPoint(const char *point) { char *p; double value; value=StringToDouble(point,&p); return((fabs(value) < DrawEpsilon) && (p == point) ? MagickFalse : MagickTrue); } static inline void TracePoint(PrimitiveInfo *primitive_info, const PointInfo point) { primitive_info->coordinates=1; primitive_info->point=point; } MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, ExceptionInfo *exception) { #define RenderImageTag "Render/Image" AffineMatrix affine, current; char keyword[MagickPathExtent], geometry[MagickPathExtent], *next_token, pattern[MagickPathExtent], *primitive, *token; const char *q; double angle, factor, primitive_extent; DrawInfo **graphic_context; MagickBooleanType proceed; MagickSizeType length, number_points; MagickStatusType status; PointInfo point; PrimitiveInfo *primitive_info; PrimitiveType primitive_type; register const char *p; register ssize_t i, x; SegmentInfo bounds; size_t extent, number_stops; ssize_t j, k, n; StopInfo *stops; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if ((draw_info->primitive == (char *) NULL) || (*draw_info->primitive == '\0')) return(MagickFalse); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image"); if (*draw_info->primitive != '@') primitive=AcquireString(draw_info->primitive); else primitive=FileToString(draw_info->primitive+1,~0UL,exception); if (primitive == (char *) NULL) return(MagickFalse); primitive_extent=(double) strlen(primitive); (void) SetImageArtifact(image,"MVG",primitive); n=0; number_stops=0; stops=(StopInfo *) NULL; /* Allocate primitive info memory. */ graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { primitive=DestroyString(primitive); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } number_points=6553; primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points, sizeof(*primitive_info)); if (primitive_info == (PrimitiveInfo *) NULL) { primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info); graphic_context[n]->viewbox=image->page; if ((image->page.width == 0) || (image->page.height == 0)) { graphic_context[n]->viewbox.width=image->columns; graphic_context[n]->viewbox.height=image->rows; } token=AcquireString(primitive); extent=strlen(token)+MagickPathExtent; if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; for (q=primitive; *q != '\0'; ) { /* Interpret graphic primitive. */ GetNextToken(q,&q,MagickPathExtent,keyword); if (*keyword == '\0') break; if (*keyword == '#') { /* Comment. */ while ((*q != '\n') && (*q != '\0')) q++; continue; } p=q-strlen(keyword)-1; primitive_type=UndefinedPrimitive; current=graphic_context[n]->affine; GetAffineMatrix(&affine); switch (*keyword) { case ';': break; case 'a': case 'A': { if (LocaleCompare("affine",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.rx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ry=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("alpha",keyword) == 0) { primitive_type=AlphaPrimitive; break; } if (LocaleCompare("arc",keyword) == 0) { primitive_type=ArcPrimitive; break; } status=MagickFalse; break; } case 'b': case 'B': { if (LocaleCompare("bezier",keyword) == 0) { primitive_type=BezierPrimitive; break; } if (LocaleCompare("border-color",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->border_color,exception); break; } status=MagickFalse; break; } case 'c': case 'C': { if (LocaleCompare("clip-path",keyword) == 0) { /* Create clip mask. */ GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->clip_mask,token); (void) DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); break; } if (LocaleCompare("clip-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("clip-units",keyword) == 0) { ssize_t clip_units; GetNextToken(q,&q,extent,token); clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse, token); if (clip_units == -1) { status=MagickFalse; break; } graphic_context[n]->clip_units=(ClipPathUnits) clip_units; if (clip_units == ObjectBoundingBox) { GetAffineMatrix(&current); affine.sx=draw_info->bounds.x2; affine.sy=draw_info->bounds.y2; affine.tx=draw_info->bounds.x1; affine.ty=draw_info->bounds.y1; break; } break; } if (LocaleCompare("circle",keyword) == 0) { primitive_type=CirclePrimitive; break; } if (LocaleCompare("color",keyword) == 0) { primitive_type=ColorPrimitive; break; } status=MagickFalse; break; } case 'd': case 'D': { if (LocaleCompare("decorate",keyword) == 0) { ssize_t decorate; GetNextToken(q,&q,extent,token); decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse, token); if (decorate == -1) status=MagickFalse; else graphic_context[n]->decorate=(DecorationType) decorate; break; } if (LocaleCompare("density",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->density,token); break; } if (LocaleCompare("direction",keyword) == 0) { ssize_t direction; GetNextToken(q,&q,extent,token); direction=ParseCommandOption(MagickDirectionOptions,MagickFalse, token); if (direction == -1) status=MagickFalse; else graphic_context[n]->direction=(DirectionType) direction; break; } status=MagickFalse; break; } case 'e': case 'E': { if (LocaleCompare("ellipse",keyword) == 0) { primitive_type=EllipsePrimitive; break; } if (LocaleCompare("encoding",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->encoding,token); break; } status=MagickFalse; break; } case 'f': case 'F': { if (LocaleCompare("fill",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->fill_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->fill,exception); if (graphic_context[n]->fill_alpha != OpaqueAlpha) graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha; if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->fill_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("fill-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->fill.alpha=QuantumRange-ClampToQuantum( (MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token, &next_token))); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("fill-rule",keyword) == 0) { ssize_t fill_rule; GetNextToken(q,&q,extent,token); fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse, token); if (fill_rule == -1) status=MagickFalse; else graphic_context[n]->fill_rule=(FillRule) fill_rule; break; } if (LocaleCompare("font",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->font,token); if (LocaleCompare("none",token) == 0) graphic_context[n]->font=(char *) RelinquishMagickMemory( graphic_context[n]->font); break; } if (LocaleCompare("font-family",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) CloneString(&graphic_context[n]->family,token); break; } if (LocaleCompare("font-size",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->pointsize=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("font-stretch",keyword) == 0) { ssize_t stretch; GetNextToken(q,&q,extent,token); stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token); if (stretch == -1) status=MagickFalse; else graphic_context[n]->stretch=(StretchType) stretch; break; } if (LocaleCompare("font-style",keyword) == 0) { ssize_t style; GetNextToken(q,&q,extent,token); style=ParseCommandOption(MagickStyleOptions,MagickFalse,token); if (style == -1) status=MagickFalse; else graphic_context[n]->style=(StyleType) style; break; } if (LocaleCompare("font-weight",keyword) == 0) { ssize_t weight; GetNextToken(q,&q,extent,token); weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(token); graphic_context[n]->weight=(size_t) weight; break; } status=MagickFalse; break; } case 'g': case 'G': { if (LocaleCompare("gradient-units",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gravity",keyword) == 0) { ssize_t gravity; GetNextToken(q,&q,extent,token); gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token); if (gravity == -1) status=MagickFalse; else graphic_context[n]->gravity=(GravityType) gravity; break; } status=MagickFalse; break; } case 'i': case 'I': { if (LocaleCompare("image",keyword) == 0) { ssize_t compose; primitive_type=ImagePrimitive; GetNextToken(q,&q,extent,token); compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token); if (compose == -1) status=MagickFalse; else graphic_context[n]->compose=(CompositeOperator) compose; break; } if (LocaleCompare("interline-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interline_spacing=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("interword-spacing",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->interword_spacing=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'k': case 'K': { if (LocaleCompare("kerning",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->kerning=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'l': case 'L': { if (LocaleCompare("line",keyword) == 0) primitive_type=LinePrimitive; else status=MagickFalse; break; } case 'o': case 'O': { if (LocaleCompare("offset",keyword) == 0) { GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->alpha=QuantumRange*(1.0-(QuantumScale* graphic_context[n]->alpha*(1.0-factor*StringToDouble(token, &next_token)))); graphic_context[n]->fill_alpha=QuantumRange*(1.0-(QuantumScale* graphic_context[n]->fill_alpha*(1.0-factor*StringToDouble(token, &next_token)))); graphic_context[n]->stroke_alpha=QuantumRange*(1.0-(QuantumScale* graphic_context[n]->stroke_alpha*(1.0-factor*StringToDouble(token, &next_token)))); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'p': case 'P': { if (LocaleCompare("path",keyword) == 0) { primitive_type=PathPrimitive; break; } if (LocaleCompare("point",keyword) == 0) { primitive_type=PointPrimitive; break; } if (LocaleCompare("polyline",keyword) == 0) { primitive_type=PolylinePrimitive; break; } if (LocaleCompare("polygon",keyword) == 0) { primitive_type=PolygonPrimitive; break; } if (LocaleCompare("pop",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) break; if (LocaleCompare("defs",token) == 0) break; if (LocaleCompare("gradient",token) == 0) break; if (LocaleCompare("graphic-context",token) == 0) { if (n <= 0) { (void) ThrowMagickException(exception,GetMagickModule(), DrawError,"UnbalancedGraphicContextPushPop","`%s'",token); status=MagickFalse; n=0; break; } if (graphic_context[n]->clip_mask != (char *) NULL) if (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0) (void) SetImageMask(image,ReadPixelMask,(Image *) NULL, exception); graphic_context[n]=DestroyDrawInfo(graphic_context[n]); n--; break; } if (LocaleCompare("pattern",token) == 0) break; status=MagickFalse; break; } if (LocaleCompare("push",keyword) == 0) { GetNextToken(q,&q,extent,token); if (LocaleCompare("clip-path",token) == 0) { char name[MagickPathExtent]; GetNextToken(q,&q,extent,token); (void) FormatLocaleString(name,MagickPathExtent,"%s",token); for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"clip-path") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) SetImageArtifact(image,name,token); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("gradient",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent], type[MagickPathExtent]; SegmentInfo segment; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); (void) CopyMagickString(type,token,MagickPathExtent); GetNextToken(q,&q,extent,token); segment.x1=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y1=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.x2=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); segment.y2=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; if (LocaleCompare(type,"radial") == 0) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); } for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"gradient") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); bounds.x1=graphic_context[n]->affine.sx*segment.x1+ graphic_context[n]->affine.ry*segment.y1+ graphic_context[n]->affine.tx; bounds.y1=graphic_context[n]->affine.rx*segment.x1+ graphic_context[n]->affine.sy*segment.y1+ graphic_context[n]->affine.ty; bounds.x2=graphic_context[n]->affine.sx*segment.x2+ graphic_context[n]->affine.ry*segment.y2+ graphic_context[n]->affine.tx; bounds.y2=graphic_context[n]->affine.rx*segment.x2+ graphic_context[n]->affine.sy*segment.y2+ graphic_context[n]->affine.ty; (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-type",name); (void) SetImageArtifact(image,key,type); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%gx%g%+.15g%+.15g", MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0), bounds.x1,bounds.y1); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("pattern",token) == 0) { char key[2*MagickPathExtent], name[MagickPathExtent]; RectangleInfo pattern_bounds; GetNextToken(q,&q,extent,token); (void) CopyMagickString(name,token,MagickPathExtent); GetNextToken(q,&q,extent,token); pattern_bounds.x=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.y=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.width=(size_t) floor(StringToDouble(token, &next_token)+0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); pattern_bounds.height=(size_t) floor(StringToDouble(token, &next_token)+0.5); if (token == next_token) status=MagickFalse; for (p=q; *q != '\0'; ) { GetNextToken(q,&q,extent,token); if (LocaleCompare(token,"pop") != 0) continue; GetNextToken(q,(const char **) NULL,extent,token); if (LocaleCompare(token,"pattern") != 0) continue; break; } (void) CopyMagickString(token,p,(size_t) (q-p-4+1)); (void) FormatLocaleString(key,MagickPathExtent,"%s",name); (void) SetImageArtifact(image,key,token); (void) FormatLocaleString(key,MagickPathExtent,"%s-geometry", name); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double)pattern_bounds.width, (double)pattern_bounds.height,(double)pattern_bounds.x, (double)pattern_bounds.y); (void) SetImageArtifact(image,key,geometry); GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("graphic-context",token) == 0) { n++; graphic_context=(DrawInfo **) ResizeQuantumMemory( graphic_context,(size_t) (n+1),sizeof(*graphic_context)); if (graphic_context == (DrawInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL, graphic_context[n-1]); break; } if (LocaleCompare("defs",token) == 0) break; status=MagickFalse; break; } status=MagickFalse; break; } case 'r': case 'R': { if (LocaleCompare("rectangle",keyword) == 0) { primitive_type=RectanglePrimitive; break; } if (LocaleCompare("rotate",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0))); affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0))); break; } if (LocaleCompare("roundRectangle",keyword) == 0) { primitive_type=RoundRectanglePrimitive; break; } status=MagickFalse; break; } case 's': case 'S': { if (LocaleCompare("scale",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.sx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.sy=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("skewX",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; affine.ry=sin(DegreesToRadians(angle)); break; } if (LocaleCompare("skewY",keyword) == 0) { GetNextToken(q,&q,extent,token); angle=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; affine.rx=(-tan(DegreesToRadians(angle)/2.0)); break; } if (LocaleCompare("stop-color",keyword) == 0) { PixelInfo stop_color; number_stops++; if (number_stops == 1) stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops)); else if (number_stops > 2) stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops, sizeof(*stops)); if (stops == (StopInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance,&stop_color, exception); stops[number_stops-1].color=stop_color; GetNextToken(q,&q,extent,token); stops[number_stops-1].offset=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("stroke",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) FormatLocaleString(pattern,MagickPathExtent,"%s",token); if (GetImageArtifact(image,pattern) != (const char *) NULL) (void) DrawPatternPath(image,draw_info,token, &graphic_context[n]->stroke_pattern,exception); else { status&=QueryColorCompliance(token,AllCompliance, &graphic_context[n]->stroke,exception); if (graphic_context[n]->stroke_alpha != OpaqueAlpha) graphic_context[n]->stroke.alpha= graphic_context[n]->stroke_alpha; if (status == MagickFalse) { ImageInfo *pattern_info; pattern_info=AcquireImageInfo(); (void) CopyMagickString(pattern_info->filename,token, MagickPathExtent); graphic_context[n]->stroke_pattern=ReadImage(pattern_info, exception); CatchException(exception); pattern_info=DestroyImageInfo(pattern_info); } } break; } if (LocaleCompare("stroke-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_antialias= StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("stroke-dasharray",keyword) == 0) { if (graphic_context[n]->dash_pattern != (double *) NULL) graphic_context[n]->dash_pattern=(double *) RelinquishMagickMemory(graphic_context[n]->dash_pattern); if (IsPoint(q) != MagickFalse) { const char *r; r=q; GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); for (x=0; IsPoint(token) != MagickFalse; x++) { GetNextToken(r,&r,extent,token); if (*token == ',') GetNextToken(r,&r,extent,token); } graphic_context[n]->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2UL*x+1UL), sizeof(*graphic_context[n]->dash_pattern)); if (graphic_context[n]->dash_pattern == (double *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); status=MagickFalse; break; } for (j=0; j < x; j++) { GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->dash_pattern[j]=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; if (graphic_context[n]->dash_pattern[j] < 0.0) status=MagickFalse; } if ((x & 0x01) != 0) for ( ; j < (2*x); j++) graphic_context[n]->dash_pattern[j]= graphic_context[n]->dash_pattern[j-x]; graphic_context[n]->dash_pattern[j]=0.0; break; } GetNextToken(q,&q,extent,token); break; } if (LocaleCompare("stroke-dashoffset",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->dash_offset=StringToDouble(token, &next_token); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("stroke-linecap",keyword) == 0) { ssize_t linecap; GetNextToken(q,&q,extent,token); linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token); if (linecap == -1) status=MagickFalse; else graphic_context[n]->linecap=(LineCap) linecap; break; } if (LocaleCompare("stroke-linejoin",keyword) == 0) { ssize_t linejoin; GetNextToken(q,&q,extent,token); linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse, token); if (linejoin == -1) status=MagickFalse; else graphic_context[n]->linejoin=(LineJoin) linejoin; break; } if (LocaleCompare("stroke-miterlimit",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->miterlimit=StringToUnsignedLong(token); break; } if (LocaleCompare("stroke-opacity",keyword) == 0) { GetNextToken(q,&q,extent,token); factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0; graphic_context[n]->stroke.alpha=QuantumRange-ClampToQuantum( (MagickRealType) QuantumRange*(1.0-factor*StringToDouble(token, &next_token))); if (token == next_token) status=MagickFalse; break; } if (LocaleCompare("stroke-width",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->stroke_width=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 't': case 'T': { if (LocaleCompare("text",keyword) == 0) { primitive_type=TextPrimitive; break; } if (LocaleCompare("text-align",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-anchor",keyword) == 0) { ssize_t align; GetNextToken(q,&q,extent,token); align=ParseCommandOption(MagickAlignOptions,MagickFalse,token); if (align == -1) status=MagickFalse; else graphic_context[n]->align=(AlignType) align; break; } if (LocaleCompare("text-antialias",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->text_antialias=StringToLong(token) != 0 ? MagickTrue : MagickFalse; break; } if (LocaleCompare("text-undercolor",keyword) == 0) { GetNextToken(q,&q,extent,token); (void) QueryColorCompliance(token,AllCompliance, &graphic_context[n]->undercolor,exception); break; } if (LocaleCompare("translate",keyword) == 0) { GetNextToken(q,&q,extent,token); affine.tx=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); affine.ty=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } case 'v': case 'V': { if (LocaleCompare("viewbox",keyword) == 0) { GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token, &next_token)-0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble( token,&next_token)+0.5); if (token == next_token) status=MagickFalse; break; } status=MagickFalse; break; } default: { status=MagickFalse; break; } } if (status == MagickFalse) break; if ((fabs(affine.sx-1.0) >= DrawEpsilon) || (fabs(affine.rx) >= DrawEpsilon) || (fabs(affine.ry) >= DrawEpsilon) || (fabs(affine.sy-1.0) >= DrawEpsilon) || (fabs(affine.tx) >= DrawEpsilon) || (fabs(affine.ty) >= DrawEpsilon)) { graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx; graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx; graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy; graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy; graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+ current.tx; graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+ current.ty; } if (primitive_type == UndefinedPrimitive) { if (*q == '\0') { if (number_stops > 1) { GradientType type; type=LinearGradient; if (draw_info->gradient.type == RadialGradient) type=RadialGradient; (void) GradientImage(image,type,PadSpread,stops,number_stops, exception); } if (number_stops > 0) stops=(StopInfo *) RelinquishMagickMemory(stops); } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); continue; } /* Parse the primitive attributes. */ i=0; j=0; primitive_info[0].point.x=0.0; primitive_info[0].point.y=0.0; for (x=0; *q != '\0'; x++) { /* Define points. */ if (IsPoint(q) == MagickFalse) break; GetNextToken(q,&q,extent,token); point.x=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,&q,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); point.y=StringToDouble(token,&next_token); if (token == next_token) status=MagickFalse; GetNextToken(q,(const char **) NULL,extent,token); if (*token == ',') GetNextToken(q,&q,extent,token); primitive_info[i].primitive=primitive_type; primitive_info[i].point=point; primitive_info[i].coordinates=0; primitive_info[i].method=FloodfillMethod; i++; if (i < (ssize_t) number_points) continue; number_points<<=1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if ((primitive_info == (PrimitiveInfo *) NULL) || (number_points != (MagickSizeType) ((size_t) number_points))) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } primitive_info[j].primitive=primitive_type; primitive_info[j].coordinates=(size_t) x; primitive_info[j].method=FloodfillMethod; primitive_info[j].text=(char *) NULL; /* Circumscribe primitive within a circle. */ bounds.x1=primitive_info[j].point.x; bounds.y1=primitive_info[j].point.y; bounds.x2=primitive_info[j].point.x; bounds.y2=primitive_info[j].point.y; for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++) { point=primitive_info[j+k].point; if (point.x < bounds.x1) bounds.x1=point.x; if (point.y < bounds.y1) bounds.y1=point.y; if (point.x > bounds.x2) bounds.x2=point.x; if (point.y > bounds.y2) bounds.y2=point.y; } /* Speculate how many points our primitive might consume. */ length=primitive_info[j].coordinates; switch (primitive_type) { case RectanglePrimitive: { length*=5; break; } case RoundRectanglePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length*=5; length+=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } case BezierPrimitive: { if (primitive_info[j].coordinates > 107) (void) ThrowMagickException(exception,GetMagickModule(),DrawError, "TooManyBezierCoordinates","`%s'",token); length=BezierQuantum*primitive_info[j].coordinates; break; } case PathPrimitive: { char *s, *t; GetNextToken(q,&q,extent,token); length=1; t=token; for (s=token; *s != '\0'; s=t) { double value; value=StringToDouble(s,&t); (void) value; if (s == t) { t++; continue; } length++; } length=length*BezierQuantum; break; } case CirclePrimitive: case ArcPrimitive: case EllipsePrimitive: { double alpha, beta, radius; alpha=bounds.x2-bounds.x1; beta=bounds.y2-bounds.y1; radius=hypot((double) alpha,(double) beta); length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360; break; } default: break; } if ((i+length) >= number_points) { /* Resize based on speculative points required by primitive. */ number_points+=length+1; primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info, (size_t) number_points,sizeof(*primitive_info)); if ((primitive_info == (PrimitiveInfo *) NULL) || (number_points != (MagickSizeType) ((size_t) number_points))) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); break; } } switch (primitive_type) { case PointPrimitive: default: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } TracePoint(primitive_info+j,primitive_info[j].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case LinePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceLine(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RectanglePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case RoundRectanglePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceRoundRectangle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case ArcPrimitive: { if (primitive_info[j].coordinates != 3) { primitive_type=UndefinedPrimitive; break; } TraceArc(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case EllipsePrimitive: { if (primitive_info[j].coordinates != 3) { status=MagickFalse; break; } TraceEllipse(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point,primitive_info[j+2].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case CirclePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } TraceCircle(primitive_info+j,primitive_info[j].point, primitive_info[j+1].point); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PolylinePrimitive: break; case PolygonPrimitive: { primitive_info[i]=primitive_info[j]; primitive_info[i].coordinates=0; primitive_info[j].coordinates++; i++; break; } case BezierPrimitive: { if (primitive_info[j].coordinates < 3) { status=MagickFalse; break; } TraceBezier(primitive_info+j,primitive_info[j].coordinates); i=(ssize_t) (j+primitive_info[j].coordinates); break; } case PathPrimitive: { i=(ssize_t) (j+TracePath(primitive_info+j,token)); break; } case AlphaPrimitive: case ColorPrimitive: { ssize_t method; if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); method=ParseCommandOption(MagickMethodOptions,MagickFalse,token); if (method == -1) status=MagickFalse; else primitive_info[j].method=(PaintMethod) method; break; } case TextPrimitive: { if (primitive_info[j].coordinates != 1) { status=MagickFalse; break; } if (*token != ',') GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } case ImagePrimitive: { if (primitive_info[j].coordinates != 2) { status=MagickFalse; break; } GetNextToken(q,&q,extent,token); primitive_info[j].text=AcquireString(token); break; } } if (primitive_info == (PrimitiveInfo *) NULL) break; if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p),p); if (status == MagickFalse) break; primitive_info[i].primitive=UndefinedPrimitive; if (i == 0) continue; /* Transform points. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+ graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx; primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+ graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty; point=primitive_info[i].point; if (point.x < graphic_context[n]->bounds.x1) graphic_context[n]->bounds.x1=point.x; if (point.y < graphic_context[n]->bounds.y1) graphic_context[n]->bounds.y1=point.y; if (point.x > graphic_context[n]->bounds.x2) graphic_context[n]->bounds.x2=point.x; if (point.y > graphic_context[n]->bounds.y2) graphic_context[n]->bounds.y2=point.y; if (primitive_info[i].primitive == ImagePrimitive) break; if (i >= (ssize_t) number_points) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } if (graphic_context[n]->render != MagickFalse) { if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) && (LocaleCompare(graphic_context[n]->clip_mask, graphic_context[n-1]->clip_mask) != 0)) status&=DrawClipPath(image,graphic_context[n], graphic_context[n]->clip_mask,exception); status&=DrawPrimitive(image,graphic_context[n],primitive_info, exception); } if (primitive_info->text != (char *) NULL) primitive_info->text=(char *) RelinquishMagickMemory( primitive_info->text); proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType) primitive_extent); if (proceed == MagickFalse) break; if (status == 0) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image"); /* Relinquish resources. */ token=DestroyString(token); if (primitive_info != (PrimitiveInfo *) NULL) primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info); primitive=DestroyString(primitive); for ( ; n >= 0; n--) graphic_context[n]=DestroyDrawInfo(graphic_context[n]); graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context); if (status == MagickFalse) ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition", keyword); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGradientImage() draws a linear gradient on the image. % % The format of the DrawGradientImage method is: % % MagickBooleanType DrawGradientImage(Image *image, % const DrawInfo *draw_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ static inline double GetStopColorOffset(const GradientInfo *gradient, const ssize_t x,const ssize_t y) { switch (gradient->type) { case UndefinedGradient: case LinearGradient: { double gamma, length, offset, scale; PointInfo p, q; const SegmentInfo *gradient_vector; gradient_vector=(&gradient->gradient_vector); p.x=gradient_vector->x2-gradient_vector->x1; p.y=gradient_vector->y2-gradient_vector->y1; q.x=(double) x-gradient_vector->x1; q.y=(double) y-gradient_vector->y1; length=sqrt(q.x*q.x+q.y*q.y); gamma=sqrt(p.x*p.x+p.y*p.y)*length; gamma=PerceptibleReciprocal(gamma); scale=p.x*q.x+p.y*q.y; offset=gamma*scale*length; return(offset); } case RadialGradient: { PointInfo v; if (gradient->spread == RepeatSpread) { v.x=(double) x-gradient->center.x; v.y=(double) y-gradient->center.y; return(sqrt(v.x*v.x+v.y*v.y)); } v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians( gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians( gradient->angle))))/gradient->radii.x; v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians( gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians( gradient->angle))))/gradient->radii.y; return(sqrt(v.x*v.x+v.y*v.y)); } } return(0.0); } static int StopInfoCompare(const void *x,const void *y) { StopInfo *stop_1, *stop_2; stop_1=(StopInfo *) x; stop_2=(StopInfo *) y; if (stop_1->offset > stop_2->offset) return(1); if (fabs(stop_1->offset-stop_2->offset) <= DrawEpsilon) return(0); return(-1); } MagickExport MagickBooleanType DrawGradientImage(Image *image, const DrawInfo *draw_info,ExceptionInfo *exception) { CacheView *image_view; const GradientInfo *gradient; const SegmentInfo *gradient_vector; double length; MagickBooleanType status; PixelInfo zero; PointInfo point; RectangleInfo bounding_box; ssize_t y; /* Draw linear or radial gradient on image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); gradient=(&draw_info->gradient); qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo), StopInfoCompare); gradient_vector=(&gradient->gradient_vector); point.x=gradient_vector->x2-gradient_vector->x1; point.y=gradient_vector->y2-gradient_vector->y1; length=sqrt(point.x*point.x+point.y*point.y); bounding_box=gradient->bounding_box; status=MagickTrue; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++) { PixelInfo composite, pixel; double alpha, offset; register Quantum *magick_restrict q; register ssize_t i, x; ssize_t j; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; composite=zero; offset=GetStopColorOffset(gradient,0,y); if (gradient->type != RadialGradient) offset/=length; for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++) { GetPixelInfoPixel(image,q,&pixel); switch (gradient->spread) { case UndefinedSpread: case PadSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset/=length; } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if ((offset < 0.0) || (i == 0)) composite=gradient->stops[0].color; else if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops)) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case ReflectSpread: { if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type != RadialGradient) offset/=length; } if (offset < 0.0) offset=(-offset); if ((ssize_t) fmod(offset,2.0) == 0) offset=fmod(offset,1.0); else offset=1.0-fmod(offset,1.0); for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } case RepeatSpread: { MagickBooleanType antialias; double repeat; antialias=MagickFalse; repeat=0.0; if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) || (y != (ssize_t) ceil(gradient_vector->y1-0.5))) { offset=GetStopColorOffset(gradient,x,y); if (gradient->type == LinearGradient) { repeat=fmod(offset,length); if (repeat < 0.0) repeat=length-fmod(-repeat,length); else repeat=fmod(offset,length); antialias=(repeat < length) && ((repeat+1.0) > length) ? MagickTrue : MagickFalse; offset=repeat/length; } else { repeat=fmod(offset,gradient->radius); if (repeat < 0.0) repeat=gradient->radius-fmod(-repeat,gradient->radius); else repeat=fmod(offset,gradient->radius); antialias=repeat+1.0 > gradient->radius ? MagickTrue : MagickFalse; offset=repeat/gradient->radius; } } for (i=0; i < (ssize_t) gradient->number_stops; i++) if (offset < gradient->stops[i].offset) break; if (i == 0) composite=gradient->stops[0].color; else if (i == (ssize_t) gradient->number_stops) composite=gradient->stops[gradient->number_stops-1].color; else { j=i; i--; alpha=(offset-gradient->stops[i].offset)/ (gradient->stops[j].offset-gradient->stops[i].offset); if (antialias != MagickFalse) { if (gradient->type == LinearGradient) alpha=length-repeat; else alpha=gradient->radius-repeat; i=0; j=(ssize_t) gradient->number_stops-1L; } CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha, &gradient->stops[j].color,alpha,&composite); } break; } } CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha, &pixel); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P a t t e r n P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPatternPath() draws a pattern. % % The format of the DrawPatternPath method is: % % MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info, % const char *name,Image **pattern,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o name: the pattern name. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DrawPatternPath(Image *image, const DrawInfo *draw_info,const char *name,Image **pattern, ExceptionInfo *exception) { char property[MagickPathExtent]; const char *geometry, *path, *type; DrawInfo *clone_info; ImageInfo *image_info; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (const DrawInfo *) NULL); assert(name != (const char *) NULL); (void) FormatLocaleString(property,MagickPathExtent,"%s",name); path=GetImageArtifact(image,property); if (path == (const char *) NULL) return(MagickFalse); (void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name); geometry=GetImageArtifact(image,property); if (geometry == (const char *) NULL) return(MagickFalse); if ((*pattern) != (Image *) NULL) *pattern=DestroyImage(*pattern); image_info=AcquireImageInfo(); image_info->size=AcquireString(geometry); *pattern=AcquireImage(image_info,exception); image_info=DestroyImageInfo(image_info); (void) QueryColorCompliance("#000000ff",AllCompliance, &(*pattern)->background_color,exception); (void) SetImageBackgroundColor(*pattern,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), "begin pattern-path %s %s",name,geometry); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill_pattern=NewImageList(); clone_info->stroke_pattern=NewImageList(); (void) FormatLocaleString(property,MagickPathExtent,"%s-type",name); type=GetImageArtifact(image,property); if (type != (const char *) NULL) clone_info->gradient.type=(GradientType) ParseCommandOption( MagickGradientOptions,MagickFalse,type); (void) CloneString(&clone_info->primitive,path); status=DrawImage(*pattern,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w P o l y g o n P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPolygonPrimitive() draws a polygon on the image. % % The format of the DrawPolygonPrimitive method is: % % MagickBooleanType DrawPolygonPrimitive(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info) { register ssize_t i; assert(polygon_info != (PolygonInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (polygon_info[i] != (PolygonInfo *) NULL) polygon_info[i]=DestroyPolygonInfo(polygon_info[i]); polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info); return(polygon_info); } static PolygonInfo **AcquirePolygonThreadSet( const PrimitiveInfo *primitive_info) { PathInfo *magick_restrict path_info; PolygonInfo **polygon_info; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads, sizeof(*polygon_info)); if (polygon_info == (PolygonInfo **) NULL) return((PolygonInfo **) NULL); (void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info)); path_info=ConvertPrimitiveToPath(primitive_info); if (path_info == (PathInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); for (i=0; i < (ssize_t) number_threads; i++) { polygon_info[i]=ConvertPathToPolygon(path_info); if (polygon_info[i] == (PolygonInfo *) NULL) return(DestroyPolygonThreadSet(polygon_info)); } path_info=(PathInfo *) RelinquishMagickMemory(path_info); return(polygon_info); } static double GetFillAlpha(PolygonInfo *polygon_info,const double mid, const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, const ssize_t y,double *stroke_alpha) { double alpha, beta, distance, subpath_alpha; PointInfo delta; register const PointInfo *q; register EdgeInfo *p; register ssize_t i; ssize_t j, winding_number; /* Compute fill & stroke opacity for this (x,y) point. */ *stroke_alpha=0.0; subpath_alpha=0.0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= (p->bounds.y1-mid-0.5)) break; if ((double) y > (p->bounds.y2+mid+0.5)) { (void) DestroyEdge(polygon_info,(size_t) j); continue; } if (((double) x <= (p->bounds.x1-mid-0.5)) || ((double) x > (p->bounds.x2+mid+0.5))) continue; i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) { if ((double) y <= (p->points[i-1].y-mid-0.5)) break; if ((double) y > (p->points[i].y+mid+0.5)) continue; if (p->scanline != (double) y) { p->scanline=(double) y; p->highwater=(size_t) i; } /* Compute distance between a point and an edge. */ q=p->points+i-1; delta.x=(q+1)->x-q->x; delta.y=(q+1)->y-q->y; beta=delta.x*(x-q->x)+delta.y*(y-q->y); if (beta < 0.0) { delta.x=(double) x-q->x; delta.y=(double) y-q->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=delta.x*delta.x+delta.y*delta.y; if (beta > alpha) { delta.x=(double) x-(q+1)->x; delta.y=(double) y-(q+1)->y; distance=delta.x*delta.x+delta.y*delta.y; } else { alpha=1.0/alpha; beta=delta.x*(y-q->y)-delta.y*(x-q->x); distance=alpha*beta*beta; } } /* Compute stroke & subpath opacity. */ beta=0.0; if (p->ghostline == MagickFalse) { alpha=mid+0.5; if ((*stroke_alpha < 1.0) && (distance <= ((alpha+0.25)*(alpha+0.25)))) { alpha=mid-0.5; if (distance <= ((alpha+0.25)*(alpha+0.25))) *stroke_alpha=1.0; else { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt((double) distance); alpha=beta-mid-0.5; if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25))) *stroke_alpha=(alpha-0.25)*(alpha-0.25); } } } if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0)) continue; if (distance <= 0.0) { subpath_alpha=1.0; continue; } if (distance > 1.0) continue; if (fabs(beta) < DrawEpsilon) { beta=1.0; if (fabs(distance-1.0) >= DrawEpsilon) beta=sqrt(distance); } alpha=beta-1.0; if (subpath_alpha < (alpha*alpha)) subpath_alpha=alpha*alpha; } } /* Compute fill opacity. */ if (fill == MagickFalse) return(0.0); if (subpath_alpha >= 1.0) return(1.0); /* Determine winding number. */ winding_number=0; p=polygon_info->edges; for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++) { if ((double) y <= p->bounds.y1) break; if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1)) continue; if ((double) x > p->bounds.x2) { winding_number+=p->direction ? 1 : -1; continue; } i=(ssize_t) MagickMax((double) p->highwater,1.0); for ( ; i < (ssize_t) p->number_points; i++) if ((double) y <= p->points[i].y) break; q=p->points+i-1; if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x))) winding_number+=p->direction ? 1 : -1; } if (fill_rule != NonZeroRule) { if ((MagickAbsoluteValue(winding_number) & 0x01) != 0) return(1.0); } else if (MagickAbsoluteValue(winding_number) != 0) return(1.0); return(subpath_alpha); } static MagickBooleanType DrawPolygonPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType fill, status; double mid; PolygonInfo **magick_restrict polygon_info; register EdgeInfo *p; register ssize_t i; SegmentInfo bounds; ssize_t start_y, stop_y, y; /* Compute bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); assert(primitive_info != (PrimitiveInfo *) NULL); if (primitive_info->coordinates == 0) return(MagickTrue); polygon_info=AcquirePolygonThreadSet(primitive_info); if (polygon_info == (PolygonInfo **) NULL) return(MagickFalse); DisableMSCWarning(4127) if (0) DrawBoundingRectangles(image,draw_info,polygon_info[0],exception); RestoreMSCWarning if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon"); fill=(primitive_info->method == FillToBorderMethod) || (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse; mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; bounds=polygon_info[0]->edges[0].bounds; for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++) { p=polygon_info[0]->edges+i; if (p->bounds.x1 < bounds.x1) bounds.x1=p->bounds.x1; if (p->bounds.y1 < bounds.y1) bounds.y1=p->bounds.y1; if (p->bounds.x2 > bounds.x2) bounds.x2=p->bounds.x2; if (p->bounds.y2 > bounds.y2) bounds.y2=p->bounds.y2; } bounds.x1-=(mid+1.0); bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >= image->columns ? (double) image->columns-1 : bounds.x1; bounds.y1-=(mid+1.0); bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >= image->rows ? (double) image->rows-1 : bounds.y1; bounds.x2+=(mid+1.0); bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >= image->columns ? (double) image->columns-1 : bounds.x2; bounds.y2+=(mid+1.0); bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >= image->rows ? (double) image->rows-1 : bounds.y2; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); if ((primitive_info->coordinates == 1) || (polygon_info[0]->number_edges == 0)) { /* Draw point. */ start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=start_y; y <= stop_y; y++) { MagickBooleanType sync; PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); x=start_x; q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for ( ; x <= stop_x; x++) { if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) && (y == (ssize_t) ceil(primitive_info->point.y-0.5))) { GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-polygon"); return(status); } /* Draw polygon or line. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); start_y=(ssize_t) ceil(bounds.y1-0.5); stop_y=(ssize_t) floor(bounds.y2+0.5); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=start_y; y <= stop_y; y++) { const int id = GetOpenMPThreadId(); double fill_alpha, stroke_alpha; PixelInfo fill_color, stroke_color; register Quantum *magick_restrict q; register ssize_t x; ssize_t start_x, stop_x; if (status == MagickFalse) continue; start_x=(ssize_t) ceil(bounds.x1-0.5); stop_x=(ssize_t) floor(bounds.x2+0.5); q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+ 1),1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=start_x; x <= stop_x; x++) { /* Fill and/or stroke. */ fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule, x,y,&stroke_alpha); if (draw_info->stroke_antialias == MagickFalse) { fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0; stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0; } GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception); fill_alpha=fill_alpha*fill_color.alpha; CompositePixelOver(image,&fill_color,fill_alpha,q,(double) GetPixelAlpha(image,q),q); GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception); stroke_alpha=stroke_alpha*stroke_color.alpha; CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double) GetPixelAlpha(image,q),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); polygon_info=DestroyPolygonThreadSet(polygon_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon"); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image. % % The format of the DrawPrimitive method is: % % MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info, % PrimitiveInfo *primitive_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % o exception: return any errors or warnings in this structure. % */ static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info) { const char *methods[] = { "point", "replace", "floodfill", "filltoborder", "reset", "?" }; PointInfo p, q, point; register ssize_t i, x; ssize_t coordinates, y; x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); switch (primitive_info->primitive) { case AlphaPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ColorPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ColorPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case ImagePrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "ImagePrimitive %.20g,%.20g",(double) x,(double) y); return; } case PointPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "PointPrimitive %.20g,%.20g %s",(double) x,(double) y, methods[primitive_info->method]); return; } case TextPrimitive: { (void) LogMagickEvent(DrawEvent,GetMagickModule(), "TextPrimitive %.20g,%.20g",(double) x,(double) y); return; } default: break; } coordinates=0; p=primitive_info[0].point; q.x=(-1.0); q.y=(-1.0); for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) { point=primitive_info[i].point; if (coordinates <= 0) { coordinates=(ssize_t) primitive_info[i].coordinates; (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin open (%.20g)",(double) coordinates); p=point; } point=primitive_info[i].point; if ((fabs(q.x-point.x) >= DrawEpsilon) || (fabs(q.y-point.y) >= DrawEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y); else (void) LogMagickEvent(DrawEvent,GetMagickModule(), " %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y); q=point; coordinates--; if (coordinates > 0) continue; if ((fabs(p.x-point.x) >= DrawEpsilon) || (fabs(p.y-point.y) >= DrawEpsilon)) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)", (double) coordinates); else (void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)", (double) coordinates); } } MagickExport MagickBooleanType DrawPrimitive(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { CacheView *image_view; MagickStatusType status; register ssize_t i, x; ssize_t y; if (image->debug != MagickFalse) { (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-primitive"); (void) LogMagickEvent(DrawEvent,GetMagickModule(), " affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx, draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy, draw_info->affine.tx,draw_info->affine.ty); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; x=(ssize_t) ceil(primitive_info->point.x-0.5); y=(ssize_t) ceil(primitive_info->point.y-0.5); image_view=AcquireAuthenticCacheView(image,exception); switch (primitive_info->primitive) { case AlphaPrimitive: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { ChannelType channel_mask; PixelInfo target; (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } channel_mask=SetImageChannelMask(image,AlphaChannel); status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); (void) SetImageChannelMask(image,channel_mask); break; } case ResetMethod: { MagickBooleanType sync; PixelInfo pixel; for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case ColorPrimitive: { switch (primitive_info->method) { case PointMethod: default: { PixelInfo pixel; register Quantum *q; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetPixelInfo(image,&pixel); GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case ReplaceMethod: { MagickBooleanType sync; PixelInfo pixel, target; (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, exception); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) { q+=GetPixelChannels(image); continue; } GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } case FloodfillMethod: case FillToBorderMethod: { PixelInfo target; (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, &target,exception); if (primitive_info->method == FillToBorderMethod) { target.red=(double) draw_info->border_color.red; target.green=(double) draw_info->border_color.green; target.blue=(double) draw_info->border_color.blue; } status&=FloodfillPaintImage(image,draw_info,&target,x,y, primitive_info->method == FloodfillMethod ? MagickFalse : MagickTrue,exception); break; } case ResetMethod: { MagickBooleanType sync; PixelInfo pixel; GetPixelInfo(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { GetFillColor(draw_info,x,y,&pixel,exception); SetPixelViaPixelInfo(image,&pixel,q); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) break; } break; } } break; } case ImagePrimitive: { AffineMatrix affine; char composite_geometry[MagickPathExtent]; Image *composite_image; ImageInfo *clone_info; RectangleInfo geometry; ssize_t x1, y1; if (primitive_info->text == (char *) NULL) break; clone_info=AcquireImageInfo(); if (LocaleNCompare(primitive_info->text,"data:",5) == 0) composite_image=ReadInlineImage(clone_info,primitive_info->text, exception); else { (void) CopyMagickString(clone_info->filename,primitive_info->text, MagickPathExtent); composite_image=ReadImage(clone_info,exception); } clone_info=DestroyImageInfo(clone_info); if (composite_image == (Image *) NULL) break; (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor) NULL,(void *) NULL); x1=(ssize_t) ceil(primitive_info[1].point.x-0.5); y1=(ssize_t) ceil(primitive_info[1].point.y-0.5); if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) || ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows))) { /* Resize image. */ (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y); composite_image->filter=image->filter; (void) TransformImage(&composite_image,(char *) NULL, composite_geometry,exception); } if (composite_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, exception); if (draw_info->alpha != OpaqueAlpha) (void) SetImageAlpha(composite_image,draw_info->alpha,exception); SetGeometry(image,&geometry); image->gravity=draw_info->gravity; geometry.x=x; geometry.y=y; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double) composite_image->rows,(double) geometry.x,(double) geometry.y); (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception); affine=draw_info->affine; affine.tx=(double) geometry.x; affine.ty=(double) geometry.y; composite_image->interpolate=image->interpolate; if (draw_info->compose == OverCompositeOp) (void) DrawAffineImage(image,composite_image,&affine,exception); else (void) CompositeImage(image,composite_image,draw_info->compose, MagickTrue,geometry.x,geometry.y,exception); composite_image=DestroyImage(composite_image); break; } case PointPrimitive: { PixelInfo fill_color; register Quantum *q; if ((y < 0) || (y >= (ssize_t) image->rows)) break; if ((x < 0) || (x >= (ssize_t) image->columns)) break; q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); if (q == (Quantum *) NULL) break; GetFillColor(draw_info,x,y,&fill_color,exception); CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q, (double) GetPixelAlpha(image,q),q); (void) SyncCacheViewAuthenticPixels(image_view,exception); break; } case TextPrimitive: { char geometry[MagickPathExtent]; DrawInfo *clone_info; if (primitive_info->text == (char *) NULL) break; clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); (void) CloneString(&clone_info->text,primitive_info->text); (void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f", primitive_info->point.x,primitive_info->point.y); (void) CloneString(&clone_info->geometry,geometry); status&=AnnotateImage(image,clone_info,exception); clone_info=DestroyDrawInfo(clone_info); break; } default: { double mid, scale; DrawInfo *clone_info; if (IsEventLogging() != MagickFalse) LogPrimitiveInfo(primitive_info); scale=ExpandAffine(&draw_info->affine); if ((draw_info->dash_pattern != (double *) NULL) && (fabs(draw_info->dash_pattern[0]) >= DrawEpsilon) && (fabs(scale*draw_info->stroke_width) >= DrawEpsilon) && (draw_info->stroke.alpha != (Quantum) TransparentAlpha)) { /* Draw dash polygon. */ clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); (void) DrawDashPolygon(draw_info,primitive_info,image,exception); break; } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; if ((mid > 1.0) && ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) || (draw_info->stroke_pattern != (Image *) NULL))) { MagickBooleanType closed_path; /* Draw strokes while respecting line cap/join attributes. */ for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ; closed_path= (fabs(primitive_info[i-1].point.x-primitive_info[0].point.x) < DrawEpsilon) && (fabs(primitive_info[i-1].point.y-primitive_info[0].point.y) < DrawEpsilon) ? MagickTrue : MagickFalse; i=(ssize_t) primitive_info[0].coordinates; if (((closed_path != MagickFalse) && (draw_info->linejoin == RoundJoin)) || (primitive_info[i].primitive != UndefinedPrimitive)) { (void) DrawPolygonPrimitive(image,draw_info,primitive_info, exception); break; } if (draw_info->linecap == RoundCap) { (void) DrawPolygonPrimitive(image,draw_info,primitive_info, exception); break; } clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->stroke_width=0.0; clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; status&=DrawPolygonPrimitive(image,clone_info,primitive_info, exception); clone_info=DestroyDrawInfo(clone_info); status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); break; } status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); break; } } image_view=DestroyCacheView(image_view); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w S t r o k e P o l y g o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on % the image while respecting the line cap and join attributes. % % The format of the DrawStrokePolygon method is: % % MagickBooleanType DrawStrokePolygon(Image *image, % const DrawInfo *draw_info,const PrimitiveInfo *primitive_info) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o primitive_info: Specifies a pointer to a PrimitiveInfo structure. % % */ static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info, const PrimitiveInfo *primitive_info,ExceptionInfo *exception) { PrimitiveInfo linecap[5]; register ssize_t i; for (i=0; i < 4; i++) linecap[i]=(*primitive_info); linecap[0].coordinates=4; linecap[1].point.x+=2.0*DrawEpsilon; linecap[2].point.x+=2.0*DrawEpsilon; linecap[2].point.y+=2.0*DrawEpsilon; linecap[3].point.y+=2.0*DrawEpsilon; linecap[4].primitive=UndefinedPrimitive; (void) DrawPolygonPrimitive(image,draw_info,linecap,exception); } static MagickBooleanType DrawStrokePolygon(Image *image, const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, ExceptionInfo *exception) { DrawInfo *clone_info; MagickBooleanType closed_path; MagickStatusType status; PrimitiveInfo *stroke_polygon; register const PrimitiveInfo *p, *q; /* Draw stroked polygon. */ if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " begin draw-stroke-polygon"); clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); clone_info->fill=draw_info->stroke; if (clone_info->fill_pattern != (Image *) NULL) clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern); if (clone_info->stroke_pattern != (Image *) NULL) clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, MagickTrue,exception); clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; clone_info->stroke_width=0.0; clone_info->fill_rule=NonZeroRule; status=MagickTrue; for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates) { stroke_polygon=TraceStrokePolygon(draw_info,p); status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception); if (status == 0) break; stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon); q=p+p->coordinates-1; closed_path=(fabs(q->point.x-p->point.x) < DrawEpsilon) && (fabs(q->point.y-p->point.y) < DrawEpsilon) ? MagickTrue : MagickFalse; if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse)) { DrawRoundLinecap(image,draw_info,p,exception); DrawRoundLinecap(image,draw_info,q,exception); } } clone_info=DestroyDrawInfo(clone_info); if (image->debug != MagickFalse) (void) LogMagickEvent(DrawEvent,GetMagickModule(), " end draw-stroke-polygon"); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A f f i n e M a t r i x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAffineMatrix() returns an AffineMatrix initialized to the identity % matrix. % % The format of the GetAffineMatrix method is: % % void GetAffineMatrix(AffineMatrix *affine_matrix) % % A description of each parameter follows: % % o affine_matrix: the affine matrix. % */ MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(affine_matrix != (AffineMatrix *) NULL); (void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix)); affine_matrix->sx=1.0; affine_matrix->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t D r a w I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetDrawInfo() initializes draw_info to default values from image_info. % % The format of the GetDrawInfo method is: % % void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) % % A description of each parameter follows: % % o image_info: the image info.. % % o draw_info: the draw info. % */ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { char *next_token; const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_width=1.0; draw_info->fill_rule=EvenOddRule; draw_info->alpha=OpaqueAlpha; draw_info->fill_alpha=OpaqueAlpha; draw_info->stroke_alpha=OpaqueAlpha; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->debug=IsEventLogging(); draw_info->stroke_antialias=clone_info->antialias; if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (fabs(clone_info->pointsize) >= DrawEpsilon) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,&next_token); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r m u t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Permutate() returns the permuation of the (n,k). % % The format of the Permutate method is: % % void Permutate(ssize_t n,ssize_t k) % % A description of each parameter follows: % % o n: % % o k: % % */ static inline double Permutate(const ssize_t n,const ssize_t k) { double r; register ssize_t i; r=1.0; for (i=k+1; i <= n; i++) r*=i; for (i=1; i <= (n-k); i++) r/=i; return(r); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a c e P r i m i t i v e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TracePrimitive is a collection of methods for generating graphic % primitives such as arcs, ellipses, paths, etc. % */ static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end,const PointInfo degrees) { PointInfo center, radii; center.x=0.5*(end.x+start.x); center.y=0.5*(end.y+start.y); radii.x=fabs(center.x-start.x); radii.y=fabs(center.y-start.y); TraceEllipse(primitive_info,center,radii,degrees); } static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end,const PointInfo arc,const double angle, const MagickBooleanType large_arc,const MagickBooleanType sweep) { double alpha, beta, delta, factor, gamma, theta; PointInfo center, points[3], radii; register double cosine, sine; register PrimitiveInfo *p; register ssize_t i; size_t arc_segments; if ((fabs(start.x-end.x) < DrawEpsilon) && (fabs(start.y-end.y) < DrawEpsilon)) { TracePoint(primitive_info,end); return; } radii.x=fabs(arc.x); radii.y=fabs(arc.y); if ((fabs(radii.x) < DrawEpsilon) || (fabs(radii.y) < DrawEpsilon)) { TraceLine(primitive_info,start,end); return; } cosine=cos(DegreesToRadians(fmod((double) angle,360.0))); sine=sin(DegreesToRadians(fmod((double) angle,360.0))); center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2); center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2); delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/ (radii.y*radii.y); if (delta < DrawEpsilon) { TraceLine(primitive_info,start,end); return; } if (delta > 1.0) { radii.x*=sqrt((double) delta); radii.y*=sqrt((double) delta); } points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x); points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y); points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x); points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y); alpha=points[1].x-points[0].x; beta=points[1].y-points[0].y; factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25; if (factor <= 0.0) factor=0.0; else { factor=sqrt((double) factor); if (sweep == large_arc) factor=(-factor); } center.x=(double) ((points[0].x+points[1].x)/2-factor*beta); center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha); alpha=atan2(points[0].y-center.y,points[0].x-center.x); theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha; if ((theta < 0.0) && (sweep != MagickFalse)) theta+=2.0*MagickPI; else if ((theta > 0.0) && (sweep == MagickFalse)) theta-=2.0*MagickPI; arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+DrawEpsilon)))); p=primitive_info; for (i=0; i < (ssize_t) arc_segments; i++) { beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments)); gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))* sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/ sin(fmod((double) beta,DegreesToRadians(360.0))); points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/ arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+ (double) i*theta/arc_segments),DegreesToRadians(360.0)))); points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)* theta/arc_segments),DegreesToRadians(360.0)))); points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double) (i+1)*theta/arc_segments),DegreesToRadians(360.0)))); p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x; p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y; (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y* points[0].y); (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y* points[0].y); (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y* points[1].y); (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y* points[1].y); (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y* points[2].y); (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y* points[2].y); if (i == (ssize_t) (arc_segments-1)) (p+3)->point=end; TraceBezier(p,4); p+=p->coordinates; } primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceBezier(PrimitiveInfo *primitive_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coeficients. */ quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=(size_t) MagickMin((double) quantum/number_coordinates, (double) BezierQuantum); control_points=quantum*number_coordinates; coefficients=(double *) AcquireQuantumMemory((size_t) number_coordinates,sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory((size_t) control_points, sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { TracePoint(p,points[i]); p+=p->coordinates; } TracePoint(p,end); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); } static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { double alpha, beta, radius; PointInfo offset, degrees; alpha=end.x-start.x; beta=end.y-start.y; radius=hypot((double) alpha,(double) beta); offset.x=(double) radius; offset.y=(double) radius; degrees.x=0.0; degrees.y=360.0; TraceEllipse(primitive_info,start,offset,degrees); } static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo stop,const PointInfo degrees) { double delta, step, y; PointInfo angle, point; register PrimitiveInfo *p; register ssize_t i; /* Ellipses are just short segmented polys. */ if ((fabs(stop.x) < DrawEpsilon) && (fabs(stop.y) < DrawEpsilon)) { TracePoint(primitive_info,start); return; } delta=2.0/MagickMax(stop.x,stop.y); step=MagickPI/8.0; if ((delta >= 0.0) && (delta < (MagickPI/8.0))) step=MagickPI/(4*(MagickPI/delta/2+0.5)); angle.x=DegreesToRadians(degrees.x); y=degrees.y; while (y < degrees.x) y+=360.0; angle.y=DegreesToRadians(y); for (p=primitive_info; angle.x < angle.y; angle.x+=step) { point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x; point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y; TracePoint(p,point); p+=p->coordinates; } point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x; point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y; TracePoint(p,point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { TracePoint(primitive_info,start); if ((fabs(start.x-end.x) < DrawEpsilon) && (fabs(start.y-end.y) < DrawEpsilon)) { primitive_info->primitive=PointPrimitive; primitive_info->coordinates=1; return; } TracePoint(primitive_info+1,end); (primitive_info+1)->primitive=primitive_info->primitive; primitive_info->coordinates=2; } static size_t TracePath(PrimitiveInfo *primitive_info,const char *path) { char *next_token, token[MagickPathExtent]; const char *p; double x, y; int attribute, last_attribute; PointInfo end = {0.0, 0.0}, points[4] = { {0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0} }, point = {0.0, 0.0}, start = {0.0, 0.0}; PrimitiveType primitive_type; register PrimitiveInfo *q; register ssize_t i; size_t number_coordinates, z_count; attribute=0; number_coordinates=0; z_count=0; primitive_type=primitive_info->primitive; q=primitive_info; for (p=path; *p != '\0'; ) { while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == '\0') break; last_attribute=attribute; attribute=(int) (*p++); switch (attribute) { case 'a': case 'A': { double angle; MagickBooleanType large_arc, sweep; PointInfo arc; /* Compute arc points. */ do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arc.x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arc.y=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); angle=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse; GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); end.x=(double) (attribute == (int) 'A' ? x : point.x+x); end.y=(double) (attribute == (int) 'A' ? y : point.y+y); TraceArcPath(q,point,end,arc,angle,large_arc,sweep); q+=q->coordinates; point=end; while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; } while (IsPoint(p) != MagickFalse); break; } case 'c': case 'C': { /* Compute bezier points. */ do { points[0]=point; for (i=1; i < 4; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); end.x=(double) (attribute == (int) 'C' ? x : point.x+x); end.y=(double) (attribute == (int) 'C' ? y : point.y+y); points[i]=end; } for (i=0; i < 4; i++) (q+i)->point=points[i]; TraceBezier(q,4); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 'H': case 'h': { do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); point.x=(double) (attribute == (int) 'H' ? x: point.x+x); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'l': case 'L': { do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); point.x=(double) (attribute == (int) 'L' ? x : point.x+x); point.y=(double) (attribute == (int) 'L' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'M': case 'm': { if (q != primitive_info) { primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; } i=0; do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); point.x=(double) (attribute == (int) 'M' ? x : point.x+x); point.y=(double) (attribute == (int) 'M' ? y : point.y+y); if (i == 0) start=point; i++; TracePoint(q,point); q+=q->coordinates; if ((i != 0) && (attribute == (int) 'M')) { TracePoint(q,point); q+=q->coordinates; } } while (IsPoint(p) != MagickFalse); break; } case 'q': case 'Q': { /* Compute bezier points. */ do { points[0]=point; for (i=1; i < 3; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (*p == ',') p++; end.x=(double) (attribute == (int) 'Q' ? x : point.x+x); end.y=(double) (attribute == (int) 'Q' ? y : point.y+y); points[i]=end; } for (i=0; i < 3; i++) (q+i)->point=points[i]; TraceBezier(q,3); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 's': case 'S': { /* Compute bezier points. */ do { points[0]=points[3]; points[1].x=2.0*points[3].x-points[2].x; points[1].y=2.0*points[3].y-points[2].y; for (i=2; i < 4; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); if (*p == ',') p++; end.x=(double) (attribute == (int) 'S' ? x : point.x+x); end.y=(double) (attribute == (int) 'S' ? y : point.y+y); points[i]=end; } if (strchr("CcSs",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 4; i++) (q+i)->point=points[i]; TraceBezier(q,4); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 't': case 'T': { /* Compute bezier points. */ do { points[0]=points[2]; points[1].x=2.0*points[2].x-points[1].x; points[1].y=2.0*points[2].y-points[1].y; for (i=2; i < 3; i++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); x=StringToDouble(token,&next_token); GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); end.x=(double) (attribute == (int) 'T' ? x : point.x+x); end.y=(double) (attribute == (int) 'T' ? y : point.y+y); points[i]=end; } if (strchr("QqTt",last_attribute) == (char *) NULL) { points[0]=point; points[1]=point; } for (i=0; i < 3; i++) (q+i)->point=points[i]; TraceBezier(q,3); q+=q->coordinates; point=end; } while (IsPoint(p) != MagickFalse); break; } case 'v': case 'V': { do { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); y=StringToDouble(token,&next_token); point.y=(double) (attribute == (int) 'V' ? y : point.y+y); TracePoint(q,point); q+=q->coordinates; } while (IsPoint(p) != MagickFalse); break; } case 'z': case 'Z': { point=start; TracePoint(q,point); q+=q->coordinates; primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; primitive_info=q; z_count++; break; } default: { if (isalpha((int) ((unsigned char) attribute)) != 0) (void) FormatLocaleFile(stderr,"attribute not recognized: %c\n", attribute); break; } } } primitive_info->coordinates=(size_t) (q-primitive_info); number_coordinates+=primitive_info->coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { q--; q->primitive=primitive_type; if (z_count > 1) q->method=FillToBorderMethod; } q=primitive_info; return(number_coordinates); } static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start, const PointInfo end) { PointInfo point; register PrimitiveInfo *p; register ssize_t i; p=primitive_info; TracePoint(p,start); p+=p->coordinates; point.x=start.x; point.y=end.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,end); p+=p->coordinates; point.x=end.x; point.y=start.y; TracePoint(p,point); p+=p->coordinates; TracePoint(p,start); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceRoundRectangle(PrimitiveInfo *primitive_info, const PointInfo start,const PointInfo end,PointInfo arc) { PointInfo degrees, offset, point; register PrimitiveInfo *p; register ssize_t i; p=primitive_info; offset.x=fabs(end.x-start.x); offset.y=fabs(end.y-start.y); if (arc.x > (0.5*offset.x)) arc.x=0.5*offset.x; if (arc.y > (0.5*offset.y)) arc.y=0.5*offset.y; point.x=start.x+offset.x-arc.x; point.y=start.y+arc.y; degrees.x=270.0; degrees.y=360.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+offset.x-arc.x; point.y=start.y+offset.y-arc.y; degrees.x=0.0; degrees.y=90.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+offset.y-arc.y; degrees.x=90.0; degrees.y=180.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; point.x=start.x+arc.x; point.y=start.y+arc.y; degrees.x=180.0; degrees.y=270.0; TraceEllipse(p,point,arc,degrees); p+=p->coordinates; TracePoint(p,primitive_info->point); p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } } static void TraceSquareLinecap(PrimitiveInfo *primitive_info, const size_t number_vertices,const double offset) { double distance; register double dx, dy; register ssize_t i; ssize_t j; dx=0.0; dy=0.0; for (i=1; i < (ssize_t) number_vertices; i++) { dx=primitive_info[0].point.x-primitive_info[i].point.x; dy=primitive_info[0].point.y-primitive_info[i].point.y; if ((fabs((double) dx) >= DrawEpsilon) || (fabs((double) dy) >= DrawEpsilon)) break; } if (i == (ssize_t) number_vertices) i=(ssize_t) number_vertices-1L; distance=hypot((double) dx,(double) dy); primitive_info[0].point.x=(double) (primitive_info[i].point.x+ dx*(distance+offset)/distance); primitive_info[0].point.y=(double) (primitive_info[i].point.y+ dy*(distance+offset)/distance); for (j=(ssize_t) number_vertices-2; j >= 0; j--) { dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x; dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y; if ((fabs((double) dx) >= DrawEpsilon) || (fabs((double) dy) >= DrawEpsilon)) break; } distance=hypot((double) dx,(double) dy); primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+ dx*(distance+offset)/distance); primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+ dy*(distance+offset)/distance); } static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { typedef struct _LineSegment { double p, q; } LineSegment; double delta_theta, dot_product, mid, miterlimit; LineSegment dx, dy, inverse_slope, slope, theta; MagickBooleanType closed_path; PointInfo box_p[5], box_q[5], center, offset, *path_p, *path_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; register ssize_t i; size_t arc_segments, max_strokes, number_vertices; ssize_t j, n, p, q; /* Allocate paths. */ number_vertices=primitive_info->coordinates; max_strokes=2*number_vertices+6*BezierQuantum+360; path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) || (polygon_primitive == (PrimitiveInfo *) NULL)) return((PrimitiveInfo *) NULL); (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t) number_vertices*sizeof(*polygon_primitive)); closed_path= (fabs(primitive_info[number_vertices-1].point.x-primitive_info[0].point.x) < DrawEpsilon) && (fabs(primitive_info[number_vertices-1].point.y-primitive_info[0].point.y) < DrawEpsilon) ? MagickTrue : MagickFalse; if (((draw_info->linejoin == RoundJoin) || (draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse)) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= DrawEpsilon) || (fabs(dy.p) >= DrawEpsilon)) break; } if (n == (ssize_t) number_vertices) n=(ssize_t) number_vertices-1L; slope.p=0.0; inverse_slope.p=0.0; if (fabs(dx.p) < DrawEpsilon) { if (dx.p >= 0.0) slope.p=dy.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else slope.p=dy.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else if (fabs(dy.p) < DrawEpsilon) { if (dy.p >= 0.0) inverse_slope.p=dx.p < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else inverse_slope.p=dx.p < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else { slope.p=dy.p/dx.p; inverse_slope.p=(-1.0/slope.p); } mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; path_q[p++]=box_q[0]; path_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=0.0; inverse_slope.q=0.0; if (fabs(dx.q) < DrawEpsilon) { if (dx.q >= 0.0) slope.q=dy.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else slope.q=dy.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else if (fabs(dy.q) < DrawEpsilon) { if (dy.q >= 0.0) inverse_slope.q=dx.q < 0.0 ? -1.0/DrawEpsilon : 1.0/DrawEpsilon; else inverse_slope.q=dx.q < 0.0 ? 1.0/DrawEpsilon : -1.0/DrawEpsilon; } else { slope.q=dy.q/dx.q; inverse_slope.q=(-1.0/slope.q); } offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < DrawEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360)) { if (~max_strokes < (6*BezierQuantum+360)) { path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); } else { max_strokes+=6*BezierQuantum+360; path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes, sizeof(*path_p)); path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes, sizeof(*path_q)); } if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) { if (path_p != (PointInfo *) NULL) path_p=(PointInfo *) RelinquishMagickMemory(path_p); if (path_q != (PointInfo *) NULL) path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return((PrimitiveInfo *) NULL); } } dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/ (2.0*sqrt((double) (1.0/mid))))); path_q[q].x=box_q[1].x; path_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } path_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=2.0*MagickPI; arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/ (2.0*sqrt((double) (1.0/mid))))); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } path_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } path_p[p++]=box_p[1]; path_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon != (PrimitiveInfo *) NULL) { for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); } path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); }
GB_unjumbled_template.c
//------------------------------------------------------------------------------ // GB_unjumble_template: unjumble the vectors of a matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ { int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { //---------------------------------------------------------------------- // get the task description //---------------------------------------------------------------------- int64_t kfirst = A_slice [tid] ; int64_t klast = A_slice [tid+1] ; //---------------------------------------------------------------------- // sort vectors kfirst to klast //---------------------------------------------------------------------- for (int64_t k = kfirst ; k < klast ; k++) { //------------------------------------------------------------------ // check if the vector needs sorting //------------------------------------------------------------------ bool jumbled = false ; int64_t pA_start = Ap [k] ; int64_t pA_end = Ap [k+1] ; int64_t ilast = -1 ; for (int64_t pA = pA_start ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; if (i < ilast) { jumbled = true ; break ; } ilast = i ; } //------------------------------------------------------------------ // sort the vector //------------------------------------------------------------------ if (jumbled) { int64_t aknz = pA_end - pA_start ; GB_QSORT_WORKER ; } } } } #undef GB_QSORT_WORKER
target_teams_distribute_simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify %s // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd foo void test_no_clause() { int i; #pragma omp target teams distribute simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp target teams distribute simd' must be a for loop}} #pragma omp target teams distribute simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp target teams distribute simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd; for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp target teams distribute simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target teams distribute simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} #pragma omp target teams distribute simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-error@+4 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp target teams distribute simd collapse(2) firstprivate(i) for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) #pragma omp parallel for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd firstprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd firstprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; // expected-error@+1 {{lastprivate variable cannot be firstprivate}} expected-note@+1 {{defined as lastprivate}} #pragma omp target teams distribute simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{lastprivate variable cannot be firstprivate}} expected-note@+1 2 {{defined as lastprivate}} #pragma omp target teams distribute simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 3 {{lastprivate variable cannot be firstprivate}} expected-note@+1 3 {{defined as lastprivate}} #pragma omp target teams distribute simd lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp target teams distribute simd simdlen(64) safelen(8) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } }
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 16; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[(t)%2][i ][j ][k ] + coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
data.c
#include "data.h" #include "utils.h" #include "image.h" #include "dark_cuda.h" #include "box.h" #include "http_stream.h" #include <stdio.h> #include <stdlib.h> #include <string.h> extern int check_mistakes; #define NUMCHARS 37 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; list *get_paths(char *filename) { char *path; FILE *file = fopen(filename, "r"); if(!file) file_error(filename); list *lines = make_list(); while((path=fgetl(file))){ list_insert(lines, path); } fclose(file); return lines; } /* char **get_random_paths_indexes(char **paths, int n, int m, int *indexes) { char **random_paths = calloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); for(i = 0; i < n; ++i){ int index = random_gen()%m; indexes[i] = index; random_paths[i] = paths[index]; if(i == 0) printf("%s\n", paths[index]); } pthread_mutex_unlock(&mutex); return random_paths; } */ char **get_sequential_paths(char **paths, int n, int m, int mini_batch, int augment_speed, int contrastive) { int speed = rand_int(1, augment_speed); if (speed < 1) speed = 1; char** sequentia_paths = (char**)xcalloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); //printf("n = %d, mini_batch = %d \n", n, mini_batch); unsigned int *start_time_indexes = (unsigned int *)xcalloc(mini_batch, sizeof(unsigned int)); for (i = 0; i < mini_batch; ++i) { if (contrastive && (i % 2) == 1) start_time_indexes[i] = start_time_indexes[i - 1]; else start_time_indexes[i] = random_gen() % m; //printf(" start_time_indexes[i] = %u, ", start_time_indexes[i]); } for (i = 0; i < n; ++i) { do { int time_line_index = i % mini_batch; unsigned int index = start_time_indexes[time_line_index] % m; start_time_indexes[time_line_index] += speed; //int index = random_gen() % m; sequentia_paths[i] = paths[index]; //printf(" index = %d, ", index); //if(i == 0) printf("%s\n", paths[index]); //printf(" index = %u - grp: %s \n", index, paths[index]); if (strlen(sequentia_paths[i]) <= 4) printf(" Very small path to the image: %s \n", sequentia_paths[i]); } while (strlen(sequentia_paths[i]) == 0); } free(start_time_indexes); pthread_mutex_unlock(&mutex); return sequentia_paths; } char **get_random_paths_custom(char **paths, int n, int m, int contrastive) { char** random_paths = (char**)xcalloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); int old_index = 0; //printf("n = %d \n", n); for(i = 0; i < n; ++i){ do { int index = random_gen() % m; if (contrastive && (i % 2 == 1)) index = old_index; else old_index = index; random_paths[i] = paths[index]; //if(i == 0) printf("%s\n", paths[index]); //printf("grp: %s\n", paths[index]); if (strlen(random_paths[i]) <= 4) printf(" Very small path to the image: %s \n", random_paths[i]); } while (strlen(random_paths[i]) == 0); } pthread_mutex_unlock(&mutex); return random_paths; } char **get_random_paths(char **paths, int n, int m) { return get_random_paths_custom(paths, n, m, 0); } char **find_replace_paths(char **paths, int n, char *find, char *replace) { char** replace_paths = (char**)xcalloc(n, sizeof(char*)); int i; for(i = 0; i < n; ++i){ char replaced[4096]; find_replace(paths[i], find, replace, replaced); replace_paths[i] = copy_string(replaced); } return replace_paths; } matrix load_image_paths_gray(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = (float**)xcalloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image(paths[i], w, h, 3); image gray = grayscale_image(im); free_image(im); im = gray; X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_paths(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = (float**)xcalloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], w, h); X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_augment_paths(char **paths, int n, int use_flip, int min, int max, int w, int h, float angle, float aspect, float hue, float saturation, float exposure, int dontuse_opencv, int contrastive) { int i; matrix X; X.rows = n; X.vals = (float**)xcalloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ int size = w > h ? w : h; image im; const int img_index = (contrastive) ? (i / 2) : i; if(dontuse_opencv) im = load_image_stb_resize(paths[img_index], 0, 0, 3); else im = load_image_color(paths[img_index], 0, 0); image crop = random_augment_image(im, angle, aspect, min, max, size); int flip = use_flip ? random_gen() % 2 : 0; if (flip) flip_image(crop); random_distort_image(crop, hue, saturation, exposure); image sized = resize_image(crop, w, h); //show_image(im, "orig"); //show_image(sized, "sized"); //show_image(sized, paths[img_index]); //wait_until_press_key_cv(); //printf("w = %d, h = %d \n", sized.w, sized.h); free_image(im); free_image(crop); X.vals[i] = sized.data; X.cols = sized.h*sized.w*sized.c; } return X; } box_label *read_boxes(char *filename, int *n) { box_label* boxes = (box_label*)xcalloc(1, sizeof(box_label)); FILE *file = fopen(filename, "r"); if (!file) { printf("Can't open label file. (This can be normal only if you use MSCOCO): %s \n", filename); //file_error(filename); FILE* fw = fopen("bad.list", "a"); fwrite(filename, sizeof(char), strlen(filename), fw); char *new_line = "\n"; fwrite(new_line, sizeof(char), strlen(new_line), fw); fclose(fw); if (check_mistakes) { printf("\n Error in read_boxes() \n"); getchar(); } *n = 0; return boxes; } const int max_obj_img = 4000;// 30000; const int img_hash = (custom_hash(filename) % max_obj_img)*max_obj_img; //printf(" img_hash = %d, filename = %s; ", img_hash, filename); float x, y, h, w; int id; int count = 0; while(fscanf(file, "%d %f %f %f %f", &id, &x, &y, &w, &h) == 5){ boxes = (box_label*)xrealloc(boxes, (count + 1) * sizeof(box_label)); boxes[count].track_id = count + img_hash; //printf(" boxes[count].track_id = %d, count = %d \n", boxes[count].track_id, count); boxes[count].id = id; boxes[count].x = x; boxes[count].y = y; boxes[count].h = h; boxes[count].w = w; boxes[count].left = x - w/2; boxes[count].right = x + w/2; boxes[count].top = y - h/2; boxes[count].bottom = y + h/2; ++count; } fclose(file); *n = count; return boxes; } void randomize_boxes(box_label *b, int n) { int i; for(i = 0; i < n; ++i){ box_label swap = b[i]; int index = random_gen()%n; b[i] = b[index]; b[index] = swap; } } void correct_boxes(box_label *boxes, int n, float dx, float dy, float sx, float sy, int flip) { int i; for(i = 0; i < n; ++i){ if(boxes[i].x == 0 && boxes[i].y == 0) { boxes[i].x = 999999; boxes[i].y = 999999; boxes[i].w = 999999; boxes[i].h = 999999; continue; } if ((boxes[i].x + boxes[i].w / 2) < 0 || (boxes[i].y + boxes[i].h / 2) < 0 || (boxes[i].x - boxes[i].w / 2) > 1 || (boxes[i].y - boxes[i].h / 2) > 1) { boxes[i].x = 999999; boxes[i].y = 999999; boxes[i].w = 999999; boxes[i].h = 999999; continue; } boxes[i].left = boxes[i].left * sx - dx; boxes[i].right = boxes[i].right * sx - dx; boxes[i].top = boxes[i].top * sy - dy; boxes[i].bottom = boxes[i].bottom* sy - dy; if(flip){ float swap = boxes[i].left; boxes[i].left = 1. - boxes[i].right; boxes[i].right = 1. - swap; } boxes[i].left = constrain(0, 1, boxes[i].left); boxes[i].right = constrain(0, 1, boxes[i].right); boxes[i].top = constrain(0, 1, boxes[i].top); boxes[i].bottom = constrain(0, 1, boxes[i].bottom); boxes[i].x = (boxes[i].left+boxes[i].right)/2; boxes[i].y = (boxes[i].top+boxes[i].bottom)/2; boxes[i].w = (boxes[i].right - boxes[i].left); boxes[i].h = (boxes[i].bottom - boxes[i].top); boxes[i].w = constrain(0, 1, boxes[i].w); boxes[i].h = constrain(0, 1, boxes[i].h); } } void fill_truth_swag(char *path, float *truth, int classes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; replace_image_to_label(path, labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count && i < 30; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .0 || h < .0) continue; int index = (4+classes) * i; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; if (id < classes) truth[index+id] = 1; } free(boxes); } void fill_truth_region(char *path, float *truth, int classes, int num_boxes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; replace_image_to_label(path, labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .001 || h < .001) continue; int col = (int)(x*num_boxes); int row = (int)(y*num_boxes); x = x*num_boxes - col; y = y*num_boxes - row; int index = (col+row*num_boxes)*(5+classes); if (truth[index]) continue; truth[index++] = 1; if (id < classes) truth[index+id] = 1; index += classes; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; } free(boxes); } int fill_truth_detection(const char *path, int num_boxes, int truth_size, float *truth, int classes, int flip, float dx, float dy, float sx, float sy, int net_w, int net_h) { char labelpath[4096]; replace_image_to_label(path, labelpath); int count = 0; int i; box_label *boxes = read_boxes(labelpath, &count); int min_w_h = 0; float lowest_w = 1.F / net_w; float lowest_h = 1.F / net_h; randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); if (count > num_boxes) count = num_boxes; float x, y, w, h; int id; int sub = 0; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; int track_id = boxes[i].track_id; // not detect small objects //if ((w < 0.001F || h < 0.001F)) continue; // if truth (box for object) is smaller than 1x1 pix char buff[256]; if (id >= classes) { printf("\n Wrong annotation: class_id = %d. But class_id should be [from 0 to %d], file: %s \n", id, (classes-1), labelpath); sprintf(buff, "echo %s \"Wrong annotation: class_id = %d. But class_id should be [from 0 to %d]\" >> bad_label.list", labelpath, id, (classes-1)); system(buff); if (check_mistakes) getchar(); ++sub; continue; } if ((w < lowest_w || h < lowest_h)) { //sprintf(buff, "echo %s \"Very small object: w < lowest_w OR h < lowest_h\" >> bad_label.list", labelpath); //system(buff); ++sub; continue; } if (x == 999999 || y == 999999) { printf("\n Wrong annotation: x = 0, y = 0, < 0 or > 1, file: %s \n", labelpath); sprintf(buff, "echo %s \"Wrong annotation: x = 0 or y = 0\" >> bad_label.list", labelpath); system(buff); ++sub; if (check_mistakes) getchar(); continue; } if (x <= 0 || x > 1 || y <= 0 || y > 1) { printf("\n Wrong annotation: x = %f, y = %f, file: %s \n", x, y, labelpath); sprintf(buff, "echo %s \"Wrong annotation: x = %f, y = %f\" >> bad_label.list", labelpath, x, y); system(buff); ++sub; if (check_mistakes) getchar(); continue; } if (w > 1) { printf("\n Wrong annotation: w = %f, file: %s \n", w, labelpath); sprintf(buff, "echo %s \"Wrong annotation: w = %f\" >> bad_label.list", labelpath, w); system(buff); w = 1; if (check_mistakes) getchar(); } if (h > 1) { printf("\n Wrong annotation: h = %f, file: %s \n", h, labelpath); sprintf(buff, "echo %s \"Wrong annotation: h = %f\" >> bad_label.list", labelpath, h); system(buff); h = 1; if (check_mistakes) getchar(); } if (x == 0) x += lowest_w; if (y == 0) y += lowest_h; truth[(i-sub)*truth_size +0] = x; truth[(i-sub)*truth_size +1] = y; truth[(i-sub)*truth_size +2] = w; truth[(i-sub)*truth_size +3] = h; truth[(i-sub)*truth_size +4] = id; truth[(i-sub)*truth_size +5] = track_id; //float val = track_id; //printf(" i = %d, sub = %d, truth_size = %d, track_id = %d, %f, %f\n", i, sub, truth_size, track_id, truth[(i - sub)*truth_size + 5], val); if (min_w_h == 0) min_w_h = w*net_w; if (min_w_h > w*net_w) min_w_h = w*net_w; if (min_w_h > h*net_h) min_w_h = h*net_h; } free(boxes); return min_w_h; } void print_letters(float *pred, int n) { int i; for(i = 0; i < n; ++i){ int index = max_index(pred+i*NUMCHARS, NUMCHARS); printf("%c", int_to_alphanum(index)); } printf("\n"); } void fill_truth_captcha(char *path, int n, float *truth) { char *begin = strrchr(path, '/'); ++begin; int i; for(i = 0; i < strlen(begin) && i < n && begin[i] != '.'; ++i){ int index = alphanum_to_int(begin[i]); if(index > 35) printf("Bad %c\n", begin[i]); truth[i*NUMCHARS+index] = 1; } for(;i < n; ++i){ truth[i*NUMCHARS + NUMCHARS-1] = 1; } } data load_data_captcha(char **paths, int n, int m, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = make_matrix(n, k*NUMCHARS); int i; for(i = 0; i < n; ++i){ fill_truth_captcha(paths[i], k, d.y.vals[i]); } if(m) free(paths); return d; } data load_data_captcha_encode(char **paths, int n, int m, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.X.cols = 17100; d.y = d.X; if(m) free(paths); return d; } void fill_truth(char *path, char **labels, int k, float *truth) { int i; memset(truth, 0, k*sizeof(float)); int count = 0; for(i = 0; i < k; ++i){ if(strstr(path, labels[i])){ truth[i] = 1; ++count; } } if (count != 1) { printf("Too many or too few labels: %d, %s\n", count, path); count = 0; for (i = 0; i < k; ++i) { if (strstr(path, labels[i])) { printf("\t label %d: %s \n", count, labels[i]); count++; } } } } void fill_truth_smooth(char *path, char **labels, int k, float *truth, float label_smooth_eps) { int i; memset(truth, 0, k * sizeof(float)); int count = 0; for (i = 0; i < k; ++i) { if (strstr(path, labels[i])) { truth[i] = (1 - label_smooth_eps); ++count; } else { truth[i] = label_smooth_eps / (k - 1); } } if (count != 1) { printf("Too many or too few labels: %d, %s\n", count, path); count = 0; for (i = 0; i < k; ++i) { if (strstr(path, labels[i])) { printf("\t label %d: %s \n", count, labels[i]); count++; } } } } void fill_hierarchy(float *truth, int k, tree *hierarchy) { int j; for(j = 0; j < k; ++j){ if(truth[j]){ int parent = hierarchy->parent[j]; while(parent >= 0){ truth[parent] = 1; parent = hierarchy->parent[parent]; } } } int i; int count = 0; for(j = 0; j < hierarchy->groups; ++j){ //printf("%d\n", count); int mask = 1; for(i = 0; i < hierarchy->group_size[j]; ++i){ if(truth[count + i]){ mask = 0; break; } } if (mask) { for(i = 0; i < hierarchy->group_size[j]; ++i){ truth[count + i] = SECRET_NUM; } } count += hierarchy->group_size[j]; } } int find_max(float *arr, int size) { int i; float max = 0; int n = 0; for (i = 0; i < size; ++i) { if (arr[i] > max) { max = arr[i]; n = i; } } return n; } matrix load_labels_paths(char **paths, int n, char **labels, int k, tree *hierarchy, float label_smooth_eps, int contrastive) { matrix y = make_matrix(n, k); int i; if (labels) { // supervised learning for (i = 0; i < n; ++i) { const int img_index = (contrastive) ? (i / 2) : i; fill_truth_smooth(paths[img_index], labels, k, y.vals[i], label_smooth_eps); //printf(" n = %d, i = %d, img_index = %d, class_id = %d \n", n, i, img_index, find_max(y.vals[i], k)); if (hierarchy) { fill_hierarchy(y.vals[i], k, hierarchy); } } } else { // unsupervised learning for (i = 0; i < n; ++i) { const int img_index = (contrastive) ? (i / 2) : i; const uintptr_t path_p = (uintptr_t)paths[img_index];// abs(random_gen()); const int class_id = path_p % k; int l; for (l = 0; l < k; ++l) y.vals[i][l] = 0; y.vals[i][class_id] = 1; } } return y; } matrix load_tags_paths(char **paths, int n, int k) { matrix y = make_matrix(n, k); int i; int count = 0; for(i = 0; i < n; ++i){ char label[4096]; find_replace(paths[i], "imgs", "labels", label); find_replace(label, "_iconl.jpeg", ".txt", label); FILE *file = fopen(label, "r"); if(!file){ find_replace(label, "labels", "labels2", label); file = fopen(label, "r"); if(!file) continue; } ++count; int tag; while(fscanf(file, "%d", &tag) == 1){ if(tag < k){ y.vals[i][tag] = 1; } } fclose(file); } printf("%d/%d\n", count, n); return y; } char **get_labels_custom(char *filename, int *size) { list *plist = get_paths(filename); if(size) *size = plist->size; char **labels = (char **)list_to_array(plist); free_list(plist); return labels; } char **get_labels(char *filename) { return get_labels_custom(filename, NULL); } void free_data(data d) { if(!d.shallow){ free_matrix(d.X); free_matrix(d.y); }else{ free(d.X.vals); free(d.y.vals); } } data load_data_region(int n, char **paths, int m, int w, int h, int size, int classes, float jitter, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = size*size*(5+classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); int oh = orig.h; int ow = orig.w; int dw = (ow*jitter); int dh = (oh*jitter); int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; int flip = random_gen()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/ow)/sx; float dy = ((float)ptop /oh)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; fill_truth_region(random_paths[i], d.y.vals[i], classes, size, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); } free(random_paths); return d; } data load_data_compare(int n, char **paths, int m, int classes, int w, int h) { if(m) paths = get_random_paths(paths, 2*n, m); int i,j; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*6; int k = 2*(classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image im1 = load_image_color(paths[i*2], w, h); image im2 = load_image_color(paths[i*2+1], w, h); d.X.vals[i] = (float*)xcalloc(d.X.cols, sizeof(float)); memcpy(d.X.vals[i], im1.data, h*w*3*sizeof(float)); memcpy(d.X.vals[i] + h*w*3, im2.data, h*w*3*sizeof(float)); int id; float iou; char imlabel1[4096]; char imlabel2[4096]; find_replace(paths[i*2], "imgs", "labels", imlabel1); find_replace(imlabel1, "jpg", "txt", imlabel1); FILE *fp1 = fopen(imlabel1, "r"); while(fscanf(fp1, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id] < iou) d.y.vals[i][2*id] = iou; } find_replace(paths[i*2+1], "imgs", "labels", imlabel2); find_replace(imlabel2, "jpg", "txt", imlabel2); FILE *fp2 = fopen(imlabel2, "r"); while(fscanf(fp2, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id + 1] < iou) d.y.vals[i][2*id + 1] = iou; } for (j = 0; j < classes; ++j){ if (d.y.vals[i][2*j] > .5 && d.y.vals[i][2*j+1] < .5){ d.y.vals[i][2*j] = 1; d.y.vals[i][2*j+1] = 0; } else if (d.y.vals[i][2*j] < .5 && d.y.vals[i][2*j+1] > .5){ d.y.vals[i][2*j] = 0; d.y.vals[i][2*j+1] = 1; } else { d.y.vals[i][2*j] = SECRET_NUM; d.y.vals[i][2*j+1] = SECRET_NUM; } } fclose(fp1); fclose(fp2); free_image(im1); free_image(im2); } if(m) free(paths); return d; } data load_data_swag(char **paths, int n, int classes, float jitter) { int index = random_gen()%n; char *random_path = paths[index]; image orig = load_image_color(random_path, 0, 0); int h = orig.h; int w = orig.w; data d = {0}; d.shallow = 0; d.w = w; d.h = h; d.X.rows = 1; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = (4+classes)*30; d.y = make_matrix(1, k); int dw = w*jitter; int dh = h*jitter; int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = w - pleft - pright; int sheight = h - ptop - pbot; float sx = (float)swidth / w; float sy = (float)sheight / h; int flip = random_gen()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/w)/sx; float dy = ((float)ptop /h)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); d.X.vals[0] = sized.data; fill_truth_swag(random_path, d.y.vals[0], classes, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); return d; } void blend_truth(float *new_truth, int boxes, int truth_size, float *old_truth) { int count_new_truth = 0; int t; for (t = 0; t < boxes; ++t) { float x = new_truth[t*truth_size]; if (!x) break; count_new_truth++; } for (t = count_new_truth; t < boxes; ++t) { float *new_truth_ptr = new_truth + t*truth_size; float *old_truth_ptr = old_truth + (t - count_new_truth)*truth_size; float x = old_truth_ptr[0]; if (!x) break; new_truth_ptr[0] = old_truth_ptr[0]; new_truth_ptr[1] = old_truth_ptr[1]; new_truth_ptr[2] = old_truth_ptr[2]; new_truth_ptr[3] = old_truth_ptr[3]; new_truth_ptr[4] = old_truth_ptr[4]; } //printf("\n was %d bboxes, now %d bboxes \n", count_new_truth, t); } void blend_truth_mosaic(float *new_truth, int boxes, int truth_size, float *old_truth, int w, int h, float cut_x, float cut_y, int i_mixup, int left_shift, int right_shift, int top_shift, int bot_shift, int net_w, int net_h, int mosaic_bound) { const float lowest_w = 1.F / net_w; const float lowest_h = 1.F / net_h; int count_new_truth = 0; int t; for (t = 0; t < boxes; ++t) { float x = new_truth[t*truth_size]; if (!x) break; count_new_truth++; } int new_t = count_new_truth; for (t = count_new_truth; t < boxes; ++t) { float *new_truth_ptr = new_truth + new_t*truth_size; new_truth_ptr[0] = 0; float *old_truth_ptr = old_truth + (t - count_new_truth)*truth_size; float x = old_truth_ptr[0]; if (!x) break; float xb = old_truth_ptr[0]; float yb = old_truth_ptr[1]; float wb = old_truth_ptr[2]; float hb = old_truth_ptr[3]; // shift 4 images if (i_mixup == 0) { xb = xb - (float)(w - cut_x - right_shift) / w; yb = yb - (float)(h - cut_y - bot_shift) / h; } if (i_mixup == 1) { xb = xb + (float)(cut_x - left_shift) / w; yb = yb - (float)(h - cut_y - bot_shift) / h; } if (i_mixup == 2) { xb = xb - (float)(w - cut_x - right_shift) / w; yb = yb + (float)(cut_y - top_shift) / h; } if (i_mixup == 3) { xb = xb + (float)(cut_x - left_shift) / w; yb = yb + (float)(cut_y - top_shift) / h; } int left = (xb - wb / 2)*w; int right = (xb + wb / 2)*w; int top = (yb - hb / 2)*h; int bot = (yb + hb / 2)*h; if(mosaic_bound) { // fix out of Mosaic-bound float left_bound = 0, right_bound = 0, top_bound = 0, bot_bound = 0; if (i_mixup == 0) { left_bound = 0; right_bound = cut_x; top_bound = 0; bot_bound = cut_y; } if (i_mixup == 1) { left_bound = cut_x; right_bound = w; top_bound = 0; bot_bound = cut_y; } if (i_mixup == 2) { left_bound = 0; right_bound = cut_x; top_bound = cut_y; bot_bound = h; } if (i_mixup == 3) { left_bound = cut_x; right_bound = w; top_bound = cut_y; bot_bound = h; } if (left < left_bound) { //printf(" i_mixup = %d, left = %d, left_bound = %f \n", i_mixup, left, left_bound); left = left_bound; } if (right > right_bound) { //printf(" i_mixup = %d, right = %d, right_bound = %f \n", i_mixup, right, right_bound); right = right_bound; } if (top < top_bound) top = top_bound; if (bot > bot_bound) bot = bot_bound; xb = ((float)(right + left) / 2) / w; wb = ((float)(right - left)) / w; yb = ((float)(bot + top) / 2) / h; hb = ((float)(bot - top)) / h; } else { // fix out of bound if (left < 0) { float diff = (float)left / w; xb = xb - diff / 2; wb = wb + diff; } if (right > w) { float diff = (float)(right - w) / w; xb = xb - diff / 2; wb = wb - diff; } if (top < 0) { float diff = (float)top / h; yb = yb - diff / 2; hb = hb + diff; } if (bot > h) { float diff = (float)(bot - h) / h; yb = yb - diff / 2; hb = hb - diff; } left = (xb - wb / 2)*w; right = (xb + wb / 2)*w; top = (yb - hb / 2)*h; bot = (yb + hb / 2)*h; } // leave only within the image if(left >= 0 && right <= w && top >= 0 && bot <= h && wb > 0 && wb < 1 && hb > 0 && hb < 1 && xb > 0 && xb < 1 && yb > 0 && yb < 1 && wb > lowest_w && hb > lowest_h) { new_truth_ptr[0] = xb; new_truth_ptr[1] = yb; new_truth_ptr[2] = wb; new_truth_ptr[3] = hb; new_truth_ptr[4] = old_truth_ptr[4]; new_t++; } } //printf("\n was %d bboxes, now %d bboxes \n", count_new_truth, t); } #ifdef OPENCV #include "http_stream.h" data load_data_detection(int n, char **paths, int m, int w, int h, int c, int boxes, int truth_size, int classes, int use_flip, int use_gaussian_noise, int use_blur, int use_mixup, float jitter, float resize, float hue, float saturation, float exposure, int mini_batch, int track, int augment_speed, int letter_box, int mosaic_bound, int contrastive, int contrastive_jit_flip, int show_imgs) { const int random_index = random_gen(); c = c ? c : 3; if (use_mixup == 2 || use_mixup == 4) { printf("\n cutmix=1 - isn't supported for Detector (use cutmix=1 only for Classifier) \n"); if (check_mistakes) getchar(); if(use_mixup == 2) use_mixup = 0; else use_mixup = 3; } if (use_mixup == 3 && letter_box) { //printf("\n Combination: letter_box=1 & mosaic=1 - isn't supported, use only 1 of these parameters \n"); //if (check_mistakes) getchar(); //exit(0); } if (random_gen() % 2 == 0) use_mixup = 0; int i; int *cut_x = NULL, *cut_y = NULL; if (use_mixup == 3) { cut_x = (int*)calloc(n, sizeof(int)); cut_y = (int*)calloc(n, sizeof(int)); const float min_offset = 0.2; // 20% for (i = 0; i < n; ++i) { cut_x[i] = rand_int(w*min_offset, w*(1 - min_offset)); cut_y[i] = rand_int(h*min_offset, h*(1 - min_offset)); } } data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*c; float r1 = 0, r2 = 0, r3 = 0, r4 = 0, r_scale = 0; float resize_r1 = 0, resize_r2 = 0; float dhue = 0, dsat = 0, dexp = 0, flip = 0, blur = 0; int augmentation_calculated = 0, gaussian_noise = 0; d.y = make_matrix(n, truth_size*boxes); int i_mixup = 0; for (i_mixup = 0; i_mixup <= use_mixup; i_mixup++) { if (i_mixup) augmentation_calculated = 0; // recalculate augmentation for the 2nd sequence if(track==1) char **random_paths; if (track) random_paths = get_sequential_paths(paths, n, m, mini_batch, augment_speed, contrastive); else random_paths = get_random_paths_custom(paths, n, m, contrastive); for (i = 0; i < n; ++i) { float *truth = (float*)xcalloc(truth_size * boxes, sizeof(float)); const char *filename = random_paths[i]; int flag = (c >= 3); mat_cv *src; src = load_image_mat_cv(filename, flag); if (src == NULL) { printf("\n Error in load_data_detection() - OpenCV \n"); fflush(stdout); if (check_mistakes) { getchar(); } continue; } int oh = get_height_mat(src); int ow = get_width_mat(src); int dw = (ow*jitter); int dh = (oh*jitter); float resize_down = resize, resize_up = resize; if (resize_down > 1.0) resize_down = 1 / resize_down; int min_rdw = ow*(1 - (1 / resize_down)) / 2; // < 0 int min_rdh = oh*(1 - (1 / resize_down)) / 2; // < 0 if (resize_up < 1.0) resize_up = 1 / resize_up; int max_rdw = ow*(1 - (1 / resize_up)) / 2; // > 0 int max_rdh = oh*(1 - (1 / resize_up)) / 2; // > 0 //printf(" down = %f, up = %f \n", (1 - (1 / resize_down)) / 2, (1 - (1 / resize_up)) / 2); if (!augmentation_calculated || !track) { augmentation_calculated = 1; resize_r1 = random_float(); resize_r2 = random_float(); if (!contrastive || contrastive_jit_flip || i % 2 == 0) { r1 = random_float(); r2 = random_float(); r3 = random_float(); r4 = random_float(); flip = use_flip ? random_gen() % 2 : 0; } r_scale = random_float(); dhue = rand_uniform_strong(-hue, hue); dsat = rand_scale(saturation); dexp = rand_scale(exposure); if (use_blur) { int tmp_blur = rand_int(0, 2); // 0 - disable, 1 - blur background, 2 - blur the whole image if (tmp_blur == 0) blur = 0; else if (tmp_blur == 1) blur = 1; else blur = use_blur; } if (use_gaussian_noise && rand_int(0, 1) == 1) gaussian_noise = use_gaussian_noise; else gaussian_noise = 0; } int pleft = rand_precalc_random(-dw, dw, r1); int pright = rand_precalc_random(-dw, dw, r2); int ptop = rand_precalc_random(-dh, dh, r3); int pbot = rand_precalc_random(-dh, dh, r4); if (resize < 1) { // downsize only pleft += rand_precalc_random(min_rdw, 0, resize_r1); pright += rand_precalc_random(min_rdw, 0, resize_r2); ptop += rand_precalc_random(min_rdh, 0, resize_r1); pbot += rand_precalc_random(min_rdh, 0, resize_r2); } else { pleft += rand_precalc_random(min_rdw, max_rdw, resize_r1); pright += rand_precalc_random(min_rdw, max_rdw, resize_r2); ptop += rand_precalc_random(min_rdh, max_rdh, resize_r1); pbot += rand_precalc_random(min_rdh, max_rdh, resize_r2); } //printf("\n pleft = %d, pright = %d, ptop = %d, pbot = %d, ow = %d, oh = %d \n", pleft, pright, ptop, pbot, ow, oh); //float scale = rand_precalc_random(.25, 2, r_scale); // unused currently //printf(" letter_box = %d \n", letter_box); if (letter_box) { float img_ar = (float)ow / (float)oh; float net_ar = (float)w / (float)h; float result_ar = img_ar / net_ar; //printf(" ow = %d, oh = %d, w = %d, h = %d, img_ar = %f, net_ar = %f, result_ar = %f \n", ow, oh, w, h, img_ar, net_ar, result_ar); if (result_ar > 1) // sheight - should be increased { float oh_tmp = ow / net_ar; float delta_h = (oh_tmp - oh)/2; ptop = ptop - delta_h; pbot = pbot - delta_h; //printf(" result_ar = %f, oh_tmp = %f, delta_h = %d, ptop = %f, pbot = %f \n", result_ar, oh_tmp, delta_h, ptop, pbot); } else // swidth - should be increased { float ow_tmp = oh * net_ar; float delta_w = (ow_tmp - ow)/2; pleft = pleft - delta_w; pright = pright - delta_w; //printf(" result_ar = %f, ow_tmp = %f, delta_w = %d, pleft = %f, pright = %f \n", result_ar, ow_tmp, delta_w, pleft, pright); } //printf("\n pleft = %d, pright = %d, ptop = %d, pbot = %d, ow = %d, oh = %d \n", pleft, pright, ptop, pbot, ow, oh); } // move each 2nd image to the corner - so that most of it was visible if (use_mixup == 3 && random_gen() % 2 == 0) { if (flip) { if (i_mixup == 0) pleft += pright, pright = 0, pbot += ptop, ptop = 0; if (i_mixup == 1) pright += pleft, pleft = 0, pbot += ptop, ptop = 0; if (i_mixup == 2) pleft += pright, pright = 0, ptop += pbot, pbot = 0; if (i_mixup == 3) pright += pleft, pleft = 0, ptop += pbot, pbot = 0; } else { if (i_mixup == 0) pright += pleft, pleft = 0, pbot += ptop, ptop = 0; if (i_mixup == 1) pleft += pright, pright = 0, pbot += ptop, ptop = 0; if (i_mixup == 2) pright += pleft, pleft = 0, ptop += pbot, pbot = 0; if (i_mixup == 3) pleft += pright, pright = 0, ptop += pbot, pbot = 0; } } int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; float dx = ((float)pleft / ow) / sx; float dy = ((float)ptop / oh) / sy; int min_w_h = fill_truth_detection(filename, boxes, truth_size, truth, classes, flip, dx, dy, 1. / sx, 1. / sy, w, h); //for (int z = 0; z < boxes; ++z) if(truth[z*truth_size] > 0) printf(" track_id = %f \n", truth[z*truth_size + 5]); //printf(" truth_size = %d \n", truth_size); if ((min_w_h / 8) < blur && blur > 1) blur = min_w_h / 8; // disable blur if one of the objects is too small image ai = image_data_augmentation(src, w, h, pleft, ptop, swidth, sheight, flip, dhue, dsat, dexp, gaussian_noise, blur, boxes, truth_size, truth); if (use_mixup == 0) { d.X.vals[i] = ai.data; memcpy(d.y.vals[i], truth, truth_size * boxes * sizeof(float)); } else if (use_mixup == 1) { if (i_mixup == 0) { d.X.vals[i] = ai.data; memcpy(d.y.vals[i], truth, truth_size * boxes * sizeof(float)); } else if (i_mixup == 1) { image old_img = make_empty_image(w, h, c); old_img.data = d.X.vals[i]; //show_image(ai, "new"); //show_image(old_img, "old"); //wait_until_press_key_cv(); blend_images_cv(ai, 0.5, old_img, 0.5); blend_truth(d.y.vals[i], boxes, truth_size, truth); free_image(old_img); d.X.vals[i] = ai.data; } } else if (use_mixup == 3) { if (i_mixup == 0) { image tmp_img = make_image(w, h, c); d.X.vals[i] = tmp_img.data; } if (flip) { int tmp = pleft; pleft = pright; pright = tmp; } const int left_shift = min_val_cmp(cut_x[i], max_val_cmp(0, (-pleft*w / ow))); const int top_shift = min_val_cmp(cut_y[i], max_val_cmp(0, (-ptop*h / oh))); const int right_shift = min_val_cmp((w - cut_x[i]), max_val_cmp(0, (-pright*w / ow))); const int bot_shift = min_val_cmp(h - cut_y[i], max_val_cmp(0, (-pbot*h / oh))); int k, x, y; for (k = 0; k < c; ++k) { for (y = 0; y < h; ++y) { int j = y*w + k*w*h; if (i_mixup == 0 && y < cut_y[i]) { int j_src = (w - cut_x[i] - right_shift) + (y + h - cut_y[i] - bot_shift)*w + k*w*h; memcpy(&d.X.vals[i][j + 0], &ai.data[j_src], cut_x[i] * sizeof(float)); } if (i_mixup == 1 && y < cut_y[i]) { int j_src = left_shift + (y + h - cut_y[i] - bot_shift)*w + k*w*h; memcpy(&d.X.vals[i][j + cut_x[i]], &ai.data[j_src], (w-cut_x[i]) * sizeof(float)); } if (i_mixup == 2 && y >= cut_y[i]) { int j_src = (w - cut_x[i] - right_shift) + (top_shift + y - cut_y[i])*w + k*w*h; memcpy(&d.X.vals[i][j + 0], &ai.data[j_src], cut_x[i] * sizeof(float)); } if (i_mixup == 3 && y >= cut_y[i]) { int j_src = left_shift + (top_shift + y - cut_y[i])*w + k*w*h; memcpy(&d.X.vals[i][j + cut_x[i]], &ai.data[j_src], (w - cut_x[i]) * sizeof(float)); } } } blend_truth_mosaic(d.y.vals[i], boxes, truth_size, truth, w, h, cut_x[i], cut_y[i], i_mixup, left_shift, right_shift, top_shift, bot_shift, w, h, mosaic_bound); free_image(ai); ai.data = d.X.vals[i]; } if (show_imgs && i_mixup == use_mixup) // delete i_mixup { image tmp_ai = copy_image(ai); char buff[1000]; //sprintf(buff, "aug_%d_%d_%s_%d", random_index, i, basecfg((char*)filename), random_gen()); sprintf(buff, "aug_%d_%d_%d", random_index, i, random_gen()); int t; for (t = 0; t < boxes; ++t) { box b = float_to_box_stride(d.y.vals[i] + t*truth_size, 1); if (!b.x) break; int left = (b.x - b.w / 2.)*ai.w; int right = (b.x + b.w / 2.)*ai.w; int top = (b.y - b.h / 2.)*ai.h; int bot = (b.y + b.h / 2.)*ai.h; draw_box_width(tmp_ai, left, top, right, bot, 1, 150, 100, 50); // 3 channels RGB } save_image(tmp_ai, buff); if (show_imgs == 1) { //char buff_src[1000]; //sprintf(buff_src, "src_%d_%d_%s_%d", random_index, i, basecfg((char*)filename), random_gen()); //show_image_mat(src, buff_src); show_image(tmp_ai, buff); wait_until_press_key_cv(); } printf("\nYou use flag -show_imgs, so will be saved aug_...jpg images. Click on window and press ESC button \n"); free_image(tmp_ai); } release_mat(&src); free(truth); } if (random_paths) free(random_paths); } return d; } #else // OPENCV void blend_images(image new_img, float alpha, image old_img, float beta) { int data_size = new_img.w * new_img.h * new_img.c; int i; #pragma omp parallel for for (i = 0; i < data_size; ++i) new_img.data[i] = new_img.data[i] * alpha + old_img.data[i] * beta; } data load_data_detection(int n, char **paths, int m, int w, int h, int c, int boxes, int truth_size, int classes, int use_flip, int gaussian_noise, int use_blur, int use_mixup, float jitter, float resize, float hue, float saturation, float exposure, int mini_batch, int track, int augment_speed, int letter_box, int mosaic_bound, int contrastive, int contrastive_jit_flip, int show_imgs) { const int random_index = random_gen(); c = c ? c : 3; char **random_paths; char **mixup_random_paths = NULL; if(track) random_paths = get_sequential_paths(paths, n, m, mini_batch, augment_speed, contrastive); else random_paths = get_random_paths_custom(paths, n, m, contrastive); //assert(use_mixup < 2); if (use_mixup == 2) { printf("\n cutmix=1 - isn't supported for Detector \n"); exit(0); } if (use_mixup == 3 || use_mixup == 4) { printf("\n mosaic=1 - compile Darknet with OpenCV for using mosaic=1 \n"); exit(0); } int mixup = use_mixup ? random_gen() % 2 : 0; //printf("\n mixup = %d \n", mixup); if (mixup) { if (track) mixup_random_paths = get_sequential_paths(paths, n, m, mini_batch, augment_speed, contrastive); else mixup_random_paths = get_random_paths(paths, n, m); } int i; data d = { 0 }; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*c; float r1 = 0, r2 = 0, r3 = 0, r4 = 0, r_scale; float resize_r1 = 0, resize_r2 = 0; float dhue = 0, dsat = 0, dexp = 0, flip = 0; int augmentation_calculated = 0; d.y = make_matrix(n, truth_size * boxes); int i_mixup = 0; for (i_mixup = 0; i_mixup <= mixup; i_mixup++) { if (i_mixup) augmentation_calculated = 0; for (i = 0; i < n; ++i) { float *truth = (float*)xcalloc(truth_size * boxes, sizeof(float)); char *filename = (i_mixup) ? mixup_random_paths[i] : random_paths[i]; image orig = load_image(filename, 0, 0, c); int oh = orig.h; int ow = orig.w; int dw = (ow*jitter); int dh = (oh*jitter); float resize_down = resize, resize_up = resize; if (resize_down > 1.0) resize_down = 1 / resize_down; int min_rdw = ow*(1 - (1 / resize_down)) / 2; int min_rdh = oh*(1 - (1 / resize_down)) / 2; if (resize_up < 1.0) resize_up = 1 / resize_up; int max_rdw = ow*(1 - (1 / resize_up)) / 2; int max_rdh = oh*(1 - (1 / resize_up)) / 2; if (!augmentation_calculated || !track) { augmentation_calculated = 1; resize_r1 = random_float(); resize_r2 = random_float(); if (!contrastive || contrastive_jit_flip || i % 2 == 0) { r1 = random_float(); r2 = random_float(); r3 = random_float(); r4 = random_float(); flip = use_flip ? random_gen() % 2 : 0; } r_scale = random_float(); dhue = rand_uniform_strong(-hue, hue); dsat = rand_scale(saturation); dexp = rand_scale(exposure); } int pleft = rand_precalc_random(-dw, dw, r1); int pright = rand_precalc_random(-dw, dw, r2); int ptop = rand_precalc_random(-dh, dh, r3); int pbot = rand_precalc_random(-dh, dh, r4); if (resize < 1) { // downsize only pleft += rand_precalc_random(min_rdw, 0, resize_r1); pright += rand_precalc_random(min_rdw, 0, resize_r2); ptop += rand_precalc_random(min_rdh, 0, resize_r1); pbot += rand_precalc_random(min_rdh, 0, resize_r2); } else { pleft += rand_precalc_random(min_rdw, max_rdw, resize_r1); pright += rand_precalc_random(min_rdw, max_rdw, resize_r2); ptop += rand_precalc_random(min_rdh, max_rdh, resize_r1); pbot += rand_precalc_random(min_rdh, max_rdh, resize_r2); } if (letter_box) { float img_ar = (float)ow / (float)oh; float net_ar = (float)w / (float)h; float result_ar = img_ar / net_ar; //printf(" ow = %d, oh = %d, w = %d, h = %d, img_ar = %f, net_ar = %f, result_ar = %f \n", ow, oh, w, h, img_ar, net_ar, result_ar); if (result_ar > 1) // sheight - should be increased { float oh_tmp = ow / net_ar; float delta_h = (oh_tmp - oh) / 2; ptop = ptop - delta_h; pbot = pbot - delta_h; //printf(" result_ar = %f, oh_tmp = %f, delta_h = %d, ptop = %f, pbot = %f \n", result_ar, oh_tmp, delta_h, ptop, pbot); } else // swidth - should be increased { float ow_tmp = oh * net_ar; float delta_w = (ow_tmp - ow) / 2; pleft = pleft - delta_w; pright = pright - delta_w; //printf(" result_ar = %f, ow_tmp = %f, delta_w = %d, pleft = %f, pright = %f \n", result_ar, ow_tmp, delta_w, pleft, pright); } } int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft / ow) / sx; float dy = ((float)ptop / oh) / sy; image sized = resize_image(cropped, w, h); if (flip) flip_image(sized); distort_image(sized, dhue, dsat, dexp); //random_distort_image(sized, hue, saturation, exposure); fill_truth_detection(filename, boxes, truth_size, truth, classes, flip, dx, dy, 1. / sx, 1. / sy, w, h); if (i_mixup) { image old_img = sized; old_img.data = d.X.vals[i]; //show_image(sized, "new"); //show_image(old_img, "old"); //wait_until_press_key_cv(); blend_images(sized, 0.5, old_img, 0.5); blend_truth(truth, boxes, truth_size, d.y.vals[i]); free_image(old_img); } d.X.vals[i] = sized.data; memcpy(d.y.vals[i], truth, truth_size * boxes * sizeof(float)); if (show_imgs)// && i_mixup) { char buff[1000]; sprintf(buff, "aug_%d_%d_%s_%d", random_index, i, basecfg(filename), random_gen()); int t; for (t = 0; t < boxes; ++t) { box b = float_to_box_stride(d.y.vals[i] + t*truth_size, 1); if (!b.x) break; int left = (b.x - b.w / 2.)*sized.w; int right = (b.x + b.w / 2.)*sized.w; int top = (b.y - b.h / 2.)*sized.h; int bot = (b.y + b.h / 2.)*sized.h; draw_box_width(sized, left, top, right, bot, 1, 150, 100, 50); // 3 channels RGB } save_image(sized, buff); if (show_imgs == 1) { show_image(sized, buff); wait_until_press_key_cv(); } printf("\nYou use flag -show_imgs, so will be saved aug_...jpg images. Press Enter: \n"); //getchar(); } free_image(orig); free_image(cropped); free(truth); } } free(random_paths); if (mixup_random_paths) free(mixup_random_paths); return d; } #endif // OPENCV void *load_thread(void *ptr) { //srand(time(0)); //printf("Loading data: %d\n", random_gen()); load_args a = *(struct load_args*)ptr; if(a.exposure == 0) a.exposure = 1; if(a.saturation == 0) a.saturation = 1; if(a.aspect == 0) a.aspect = 1; if (a.type == OLD_CLASSIFICATION_DATA){ *a.d = load_data_old(a.paths, a.n, a.m, a.labels, a.classes, a.w, a.h); } else if (a.type == CLASSIFICATION_DATA){ *a.d = load_data_augment(a.paths, a.n, a.m, a.labels, a.classes, a.hierarchy, a.flip, a.min, a.max, a.w, a.h, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.mixup, a.blur, a.show_imgs, a.label_smooth_eps, a.dontuse_opencv, a.contrastive); } else if (a.type == SUPER_DATA){ *a.d = load_data_super(a.paths, a.n, a.m, a.w, a.h, a.scale); } else if (a.type == WRITING_DATA){ *a.d = load_data_writing(a.paths, a.n, a.m, a.w, a.h, a.out_w, a.out_h); } else if (a.type == REGION_DATA){ *a.d = load_data_region(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure); } else if (a.type == DETECTION_DATA){ *a.d = load_data_detection(a.n, a.paths, a.m, a.w, a.h, a.c, a.num_boxes, a.truth_size, a.classes, a.flip, a.gaussian_noise, a.blur, a.mixup, a.jitter, a.resize, a.hue, a.saturation, a.exposure, a.mini_batch, a.track, a.augment_speed, a.letter_box, a.mosaic_bound, a.contrastive, a.contrastive_jit_flip, a.show_imgs); } else if (a.type == SWAG_DATA){ *a.d = load_data_swag(a.paths, a.n, a.classes, a.jitter); } else if (a.type == COMPARE_DATA){ *a.d = load_data_compare(a.n, a.paths, a.m, a.classes, a.w, a.h); } else if (a.type == IMAGE_DATA){ *(a.im) = load_image(a.path, 0, 0, a.c); *(a.resized) = resize_image(*(a.im), a.w, a.h); }else if (a.type == LETTERBOX_DATA) { *(a.im) = load_image(a.path, 0, 0, a.c); *(a.resized) = letterbox_image(*(a.im), a.w, a.h); } else if (a.type == TAG_DATA){ *a.d = load_data_tag(a.paths, a.n, a.m, a.classes, a.flip, a.min, a.max, a.w, a.h, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } free(ptr); return 0; } pthread_t load_data_in_thread(load_args args) { pthread_t thread; struct load_args* ptr = (load_args*)xcalloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_thread, ptr)) error("Thread creation failed"); return thread; } static const int thread_wait_ms = 5; static volatile int flag_exit; static volatile int * run_load_data = NULL; static load_args * args_swap = NULL; static pthread_t* threads = NULL; pthread_mutex_t mtx_load_data = PTHREAD_MUTEX_INITIALIZER; void *run_thread_loop(void *ptr) { const int i = *(int *)ptr; while (!custom_atomic_load_int(&flag_exit)) { while (!custom_atomic_load_int(&run_load_data[i])) { if (custom_atomic_load_int(&flag_exit)) { free(ptr); return 0; } this_thread_sleep_for(thread_wait_ms); } pthread_mutex_lock(&mtx_load_data); load_args *args_local = (load_args *)xcalloc(1, sizeof(load_args)); *args_local = args_swap[i]; pthread_mutex_unlock(&mtx_load_data); load_thread(args_local); custom_atomic_store_int(&run_load_data[i], 0); } free(ptr); return 0; } void *load_threads(void *ptr) { //srand(time(0)); int i; load_args args = *(load_args *)ptr; if (args.threads == 0) args.threads = 1; data *out = args.d; int total = args.n; free(ptr); data* buffers = (data*)xcalloc(args.threads, sizeof(data)); if (!threads) { threads = (pthread_t*)xcalloc(args.threads, sizeof(pthread_t)); run_load_data = (volatile int *)xcalloc(args.threads, sizeof(int)); args_swap = (load_args *)xcalloc(args.threads, sizeof(load_args)); fprintf(stderr, " Create %d permanent cpu-threads \n", args.threads); for (i = 0; i < args.threads; ++i) { int* ptr = (int*)xcalloc(1, sizeof(int)); *ptr = i; if (pthread_create(&threads[i], 0, run_thread_loop, ptr)) error("Thread creation failed"); } } for (i = 0; i < args.threads; ++i) { args.d = buffers + i; args.n = (i + 1) * total / args.threads - i * total / args.threads; pthread_mutex_lock(&mtx_load_data); args_swap[i] = args; pthread_mutex_unlock(&mtx_load_data); custom_atomic_store_int(&run_load_data[i], 1); // run thread } for (i = 0; i < args.threads; ++i) { while (custom_atomic_load_int(&run_load_data[i])) this_thread_sleep_for(thread_wait_ms); // join } /* pthread_t* threads = (pthread_t*)xcalloc(args.threads, sizeof(pthread_t)); for(i = 0; i < args.threads; ++i){ args.d = buffers + i; args.n = (i+1) * total/args.threads - i * total/args.threads; threads[i] = load_data_in_thread(args); } for(i = 0; i < args.threads; ++i){ pthread_join(threads[i], 0); } */ *out = concat_datas(buffers, args.threads); out->shallow = 0; for(i = 0; i < args.threads; ++i){ buffers[i].shallow = 1; free_data(buffers[i]); } free(buffers); //free(threads); return 0; } void free_load_threads(void *ptr) { load_args args = *(load_args *)ptr; if (args.threads == 0) args.threads = 1; int i; if (threads) { custom_atomic_store_int(&flag_exit, 1); for (i = 0; i < args.threads; ++i) { pthread_join(threads[i], 0); } free((void*)run_load_data); free(args_swap); free(threads); threads = NULL; custom_atomic_store_int(&flag_exit, 0); } } pthread_t load_data(load_args args) { pthread_t thread; struct load_args* ptr = (load_args*)xcalloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_threads, ptr)) error("Thread creation failed"); return thread; } data load_data_writing(char **paths, int n, int m, int w, int h, int out_w, int out_h) { if(m) paths = get_random_paths(paths, n, m); char **replace_paths = find_replace_paths(paths, n, ".png", "-label.png"); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_image_paths_gray(replace_paths, n, out_w, out_h); if(m) free(paths); int i; for(i = 0; i < n; ++i) free(replace_paths[i]); free(replace_paths); return d; } data load_data_old(char **paths, int n, int m, char **labels, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_labels_paths(paths, n, labels, k, 0, 0, 0); if(m) free(paths); return d; } /* data load_data_study(char **paths, int n, int m, char **labels, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { data d = {0}; d.indexes = calloc(n, sizeof(int)); if(m) paths = get_random_paths_indexes(paths, n, m, d.indexes); d.shallow = 0; d.X = load_image_augment_paths(paths, n, flip, min, max, size, angle, aspect, hue, saturation, exposure); d.y = load_labels_paths(paths, n, labels, k); if(m) free(paths); return d; } */ data load_data_super(char **paths, int n, int m, int w, int h, int scale) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; int i; d.X.rows = n; d.X.vals = (float**)xcalloc(n, sizeof(float*)); d.X.cols = w*h*3; d.y.rows = n; d.y.vals = (float**)xcalloc(n, sizeof(float*)); d.y.cols = w*scale * h*scale * 3; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], 0, 0); image crop = random_crop_image(im, w*scale, h*scale); int flip = random_gen()%2; if (flip) flip_image(crop); image resize = resize_image(crop, w, h); d.X.vals[i] = resize.data; d.y.vals[i] = crop.data; free_image(im); } if(m) free(paths); return d; } data load_data_augment(char **paths, int n, int m, char **labels, int k, tree *hierarchy, int use_flip, int min, int max, int w, int h, float angle, float aspect, float hue, float saturation, float exposure, int use_mixup, int use_blur, int show_imgs, float label_smooth_eps, int dontuse_opencv, int contrastive) { char **paths_stored = paths; if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_augment_paths(paths, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv, contrastive); d.y = load_labels_paths(paths, n, labels, k, hierarchy, label_smooth_eps, contrastive); if (use_mixup && rand_int(0, 1)) { char **paths_mix = get_random_paths(paths_stored, n, m); data d2 = { 0 }; d2.shallow = 0; d2.X = load_image_augment_paths(paths_mix, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv, contrastive); d2.y = load_labels_paths(paths_mix, n, labels, k, hierarchy, label_smooth_eps, contrastive); free(paths_mix); data d3 = { 0 }; d3.shallow = 0; data d4 = { 0 }; d4.shallow = 0; if (use_mixup >= 3) { char **paths_mix3 = get_random_paths(paths_stored, n, m); d3.X = load_image_augment_paths(paths_mix3, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv, contrastive); d3.y = load_labels_paths(paths_mix3, n, labels, k, hierarchy, label_smooth_eps, contrastive); free(paths_mix3); char **paths_mix4 = get_random_paths(paths_stored, n, m); d4.X = load_image_augment_paths(paths_mix4, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv, contrastive); d4.y = load_labels_paths(paths_mix4, n, labels, k, hierarchy, label_smooth_eps, contrastive); free(paths_mix4); } // mix int i, j; for (i = 0; i < d2.X.rows; ++i) { int mixup = use_mixup; if (use_mixup == 4) mixup = rand_int(2, 3); // alternate CutMix and Mosaic // MixUp ----------------------------------- if (mixup == 1) { // mix images for (j = 0; j < d2.X.cols; ++j) { d.X.vals[i][j] = (d.X.vals[i][j] + d2.X.vals[i][j]) / 2.0f; } // mix labels for (j = 0; j < d2.y.cols; ++j) { d.y.vals[i][j] = (d.y.vals[i][j] + d2.y.vals[i][j]) / 2.0f; } } // CutMix ----------------------------------- else if (mixup == 2) { const float min = 0.3; // 0.3*0.3 = 9% const float max = 0.8; // 0.8*0.8 = 64% const int cut_w = rand_int(w*min, w*max); const int cut_h = rand_int(h*min, h*max); const int cut_x = rand_int(0, w - cut_w - 1); const int cut_y = rand_int(0, h - cut_h - 1); const int left = cut_x; const int right = cut_x + cut_w; const int top = cut_y; const int bot = cut_y + cut_h; assert(cut_x >= 0 && cut_x <= w); assert(cut_y >= 0 && cut_y <= h); assert(cut_w >= 0 && cut_w <= w); assert(cut_h >= 0 && cut_h <= h); assert(right >= 0 && right <= w); assert(bot >= 0 && bot <= h); assert(top <= bot); assert(left <= right); const float alpha = (float)(cut_w*cut_h) / (float)(w*h); const float beta = 1 - alpha; int c, x, y; for (c = 0; c < 3; ++c) { for (y = top; y < bot; ++y) { for (x = left; x < right; ++x) { int j = x + y*w + c*w*h; d.X.vals[i][j] = d2.X.vals[i][j]; } } } //printf("\n alpha = %f, beta = %f \n", alpha, beta); // mix labels for (j = 0; j < d.y.cols; ++j) { d.y.vals[i][j] = d.y.vals[i][j] * beta + d2.y.vals[i][j] * alpha; } } // Mosaic ----------------------------------- else if (mixup == 3) { const float min_offset = 0.2; // 20% const int cut_x = rand_int(w*min_offset, w*(1 - min_offset)); const int cut_y = rand_int(h*min_offset, h*(1 - min_offset)); float s1 = (float)(cut_x * cut_y) / (w*h); float s2 = (float)((w - cut_x) * cut_y) / (w*h); float s3 = (float)(cut_x * (h - cut_y)) / (w*h); float s4 = (float)((w - cut_x) * (h - cut_y)) / (w*h); int c, x, y; for (c = 0; c < 3; ++c) { for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { int j = x + y*w + c*w*h; if (x < cut_x && y < cut_y) d.X.vals[i][j] = d.X.vals[i][j]; if (x >= cut_x && y < cut_y) d.X.vals[i][j] = d2.X.vals[i][j]; if (x < cut_x && y >= cut_y) d.X.vals[i][j] = d3.X.vals[i][j]; if (x >= cut_x && y >= cut_y) d.X.vals[i][j] = d4.X.vals[i][j]; } } } for (j = 0; j < d.y.cols; ++j) { const float max_s = 1;// max_val_cmp(s1, max_val_cmp(s2, max_val_cmp(s3, s4))); d.y.vals[i][j] = d.y.vals[i][j] * s1 / max_s + d2.y.vals[i][j] * s2 / max_s + d3.y.vals[i][j] * s3 / max_s + d4.y.vals[i][j] * s4 / max_s; } } } free_data(d2); if (use_mixup >= 3) { free_data(d3); free_data(d4); } } #ifdef OPENCV if (use_blur) { int i; for (i = 0; i < d.X.rows; ++i) { if (random_gen() % 4 == 0) { image im = make_empty_image(w, h, 3); im.data = d.X.vals[i]; int ksize = use_blur; if (use_blur == 1) ksize = 15; image blurred = blur_image(im, ksize); free_image(im); d.X.vals[i] = blurred.data; //if (i == 0) { // show_image(im, "Not blurred"); // show_image(blurred, "blurred"); // wait_until_press_key_cv(); //} } } } #endif // OPENCV if (show_imgs) { int i, j; for (i = 0; i < d.X.rows; ++i) { image im = make_empty_image(w, h, 3); im.data = d.X.vals[i]; char buff[1000]; sprintf(buff, "aug_%d_%s_%d", i, basecfg((char*)paths[i]), random_gen()); save_image(im, buff); char buff_string[1000]; sprintf(buff_string, "\n Classes: "); for (j = 0; j < d.y.cols; ++j) { if (d.y.vals[i][j] > 0) { char buff_tmp[100]; sprintf(buff_tmp, " %d (%f), ", j, d.y.vals[i][j]); strcat(buff_string, buff_tmp); } } printf("%s \n", buff_string); if (show_imgs == 1) { show_image(im, buff); wait_until_press_key_cv(); } } printf("\nYou use flag -show_imgs, so will be saved aug_...jpg images. Click on window and press ESC button \n"); } if (m) free(paths); return d; } data load_data_tag(char **paths, int n, int m, int k, int use_flip, int min, int max, int w, int h, float angle, float aspect, float hue, float saturation, float exposure) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.w = w; d.h = h; d.shallow = 0; d.X = load_image_augment_paths(paths, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, 0, 0); d.y = load_tags_paths(paths, n, k); if(m) free(paths); return d; } matrix concat_matrix(matrix m1, matrix m2) { int i, count = 0; matrix m; m.cols = m1.cols; m.rows = m1.rows+m2.rows; m.vals = (float**)xcalloc(m1.rows + m2.rows, sizeof(float*)); for(i = 0; i < m1.rows; ++i){ m.vals[count++] = m1.vals[i]; } for(i = 0; i < m2.rows; ++i){ m.vals[count++] = m2.vals[i]; } return m; } data concat_data(data d1, data d2) { data d = {0}; d.shallow = 1; d.X = concat_matrix(d1.X, d2.X); d.y = concat_matrix(d1.y, d2.y); return d; } data concat_datas(data *d, int n) { int i; data out = {0}; for(i = 0; i < n; ++i){ data newdata = concat_data(d[i], out); free_data(out); out = newdata; } return out; } data load_categorical_data_csv(char *filename, int target, int k) { data d = {0}; d.shallow = 0; matrix X = csv_to_matrix(filename); float *truth_1d = pop_column(&X, target); float **truth = one_hot_encode(truth_1d, X.rows, k); matrix y; y.rows = X.rows; y.cols = k; y.vals = truth; d.X = X; d.y = y; free(truth_1d); return d; } data load_cifar10_data(char *filename) { data d = {0}; d.shallow = 0; long i,j; matrix X = make_matrix(10000, 3072); matrix y = make_matrix(10000, 10); d.X = X; d.y = y; FILE *fp = fopen(filename, "rb"); if(!fp) file_error(filename); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class_id = bytes[0]; y.vals[i][class_id] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i][j] = (double)bytes[j+1]; } } //translate_data_rows(d, -128); scale_data_rows(d, 1./255); //normalize_data_rows(d); fclose(fp); return d; } void get_random_batch(data d, int n, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = random_gen()%d.X.rows; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void get_next_batch(data d, int n, int offset, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = offset + j; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void smooth_data(data d) { int i, j; float scale = 1. / d.y.cols; float eps = .1; for(i = 0; i < d.y.rows; ++i){ for(j = 0; j < d.y.cols; ++j){ d.y.vals[i][j] = eps * scale + (1-eps) * d.y.vals[i][j]; } } } data load_all_cifar10() { data d = {0}; d.shallow = 0; int i,j,b; matrix X = make_matrix(50000, 3072); matrix y = make_matrix(50000, 10); d.X = X; d.y = y; for(b = 0; b < 5; ++b){ char buff[256]; sprintf(buff, "data/cifar/cifar-10-batches-bin/data_batch_%d.bin", b+1); FILE *fp = fopen(buff, "rb"); if(!fp) file_error(buff); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class_id = bytes[0]; y.vals[i+b*10000][class_id] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i+b*10000][j] = (double)bytes[j+1]; } } fclose(fp); } //normalize_data_rows(d); //translate_data_rows(d, -128); scale_data_rows(d, 1./255); smooth_data(d); return d; } data load_go(char *filename) { FILE *fp = fopen(filename, "rb"); matrix X = make_matrix(3363059, 361); matrix y = make_matrix(3363059, 361); int row, col; if(!fp) file_error(filename); char *label; int count = 0; while((label = fgetl(fp))){ int i; if(count == X.rows){ X = resize_matrix(X, count*2); y = resize_matrix(y, count*2); } sscanf(label, "%d %d", &row, &col); char *board = fgetl(fp); int index = row*19 + col; y.vals[count][index] = 1; for(i = 0; i < 19*19; ++i){ float val = 0; if(board[i] == '1') val = 1; else if(board[i] == '2') val = -1; X.vals[count][i] = val; } ++count; free(label); free(board); } X = resize_matrix(X, count); y = resize_matrix(y, count); data d = {0}; d.shallow = 0; d.X = X; d.y = y; fclose(fp); return d; } void randomize_data(data d) { int i; for(i = d.X.rows-1; i > 0; --i){ int index = random_gen()%i; float *swap = d.X.vals[index]; d.X.vals[index] = d.X.vals[i]; d.X.vals[i] = swap; swap = d.y.vals[index]; d.y.vals[index] = d.y.vals[i]; d.y.vals[i] = swap; } } void scale_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ scale_array(d.X.vals[i], d.X.cols, s); } } void translate_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ translate_array(d.X.vals[i], d.X.cols, s); } } void normalize_data_rows(data d) { int i; for(i = 0; i < d.X.rows; ++i){ normalize_array(d.X.vals[i], d.X.cols); } } data get_data_part(data d, int part, int total) { data p = {0}; p.shallow = 1; p.X.rows = d.X.rows * (part + 1) / total - d.X.rows * part / total; p.y.rows = d.y.rows * (part + 1) / total - d.y.rows * part / total; p.X.cols = d.X.cols; p.y.cols = d.y.cols; p.X.vals = d.X.vals + d.X.rows * part / total; p.y.vals = d.y.vals + d.y.rows * part / total; return p; } data get_random_data(data d, int num) { data r = {0}; r.shallow = 1; r.X.rows = num; r.y.rows = num; r.X.cols = d.X.cols; r.y.cols = d.y.cols; r.X.vals = (float**)xcalloc(num, sizeof(float*)); r.y.vals = (float**)xcalloc(num, sizeof(float*)); int i; for(i = 0; i < num; ++i){ int index = random_gen()%d.X.rows; r.X.vals[i] = d.X.vals[index]; r.y.vals[i] = d.y.vals[index]; } return r; } data *split_data(data d, int part, int total) { data* split = (data*)xcalloc(2, sizeof(data)); int i; int start = part*d.X.rows/total; int end = (part+1)*d.X.rows/total; data train ={0}; data test ={0}; train.shallow = test.shallow = 1; test.X.rows = test.y.rows = end-start; train.X.rows = train.y.rows = d.X.rows - (end-start); train.X.cols = test.X.cols = d.X.cols; train.y.cols = test.y.cols = d.y.cols; train.X.vals = (float**)xcalloc(train.X.rows, sizeof(float*)); test.X.vals = (float**)xcalloc(test.X.rows, sizeof(float*)); train.y.vals = (float**)xcalloc(train.y.rows, sizeof(float*)); test.y.vals = (float**)xcalloc(test.y.rows, sizeof(float*)); for(i = 0; i < start; ++i){ train.X.vals[i] = d.X.vals[i]; train.y.vals[i] = d.y.vals[i]; } for(i = start; i < end; ++i){ test.X.vals[i-start] = d.X.vals[i]; test.y.vals[i-start] = d.y.vals[i]; } for(i = end; i < d.X.rows; ++i){ train.X.vals[i-(end-start)] = d.X.vals[i]; train.y.vals[i-(end-start)] = d.y.vals[i]; } split[0] = train; split[1] = test; return split; }
viterbi_decode_op.h
/* Copyright (c) 2021 PaddlePaddle 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. */ #pragma once #include <algorithm> #include <memory> #include <string> #include <vector> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/elementwise/elementwise_functor.h" #include "paddle/fluid/operators/elementwise/elementwise_op_function.h" #include "paddle/fluid/operators/math/concat_and_split.h" #include "paddle/fluid/operators/transpose_op.h" #include "paddle/fluid/operators/unique_op.h" #include "paddle/phi/kernels/funcs/compare_functors.h" #include "paddle/phi/kernels/funcs/gather.h" #ifdef PADDLE_WITH_MKLML #include <omp.h> #endif namespace paddle { namespace operators { template <typename DeviceContext, typename T, typename IndType> struct Argmax { void operator()(const framework::ExecutionContext& ctx, const framework::Tensor& input, framework::Tensor* out_idx, framework::Tensor* out, int axis) { framework::DDim input_dims = input.dims(); int64_t pre = 1; int64_t post = 1; int64_t n = input_dims[axis]; for (int i = 0; i < axis; i++) { pre *= input_dims[i]; } for (int i = axis + 1; i < input_dims.size(); i++) { post *= input_dims[i]; } int64_t height = pre * post; int64_t width = n; const T* in_data = input.data<T>(); IndType* out_idx_data = out_idx->data<IndType>(); T* out_data = out->data<T>(); // Reduce #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int64_t i = 0; i < height; ++i) { int64_t h = i / post; int64_t w = i % post; IndType max_idx = -1; T max_value = (std::numeric_limits<T>::lowest)(); // for windows compile for (int64_t j = 0; j < width; ++j) { if (in_data[h * width * post + j * post + w] > max_value) { max_value = in_data[h * width * post + j * post + w]; max_idx = j; } } out_data[i] = max_value; out_idx_data[i] = max_idx; } } }; template <typename DeviceContext> struct ARange { void operator()(const DeviceContext& dev_ctx, int64_t* data, int end, int64_t scale) { for (int i = 0; i < end; ++i) { data[i] = i * scale; } } }; template <typename DeviceContext, typename T> struct GetMaxValue { void operator()(const DeviceContext& dev_ctx, const framework::Tensor& input, T* max_value) { auto input_ptr = input.data<T>(); auto num = input.numel(); *max_value = *std::max_element(input_ptr, input_ptr + num); } }; template <typename DeviceContext, typename T, typename IndexT = int> struct Gather { void operator()(const DeviceContext& ctx, const framework::Tensor& src, const framework::Tensor& index, framework::Tensor* output) { phi::funcs::CPUGather<T, IndexT>(ctx, src, index, output); } }; template <typename T, typename Functor, typename OutT = T> void SameDimsBinaryOP(const framework::Tensor& lhs, const framework::Tensor& rhs, framework::Tensor* out) { const T* lhs_ptr = lhs.data<T>(); const T* rhs_ptr = rhs.data<T>(); OutT* out_ptr = out->data<OutT>(); Functor functor; #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int i = 0; i < out->numel(); ++i) { out_ptr[i] = functor(lhs_ptr[i], rhs_ptr[i]); } } template <typename DeviceContext, template <typename InT, typename OutT> typename CompareFunctor, typename T> struct GetMask { void operator()(const framework::ExecutionContext& ctx, const framework::Tensor& lhs, const framework::Tensor& rhs, framework::Tensor* mask) { SameDimsBinaryOP<int64_t, CompareFunctor<int64_t, T>, T>(lhs, rhs, mask); } }; template <bool is_multi_threads> struct GetInputIndex { void operator()(const std::vector<int>& lhs_dims, const std::vector<int>& rhs_dims, const std::vector<int>& output_dims, const std::vector<int>& lhs_strides, const std::vector<int>& rhs_strides, const std::vector<int>& output_strides, int output_idx, int* index_array, int* lhs_idx, int* rhs_idx) { int out_dims_size = output_strides.size(); for (int j = 0; j < out_dims_size; ++j) { int curr_idx = output_idx / output_strides[j]; output_idx %= output_strides[j]; *lhs_idx += (lhs_dims[j] > 1) ? curr_idx * lhs_strides[j] : 0; *rhs_idx += (rhs_dims[j] > 1) ? curr_idx * rhs_strides[j] : 0; } } }; template <> struct GetInputIndex<false> { void operator()(const std::vector<int>& lhs_dims, const std::vector<int>& rhs_dims, const std::vector<int>& output_dims, const std::vector<int>& lhs_strides, const std::vector<int>& rhs_strides, const std::vector<int>& output_strides, int output_idx, int* index_array, int* lhs_idx, int* rhs_idx) { int out_dims_size = output_strides.size(); *lhs_idx = phi::funcs::GetElementwiseIndex(lhs_dims.data(), out_dims_size, index_array); *rhs_idx = phi::funcs::GetElementwiseIndex(rhs_dims.data(), out_dims_size, index_array); phi::funcs::UpdateElementwiseIndexArray(output_dims.data(), out_dims_size, index_array); } }; template <typename T, typename Functor, bool is_multi_threads = false> void SimpleBroadcastBinaryOP(const framework::Tensor& lhs, const framework::Tensor& rhs, framework::Tensor* out) { const T* lhs_ptr = lhs.data<T>(); const T* rhs_ptr = rhs.data<T>(); T* out_ptr = out->data<T>(); int out_size = static_cast<int>(out->dims().size()); std::vector<int> out_dims(out_size); std::vector<int> lhs_dims(out_size); std::vector<int> rhs_dims(out_size); std::copy(lhs.dims().Get(), lhs.dims().Get() + out_size, lhs_dims.data()); std::copy(rhs.dims().Get(), rhs.dims().Get() + out_size, rhs_dims.data()); std::copy(out->dims().Get(), out->dims().Get() + out_size, out_dims.data()); std::vector<int> output_strides(out_size, 1); std::vector<int> lhs_strides(out_size, 1); std::vector<int> rhs_strides(out_size, 1); std::vector<int> index_array(out_size, 0); // calculate strides for (int i = out_size - 2; i >= 0; --i) { output_strides[i] = output_strides[i + 1] * out_dims[i + 1]; lhs_strides[i] = lhs_strides[i + 1] * lhs_dims[i + 1]; rhs_strides[i] = rhs_strides[i + 1] * rhs_dims[i + 1]; } Functor functor; GetInputIndex<is_multi_threads> get_input_index; #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int i = 0; i < out->numel(); ++i) { int lhs_idx = 0; int rhs_idx = 0; get_input_index(lhs_dims, rhs_dims, out_dims, lhs_strides, rhs_strides, output_strides, i, index_array.data(), &lhs_idx, &rhs_idx); out_ptr[i] = functor(lhs_ptr[lhs_idx], rhs_ptr[rhs_idx]); } } template <typename DeviceContext, template <typename T> typename BinaryFunctor, typename T> struct BinaryOperation { void operator()(const DeviceContext& dev_ctx, const framework::Tensor& lhs, const framework::Tensor& rhs, framework::Tensor* output) { if (lhs.dims() == rhs.dims()) { SameDimsBinaryOP<T, BinaryFunctor<T>>(lhs, rhs, output); } else { bool is_multi_threads = false; #ifdef PADDLE_WITH_MKLML if (omp_get_max_threads() > 1) { is_multi_threads = true; } #endif if (is_multi_threads) { SimpleBroadcastBinaryOP<T, BinaryFunctor<T>, true>(lhs, rhs, output); } else { SimpleBroadcastBinaryOP<T, BinaryFunctor<T>, false>(lhs, rhs, output); } } } }; class TensorBuffer { public: explicit TensorBuffer(const framework::LoDTensor& in) : buffer_(in), offset_(0) { buffer_.Resize({buffer_.numel()}); } framework::Tensor GetBufferBlock(std::initializer_list<int64_t> shape) { int64_t size = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int64_t>()); framework::Tensor block = buffer_.Slice(offset_, offset_ + size); offset_ += size; block.Resize(shape); return block; } private: framework::LoDTensor buffer_; // need to resize 1-D Tensor int offset_; }; template <typename DeviceContext, typename T> class ViterbiDecodeKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { bool include_bos_eos_tag = ctx.Attr<bool>("include_bos_eos_tag"); auto& dev_ctx = ctx.template device_context<DeviceContext>(); auto curr_place = ctx.GetPlace(); auto* input = ctx.Input<framework::Tensor>("Input"); auto batch_size = static_cast<int>(input->dims()[0]); auto seq_len = static_cast<int>(input->dims()[1]); auto n_labels = static_cast<int>(input->dims()[2]); phi::funcs::SetConstant<DeviceContext, T> float_functor; phi::funcs::SetConstant<DeviceContext, int64_t> int_functor; std::vector<framework::Tensor> historys; // We create tensor buffer in order to avoid allocating memory frequently // 10 means allocate 10*batch_size bytes memory, such as int_mask, zero... int buffer_size = batch_size * (n_labels + 1) * seq_len + 10 * batch_size; framework::LoDTensor int_buffer; int_buffer.Resize(phi::make_ddim({buffer_size})); int_buffer.mutable_data<int64_t>(ctx.GetPlace()); TensorBuffer int_tensor_buffer(int_buffer); // create float tensor buffer // 10 means allocate 10*batch_size*n_labels bytes, such as alpha, alpha_max buffer_size = batch_size * (seq_len + 10) * n_labels + (batch_size + 2) * n_labels * n_labels; framework::LoDTensor float_buffer; float_buffer.Resize(phi::make_ddim({buffer_size})); float_buffer.mutable_data<T>(ctx.GetPlace()); TensorBuffer float_tensor_buffer(float_buffer); auto* length = ctx.Input<framework::Tensor>("Length"); framework::Tensor left_length = int_tensor_buffer.GetBufferBlock({batch_size, 1}); framework::TensorCopy(*length, curr_place, dev_ctx, &left_length); int64_t max_seq_len = 0; GetMaxValue<DeviceContext, int64_t> get_max_value; get_max_value(dev_ctx, left_length, &max_seq_len); auto* scores = ctx.Output<framework::Tensor>("Scores"); scores->mutable_data<T>(curr_place); auto* path = ctx.Output<framework::Tensor>("Path"); path->Resize({batch_size, max_seq_len}); path->mutable_data<int64_t>(curr_place); framework::Tensor tpath = int_tensor_buffer.GetBufferBlock({max_seq_len, batch_size}); auto batch_path = Unbind(tpath); for (auto it = batch_path.begin(); it != batch_path.end(); ++it) { it->Resize({batch_size}); } // create and init required tensor framework::Tensor input_exp = float_tensor_buffer.GetBufferBlock({seq_len, batch_size, n_labels}); TransCompute<DeviceContext, T>(3, dev_ctx, *input, &input_exp, {1, 0, 2}); auto* transition = ctx.Input<framework::Tensor>("Transition"); framework::Tensor trans_exp = float_tensor_buffer.GetBufferBlock({n_labels, n_labels}); framework::TensorCopy(*transition, curr_place, dev_ctx, &trans_exp); trans_exp.Resize({1, n_labels, n_labels}); framework::Tensor alpha = float_tensor_buffer.GetBufferBlock({batch_size, n_labels}); framework::Tensor zero = int_tensor_buffer.GetBufferBlock({batch_size, 1}); int_functor(dev_ctx, &zero, 0); framework::Tensor one = int_tensor_buffer.GetBufferBlock({batch_size, 1}); int_functor(dev_ctx, &one, 1); framework::Tensor float_one = float_tensor_buffer.GetBufferBlock({batch_size, 1}); float_functor(dev_ctx, &float_one, static_cast<T>(1.0)); framework::Tensor alpha_trn_sum = float_tensor_buffer.GetBufferBlock({batch_size, n_labels, n_labels}); framework::Tensor alpha_max = float_tensor_buffer.GetBufferBlock({batch_size, n_labels}); framework::Tensor alpha_argmax = int_tensor_buffer.GetBufferBlock({seq_len, batch_size, n_labels}); auto alpha_argmax_unbind = Unbind(alpha_argmax); framework::Tensor alpha_nxt = float_tensor_buffer.GetBufferBlock({batch_size, n_labels}); framework::Tensor int_mask = int_tensor_buffer.GetBufferBlock({batch_size}); framework::Tensor zero_len_mask = int_tensor_buffer.GetBufferBlock({batch_size}); framework::Tensor float_mask = float_tensor_buffer.GetBufferBlock({batch_size, 1}); framework::Tensor stop_trans = float_tensor_buffer.GetBufferBlock({1, 1, n_labels}); framework::Tensor start_trans = float_tensor_buffer.GetBufferBlock({1, 1, n_labels}); framework::Tensor rest_trans = float_tensor_buffer.GetBufferBlock({1, n_labels - 2, n_labels}); framework::Tensor last_ids = int_tensor_buffer.GetBufferBlock({batch_size}); framework::Tensor last_ids_tmp = int_tensor_buffer.GetBufferBlock({batch_size}); framework::Tensor batch_offset = int_tensor_buffer.GetBufferBlock({batch_size}); framework::Tensor gather_idx = int_tensor_buffer.GetBufferBlock({batch_size}); std::vector<const framework::Tensor*> shape{&rest_trans, &stop_trans, &start_trans}; std::vector<framework::Tensor*> outputs{&rest_trans, &stop_trans, &start_trans}; math::SplitFunctor<DeviceContext, T> split_functor; split_functor(dev_ctx, trans_exp, shape, 1, &outputs); stop_trans.Resize({1, n_labels}); start_trans.Resize({1, n_labels}); auto logit0 = input_exp.Slice(0, 1); logit0.Resize({batch_size, n_labels}); BinaryOperation<DeviceContext, AddFunctor, T> AddFloat; BinaryOperation<DeviceContext, AddFunctor, int64_t> AddInt; BinaryOperation<DeviceContext, MulFunctor, T> MulFloat; BinaryOperation<DeviceContext, MulFunctor, int64_t> MulInt; BinaryOperation<DeviceContext, SubFunctor, T> SubFloat; BinaryOperation<DeviceContext, SubFunctor, int64_t> SubInt; if (include_bos_eos_tag) { AddFloat(dev_ctx, logit0, start_trans, &alpha); GetMask<DeviceContext, phi::funcs::EqualFunctor, T>()(ctx, left_length, one, &float_mask); MulFloat(dev_ctx, stop_trans, float_mask, &alpha_nxt); AddFloat(dev_ctx, alpha, alpha_nxt, &alpha); } else { alpha = logit0; } SubInt(dev_ctx, left_length, one, &left_length); Argmax<DeviceContext, T, int64_t> argmax; for (int64_t i = 1; i < max_seq_len; ++i) { framework::Tensor logit = input_exp.Slice(i, i + 1); logit.Resize({batch_size, n_labels}); framework::Tensor& alpha_exp = alpha.Resize({batch_size, n_labels, 1}); AddFloat(dev_ctx, alpha_exp, trans_exp, &alpha_trn_sum); auto alpha_argmax_temp = alpha_argmax_unbind[i - 1]; alpha_argmax_temp.Resize({batch_size, n_labels}); argmax(ctx, alpha_trn_sum, &alpha_argmax_temp, &alpha_max, 1); historys.emplace_back(alpha_argmax_temp); AddFloat(dev_ctx, alpha_max, logit, &alpha_nxt); alpha.Resize({batch_size, n_labels}); // mask = paddle.cast((left_length > 0), dtype='float32') // alpha = mask * alpha_nxt + (1 - mask) * alpha GetMask<DeviceContext, phi::funcs::GreaterThanFunctor, T>()( ctx, left_length, zero, &float_mask); // alpha_nxt = mask * alpha_nxt MulFloat(dev_ctx, alpha_nxt, float_mask, &alpha_nxt); // inv_mask = 1 - mask SubFloat(dev_ctx, float_one, float_mask, &float_mask); // alpha = (1 - mask) * alpha MulFloat(dev_ctx, alpha, float_mask, &alpha); // alpha += alpha_nxt AddFloat(dev_ctx, alpha, alpha_nxt, &alpha); if (include_bos_eos_tag) { GetMask<DeviceContext, phi::funcs::EqualFunctor, T>()(ctx, left_length, one, &float_mask); // alpha += mask * trans_exp[:, self.stop_idx] MulFloat(dev_ctx, stop_trans, float_mask, &alpha_nxt); AddFloat(dev_ctx, alpha, alpha_nxt, &alpha); } SubInt(dev_ctx, left_length, one, &left_length); } argmax(ctx, alpha, &last_ids, scores, 1); left_length.Resize({batch_size}); GetMask<DeviceContext, phi::funcs::GreaterEqualFunctor, int64_t>()( ctx, left_length, zero, &int_mask); // last_ids_update = last_ids * tag_mask int last_ids_index = 1; int actual_len = (std::min)(seq_len, static_cast<int>(max_seq_len)); MulInt(dev_ctx, last_ids, int_mask, &batch_path[actual_len - last_ids_index]); // The algorithm below can refer to // https://github.com/PaddlePaddle/PaddleNLP/blob/develop/paddlenlp/layers/crf.py#L438 ARange<DeviceContext> arange; arange(dev_ctx, batch_offset.data<int64_t>(), batch_size, n_labels); Gather<DeviceContext, int64_t, int64_t> gather; for (auto hist = historys.rbegin(); hist != historys.rend(); ++hist) { ++last_ids_index; AddInt(dev_ctx, left_length, one, &left_length); AddInt(dev_ctx, batch_offset, last_ids, &gather_idx); framework::Tensor& last_ids_update = batch_path[actual_len - last_ids_index]; hist->Resize({batch_size * n_labels}); gather(dev_ctx, *hist, gather_idx, &last_ids_update); GetMask<DeviceContext, phi::funcs::GreaterThanFunctor, int64_t>()( ctx, left_length, zero, &int_mask); MulInt(dev_ctx, last_ids_update, int_mask, &last_ids_update); GetMask<DeviceContext, phi::funcs::EqualFunctor, int64_t>()( ctx, left_length, zero, &zero_len_mask); MulInt(dev_ctx, last_ids, zero_len_mask, &last_ids_tmp); SubInt(dev_ctx, one, zero_len_mask, &zero_len_mask); MulInt(dev_ctx, last_ids_update, zero_len_mask, &last_ids_update); AddInt(dev_ctx, last_ids_update, last_ids_tmp, &last_ids_update); GetMask<DeviceContext, phi::funcs::LessThanFunctor, int64_t>()( ctx, left_length, zero, &int_mask); MulInt(dev_ctx, last_ids, int_mask, &last_ids); AddInt(dev_ctx, last_ids_update, last_ids, &last_ids); } TransCompute<DeviceContext, int64_t>(2, dev_ctx, tpath, path, {1, 0}); } }; } // namespace operators } // namespace paddle
irbuilder_unroll_partial_heuristic_for_collapse.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=51 -x c -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics // REQUIRES: x86-registered-target #ifndef HEADER #define HEADER double sind(double); // CHECK-LABEL: define {{.*}}@unroll_partial_heuristic_for( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[M_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[E_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[OFFSET_ADDR:.+]] = alloca float, align 4 // CHECK-NEXT: %[[DOTOMP_IV:.+]] = alloca i64, align 8 // CHECK-NEXT: %[[TMP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[TMP1:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTCAPTURE_EXPR_:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[J:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTCAPTURE_EXPR_2:.+]] = alloca i64, align 8 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTUNROLLED_IV_J:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTOMP_LB:.+]] = alloca i64, align 8 // CHECK-NEXT: %[[DOTOMP_UB:.+]] = alloca i64, align 8 // CHECK-NEXT: %[[DOTOMP_STRIDE:.+]] = alloca i64, align 8 // CHECK-NEXT: %[[DOTOMP_IS_LAST:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[I6:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTUNROLLED_IV_J7:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTUNROLL_INNER_IV_J:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32 %[[M:.+]], i32* %[[M_ADDR]], align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8 // CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8 // CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8 // CHECK-NEXT: store float* %[[E:.+]], float** %[[E_ADDR]], align 8 // CHECK-NEXT: store float %[[OFFSET:.+]], float* %[[OFFSET_ADDR]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = load i32, i32* %[[M_ADDR]], align 4 // CHECK-NEXT: store i32 %[[TMP0]], i32* %[[DOTCAPTURE_EXPR_]], align 4 // CHECK-NEXT: store i32 0, i32* %[[J]], align 4 // CHECK-NEXT: %[[TMP1_1:.+]] = load i32, i32* %[[DOTCAPTURE_EXPR_]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub nsw i32 %[[TMP1_1]], 0 // CHECK-NEXT: %[[DIV:.+]] = sdiv i32 %[[SUB]], 1 // CHECK-NEXT: %[[CONV:.+]] = sext i32 %[[DIV]] to i64 // CHECK-NEXT: %[[MUL:.+]] = mul nsw i64 %[[CONV]], 4 // CHECK-NEXT: %[[SUB3:.+]] = sub nsw i64 %[[MUL]], 1 // CHECK-NEXT: store i64 %[[SUB3]], i64* %[[DOTCAPTURE_EXPR_2]], align 8 // CHECK-NEXT: store i32 0, i32* %[[I]], align 4 // CHECK-NEXT: store i32 0, i32* %[[DOTUNROLLED_IV_J]], align 4 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[DOTCAPTURE_EXPR_]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp slt i32 0, %[[TMP2]] // CHECK-NEXT: br i1 %[[CMP]], label %[[OMP_PRECOND_THEN:.+]], label %[[OMP_PRECOND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_PRECOND_THEN]]: // CHECK-NEXT: store i64 0, i64* %[[DOTOMP_LB]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i64, i64* %[[DOTCAPTURE_EXPR_2]], align 8 // CHECK-NEXT: store i64 %[[TMP3]], i64* %[[DOTOMP_UB]], align 8 // CHECK-NEXT: store i64 1, i64* %[[DOTOMP_STRIDE]], align 8 // CHECK-NEXT: store i32 0, i32* %[[DOTOMP_IS_LAST]], align 4 // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @3) // CHECK-NEXT: call void @__kmpc_for_static_init_8(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 34, i32* %[[DOTOMP_IS_LAST]], i64* %[[DOTOMP_LB]], i64* %[[DOTOMP_UB]], i64* %[[DOTOMP_STRIDE]], i64 1, i64 1) // CHECK-NEXT: %[[TMP4:.+]] = load i64, i64* %[[DOTOMP_UB]], align 8 // CHECK-NEXT: %[[TMP5:.+]] = load i64, i64* %[[DOTCAPTURE_EXPR_2]], align 8 // CHECK-NEXT: %[[CMP8:.+]] = icmp sgt i64 %[[TMP4]], %[[TMP5]] // CHECK-NEXT: br i1 %[[CMP8]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP6:.+]] = load i64, i64* %[[DOTCAPTURE_EXPR_2]], align 8 // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: %[[TMP7:.+]] = load i64, i64* %[[DOTOMP_UB]], align 8 // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i64 [ %[[TMP6]], %[[COND_TRUE]] ], [ %[[TMP7]], %[[COND_FALSE]] ] // CHECK-NEXT: store i64 %[[COND]], i64* %[[DOTOMP_UB]], align 8 // CHECK-NEXT: %[[TMP8:.+]] = load i64, i64* %[[DOTOMP_LB]], align 8 // CHECK-NEXT: store i64 %[[TMP8]], i64* %[[DOTOMP_IV]], align 8 // CHECK-NEXT: br label %[[OMP_INNER_FOR_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_INNER_FOR_COND]]: // CHECK-NEXT: %[[TMP9:.+]] = load i64, i64* %[[DOTOMP_IV]], align 8 // CHECK-NEXT: %[[TMP10:.+]] = load i64, i64* %[[DOTOMP_UB]], align 8 // CHECK-NEXT: %[[CMP10:.+]] = icmp sle i64 %[[TMP9]], %[[TMP10]] // CHECK-NEXT: br i1 %[[CMP10]], label %[[OMP_INNER_FOR_BODY:.+]], label %[[OMP_INNER_FOR_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_INNER_FOR_BODY]]: // CHECK-NEXT: %[[TMP11:.+]] = load i64, i64* %[[DOTOMP_IV]], align 8 // CHECK-NEXT: %[[DIV12:.+]] = sdiv i64 %[[TMP11]], 4 // CHECK-NEXT: %[[MUL13:.+]] = mul nsw i64 %[[DIV12]], 1 // CHECK-NEXT: %[[ADD:.+]] = add nsw i64 0, %[[MUL13]] // CHECK-NEXT: %[[CONV14:.+]] = trunc i64 %[[ADD]] to i32 // CHECK-NEXT: store i32 %[[CONV14]], i32* %[[I6]], align 4 // CHECK-NEXT: %[[TMP12:.+]] = load i64, i64* %[[DOTOMP_IV]], align 8 // CHECK-NEXT: %[[TMP13:.+]] = load i64, i64* %[[DOTOMP_IV]], align 8 // CHECK-NEXT: %[[DIV15:.+]] = sdiv i64 %[[TMP13]], 4 // CHECK-NEXT: %[[MUL16:.+]] = mul nsw i64 %[[DIV15]], 4 // CHECK-NEXT: %[[SUB17:.+]] = sub nsw i64 %[[TMP12]], %[[MUL16]] // CHECK-NEXT: %[[MUL18:.+]] = mul nsw i64 %[[SUB17]], 2 // CHECK-NEXT: %[[ADD19:.+]] = add nsw i64 0, %[[MUL18]] // CHECK-NEXT: %[[CONV20:.+]] = trunc i64 %[[ADD19]] to i32 // CHECK-NEXT: store i32 %[[CONV20]], i32* %[[DOTUNROLLED_IV_J7]], align 4 // CHECK-NEXT: %[[TMP14:.+]] = load i32, i32* %[[DOTUNROLLED_IV_J7]], align 4 // CHECK-NEXT: store i32 %[[TMP14]], i32* %[[DOTUNROLL_INNER_IV_J]], align 4 // CHECK-NEXT: br label %[[FOR_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[FOR_COND]]: // CHECK-NEXT: %[[TMP15:.+]] = load i32, i32* %[[DOTUNROLL_INNER_IV_J]], align 4 // CHECK-NEXT: %[[TMP16:.+]] = load i32, i32* %[[DOTUNROLLED_IV_J7]], align 4 // CHECK-NEXT: %[[ADD21:.+]] = add nsw i32 %[[TMP16]], 2 // CHECK-NEXT: %[[CMP22:.+]] = icmp sle i32 %[[TMP15]], %[[ADD21]] // CHECK-NEXT: br i1 %[[CMP22]], label %[[LAND_RHS:.+]], label %[[LAND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[LAND_RHS]]: // CHECK-NEXT: %[[TMP17:.+]] = load i32, i32* %[[DOTUNROLL_INNER_IV_J]], align 4 // CHECK-NEXT: %[[CMP24:.+]] = icmp sle i32 %[[TMP17]], 8 // CHECK-NEXT: br label %[[LAND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[LAND_END]]: // CHECK-NEXT: %[[TMP18:.+]] = phi i1 [ false, %[[FOR_COND]] ], [ %[[CMP24]], %[[LAND_RHS]] ] // CHECK-NEXT: br i1 %[[TMP18]], label %[[FOR_BODY:.+]], label %[[FOR_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[FOR_BODY]]: // CHECK-NEXT: %[[TMP19:.+]] = load i32, i32* %[[DOTUNROLL_INNER_IV_J]], align 4 // CHECK-NEXT: %[[MUL26:.+]] = mul nsw i32 %[[TMP19]], 1 // CHECK-NEXT: %[[ADD27:.+]] = add nsw i32 0, %[[MUL26]] // CHECK-NEXT: store i32 %[[ADD27]], i32* %[[J]], align 4 // CHECK-NEXT: %[[TMP20:.+]] = load float*, float** %[[B_ADDR]], align 8 // CHECK-NEXT: %[[TMP21:.+]] = load i32, i32* %[[I6]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = sext i32 %[[TMP21]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP20]], i64 %[[IDXPROM]] // CHECK-NEXT: %[[TMP22:.+]] = load float, float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: %[[CONV28:.+]] = fpext float %[[TMP22]] to double // CHECK-NEXT: %[[CALL:.+]] = call double @sind(double %[[CONV28]]) // CHECK-NEXT: %[[TMP23:.+]] = load float*, float** %[[C_ADDR]], align 8 // CHECK-NEXT: %[[TMP24:.+]] = load i32, i32* %[[I6]], align 4 // CHECK-NEXT: %[[IDXPROM29:.+]] = sext i32 %[[TMP24]] to i64 // CHECK-NEXT: %[[ARRAYIDX30:.+]] = getelementptr inbounds float, float* %[[TMP23]], i64 %[[IDXPROM29]] // CHECK-NEXT: %[[TMP25:.+]] = load float, float* %[[ARRAYIDX30]], align 4 // CHECK-NEXT: %[[CONV31:.+]] = fpext float %[[TMP25]] to double // CHECK-NEXT: %[[MUL32:.+]] = fmul double %[[CALL]], %[[CONV31]] // CHECK-NEXT: %[[TMP26:.+]] = load float*, float** %[[D_ADDR]], align 8 // CHECK-NEXT: %[[TMP27:.+]] = load i32, i32* %[[I6]], align 4 // CHECK-NEXT: %[[IDXPROM33:.+]] = sext i32 %[[TMP27]] to i64 // CHECK-NEXT: %[[ARRAYIDX34:.+]] = getelementptr inbounds float, float* %[[TMP26]], i64 %[[IDXPROM33]] // CHECK-NEXT: %[[TMP28:.+]] = load float, float* %[[ARRAYIDX34]], align 4 // CHECK-NEXT: %[[CONV35:.+]] = fpext float %[[TMP28]] to double // CHECK-NEXT: %[[MUL36:.+]] = fmul double %[[MUL32]], %[[CONV35]] // CHECK-NEXT: %[[TMP29:.+]] = load float*, float** %[[E_ADDR]], align 8 // CHECK-NEXT: %[[TMP30:.+]] = load i32, i32* %[[I6]], align 4 // CHECK-NEXT: %[[IDXPROM37:.+]] = sext i32 %[[TMP30]] to i64 // CHECK-NEXT: %[[ARRAYIDX38:.+]] = getelementptr inbounds float, float* %[[TMP29]], i64 %[[IDXPROM37]] // CHECK-NEXT: %[[TMP31:.+]] = load float, float* %[[ARRAYIDX38]], align 4 // CHECK-NEXT: %[[CONV39:.+]] = fpext float %[[TMP31]] to double // CHECK-NEXT: %[[MUL40:.+]] = fmul double %[[MUL36]], %[[CONV39]] // CHECK-NEXT: %[[TMP32:.+]] = load float, float* %[[OFFSET_ADDR]], align 4 // CHECK-NEXT: %[[CONV41:.+]] = fpext float %[[TMP32]] to double // CHECK-NEXT: %[[ADD42:.+]] = fadd double %[[MUL40]], %[[CONV41]] // CHECK-NEXT: %[[TMP33:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP34:.+]] = load i32, i32* %[[I6]], align 4 // CHECK-NEXT: %[[IDXPROM43:.+]] = sext i32 %[[TMP34]] to i64 // CHECK-NEXT: %[[ARRAYIDX44:.+]] = getelementptr inbounds float, float* %[[TMP33]], i64 %[[IDXPROM43]] // CHECK-NEXT: %[[TMP35:.+]] = load float, float* %[[ARRAYIDX44]], align 4 // CHECK-NEXT: %[[CONV45:.+]] = fpext float %[[TMP35]] to double // CHECK-NEXT: %[[ADD46:.+]] = fadd double %[[CONV45]], %[[ADD42]] // CHECK-NEXT: %[[CONV47:.+]] = fptrunc double %[[ADD46]] to float // CHECK-NEXT: store float %[[CONV47]], float* %[[ARRAYIDX44]], align 4 // CHECK-NEXT: br label %[[FOR_INC:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[FOR_INC]]: // CHECK-NEXT: %[[TMP36:.+]] = load i32, i32* %[[DOTUNROLL_INNER_IV_J]], align 4 // CHECK-NEXT: %[[INC:.+]] = add nsw i32 %[[TMP36]], 1 // CHECK-NEXT: store i32 %[[INC]], i32* %[[DOTUNROLL_INNER_IV_J]], align 4 // CHECK-NEXT: br label %[[FOR_COND]], !llvm.loop ![[LOOP3:[0-9]+]] // CHECK-EMPTY: // CHECK-NEXT: [[FOR_END]]: // CHECK-NEXT: br label %[[OMP_BODY_CONTINUE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_BODY_CONTINUE]]: // CHECK-NEXT: br label %[[OMP_INNER_FOR_INC:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_INNER_FOR_INC]]: // CHECK-NEXT: %[[TMP37:.+]] = load i64, i64* %[[DOTOMP_IV]], align 8 // CHECK-NEXT: %[[ADD48:.+]] = add nsw i64 %[[TMP37]], 1 // CHECK-NEXT: store i64 %[[ADD48]], i64* %[[DOTOMP_IV]], align 8 // CHECK-NEXT: br label %[[OMP_INNER_FOR_COND]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_INNER_FOR_END]]: // CHECK-NEXT: br label %[[OMP_LOOP_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_EXIT]]: // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM49:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @5) // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM49]]) // CHECK-NEXT: br label %[[OMP_PRECOND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_PRECOND_END]]: // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM50:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @7) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @6, i32 %[[OMP_GLOBAL_THREAD_NUM50]]) // CHECK-NEXT: ret void // CHECK-NEXT: } void unroll_partial_heuristic_for(int m, float *a, float *b, float *c, float *d, float *e, float offset) { #pragma omp for collapse(2) for (int i = 0; i < m; i++) { #pragma omp unroll partial for (int j = 0; j < 8; j++) { a[i] += sind(b[i]) * c[i] * d[i] * e[i] + offset; } } } #endif // HEADER // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 51} // CHECK: ![[META2:[0-9]+]] = // CHECK: ![[LOOP3]] = distinct !{![[LOOP3]], ![[LOOPPROP4:[0-9]+]], ![[LOOPPROP5:[0-9]+]]} // CHECK: ![[LOOPPROP4]] = !{!"llvm.loop.mustprogress"} // CHECK: ![[LOOPPROP5]] = !{!"llvm.loop.unroll.count", i32 2}
ofmo-oneint.c
/** * @file ofmo-oneint.c * 通常のHartree-Fock SCF計算で用いる1電子積分計算を行う関数群 * */ /** * @defgroup integ-oneint 1電子積分行う関数群 * * 通常のHartree-Fock計算で用いる、重なり積分、および、1電子ハミルトン行列 * の計算を行う関数群。各積分タイプの1電子積分をまとめて行う。 * * すべての関数は、同じ引数をとるので、以下にそれらの内容を示す。 * * @param[in] La CSペアのうち、1つめのCSの軌道量子数 * @param[in] Lb CSペアのうち、2つ目のCSの軌道量子数 * (\f$ \tt{La} \ge \tt{Lb} \ge 0 \f$ * @param[in] leading_cs[lqn] 軌道量子数 /c lqn の先頭CS番号 * @param[in] shel_tem[ics] CS番号 \c ics のCSの縮約長 * @param[in] shel_atm[ics] CS番号 \c ics のCSが属する原子の番号 * @param[in] shel_add[ics] CS番号 \c ics のCSに含まれるPSの先頭PS番号 * @param[in] atom_x[iat] 原子の番号 \c iat のx座標(au単位) * @param[in] atom_y[iat] 原子の番号 \c iat のy座標(au単位) * @param[in] atom_z[iat] 原子の番号 \c iat のz座標(au単位) * @param[in] prim_exp[ips] PS番号 \c ips のPSの軌道指数 * @param[in] prim_coe[ips] PS番号 \c ips のPSの規格化定数込みの縮約係数 * @param[in] nat 原子数 * @param[in] atomic_number[iat] 原子の番号 \c iat の原子の原子番号 * @param[out] S[] 計算された重なり行列の要素を格納する配列 * (圧縮"U"形式) * @param[out] H[] 計算された1電子ハミルトン行列の要素を格納する配列 * (圧縮"U"形式) * * @ingroup integ-med * * */ #include <stdio.h> #include <string.h> #include <math.h> #include "ofmo-oneint-core.h" /** SSタイプの1電子積分を行う関数 * @ingroup integ-oneint * */ int ofmo_oneint_ss__( const int *pnworkers, const int *pworkerid, const int *pLa, const int *pLb, const int leading_cs[], const int shel_tem[], const int shel_atm[], const int shel_add[], const int shel_ini[], const double atom_x[], const double atom_y[], const double atom_z[], const double prim_exp[], const double prim_coe[], const int *pnat, const int atomic_number[], double S[], double H[] ) { int iao2, ijao; int ips0, ics, ics0, ics1, iat, iao; int jps0, jcs, jcs0 , jat, jao; int nps_i, nps_j; double A[3], B[3]; // int nworkers=*pnworkers, workerid=*pworkerid; int La=*pLa, Lb=*pLb, nat=*pnat; double oviss, hcoress; /*#pragma omp master { printf("SS\n"); fflush(stdout); }*/ ics0 = jcs0 = leading_cs[La]; ics1 = leading_cs[La+1]; for ( ics=ics0+workerid; ics<ics1; ics+=nworkers ) { ips0 = shel_add[ics]; iat = shel_atm[ics]; iao = shel_ini[ics]; nps_i = shel_tem[ics]; A[0]=atom_x[ iat ]; A[1]=atom_y[ iat ]; A[2]=atom_z[ iat ]; iao2 = iao*(iao+1)/2; for ( jcs=jcs0; jcs<=ics; jcs++ ) { jps0 = shel_add[jcs]; jat = shel_atm[jcs]; jao = shel_ini[jcs]; nps_j = shel_tem[jcs]; B[0]=atom_x[ jat ]; B[1]=atom_y[ jat ]; B[2]=atom_z[ jat ]; ijao = iao2+jao; /*// debug #pragma omp master { printf("iao, jao= %d, %d\n", iao, jao ); fflush(stdout); }*/ oneint_core_ss__( &ips0, &nps_i, A, &jps0, &nps_j, B, prim_exp, prim_coe, &nat, atom_x, atom_y, atom_z, atomic_number, &oviss, &hcoress ); S[ijao] = oviss; H[ijao] = hcoress; } } return 0; } /** PSタイプの1電子積分を行う関数 * @ingroup integ-oneint * */ int ofmo_oneint_ps__( const int *pnworkers, const int *pworkerid, const int *pLa, const int *pLb, const int leading_cs[], const int shel_tem[], const int shel_atm[], const int shel_add[], const int shel_ini[], const double atom_x[], const double atom_y[], const double atom_z[], const double prim_exp[], const double prim_coe[], const int *pnat, const int atomic_number[], double S[], double H[] ) { int i, iao2, ijao; int ips0, ics, ics0, ics1, iat, iao, iao0; int jps0, jcs, jcs0, jcs1, jat, jao; int nps_i, nps_j; double A[3], B[3]; // int nworkers=*pnworkers, workerid=*pworkerid; int La=*pLa, Lb=*pLb, nat=*pnat; double ovips[3], hcoreps[3]; ics0 = leading_cs[La]; ics1 = leading_cs[La+1]; jcs0 = leading_cs[Lb]; jcs1 = leading_cs[Lb+1]; for ( ics=ics0+workerid; ics<ics1; ics+=nworkers ) { ips0 = shel_add[ics]; iat = shel_atm[ics]; iao0 = shel_ini[ics]; nps_i = shel_tem[ics]; A[0]=atom_x[ iat ]; A[1]=atom_y[ iat ]; A[2]=atom_z[ iat ]; for ( jcs=jcs0; jcs<jcs1; jcs++ ) { jps0 = shel_add[jcs]; jat = shel_atm[jcs]; jao = shel_ini[jcs]; nps_j = shel_tem[jcs]; B[0]=atom_x[ jat ]; B[1]=atom_y[ jat ]; B[2]=atom_z[ jat ]; oneint_core_ps__( &ips0, &nps_i, A, &jps0, &nps_j, B, prim_exp, prim_coe, &nat, atom_x, atom_y, atom_z, atomic_number, ovips, hcoreps ); for ( i=0, iao=iao0; i<3; i++, iao++ ) { iao2 = (iao*iao+iao)>>1; ijao = iao2 + jao; S[ijao] = ovips[i]; H[ijao] = hcoreps[i]; } } } return 0; } /** PPタイプの1電子積分を行う関数 * @ingroup integ-oneint * */ int ofmo_oneint_pp__( const int *pnworkers, const int *pworkerid, const int *pLa, const int *pLb, const int leading_cs[], const int shel_tem[], const int shel_atm[], const int shel_add[], const int shel_ini[], const double atom_x[], const double atom_y[], const double atom_z[], const double prim_exp[], const double prim_coe[], const int *pnat, const int atomic_number[], double S[], double H[] ) { int i, j, ij, ii, iao2, ijao; int ips0, ics, ics0, ics1, iat, iao, iao0; int jps0, jcs, jcs0 , jat, jao, jao0; int nps_i, nps_j; double A[3], B[3]; // int nworkers=*pnworkers, workerid=*pworkerid; int La=*pLa, Lb=*pLb, nat=*pnat; double ovipp[3*3], hcorepp[3*3]; ics0 = jcs0 = leading_cs[La]; ics1 = leading_cs[La+1]; for ( ics=ics0+workerid; ics<ics1; ics+=nworkers ) { ips0 = shel_add[ics]; iat = shel_atm[ics]; iao0 = shel_ini[ics]; nps_i = shel_tem[ics]; A[0]=atom_x[ iat ]; A[1]=atom_y[ iat ]; A[2]=atom_z[ iat ]; for ( jcs=jcs0; jcs<=ics; jcs++ ) { jps0 = shel_add[jcs]; jat = shel_atm[jcs]; jao0 = shel_ini[jcs]; nps_j = shel_tem[jcs]; B[0]=atom_x[ jat ]; B[1]=atom_y[ jat ]; B[2]=atom_z[ jat ]; oneint_core_pp__( &ips0, &nps_i, A, &jps0, &nps_j, B, prim_exp, prim_coe, &nat, atom_x, atom_y, atom_z, atomic_number, ovipp, hcorepp ); if ( ics != jcs ) { ij = 0; for ( i=0, iao=iao0; i<3; i++, iao++ ) { iao2 = (iao*iao+iao)>>1; for ( j=0, jao=jao0; j<3; j++,jao++ ) { ijao = iao2 + jao; S[ijao] = ovipp[ij]; H[ijao] = hcorepp[ij]; ij++; } } } else { for ( i=0, ii=0, iao=iao0; i<3; i++, iao++, ii+=3 ) { iao2 = (iao*iao+iao)>>1; for ( j=0, jao=jao0, ij=ii; j<=i; j++, jao++, ij++ ) { ijao = iao2 + jao; S[ijao] = ovipp[ij]; H[ijao] = hcorepp[ij]; } } } } } return 0; } /** DSタイプの1電子積分を行う関数 * @ingroup integ-oneint * */ int ofmo_oneint_ds__( const int *pnworkers, const int *pworkerid, const int *pLa, const int *pLb, const int leading_cs[], const int shel_tem[], const int shel_atm[], const int shel_add[], const int shel_ini[], const double atom_x[], const double atom_y[], const double atom_z[], const double prim_exp[], const double prim_coe[], const int *pnat, const int atomic_number[], double S[], double H[] ) { int i, iao2, ijao; int ips0, ics, ics0, ics1, iat, iao, iao0; int jps0, jcs, jcs0, jcs1, jat, jao; int nps_i, nps_j; double A[3], B[3]; // int nworkers=*pnworkers, workerid=*pworkerid; int La=*pLa, Lb=*pLb, nat=*pnat; double ovids[6], hcoreds[6]; ics0 = leading_cs[La]; ics1 = leading_cs[La+1]; jcs0 = leading_cs[Lb]; jcs1 = leading_cs[Lb+1]; for ( ics=ics0+workerid; ics<ics1; ics+=nworkers ) { ips0 = shel_add[ics]; iat = shel_atm[ics]; iao0 = shel_ini[ics]; nps_i = shel_tem[ics]; A[0]=atom_x[ iat ]; A[1]=atom_y[ iat ]; A[2]=atom_z[ iat ]; for ( jcs=jcs0; jcs<jcs1; jcs++ ) { jps0 = shel_add[jcs]; jat = shel_atm[jcs]; jao = shel_ini[jcs]; nps_j = shel_tem[jcs]; B[0]=atom_x[ jat ]; B[1]=atom_y[ jat ]; B[2]=atom_z[ jat ]; oneint_core_ds__( &ips0, &nps_i, A, &jps0, &nps_j, B, prim_exp, prim_coe, &nat, atom_x, atom_y, atom_z, atomic_number, ovids, hcoreds ); for ( i=0, iao=iao0; i<6; i++, iao++ ) { iao2 = (iao*iao+iao)>>1; ijao = iao2 + jao; S[ijao] = ovids[i]; H[ijao] = hcoreds[i]; } } } return 0; } /** DPタイプの1電子積分を行う関数 * @ingroup integ-oneint * */ int ofmo_oneint_dp__( const int *pnworkers, const int *pworkerid, const int *pLa, const int *pLb, const int leading_cs[], const int shel_tem[], const int shel_atm[], const int shel_add[], const int shel_ini[], const double atom_x[], const double atom_y[], const double atom_z[], const double prim_exp[], const double prim_coe[], const int *pnat, const int atomic_number[], double S[], double H[] ) { int i, j, ij, iao2, ijao; int ips0, ics, ics0, ics1, iat, iao, iao0; int jps0, jcs, jcs0, jcs1, jat, jao, jao0; int nps_i, nps_j; double A[3], B[3]; // int nworkers=*pnworkers, workerid=*pworkerid; int La=*pLa, Lb=*pLb, nat=*pnat; double ovidp[6*3], hcoredp[6*3]; ics0 = leading_cs[La]; ics1 = leading_cs[La+1]; jcs0 = leading_cs[Lb]; jcs1 = leading_cs[Lb+1]; for ( ics=ics0+workerid; ics<ics1; ics+=nworkers ) { ips0 = shel_add[ics]; iat = shel_atm[ics]; iao0 = shel_ini[ics]; nps_i = shel_tem[ics]; A[0]=atom_x[ iat ]; A[1]=atom_y[ iat ]; A[2]=atom_z[ iat ]; for ( jcs=jcs0; jcs<jcs1; jcs++ ) { jps0 = shel_add[jcs]; jat = shel_atm[jcs]; jao0 = shel_ini[jcs]; nps_j = shel_tem[jcs]; B[0]=atom_x[ jat ]; B[1]=atom_y[ jat ]; B[2]=atom_z[ jat ]; oneint_core_dp__( &ips0, &nps_i, A, &jps0, &nps_j, B, prim_exp, prim_coe, &nat, atom_x, atom_y, atom_z, atomic_number, ovidp, hcoredp ); ij = 0; for ( i=0, iao=iao0; i<6; i++, iao++ ) { iao2 = (iao*iao+iao)>>1; for ( j=0, jao=jao0; j<3; j++, jao++ ) { ijao = iao2 + jao; S[ijao] = ovidp[ij]; H[ijao] = hcoredp[ij]; ij++; } } } } return 0; } /** DDタイプの1電子積分を行う関数 * @ingroup integ-oneint * */ int ofmo_oneint_dd__( const int *pnworkers, const int *pworkerid, const int *pLa, const int *pLb, const int leading_cs[], const int shel_tem[], const int shel_atm[], const int shel_add[], const int shel_ini[], const double atom_x[], const double atom_y[], const double atom_z[], const double prim_exp[], const double prim_coe[], const int *pnat, const int atomic_number[], double S[], double H[] ) { int i, j, ij, ii, iao2, ijao; int ips0, ics, ics0, ics1, iat, iao, iao0; int jps0, jcs, jcs0 , jat, jao, jao0; int nps_i, nps_j; double A[3], B[3]; // int nworkers=*pnworkers, workerid=*pworkerid; int La=*pLa, Lb=*pLb, nat=*pnat; double ovidd[6*6], hcoredd[6*6]; ics0 = jcs0 = leading_cs[La]; ics1 = leading_cs[La+1]; for ( ics=ics0+workerid; ics<ics1; ics+=nworkers ) { ips0 = shel_add[ics]; iat = shel_atm[ics]; iao0 = shel_ini[ics]; nps_i = shel_tem[ics]; A[0]=atom_x[ iat ]; A[1]=atom_y[ iat ]; A[2]=atom_z[ iat ]; for ( jcs=jcs0; jcs<=ics; jcs++ ) { jps0 = shel_add[jcs]; jat = shel_atm[jcs]; jao0 = shel_ini[jcs]; nps_j = shel_tem[jcs]; B[0]=atom_x[ jat ]; B[1]=atom_y[ jat ]; B[2]=atom_z[ jat ]; oneint_core_dd__( &ips0, &nps_i, A, &jps0, &nps_j, B, prim_exp, prim_coe, &nat, atom_x, atom_y, atom_z, atomic_number, ovidd, hcoredd ); if ( ics != jcs ) { ij = 0; for ( i=0, iao=iao0; i<6; i++, iao++ ) { iao2 = (iao*iao+iao)>>1; for ( j=0, jao=jao0; j<6; j++,jao++ ) { ijao = iao2 + jao; S[ijao] = ovidd[ij]; H[ijao] = hcoredd[ij]; ij++; } } } else { for ( i=0, ii=0, iao=iao0; i<6; i++, iao++, ii+=6 ) { iao2 = (iao*iao+iao)>>1; for ( j=0, jao=jao0, ij=ii; j<=i; j++, jao++, ij++ ) { ijao = iao2 + jao; S[ijao] = ovidd[ij]; H[ijao] = hcoredd[ij]; } } } } } return 0; }
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_08__plus_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__plus_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__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 // A pattern? 0 // B type: float // B pattern? 0 // 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) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ float bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__plus_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__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, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__plus_fp32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, 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 is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__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_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__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_04__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_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__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
HelloOMP.c
/* gcc -fopenmp -O3 -Wall HelloOMP.c -o HelloOMP */ #include <stdio.h> #include <omp.h> int main(void) { #pragma omp parallel printf("[%d]: hello world!\n", omp_get_thread_num()); return 0; }
SizeField.h
#pragma once #include <ScalarField/ScalarField.h> #include "MeshHeader.h" #include "HelperFunctions.h" #include <nanoflann.hpp> class SizeField { struct MeshPointsNN { using kd_tree_t = nanoflann::KDTreeSingleIndexAdaptor<nanoflann::L2_Simple_Adaptor<float, MeshPointsNN >, MeshPointsNN, 3>; std::unique_ptr<kd_tree_t> kdTree_; std::vector<TriMesh::Point> points_; MeshPointsNN( TriMesh& mesh ) { points_.reserve( mesh.n_vertices() ); for( const auto& vh : mesh.vertices() ) { points_.push_back( mesh.point( vh ) ); } for( auto& p : points_ ) { p[2] = 0; } // init kd tree kdTree_ = std::make_unique<kd_tree_t>( 3, *this ); kdTree_->buildIndex(); } std::vector<size_t> findNearestNeighbor( const TriMesh::Point& p, int k ) const { std::vector<size_t> ret_indexes( k ); std::vector<float> out_dists_sqr( k ); nanoflann::KNNResultSet<float> resultSet( k ); resultSet.init( &ret_indexes[0], &out_dists_sqr[0] ); kdTree_->findNeighbors( resultSet, &p[0], nanoflann::SearchParams() ); return ret_indexes; } /*----- nanoflann functions -----*/ // Must return the number of data points inline size_t kdtree_get_point_count() const { return points_.size(); } // Returns the dim'th component of the idx'th point in the class inline float kdtree_get_pt( const size_t idx, const size_t dim ) const { return points_[idx][dim]; } template <class BBOX> bool kdtree_get_bbox( BBOX& ) const { return false; } }; ScalarField::ScalarField field_; public: SizeField( const std::experimental::filesystem::path& filename ) : field_(filename) {} SizeField( const ScalarField::ScalarField& field ) : field_( field ) {} SizeField( TriMesh& mesh, const size_t& Nx, const size_t& Ny, const bool useInterpolation = true ) : field_( useInterpolation ? computeAabbLecacy( mesh ) : computeAabbLecacy( mesh ), Nx, Ny ) { if( useInterpolation ) { fillGrid( mesh ); } else { fillGridFromNearestNeighbors( mesh ); } } const auto& field() const { return field_; } private: void gaussSeidelStep( ScalarField::ScalarField& sf, int i, int j, float* v, float* vNew ) { int n = 0; float val = 0; if( i > 0 && v[sf.lex( i - 1, j )] != -FLT_MAX ) { val += v[sf.lex( i - 1, j )]; ++n; } if( i < sf.Nx() - 1 && v[sf.lex( i + 1, j )] != -FLT_MAX ) { val += v[sf.lex( i + 1, j )]; ++n; } if( j > 0 && v[sf.lex( i, j - 1 )] != -FLT_MAX ) { val += v[sf.lex( i, j - 1 )]; ++n; } if( j < sf.Ny() - 1 && v[sf.lex( i, j + 1 )] != -FLT_MAX ) { val += v[sf.lex( i, j + 1 )]; ++n; } if( n != 0 ) vNew[sf.lex( i, j )] = val / n; } void gaussSeidelStepInterior( ScalarField::ScalarField& sf, int i, int j, float* v, float* vNew ) { vNew[sf.lex( i, j )] = 0.25f * ( v[sf.lex( i - 1, j )] + v[sf.lex( i + 1, j )] + v[sf.lex( i, j - 1 )] + v[sf.lex( i, j + 1 )] ); } void fillGrid( TriMesh& mesh ) { // fill scalar field std::vector<float> vertexAvg( mesh.n_vertices() ); std::vector<bool> isDomain( field_.scalars().size(), false ); for( const auto& v : mesh.vertices() ) { float avg{ 0.f }; auto nEdges{ 0 }; for( const auto& voh : v.outgoing_halfedges() ) { ++nEdges; auto p1 = mesh.point( voh.from() ); auto p2 = mesh.point( voh.to() ); p1[2] = 0; p2[2] = 0; avg += ( p1 - p2 ).length(); } vertexAvg[v.idx()] = avg / (float)nEdges; } for( const auto& fh : mesh.faces() ) { std::vector<TriMesh::Point> triangle; // points of the triangle for( const auto& v : fh.vertices() ) { TriMesh::Point p{ mesh.point( v )[0], mesh.point( v )[1], vertexAvg[v.idx()] }; triangle.push_back( p ); } // get the rectangle of grid points that surrounds the triangle float x_t_max = std::fmaxf( std::max( triangle[0][0], triangle[1][0] ), triangle[2][0] ); float x_t_min = std::fminf( std::min( triangle[0][0], triangle[1][0] ), triangle[2][0] ); float y_t_max = std::fmaxf( std::max( triangle[0][1], triangle[1][1] ), triangle[2][1] ); float y_t_min = std::fminf( std::min( triangle[0][1], triangle[1][1] ), triangle[2][1] ); size_t i_min = field_.x2col( x_t_min ); size_t i_max = field_.x2col( x_t_max ) + 1; size_t j_min = field_.y2row( y_t_min ); size_t j_max = field_.y2row( y_t_max ) + 1; // check for all inner points of rectangle if they are inside the triangle. If yes, calculate the depth for( size_t i = i_min + 1; i < i_max; ++i ) { const float xv = field_.x( i ); for( size_t j = j_min + 1; j < j_max; ++j ) { const float yv = field_.y( j ); const auto [a, b, c] = HelperFunctions::barycentricCoordinates( { triangle[0], triangle[1], triangle[2] }, { xv,yv,0 } ); if( HelperFunctions::isInsideTriangle( a, b, c ) ) { // calculate average edge length field_( i, j ) = HelperFunctions::barycentricInterpolation( triangle, a, b, c ); isDomain[field_.lex( i, j )] = true; } } } } auto v2 = field_.scalars(); auto vDiff = decltype( v2 )( v2.size(), 0 ); float* pv1 = field_.scalars().data(); float* pv2 = v2.data(); const auto& v1Size = field_.scalars().size(); std::vector<std::array<int, 2>> warmUpRed; std::vector<std::array<int, 2>> warmUpBlack; for( int i = 0; i < field_.Nx(); ++i ) { for( int j = 0; j < field_.Ny(); ++j ) { if( isDomain[field_.lex( i, j )] ) continue; if( ( i + j ) % 2 == 0 ) warmUpRed.push_back( { i,j } ); else warmUpBlack.push_back( { i,j } ); } } const auto warmUpRedSize = warmUpRed.size(); const auto warmUpBlackSize = warmUpBlack.size(); // warm-up phase (spread reasonable values fast) for( long k = 0; k < 1e6; ++k ) { #pragma omp parallel for for( int idx = 0; idx < warmUpRedSize; ++idx ) { const int i = warmUpRed[idx][0]; const int j = warmUpRed[idx][1]; gaussSeidelStep( field_, i, j, pv1, pv2 ); } #pragma omp parallel for for( int idx = 0; idx < warmUpBlackSize; ++idx ) { const int i = warmUpBlack[idx][0]; const int j = warmUpBlack[idx][1]; gaussSeidelStep( field_, i, j, pv2, pv2 ); } std::swap( pv1, pv2 ); auto minIt = std::min_element( field_.scalars().begin(), field_.scalars().end() ); if( *minIt != -FLT_MAX ) { break; } } std::vector<std::array<int, 2>> interiorRed; std::vector<std::array<int, 2>> interiorBlack; for( int i = 1; i < field_.Nx() - 1; ++i ) { for( int j = 1; j < field_.Ny() - 1; ++j ) { if( isDomain[field_.lex( i, j )] ) continue; if( ( i + j ) % 2 == 0 ) interiorRed.push_back( { i,j } ); else interiorBlack.push_back( { i,j } ); } } const auto interiorRedSize = interiorRed.size(); const auto interiorBlackSize = interiorBlack.size(); // main loop (after warm-up) for( long k = 0; k < 1e6; ++k ) { #pragma omp parallel for for( int idx = 0; idx < interiorRedSize; ++idx ) { const int i = interiorRed[idx][0]; const int j = interiorRed[idx][1]; gaussSeidelStepInterior( field_, i, j, pv1, pv2 ); } // edges red for( int i = 2; i < field_.Nx() - 1; i += 2 ) { const int j = 0; pv2[field_.lex( i, j )] = ( pv1[field_.lex( i - 1, j )] + pv1[field_.lex( i + 1, j )] + pv1[field_.lex( i, j + 1 )] ) / 3; } for( int j = 2; j < field_.Ny() - 1; j += 2 ) { const int i = 0; pv2[field_.lex( i, j )] = ( pv1[field_.lex( i + 1, j )] + pv1[field_.lex( i, j - 1 )] + pv1[field_.lex( i, j + 1 )] ) / 3; } for( int i = field_.Ny() % 2 == 0 ? 1 : 2; i < field_.Nx() - 1; i += 2 ) { const int j = field_.Ny() - 1; pv2[field_.lex( i, j )] = ( pv1[field_.lex( i - 1, j )] + pv1[field_.lex( i + 1, j )] + pv1[field_.lex( i, j - 1 )] ) / 3; } for( int j = field_.Nx() % 2 == 0 ? 1 : 2; j < field_.Ny() - 1; j += 2 ) { const int i = field_.Nx() - 1; pv2[field_.lex( i, j )] = ( pv1[field_.lex( i - 1, j )] + pv1[field_.lex( i, j - 1 )] + pv1[field_.lex( i, j + 1 )] ) / 3; } // corners red pv2[field_.lex( 0, 0 )] = ( pv1[field_.lex( 0 + 1, 0 )] + pv1[field_.lex( 0, 0 + 1 )] ) / 2; if( field_.Ny() % 2 == 1 ) pv2[field_.lex( field_.Nx() - 1, 0 )] = ( pv1[field_.lex( field_.Nx() - 1 - 1, 0 )] + pv1[field_.lex( field_.Nx() - 1, 0 + 1 )] ) / 2; if( field_.Ny() % 2 == 1 ) pv2[field_.lex( 0, field_.Ny() - 1 )] = ( pv1[field_.lex( 0 + 1, field_.Ny() - 1 )] + pv1[field_.lex( 0, field_.Ny() - 1 - 1 )] ) / 2; if( ( field_.Ny() + field_.Nx() ) % 2 == 0 ) pv2[field_.lex( field_.Nx() - 1, field_.Ny() - 1 )] = ( pv1[field_.lex( field_.Nx() - 1 - 1, field_.Ny() - 1 )] + pv1[field_.lex( field_.Nx() - 1, field_.Ny() - 1 - 1 )] ) / 2; #pragma omp parallel for for( int idx = 0; idx < interiorBlackSize; ++idx ) { const int i = interiorBlack[idx][0]; const int j = interiorBlack[idx][1]; gaussSeidelStepInterior( field_, i, j, pv2, pv2 ); } // edges black for( int i = 1; i < field_.Nx() - 1; i += 2 ) { const int j = 0; pv2[field_.lex( i, j )] = ( pv2[field_.lex( i - 1, j )] + pv2[field_.lex( i + 1, j )] + pv2[field_.lex( i, j + 1 )] ) / 3; } for( int j = 1; j < field_.Ny() - 1; j += 2 ) { const int i = 0; pv2[field_.lex( i, j )] = ( pv2[field_.lex( i + 1, j )] + pv2[field_.lex( i, j - 1 )] + pv2[field_.lex( i, j + 1 )] ) / 3; } for( int i = field_.Ny() % 2 == 1 ? 1 : 2; i < field_.Nx() - 1; i += 2 ) { const int j = field_.Ny() - 1; pv2[field_.lex( i, j )] = ( pv2[field_.lex( i - 1, j )] + pv2[field_.lex( i + 1, j )] + pv2[field_.lex( i, j - 1 )] ) / 3; } for( int j = field_.Nx() % 2 == 1 ? 1 : 2; j < field_.Ny() - 1; j += 2 ) { const int i = field_.Nx() - 1; pv2[field_.lex( i, j )] = ( pv2[field_.lex( i - 1, j )] + pv2[field_.lex( i, j - 1 )] + pv2[field_.lex( i, j + 1 )] ) / 3; } // corners black if( field_.Ny() % 2 == 0 ) pv2[field_.lex( field_.Nx() - 1, 0 )] = ( pv2[field_.lex( field_.Nx() - 1 - 1, 0 )] + pv2[field_.lex( field_.Nx() - 1, 0 + 1 )] ) / 2; if( field_.Ny() % 2 == 0 ) pv2[field_.lex( 0, field_.Ny() - 1 )] = ( pv2[field_.lex( 0 + 1, field_.Ny() - 1 )] + pv2[field_.lex( 0, field_.Ny() - 1 - 1 )] ) / 2; if( ( field_.Ny() + field_.Nx() ) % 2 == 1 ) pv2[field_.lex( field_.Nx() - 1, field_.Ny() - 1 )] = ( pv2[field_.lex( field_.Nx() - 1 - 1, field_.Ny() - 1 )] + pv2[field_.lex( field_.Nx() - 1, field_.Ny() - 1 - 1 )] ) / 2; #pragma omp parallel for for( int i = 0; i < v1Size; ++i ) { vDiff[i] = std::fabs( pv2[i] - pv1[i] ); } auto maxIt = std::max_element( vDiff.begin(), vDiff.end() ); std::swap( pv1, pv2 ); if( *maxIt <= 1e-5 * pv1[std::distance( vDiff.begin(), maxIt )] ) { break; } } } void fillGridFromNearestNeighbors( TriMesh& mesh ) { std::vector<float> vertexAvg( mesh.n_vertices() ); for( const auto& v : mesh.vertices() ) { float avg{ 0.f }; auto nEdges{ 0 }; for( const auto& voh : v.outgoing_halfedges() ) { ++nEdges; auto p1 = mesh.point( voh.from() ); auto p2 = mesh.point( voh.to() ); p1[2] = 0; p2[2] = 0; avg += ( p1 - p2 ).length(); } vertexAvg[v.idx()] = avg / (float)nEdges; } MeshPointsNN knn( mesh ); for( int i = 0; i < field_.Nx(); ++i ) { for( int j = 0; j < field_.Ny(); ++j ) { const auto& pos = field_.pos( i, j ); TriMesh::Point p{ pos.x, pos.y, 0 }; const auto nnIdxs = knn.findNearestNeighbor( p, 5 ); float invDistSum = 0; float avg = 0; for( const auto& idx : nnIdxs ) { const auto& pn = mesh.point( mesh.vertex_handle( idx ) ); auto dist = ( pn - p ).sqrnorm(); auto invDist = 1.f / ( dist + 0.0001f ); auto val = vertexAvg[idx]; avg += val * invDist; invDistSum += invDist; } avg /= invDistSum; field_( i, j ) = avg; } } } static ScalarField::AxisAlignedBoundingBox computeAabbLecacy( TriMesh& mesh ) { const auto n_vertices = mesh.n_vertices(); auto xMax = -std::numeric_limits<float>::max(); auto yMax = -std::numeric_limits<float>::max(); auto xMin = std::numeric_limits<float>::max(); auto yMin = std::numeric_limits<float>::max(); for( unsigned int i = 0; i < n_vertices; ++i ) { TriMesh::Point point = mesh.point( mesh.vertex_handle( i ) ); xMax = std::max( xMax, point[0] ); yMax = std::max( yMax, point[1] ); xMin = std::min( xMin, point[0] ); yMin = std::min( yMin, point[1] ); } const float x_range_old = xMax - xMin; const float y_range_old = yMax - yMin; xMax += 0.1 * x_range_old; xMin -= 0.1 * x_range_old; yMax += 0.1 * y_range_old; yMin -= 0.1 * y_range_old; return { xMin, xMax, yMin, yMax }; } static ScalarField::AxisAlignedBoundingBox computeAabb( TriMesh& mesh ) { auto xMax = -std::numeric_limits<float>::max(); auto yMax = -std::numeric_limits<float>::max(); auto xMin = std::numeric_limits<float>::max(); auto yMin = std::numeric_limits<float>::max(); for( const auto& v : mesh.vertices() ) { const auto& point = mesh.point( v ); xMax = std::max( xMax, point[0] ); yMax = std::max( yMax, point[1] ); xMin = std::min( xMin, point[0] ); yMin = std::min( yMin, point[1] ); } return { xMin, xMax, yMin, yMax }; } public: // load size field if it already exists in cache, otherwise generate and store it. static ScalarField::ScalarField load( TriMesh& mesh, const std::experimental::filesystem::path& cacheFolder, const std::experimental::filesystem::path& meshFile, const size_t& sizeGridSizeX, const size_t& sizeGridSizeY ) { namespace fs = std::experimental::filesystem; fs::path file = cacheFolder / ( meshFile.stem().string() + "_SizeField_" + std::to_string( sizeGridSizeX ) + "_" + std::to_string( sizeGridSizeY ) + ".bin" ); auto sfLoad = ScalarField::load( file, sizeGridSizeX, sizeGridSizeY ); //std::optional<ScalarField::ScalarField> sfLoad = {}; if( sfLoad ) { return sfLoad.value(); } else { LOG( INFO ) << "Generate SizeField"; SizeField sf( mesh, sizeGridSizeX, sizeGridSizeY, true ); LOG( INFO ) << "Store in cache file '" << file << "'"; sf.field().writeBinary( file.string() ); return sf.field(); } } };
owl_ndarray_maths_map_omp.h
/* * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2019 Liang Wang <liang.wang@cl.cam.ac.uk> */ #ifdef OWL_ENABLE_TEMPLATE #ifndef INIT // Because some functions do not really utilise this, #define INIT // so define an empty string as default. #endif #include "owl_core_engine.h" #include "owl_omp_parameters.h" // function to perform mapping of elements from x to y #ifdef FUN4 #undef OWL_OMP_THRESHOLD #define OWL_OMP_THRESHOLD OWL_OMP_THRESHOLD_FUN(FUN4) CAMLprim value FUN4(value vN, value vX, value vY) { CAMLparam3(vN, vX, vY); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x, *stop_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; stop_x = start_x + N; start_y = Y_data; if (N >= OWL_OMP_THRESHOLD) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { NUMBER x = *(start_x + i); *(start_y + i) = (MAPFN(x)); } } else { while (start_x != stop_x) { NUMBER x = *start_x; *start_y = (MAPFN(x)); start_x += 1; start_y += 1; }; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN4 */ // function to map elements in [x] w.r.t scalar values, linspace and etc. #ifdef FUN12 CAMLprim value FUN12(value vN, value vA, value vB, value vX) { CAMLparam1(vX); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; caml_release_runtime_system(); /* Allow other threads */ if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 1; i <= N; i++) { MAPFN(*(X_data + i - 1)); } } else { for (int i = 1; i <= N; i++) { MAPFN(*X_data); X_data++; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN12 */ // function to calculate logspace_base function #ifdef FUN13 CAMLprim value FUN13(value vN, value vBase, value vA, value vB, value vX) { CAMLparam1(vX); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; caml_release_runtime_system(); /* Allow other threads */ for (int i = 1; i <= N; i++) { MAPFN(X_data); X_data++; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN13 */ // TODO: this needs to be unified with FUN4 in future // similar to FUN4, but mostly for complex numbers #ifdef FUN14 CAMLprim value FUN14(value vN, value vX, value vY) { CAMLparam3(vN, vX, vY); int N = Long_val(vN); struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; start_y = Y_data; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i), (start_y + i)); } } else { for (int i = 0; i < N; i++) { MAPFN(start_x, start_y); start_x += 1; start_y += 1; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN14 */ // function to map pairwise elements in x and y then save results to z #ifdef FUN15 CAMLprim value FUN15(value vN, value vX, value vY, value vZ) { CAMLparam4(vN, vX, vY, vZ); int N = Long_val(vN); struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; struct caml_ba_array *Z = Caml_ba_array_val(vZ); NUMBER2 *Z_data = (NUMBER2 *) Z->data; NUMBER *start_x, *stop_x; NUMBER1 *start_y; NUMBER2 *start_z; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; stop_x = start_x + N; start_y = Y_data; start_z = Z_data; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i), (start_y + i), (start_z + i)); } } else { while (start_x != stop_x) { MAPFN(start_x, start_y, start_z); start_x += 1; start_y += 1; start_z += 1; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN15 */ // function to map all elements in [x] w.r.t to [a] then save results to [y] #ifdef FUN17 CAMLprim value FUN17(value vN, value vX, value vY, value vA) { CAMLparam4(vN, vX, vY, vA); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; start_y = Y_data; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i), (start_y + i)); } } else { for (int i = 0; i < N; i++) { MAPFN(start_x, start_y); start_x += 1; start_y += 1; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN17 */ // function to map elements in [x] w.r.t [a] and [b] then save results to [x] #ifdef FUN18 CAMLprim value FUN18(value vN, value vX, value vA, value vB) { CAMLparam4(vN, vX, vA, vB); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; NUMBER *start_x, *stop_x; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; stop_x = start_x + N; while (start_x != stop_x) { MAPFN(start_x); start_x += 1; }; caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN18 */ // function to map x to y with explicit offset, step size, number of ops #ifdef FUN19 CAMLprim value FUN19_IMPL( value vN, value vX, value vOFSX, value vINCX, value vY, value vOFSY, value vINCY ) { CAMLparam5(vN, vX, vOFSX, vINCX, vY); CAMLxparam2(vOFSY, vINCY); int N = Long_val(vN); int ofsx = Long_val(vOFSX); int incx = Long_val(vINCX); int ofsy = Long_val(vOFSY); int incy = Long_val(vINCY); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data + ofsx; start_y = Y_data + ofsy; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i * incx), (start_y + i * incy)); } } else { for (int i = 0; i < N; i++) { MAPFN(start_x, start_y); start_x += incx; start_y += incy; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN19(value *argv, int __unused_argn) { return FUN19_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]); } #endif /* FUN19 */ // function to map x to y with explicit offset, step size, number of ops // more general version of FUN19, so more control over the access pattern to // the data with two embedded loops. #ifdef FUN20 CAMLprim value FUN20_IMPL( value vM, value vN, value vX, value vOFSX, value vINCX_M, value vINCX_N, value vY, value vOFSY, value vINCY_M, value vINCY_N ) { CAMLparam2(vM, vN); CAMLxparam4(vX, vOFSX, vINCX_M, vINCX_N); CAMLxparam4(vY, vOFSY, vINCY_M, vINCY_N); int M = Long_val(vM); int N = Long_val(vN); int ofsx = Long_val(vOFSX); int incx_m = Long_val(vINCX_M); int incx_n = Long_val(vINCX_N); int ofsy = Long_val(vOFSY); int incy_m = Long_val(vINCY_M); int incy_n = Long_val(vINCY_N); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x_m; NUMBER *start_x_n; NUMBER1 *start_y_m; NUMBER1 *start_y_n; caml_release_runtime_system(); /* Allow other threads */ start_x_m = X_data + ofsx; start_y_m = Y_data + ofsy; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < M; i++) { start_x_n = start_x_m + i * incx_m; start_y_n = start_y_m + i * incy_m; for (int j = 0; j < N; j++) { MAPFN(start_x_n, start_y_n); start_x_n += incx_n; start_y_n += incy_n; } } } else { for (int i = 0; i < M; i++) { start_x_n = start_x_m; start_y_n = start_y_m; for (int j = 0; j < N; j++) { MAPFN(start_x_n, start_y_n); start_x_n += incx_n; start_y_n += incy_n; } start_x_m += incx_m; start_y_m += incy_m; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN20(value *argv, int __unused_argn) { return FUN20_IMPL( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9] ); } #endif /* FUN20 */ // broadcast function of x and y then save the result to z #ifdef FUN24 static OWL_INLINE void FUN24_CODE ( int d, struct caml_ba_array *X, int64_t *stride_x, int ofs_x, struct caml_ba_array *Y, int64_t *stride_y, int ofs_y, struct caml_ba_array *Z, int64_t *stride_z, int ofs_z ) { int inc_x = X->dim[d] == Z->dim[d] ? stride_x[d] : 0; int inc_y = Y->dim[d] == Z->dim[d] ? stride_y[d] : 0; int inc_z = stride_z[d]; const int n = Z->dim[d]; if (d == X->num_dims - 1) { NUMBER *x = (NUMBER *) X->data + ofs_x; NUMBER *y = (NUMBER *) Y->data + ofs_y; NUMBER *z = (NUMBER *) Z->data + ofs_z; for (int i = 0; i < n; i++) { MAPFN(x, y, z); x += inc_x; y += inc_y; z += inc_z; } } else { for (int i = 0; i < n; i++) { FUN24_CODE (d+1, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z); ofs_x += inc_x; ofs_y += inc_y; ofs_z += inc_z; } } return; } CAMLprim value FUN24_IMPL( value vX, value vSTRIDE_X, value vY, value vSTRIDE_Y, value vZ, value vSTRIDE_Z ) { CAMLparam4(vX, vSTRIDE_X, vY, vSTRIDE_Y); CAMLxparam2(vZ, vSTRIDE_Z); struct caml_ba_array *X = Caml_ba_array_val(vX); struct caml_ba_array *Y = Caml_ba_array_val(vY); struct caml_ba_array *Z = Caml_ba_array_val(vZ); struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X); int64_t *stride_x = (int64_t *) stride_X->data; struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y); int64_t *stride_y = (int64_t *) stride_Y->data; struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z); int64_t *stride_z = (int64_t *) stride_Z->data; caml_release_runtime_system(); /* Allow other threads */ FUN24_CODE (0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, 0); caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN24(value *argv, int __unused_argn) { return FUN24_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); } #endif /* FUN24 */ // broadcast function of x and y then save the result to z. Compared to FUN24, // the difference of FUN25 is z has one extra dimension than max(dim_x, dim_y). // This function is used in owl's distribution module and extra dimension is // used as sample dimension. #ifdef FUN25 static OWL_INLINE void FUN25_CODE ( int d, struct caml_ba_array *X, int64_t *stride_x, int ofs_x, struct caml_ba_array *Y, int64_t *stride_y, int ofs_y, struct caml_ba_array *Z, int64_t *stride_z, int ofs_z ) { int inc_x = X->dim[d] == Z->dim[d+1] ? stride_x[d] : 0; int inc_y = Y->dim[d] == Z->dim[d+1] ? stride_y[d] : 0; int inc_z = stride_z[d+1]; const int n = Z->dim[d+1]; if (d == X->num_dims - 1) { NUMBER *x = (NUMBER *) X->data + ofs_x; NUMBER *y = (NUMBER *) Y->data + ofs_y; NUMBER *z = (NUMBER *) Z->data + ofs_z; for (int i = 0; i < n; i++) { MAPFN(x, y, z); x += inc_x; y += inc_y; z += inc_z; } } else { for (int i = 0; i < n; i++) { FUN25_CODE (d+1, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z); ofs_x += inc_x; ofs_y += inc_y; ofs_z += inc_z; } } return; } CAMLprim value FUN25_IMPL( value vX, value vSTRIDE_X, value vY, value vSTRIDE_Y, value vZ, value vSTRIDE_Z ) { CAMLparam4(vX, vSTRIDE_X, vY, vSTRIDE_Y); CAMLxparam2(vZ, vSTRIDE_Z); struct caml_ba_array *X = Caml_ba_array_val(vX); struct caml_ba_array *Y = Caml_ba_array_val(vY); struct caml_ba_array *Z = Caml_ba_array_val(vZ); struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X); int64_t *stride_x = (int64_t *) stride_X->data; struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y); int64_t *stride_y = (int64_t *) stride_Y->data; struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z); int64_t *stride_z = (int64_t *) stride_Z->data; caml_release_runtime_system(); /* Allow other threads */ int ofs_z = 0; for (int i = 0; i < Z->dim[0]; i++) { FUN25_CODE (0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, ofs_z); ofs_z += stride_z[0]; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN25(value *argv, int __unused_argn) { return FUN25_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); } #endif /* FUN25 */ // Similar to FUN25, but broadcast between w, x, y, then save the result to z #ifdef FUN27 static OWL_INLINE void FUN27_CODE ( int d, struct caml_ba_array *W, int64_t *stride_w, int ofs_w, struct caml_ba_array *X, int64_t *stride_x, int ofs_x, struct caml_ba_array *Y, int64_t *stride_y, int ofs_y, struct caml_ba_array *Z, int64_t *stride_z, int ofs_z ) { int inc_w = W->dim[d] == Z->dim[d+1] ? stride_w[d] : 0; int inc_x = X->dim[d] == Z->dim[d+1] ? stride_x[d] : 0; int inc_y = Y->dim[d] == Z->dim[d+1] ? stride_y[d] : 0; int inc_z = stride_z[d+1]; const int n = Z->dim[d+1]; if (d == X->num_dims - 1) { NUMBER *w = (NUMBER *) W->data + ofs_w; NUMBER *x = (NUMBER *) X->data + ofs_x; NUMBER *y = (NUMBER *) Y->data + ofs_y; NUMBER *z = (NUMBER *) Z->data + ofs_z; for (int i = 0; i < n; i++) { MAPFN(w, x, y, z); w += inc_w; x += inc_x; y += inc_y; z += inc_z; } } else { for (int i = 0; i < n; i++) { FUN27_CODE (d+1, W, stride_w, ofs_w, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z); ofs_w += inc_w; ofs_x += inc_x; ofs_y += inc_y; ofs_z += inc_z; } } return; } CAMLprim value FUN27_IMPL( value vW, value vSTRIDE_W, value vX, value vSTRIDE_X, value vY, value vSTRIDE_Y, value vZ, value vSTRIDE_Z ) { CAMLparam4(vW, vSTRIDE_W, vX, vSTRIDE_X); CAMLparam4(vY, vSTRIDE_Y, vZ, vSTRIDE_Z); struct caml_ba_array *W = Caml_ba_array_val(vW); struct caml_ba_array *X = Caml_ba_array_val(vX); struct caml_ba_array *Y = Caml_ba_array_val(vY); struct caml_ba_array *Z = Caml_ba_array_val(vZ); struct caml_ba_array *stride_W = Caml_ba_array_val(vSTRIDE_W); int64_t *stride_w = (int64_t *) stride_W->data; struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X); int64_t *stride_x = (int64_t *) stride_X->data; struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y); int64_t *stride_y = (int64_t *) stride_Y->data; struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z); int64_t *stride_z = (int64_t *) stride_Z->data; caml_release_runtime_system(); /* Allow other threads */ int ofs_z = 0; for (int i = 0; i < Z->dim[0]; i++) { FUN27_CODE (0, W, stride_w, 0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, ofs_z); ofs_z += stride_z[0]; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN27(value *argv, int __unused_argn) { return FUN27_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]); } #endif /* FUN27 */ // function to map x to y with explicit offset, step size, number of ops // more general version of FUN20, so more control over the access pattern to // the data with three embedded loops. #ifdef FUN28 CAMLprim value FUN28_IMPL( value vM, value vN, value vO, value vX, value vOFSX, value vINCX_M, value vINCX_N, value vINCX_O, value vY, value vOFSY, value vINCY_M, value vINCY_N, value vINCY_O ) { CAMLparam3(vM, vN, vO); CAMLxparam5(vX, vOFSX, vINCX_M, vINCX_N, vINCX_O); CAMLxparam5(vY, vOFSY, vINCY_M, vINCY_N, vINCY_O); int M = Long_val(vM); int N = Long_val(vN); int O = Long_val(vO); int ofsx = Long_val(vOFSX); int incx_m = Long_val(vINCX_M); int incx_n = Long_val(vINCX_N); int incx_o = Long_val(vINCX_O); int ofsy = Long_val(vOFSY); int incy_m = Long_val(vINCY_M); int incy_n = Long_val(vINCY_N); int incy_o = Long_val(vINCY_O); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x_m; NUMBER *start_x_n; NUMBER *start_x_o; NUMBER1 *start_y_m; NUMBER1 *start_y_n; NUMBER1 *start_y_o; caml_release_runtime_system(); /* Allow other threads */ start_x_m = X_data + ofsx; start_y_m = Y_data + ofsy; for (int i = 0; i < M; i++) { start_x_n = start_x_m; start_y_n = start_y_m; for (int j = 0; j < N; j++) { start_x_o = start_x_n; start_y_o = start_y_n; for (int k = 0; k < O; k++) { MAPFN(start_x_o, start_y_o); start_x_o += incx_o; start_y_o += incy_o; } start_x_n += incx_n; start_y_n += incy_n; } start_x_m += incx_m; start_y_m += incy_m; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN28(value *argv, int __unused_argn) { return FUN28_IMPL( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12] ); } #endif /* FUN28 */ // function to map [x] w.r.t scalar values, similar to FUN12 but saves to Y #ifdef FUN29 CAMLprim value FUN29(value vN, value vA, value vB, value vX, value vY) { CAMLparam5(vN, vA, vB, vX, vY); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER *Y_data = (NUMBER *) Y->data; caml_release_runtime_system(); /* Allow other threads */ if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN(*(X_data + i), *(Y_data + i)); } } else { for (int i = 0; i < N; i++) { MAPFN(*(X_data + i), *(Y_data + i)); } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN29 */ #undef NUMBER #undef NUMBER1 #undef NUMBER2 #undef MAPFN #undef MAPFN1 #undef MAPFN2 #undef MAPFN3 #undef INIT #undef FUN4 #undef FUN12 #undef FUN13 #undef FUN14 #undef FUN15 #undef FUN17 #undef FUN18 #undef FUN19 #undef FUN19_IMPL #undef FUN20 #undef FUN20_IMPL #undef FUN24 #undef FUN24_IMPL #undef FUN24_CODE #undef FUN25 #undef FUN25_IMPL #undef FUN25_CODE #undef FUN27 #undef FUN27_IMPL #undef FUN27_CODE #undef FUN28 #undef FUN28_IMPL #undef FUN29 #undef OWL_OMP_THRESHOLD #endif /* OWL_ENABLE_TEMPLATE */