source
stringlengths
3
92
c
stringlengths
26
2.25M
iRCCE_get.c
//*************************************************************************************** // Get data from communication buffer. //*************************************************************************************** // // Author: Rob F. Van der Wijngaart // Intel Corporation // Date: 008/30/2010 // //*************************************************************************************** // // Copyright 2010 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // [2010-11-03] switched to SCC-optimized memcpy() functions in scc_memcpy.h: // - memcpy_to_mpb() // - memcpy_from_mpb() // by Stefan Lankes, Carsten Clauss, Chair for Operating Systems, // RWTH Aachen University // #include "iRCCE_lib.h" #ifdef __hermit__ #include "rte_memcpy.h" #elif defined COPPERRIDGE || defined SCC #include "scc_memcpy.h" #endif void* iRCCE_memcpy_get(void *dest, const void *src, size_t count) { #ifdef __hermit__ return rte_memcpy(dest, src, count); #elif defined COPPERRIDGE || defined SCC return memcpy_from_mpb(dest, src, count); #else return memcpy(dest, src, count); #endif } //-------------------------------------------------------------------------------------- // FUNCTION: iRCCE_get //-------------------------------------------------------------------------------------- // copy data from address "source" in the remote MPB to address "target" in either the // local MPB, or in the calling UE's private memory. We do not test to see if a move // into the calling UE's private memory stays within allocated memory * //-------------------------------------------------------------------------------------- int iRCCE_get( t_vcharp target, // target buffer, MPB or private memory t_vcharp source, // source buffer, MPB int num_bytes, // number of bytes to copy (must be multiple of cache line size int ID // rank of source UE ) { // in non-GORY mode we only need to retain the MPB source shift; we // already know the source is in the MPB, not private memory source = RCCE_comm_buffer[ID]+(source-RCCE_comm_buffer[RCCE_IAM]); // do the actual copy, making sure we copy fresh data #ifdef _OPENMP #pragma omp flush #endif RC_cache_invalidate(); iRCCE_memcpy_get((void *)target, (void *)source, num_bytes); // flush data to make sure it is visible to all threads; cannot use a flush list // because it concerns malloced space #ifdef _OPENMP #pragma omp flush #endif return(iRCCE_SUCCESS); }
test.c
#include <stdio.h> #include <omp.h> #pragma omp requires unified_shared_memory #include "../utilities/check.h" #include "../utilities/utilities.h" #define TRIALS (1) #define N (992) #define INIT() INIT_LOOP(N, {C[i] = 1; D[i] = i; E[i] = -i;}) #define ZERO(X) ZERO_ARRAY(N, X) // // TODO: Add the following runtime calls. // omp_set_num_threads // // All Lock Routines. // int main(void) { // CHECK: Able to use offloading! check_offloading(); int fail; double A[N], B[N], C[N], D[N], E[N]; INIT(); // // Test: omp_get_num_threads() // ZERO(A); TEST({ A[0] = omp_get_num_threads(); // 1 _Pragma("omp parallel num_threads(128)") { if (omp_get_thread_num() == 3) { A[0] += omp_get_num_threads(); // 128 } } }, VERIFY(0, 1, A[i], 129)); // // Test: omp_get_max_threads() (depends on device type) // ZERO(A); TEST({ A[0] = omp_get_max_threads(); _Pragma("omp parallel") { if (omp_get_thread_num() == 0) { A[0] += omp_get_max_threads(); // 1 A[1] = omp_get_num_threads(); } } }, if (!omp_is_initial_device()) VERIFY(0, 1, A[i], A[1] + 1)); // // Test: omp_get_num_procs() // ZERO(A); TEST({ A[0] = omp_get_num_procs(); _Pragma("omp parallel") { if (omp_get_thread_num() == 18) { A[0] += omp_get_num_procs(); A[1] = 2*omp_get_num_threads(); } } }, VERIFY(0, 1, A[i], A[1])); // // Test: omp_in_parallel() // ZERO(A); TEST({ A[0] = omp_in_parallel(); // 0 // Serialized parallel _Pragma("omp parallel num_threads(32) if (A[0] == 0)") { A[0] += omp_in_parallel(); // 0 } // Parallel execution _Pragma("omp parallel num_threads(32) if (A[0] == 0)") { if (omp_get_thread_num() == 0) { A[0] += omp_in_parallel(); // 1 } } }, VERIFY(0, 1, A[i], 1)); // // Test: omp_set/get_dynamic() // ZERO(A); TEST({ A[0] = omp_get_dynamic(); // 0 omp_set_dynamic(1); A[0] += omp_get_dynamic(); // 1 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_dynamic(); // 1 omp_set_dynamic(0); // Only for this parallel region. } } A[0] += omp_get_dynamic(); // 1 }, VERIFY(0, 1, A[i], 0)); // // Test: omp_get_cancellation() // FIXME: Rewrite test case once we have cancellation support. // ZERO(A); TEST({ A[0] = omp_get_cancellation(); // 0 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_cancellation(); // 0 } } }, VERIFY(0, 1, A[i], 0)); // // Test: omp_set/get_nested(). Not used on the device currently. // ZERO(A); TEST({ A[0] = omp_get_nested(); // 0 omp_set_nested(0); A[0] += omp_get_nested(); // 0 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 18) { A[0] += omp_get_nested(); // 0 omp_set_nested(0); } } A[0] += omp_get_nested(); // 0 }, VERIFY(0, 1, A[i], 0)); // // Test: omp_set/get_schedule(). // ZERO(A); int result = 2 * (omp_sched_static + omp_sched_dynamic + omp_sched_guided) + omp_sched_static; result += 2 * (1110) + 10; TEST({ omp_sched_t t; int chunk_size; t = omp_sched_static; chunk_size = 10; omp_set_schedule(t, chunk_size); t = 0; chunk_size = 0; omp_get_schedule(&t, &chunk_size); A[0] = t + chunk_size; t = omp_sched_dynamic; chunk_size = 100; omp_set_schedule(t, chunk_size); t = 0; chunk_size = 0; omp_get_schedule(&t, &chunk_size); A[0] += t + chunk_size; t = omp_sched_guided; chunk_size = 1000; omp_set_schedule(t, chunk_size); t = 0; chunk_size = 0; omp_get_schedule(&t, &chunk_size); A[0] += t + chunk_size; t = omp_sched_static; chunk_size = 10; omp_set_schedule(t, chunk_size); _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { omp_sched_t t; int chunk_size; t = omp_sched_static; chunk_size = 10; omp_set_schedule(t, chunk_size); t = 0; chunk_size = 0; omp_get_schedule(&t, &chunk_size); A[0] += t + chunk_size; t = omp_sched_dynamic; chunk_size = 100; omp_set_schedule(t, chunk_size); t = 0; chunk_size = 0; omp_get_schedule(&t, &chunk_size); A[0] += t + chunk_size; t = omp_sched_guided; chunk_size = 1000; omp_set_schedule(t, chunk_size); t = 0; chunk_size = 0; omp_get_schedule(&t, &chunk_size); A[0] += t + chunk_size; } } t = 0; chunk_size = 0; omp_get_schedule(&t, &chunk_size); // should read 1, 10; A[0] += t + chunk_size; }, VERIFY(0, 1, A[i], result)); // // Test: omp_get_thread_limit() // ZERO(A); TEST({ A[0] = omp_get_thread_limit(); _Pragma("omp parallel") { if (omp_get_thread_num() == 0) { A[0] += omp_get_thread_limit(); A[1] = 2*omp_get_num_threads(); } } }, VERIFY(0, 1, A[i], A[1])); // // Test: omp_set/get_max_active_levels() // ZERO(A); TEST({ // Our runtime ignores this. omp_set_max_active_levels(1); A[0] = omp_get_max_active_levels(); // 1 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_max_active_levels(); // 1 } } }, VERIFY(0, 1, A[i], 2)); // // Test: omp_get_level() // ZERO(A); TEST({ A[0] = omp_get_level(); // 0 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_level(); // 1 } } }, VERIFY(0, 1, A[i], 1)); // // Test: omp_get_ancestor_thread_num() // ZERO(A); TEST({ A[0] = omp_get_ancestor_thread_num(0); // 0 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_ancestor_thread_num(0) + omp_get_ancestor_thread_num(1); // 0 + 18 } } }, VERIFY(0, 1, A[i], 0)); // // Test: omp_get_team_size() // ZERO(A); TEST({ A[0] = omp_get_team_size(0) + omp_get_team_size(1); // 1 + 1 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_team_size(0) + omp_get_team_size(1); // 1 + 19 } } }, if (!omp_is_initial_device()) VERIFY(0, 1, A[i], 22)); // TODO: fix host execution // // Test: omp_get_active_level() // ZERO(A); TEST({ A[0] = omp_get_active_level(); // 0 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { if (omp_get_num_threads() == 1) A[0] += 1; else A[0] += omp_get_active_level(); // 1 } } }, VERIFY(0, 1, A[i], 1)); // // Test: omp_in_final() // ZERO(A); TEST({ A[0] = omp_in_final(); // 1 always returns true. _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_in_final(); // 1 always returns true. } } }, VERIFY(0, 1, A[i], omp_is_initial_device() ? 0 : 2)); // // Test: omp_get_proc_bind() // ZERO(A); TEST({ A[0] = omp_get_proc_bind(); // 1 always returns omp_proc_bind_true. _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_proc_bind(); // 1 always returns omp_proc_bind_true. } } }, VERIFY(0, 1, A[i], omp_is_initial_device() ? 0 : 2)); #if 0 // // Test: Place routines (linking only). // ZERO(A); TEST({ (void) omp_get_num_places(); (void) omp_get_place_num_procs(0); int *ids; omp_get_place_proc_ids(0, ids); (void) omp_get_place_num(); (void) omp_get_partition_num_places(); int *place_nums; omp_get_partition_place_nums(place_nums); }, VERIFY(0, 1, A[i], 0)); #endif // // Test: omp_set/get_default_device() // ZERO(A); TEST({ omp_set_default_device(0); // Not used on device. A[0] = omp_get_default_device(); // 0 always returns 0. _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_default_device(); // 0 always returns 0. } } }, VERIFY(0, 1, A[i], 0)); // // Test: omp_get_num_devices(). Undefined on the target. // ZERO(A); TEST({ A[0] = omp_get_num_devices(); _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[1] = omp_get_num_devices(); } } }, VERIFY(0, 1, A[i], A[i] - A[1])); // // Test: omp_get_num_teams(), omp_get_team_num() // FIXME: Start teams region when supported. // ZERO(A); TEST({ A[0] = omp_get_num_teams(); // 1 A[0] += omp_get_team_num(); // 0 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_get_num_teams(); // 1 A[0] += omp_get_team_num(); // 0 } } }, VERIFY(0, 1, A[i], 2)); // // Test: omp_is_initial_device() // ZERO(A); A[1] = omp_is_initial_device(); TEST({ A[0] = omp_is_initial_device(); // 0 _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 0) { A[0] += omp_is_initial_device(); // 0 } } }, VERIFY(0, 1, A[i], omp_is_initial_device() ? A[1] - A[1] : 2.0)); return 0; #if 0 // // Test: omp_get_initial_device(). Unspecified behavior when // called from device. // ZERO(A); TEST({ A[0] = omp_get_initial_device(); _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 18) { A[0] -= omp_get_initial_device(); } } }, VERIFY(0, 1, A[i], 0)); #endif #if 0 // // Test: omp_get_max_task_priority(). // TODO: Not used on the gpu at the moment. // ZERO(A); TEST({ A[0] = omp_get_max_task_priority(); _Pragma("omp parallel num_threads(19)") { if (omp_get_thread_num() == 18) { A[0] -= omp_get_max_task_priority(); } } }, VERIFY(0, 1, A[i], 0)); #endif // // Test: Timing Routines (linking only). // ZERO(A); TEST({ double precision; precision = omp_get_wtick(); double start; double end; start = omp_get_wtime(); end = omp_get_wtime(); }, VERIFY(0, 1, A[i], 0)); return 0; }
GB_binop__bor_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bor_uint64) // A.*B function (eWiseMult): GB (_AemultB_01__bor_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__bor_uint64) // A.*B function (eWiseMult): GB (_AemultB_03__bor_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bor_uint64) // A*D function (colscale): GB (_AxD__bor_uint64) // D*A function (rowscale): GB (_DxB__bor_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__bor_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__bor_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bor_uint64) // C=scalar+B GB (_bind1st__bor_uint64) // C=scalar+B' GB (_bind1st_tran__bor_uint64) // C=A+scalar GB (_bind2nd__bor_uint64) // C=A'+scalar GB (_bind2nd_tran__bor_uint64) // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij) | (bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x) | (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BOR || GxB_NO_UINT64 || GxB_NO_BOR_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bor_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bor_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bor_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__bor_uint64) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__bor_uint64) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bor_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__bor_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bor_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bor_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bor_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__bor_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = (x) | (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bor_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) | (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) | (aij) ; \ } GrB_Info GB (_bind1st_tran__bor_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__bor_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
cholesky.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include "nb/math_bot.h" #include "nb/memory_bot.h" #include "nb/container_bot.h" #include "nb/graph_bot.h" #include "nb/solver_bot.h" #include "../sparse_struct.h" #define POW2(a) ((a)*(a)) int nb_sparse_decompose_Cholesky(const nb_sparse_t *const A, nb_sparse_t *L, /* Out */ nb_sparse_t* Lt, /* Out */ uint32_t omp_parallel_threads) { /* "L" must be a lower triangular matrix with the main diagonal * complete, and "Lt" must be an upper triangular matrix with * the main diagonal complete. * The structure of L must be congrous with Lt, since Lt = L'. */ /* Compute the decomposition */ for(uint32_t j=0; j< A->N; j++){ L->rows_values[j][L->rows_size[j]-1] = nb_sparse_get(A, j, j); double sum = 0; for(uint32_t q = 0; q < L->rows_size[j]-1; q++) sum += POW2(L->rows_values[j][q]); L->rows_values[j][L->rows_size[j]-1] -= sum; if(L->rows_values[j][L->rows_size[j]-1] <= 0.0) return 1; double valuejj = sqrt(L->rows_values[j][L->rows_size[j]-1]); L->rows_values[j][L->rows_size[j]-1] = valuejj; Lt->rows_values[j][0] = valuejj; #pragma omp parallel for num_threads(omp_parallel_threads) schedule(guided) for(uint32_t q = 1; q < Lt->rows_size[j]; q++){ uint32_t i = Lt->rows_index[j][q]; /*** L_ij <- A_ij ********************************************************/ uint32_t L_jindex = nb_sparse_bsearch_row(L, i, j, 0, L->rows_size[i]-1); /**/ L->rows_values[i][L_jindex] = nb_sparse_get(A, i, j); /**/ /*************************************************************************/ uint32_t r = 0; uint32_t s = 0; uint32_t _ro = L->rows_index[i][r]; uint32_t _sigma = L->rows_index[j][s]; bool flag = true; /* Flag to know when to stop the cylce */ while(flag){ while(_ro < _sigma) _ro = L->rows_index[i][++r]; while(_ro > _sigma) _sigma = L->rows_index[j][++s]; while(_ro == _sigma){ if(_ro == j){ flag = false; /* Finish the cycle */ break; } double vir = L->rows_values[i][r]; double vjs = L->rows_values[j][s]; L->rows_values[i][L_jindex] -= vir*vjs; _ro = L->rows_index[i][++r]; _sigma = L->rows_index[j][++s]; } } L->rows_values[i][L_jindex] /= L->rows_values[j][L->rows_size[j]-1]; Lt->rows_values[j][q] = L->rows_values[i][L_jindex]; } } /* Successful exit */ return 0; } int nb_sparse_solve_Cholesky(const nb_sparse_t *const A, const double *const b, double* x, /* Out */ uint32_t omp_parallel_threads){ nb_sparse_t *L = NULL; nb_sparse_t *U = NULL; nb_sparse_alloc_LU(A, &L, &U); if (NULL == L) return 10; int status = nb_sparse_decompose_Cholesky(A, L, U, omp_parallel_threads); if (0 == status) nb_sparse_solve_LU(L, U, b, x); nb_sparse_destroy(L); nb_sparse_destroy(U); return status; } int nb_sparse_relabel_and_solve_Cholesky(const nb_sparse_t *const A, const double *const b, double* x, /* Out */ uint32_t omp_parallel_threads) { uint32_t N = nb_sparse_get_size(A); uint32_t memsize = 2 * N * (sizeof(uint32_t) + sizeof(double)); char *memblock = nb_soft_allocate_mem(memsize); uint32_t *perm = (void*) memblock; uint32_t *iperm = (void*) (memblock + N * sizeof(uint32_t)); double *br = (void*) (memblock + 2 * N * sizeof(uint32_t)); double *xr = (void*) (memblock + 2 * N * sizeof(uint32_t) + N * sizeof(double)); nb_sparse_calculate_permutation(A, perm, iperm); nb_sparse_t *Ar = nb_sparse_create_permutation(A, perm, iperm); nb_vector_permutation(N, b, perm, br); int status = nb_sparse_solve_Cholesky(Ar, br, xr, omp_parallel_threads); nb_vector_permutation(N, xr, iperm, x); nb_sparse_destroy(Ar); nb_soft_free_mem(memsize, memblock); return status; }
nbodysystem.h
/*MIT License Copyright (c) 2021 Keigo Nitadori 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.*/ /* -added support for QD in addition to DD by Thomas Schano QD is available at http://crd-legacy.lbl.gov/~dhbailey/mpdist/ (https://github.com/GFTwrt/QD) -added support for additional step acceleration by Thomas Schano */ #include <cstdio> #include <cassert> #include <cmath> #include <vector> #include <omp.h> struct NbodySystem{ long nbody; long num_step, num_bstep; long num_step_tot, num_bstep_tot; typedef m_real real_type; typedef qvec3 vect_type; real_type eps2; real_type tsys; real_type init_energy, prev_energy; real_type dtmax; real_type eta, eta_s; std::vector<Particle> ptcl; std::vector<Predictor> pred; std::vector<Force> force; void reset_counters(){ init_energy = prev_energy; tsys = 0.0; num_step_tot = num_bstep_tot = 0; for(int i=0; i<nbody; i++) ptcl[i].tlast = tsys; puts("reset done!"); } #if 0 void read_snapshot_masaki(const char *filename){ int nread; FILE *fp = fopen(filename, "r"); assert(fp); int snapid; long nbody; nread = fscanf(fp, "%d %ld %lf", &snapid, &nbody, &tsys); this->nbody = nbody; assert(3 == nread); fprintf(stderr, "read snapshot (form M.I.), n = %ld, t = %f\n", nbody, tsys); ptcl .resize(nbody); pred .resize(nbody); force.resize(nbody); for(int i=0; i<nbody; i++){ long id; double mass, pot; dvec3 pos, vel; nread = fscanf(fp, "%ld %lA %lA %lA %lA %lA %lA %lA %lA", &id, &mass, &pos.x, &pos.y, &pos.z, &vel.x, &vel.y, &vel.z, &pot); assert(9 == nread); ptcl[i].id = id; ptcl[i].mass = mass; ptcl[i].coord[0] = qvec3(pos); ptcl[i].coord[1] = qvec3(vel); } fclose(fp); const real_type eps = 4.0 / nbody; ttthis->eps2 = eps * eps; num_step = num_bstep = 0; num_step_tot = num_bstep_tot = 0; } #endif real_type get_mass(const int i) const { return pred[i].mass; } template <int p> vect_type get_coord(const int i) const { return pred[i].coord[p]; } template <int p> void set_force(const int i, const vect_type &f){ force[i].force[p] = f; } vect_type get_add_acc(const int i) const { return ptcl[i].add_acc; } template <typename PTCL> // Particle or Predictor real_type calc_energy(const std::vector<PTCL> &p){ real_type pe = 0.0; real_type ke2 = 0.0; for(int i=0; i<nbody; i++){ real_type phi = 0.0; for(int j=i+1; j<nbody; j++){ vect_type dr = p[j].coord[0] - p[i].coord[0]; // real_type rinv = 1.0 / sqrt(eps2 + dr*dr); real_type rinv = rsqrt(eps2 + dr*dr); phi -= p[j].mass * rinv; } pe += p[i].mass * phi; } for(int i=0; i<nbody; i++){ ke2 += p[i].mass * p[i].coord[1].norm2(); } return pe + 0.5 * ke2; } real_type calc_energy_from_ptcl(){ return calc_energy(ptcl); } real_type calc_energy_from_pred(){ return calc_energy(pred); } void calc_force_on_first_nact(int nact){ #pragma omp parallel for // #pragma omp loop for(int i=0; i<nact; i++){ calc_force_on_i <NbodySystem, real_type, vect_type> (*this, nbody, i, this->eps2); } } void init_force(){ const int niter = (Particle::NFORCE+1)/2; for(int n=0; n<niter; n++){ #pragma omp parallel for for(int i=0; i<nbody; i++){ pred[i].zero_predict(ptcl[i]); } calc_force_on_first_nact(nbody); #pragma omp parallel for for(int i=0; i<nbody; i++){ force[i].init_assign(ptcl[i]); } } } void set_fixed_dt(const real_type dt){ for(int i=0; i<nbody; i++){ ptcl[i].tlast = tsys; ptcl[i].dt = dt; } } void predict_all(){ #pragma omp parallel for for(int i=0; i<nbody; i++){ pred[i].predict(tsys, ptcl[i]); } } void round_predictor(){ for(int i=0; i<nbody; i++){ for(int j=0; j<Particle::NFORCE; j++){ pred[i].coord[j].x.x[1] = 0.0; pred[i].coord[j].y.x[1] = 0.0; pred[i].coord[j].z.x[1] = 0.0; } } } void correct_and_feedback(){ #pragma omp parallel for for(int i=0; i<nbody; i++){ Corrector corr; corr.correct (ptcl[i], force[i]); corr.feedback (pred[i]); } } void correct_and_commit(){ #pragma omp parallel for for(int i=0; i<nbody; i++){ Corrector corr; corr.correct (ptcl[i], force[i]); corr.interpolate(ptcl[i], force[i]); #if 0 corr.taylor_test(ptcl[i]); puts(""); // exit(0); #endif corr.commit (ptcl[i]); } } void integrate_pec_nth(const int n, const real_type dt){ tsys += dt; predict_all(); for(int iter=0; iter<n-1; iter++){ calc_force_on_first_nact(nbody); correct_and_feedback(); } calc_force_on_first_nact(nbody); correct_and_commit(); } };
GB_unop__isfinite_bool_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__isfinite_bool_fc64) // op(A') function: GB (_unop_tran__isfinite_bool_fc64) // C type: bool // A type: GxB_FC64_t // cast: GxB_FC64_t cij = (aij) // unaryop: cij = GB_cisfinite (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_cisfinite (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = (aij) ; \ Cx [pC] = GB_cisfinite (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISFINITE || GxB_NO_BOOL || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__isfinite_bool_fc64) ( bool *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = GB_cisfinite (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = GB_cisfinite (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__isfinite_bool_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
scheduling_time_cluster.h
/* Copyright (c) 2020, VSB - Technical University of Ostrava and Graz University of Technology 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 names of VSB - Technical University of Ostrava and Graz University of Technology 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 VSB - TECHNICAL UNIVERSITY OF OSTRAVA AND GRAZ UNIVERSITY OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file scheduling_time_cluster.h * @brief Reduced time cluster used for job scheduling. */ #ifndef INCLUDE_BESTHEA_SCHEDULING_TIME_CLUSTER_H_ #define INCLUDE_BESTHEA_SCHEDULING_TIME_CLUSTER_H_ #include "besthea/general_spacetime_cluster.h" #include "besthea/settings.h" #include "besthea/vector.h" #include <iostream> #include <map> #include <vector> // forward declaration of general spacetime clusters namespace besthea { namespace mesh { class general_spacetime_cluster; } } namespace besthea { namespace mesh { class scheduling_time_cluster; } } /** * Class representing 1D temporal cluster used for job scheduling in 3+1D FMM. */ class besthea::mesh::scheduling_time_cluster { public: using vector_type = besthea::linear_algebra::vector; //!< Block vector type. /** * Constructor. * @param[in] center Center of the cluster. * @param[in] half_size Half size of the cluster. * @param[in] parent Pointer to the cluster's parent. * @param[in] left_right Indicates if the cluster is the left (0) or * right (1) child of its parent. * @param[in] level Level within the cluster tree structure. * @param[in] process_id Id of the process which is responsible for the * cluster in an MPI parallelized FMM. Default value * is -1. */ scheduling_time_cluster( sc center, sc half_size, scheduling_time_cluster * parent, short left_right, lo level, lo process_id = -1 ) : _center( center ), _half_size( half_size ), _parent( parent ), _left_right( left_right ), _children( nullptr ), _level( level ), _global_index( -1 ), _process_id( process_id ), _time_slices( nullptr ), _global_leaf_status( false ), _mesh_available( false ), _nearfield_list( nullptr ), _interaction_list( nullptr ), _send_list( nullptr ), _essential_status( -1 ), _active_upward_path( false ), _active_downward_path( false ), _upward_path_counter( -1 ), _m2l_counter( 0 ), _downward_path_status( 0 ), _associated_spacetime_clusters( nullptr ), _n_associated_leaves( 0 ), _associated_moments( nullptr ), _associated_local_contributions( nullptr ), _contribution_size( 0 ), _map_to_moment_receive_buffers( nullptr ), _pos_in_m_list( -1 ), _pos_in_l_list( -1 ), _pos_in_m2l_list( -1 ), _ready_interaction_list_size( 0 ) { } scheduling_time_cluster( const scheduling_time_cluster & that ) = delete; /** * Destructor. */ virtual ~scheduling_time_cluster( ) { if ( _children != nullptr ) { for ( auto it = _children->begin( ); it != _children->end( ); ++it ) { if ( *it != nullptr ) { delete *it; } } delete _children; } if ( _time_slices != nullptr ) delete _time_slices; if ( _nearfield_list != nullptr ) delete _nearfield_list; if ( _interaction_list != nullptr ) delete _interaction_list; if ( _send_list != nullptr ) delete _send_list; if ( _associated_spacetime_clusters != nullptr ) delete _associated_spacetime_clusters; if ( _associated_moments != nullptr ) delete[] _associated_moments; if ( _associated_local_contributions != nullptr ) delete[] _associated_local_contributions; for ( auto moment_buffer : _associated_moments_receive_buffers ) { delete[] moment_buffer; } if ( _map_to_moment_receive_buffers != nullptr ) delete _map_to_moment_receive_buffers; } /** * Deletes the nearfield */ void delete_nearfield( ) { delete _nearfield_list; _nearfield_list = nullptr; } /** * Deletes the interaction list */ void delete_interaction_list( ) { delete _interaction_list; _interaction_list = nullptr; } /** * Deletes the ready interaction list */ void delete_ready_interaction_list( ) { _ready_interaction_list_size = 0; } /** * Deletes the send list */ void delete_send_list( ) { delete _send_list; _send_list = nullptr; } /** * Deletes the vector of children * @warning If _children still contains elements these are also deleted! */ void delete_children( ) { if ( _children != nullptr ) { for ( auto it = _children->begin( ); it != _children->end( ); ++it ) { if ( *it != nullptr ) { delete *it; } } delete _children; } _children = nullptr; } /** * Adds a cluster to the list of children. * @param[in] child Child cluster. */ void add_child( scheduling_time_cluster * child ) { if ( _children == nullptr ) { _children = new std::vector< scheduling_time_cluster * >( ); } _children->push_back( child ); } /** * Returns the center of the cluster. */ sc get_center( ) const { return _center; } /** * Returns the half size of the cluster. */ sc get_half_size( ) const { return _half_size; } /** * Sets a number of children and allocates the vector of pointers to children. * @param[in] n_children Number of cluster's children. */ void set_n_children( lo n_children ) { if ( n_children > 0 ) { _children = new std::vector< scheduling_time_cluster * >( ); _children->reserve( n_children ); } else { _children = nullptr; } } /** * Returns the number of the cluster's children. */ lo get_n_children( ) const { if ( _children != nullptr ) { return _children->size( ); } else { return 0; } } /** * Returns a pointer to the children. */ std::vector< scheduling_time_cluster * > * get_children( ) { return _children; } /** * Returns a const pointer to the children. */ const std::vector< scheduling_time_cluster * > * get_children( ) const { return _children; } /** * Returns a pointer to the parent. */ scheduling_time_cluster * get_parent( ) { return _parent; } /** * Returns the configuration of the cluster with respect to its parent, i.e. * the value of _left_right */ short get_configuration( ) const { return _left_right; } /** * Returns the level of the cluster in the cluster tree it is contained in. */ lo get_level( ) const { return _level; } /** * Returns id of the process to which the cluster is assigned. */ lo get_process_id( ) const { return _process_id; } /** * Sets the process id of the cluster. * @param[in] process_id Id of the process. */ void set_process_id( lo process_id ) { _process_id = process_id; } /** * Returns the levelwise index of the cluster in the cluster tree. * @note The clusters are enumerated according to a tree traversal, see * @ref besthea::mesh::tree_structure::set_indices for more details. */ lo get_global_index( ) const { return _global_index; } /** * Sets the index of the cluster. * @param[in] index Index which is set. */ void set_index( lo index ) { _global_index = index; } /** * Sets the number of time slices and allocates the vector of indices of time * slices. * @param[in] n_slices Number of cluster's time slices. */ void set_n_time_slices( lou n_slices ) { if ( n_slices > 0 ) { _time_slices = new std::vector< lo >( ); _time_slices->reserve( n_slices ); } } /** * Returns the number of time slices in the current cluster. */ lo get_n_time_slices( ) const { if ( _time_slices != nullptr ) { return _time_slices->size( ); } else { return 0; } } /** * Adds the index of a time slice to the vector of time slices. * @param[in] idx Global index of the time slices which is added. */ void add_time_slice( lo idx ) { _time_slices->push_back( idx ); } /** * Returns a pointer to the time slices (unmodifiable). */ const std::vector< lo > * get_time_slices( ) const { return _time_slices; } /** * Sets global leaf status to a new value. * @param[in] new_status New global leaf status. */ void set_global_leaf_status( bool new_status ) { _global_leaf_status = new_status; } /** * Returns the global leaf status of the cluster. */ bool is_global_leaf( ) const { return _global_leaf_status; } /** * Sets status of mesh availability. * @param[in] new_status New mesh availability status. */ void set_mesh_availability( bool new_status ) { _mesh_available = new_status; } /** * Indicates whether a mesh is available for the current cluster or not. */ bool mesh_is_available( ) const { return _mesh_available; } /** * Adds a cluster to @p _nearfield_list. * @param[in] src_cluster Pointer to a nearfield cluster. * @note If @p _nearfield_list is not allocated this is done here. */ void add_to_nearfield_list( scheduling_time_cluster * src_cluster ) { if ( _nearfield_list == nullptr ) { _nearfield_list = new std::vector< scheduling_time_cluster * >( ); } _nearfield_list->push_back( src_cluster ); } /** * Returns a pointer to the const nearfield. */ const std::vector< scheduling_time_cluster * > * get_nearfield_list( ) const { return _nearfield_list; } /** * Returns a pointer to the nearfield. */ std::vector< scheduling_time_cluster * > * get_nearfield_list( ) { return _nearfield_list; } /** * Returns a pointer to the const interaction list. */ const std::vector< scheduling_time_cluster * > * get_interaction_list( ) const { return _interaction_list; } /** * Returns a pointer to the interaction list. */ std::vector< scheduling_time_cluster * > * get_interaction_list( ) { return _interaction_list; } /** * Adds a cluster to @p _interaction_list. * @param[in] src_cluster Pointer to a farfield cluster. * @note If @p _interaction_list is not allocated this is done here. */ void add_to_interaction_list( scheduling_time_cluster * src_cluster ) { if ( _interaction_list == nullptr ) { _interaction_list = new std::vector< scheduling_time_cluster * >( ); } _interaction_list->push_back( src_cluster ); } /** * Determines admissibility based on the "neighborhood criterion" (as in * Messner's work). * @param[in] src_cluster Source cluster whose admissibility is checked. * @warning This check of admissibility is only reasonable for clusters at the * same level of a tree. * @note The current criterion guarantees that the distance in time of two * admissible clusters is greater than the minimum of the half sizes of the * two clusters. */ bool determine_admissibility( scheduling_time_cluster * src_cluster ) { bool admissibility = false; sc src_center = src_cluster->get_center( ); sc src_half_size = src_cluster->get_half_size( ); sc min_half_size = ( src_half_size < _half_size ) ? src_half_size : _half_size; if ( src_center < _center - _half_size - src_half_size - min_half_size ) { admissibility = true; } return admissibility; } /** * Adds a cluster to @p _send_list. * @param[in] tar_cluster Pointer to a target cluster. * @note If @p _send_list is not allocated this is done here. */ void add_to_send_list( scheduling_time_cluster * tar_cluster ) { if ( _send_list == nullptr ) { _send_list = new std::vector< scheduling_time_cluster * >( ); } _send_list->push_back( tar_cluster ); } /** * Returns a pointer to the const send list. */ const std::vector< scheduling_time_cluster * > * get_send_list( ) const { return _send_list; } /** * Returns a pointer to the send list. */ std::vector< scheduling_time_cluster * > * get_send_list( ) { return _send_list; } /** * Adds a cluster to @p _ready_interaction_list. */ void add_to_ready_interaction_list( ) { #pragma omp atomic update _ready_interaction_list_size++; } /** * Clears the ready interaction list. */ void clear_ready_interaction_list( ) { #pragma omp atomic write _ready_interaction_list_size = 0; } /** * Increases the value of @ref _ready_interaction_list_size by 1. */ void update_ready_interaction_size( ) { #pragma omp atomic update _ready_interaction_list_size++; } /** * Returns the number of clusters ready for interaction, i.e. the value of * @ref _ready_interaction_list_size. */ lou get_ready_interaction_list_size( ) { lou size; #pragma omp atomic read size = _ready_interaction_list_size; return size; } /** * Sets the essential status of the current cluster (in the setting of a * distributed tree) to a given value. * @param[in] status Value to be set. */ void set_essential_status( const char status ) { _essential_status = status; } /** * Returns the essential status of the current cluster (in the setting of a * distributed tree). */ char get_essential_status( ) const { return _essential_status; } /** * Sets a flag which indicates if the cluster is active in the upward path of * the FMM. * \param[in] new_status Value to set. */ void set_active_upward_path_status( const bool new_status ) { _active_upward_path = new_status; } /** * Indicates if the cluster is active in the upward path, i.e. moments of * associated spacetime clusters have to be computed. */ bool is_active_in_upward_path( ) const { return _active_upward_path; } /** * Sets a flag which indicates if the cluster is active in the downward path * of the FMM. * \param[in] new_status Value to set. */ void set_active_downward_path_status( const bool new_status ) { _active_downward_path = new_status; } /** * Indicates if the cluster is active in the downward path, i.e. local * contributions of associated spacetime clusters have to be computed. */ bool is_active_in_downward_path( ) const { return _active_downward_path; } /** * Sets the upward path counter to the given value. * @param[in] upward_path_counter Value to set. */ void set_upward_path_counter( const lo upward_path_counter ) { #pragma omp atomic write _upward_path_counter = upward_path_counter; } /** * Returns the value of @p _upward_path_counter. */ lo get_upward_path_counter( ) const { lo counter; #pragma omp atomic read counter = _upward_path_counter; return counter; } /** * Reduces @p _upward_path_counter by 1. */ void reduce_upward_path_counter( ) { #pragma omp atomic update _upward_path_counter -= 1; } /** * Returns the value of @p _m2l_counter. */ lou get_m2l_counter( ) const { lou counter; #pragma omp atomic read counter = _m2l_counter; return counter; } /** * Sets the m2l counter to a new given value. * @param[in] new_value Value to which the counter is set. */ void set_m2l_counter( const slou new_value ) { #pragma omp atomic write _m2l_counter = new_value; } /** * Sets the downward path status to the given value. * @param[in] new_status Value to be set. */ void set_downward_path_status( const char new_status ) { #pragma omp atomic write _downward_path_status = new_status; } /** * Returns the value of @p _downward_path_status. */ char get_downward_path_status( ) const { char status; #pragma omp atomic read status = _downward_path_status; return status; } /** * Adds a space-time cluster to @p _associated_spacetime_clusters. * @param[in] cluster Cluster which is added to the list. * @note If @p _associated_spacetime_clusters is not allocated this is done * here. */ void add_associated_spacetime_cluster( general_spacetime_cluster * cluster ) { if ( _associated_spacetime_clusters == nullptr ) { _associated_spacetime_clusters = new std::vector< general_spacetime_cluster * >( ); } _associated_spacetime_clusters->push_back( cluster ); } /** * Returns a pointer to the const list of associated spacetime clusters. */ const std::vector< general_spacetime_cluster * > * get_associated_spacetime_clusters( ) const { return _associated_spacetime_clusters; } /** * Returns a pointer to the list of associated spacetime clusters. */ std::vector< general_spacetime_cluster * > * get_associated_spacetime_clusters( ) { return _associated_spacetime_clusters; } /** * Returns the number of associated spacetime leaf clusters. */ lou get_n_associated_leaves( ) const { return _n_associated_leaves; } /** * Sets the number of associated spacetime leaf clusters to the given value. * @param[in] n_associated_leaves Value to be set. */ void set_n_associated_leaves( lou n_associated_leaves ) { _n_associated_leaves = n_associated_leaves; } /** * Adds an entry to the map from process ids to moments. * @param[in] proc_id Key value of the element to be added * @note @p _map_to_moment_receive_buffers is allocated if it does not exist * allready. */ void add_receive_buffer( const lo proc_id ) { if ( _map_to_moment_receive_buffers == nullptr ) { _map_to_moment_receive_buffers = new std::map< lo, lou >( ); } sc * moment_buffer = new sc[ _contribution_size * _associated_spacetime_clusters->size( ) ]; _associated_moments_receive_buffers.push_back( moment_buffer ); _map_to_moment_receive_buffers->insert( { proc_id, _associated_moments_receive_buffers.size( ) - 1 } ); } /** * Returns a pointer to the position where the moments of an extraneous * process are stored. * @param[in] proc_id Id of the extraneous process. */ sc * get_extraneous_moment_pointer( lo proc_id ) { return _associated_moments_receive_buffers[ _map_to_moment_receive_buffers ->at( proc_id ) ]; } /** * Returns the number of associated moment receive buffers. It corresponds * to the number of children of the current scheduling time cluster which are * handled by a different process than the current cluster. */ lou get_n_associated_moment_receive_buffers( ) { return _associated_moments_receive_buffers.size( ); } /** * Determines the tree structure of the subtree whose root is the current * cluster. * @return A vector of the tree structure in the usual tree format * (see @ref time_cluster_tree::compute_tree_structure ). */ std::vector< char > determine_subtree_structure( ) const { std::vector< char > tree_vector; if ( _children == nullptr ) { tree_vector.push_back( 2 ); } else { tree_vector.push_back( 1 ); append_tree_structure_vector_recursively( tree_vector ); } return tree_vector; } /** * Determines the cluster bounds of the clusters in the subtree whose * root is the current cluster. * @return A vector of the cluster bounds of the subtree in the usual tree * format (see @ref time_cluster_tree::compute_tree_structure ). */ std::vector< sc > determine_subtree_cluster_bounds( ) const { std::vector< sc > cluster_bounds_vector; cluster_bounds_vector.push_back( _center - _half_size ); cluster_bounds_vector.push_back( _center + _half_size ); if ( _children != nullptr ) { append_cluster_bound_vector_recursively( cluster_bounds_vector ); } return cluster_bounds_vector; } /** * Adds the status of the two children of the current cluster to the end * of the tree structure vector. * * The status is: * - 0: if the child does not exist. * - 1: if the child is a non-leaf cluster. * - 2: if the child is a leaf cluster. * * The routine is called recursively for the children (first left child, then * right child) * @param[in,out] tree_vector Vector to which the status of the children is * added. * @warning This routine has to be called for a non-leaf cluster only, * otherwise a segmentation fault occurs. */ void append_tree_structure_vector_recursively( std::vector< char > & tree_vector ) const { char left_child_status = 0; char right_child_status = 0; scheduling_time_cluster * left_child = nullptr; scheduling_time_cluster * right_child = nullptr; for ( auto child : *_children ) { char * status_pointer; if ( child->get_configuration( ) == 0 ) { left_child = child; status_pointer = &left_child_status; } else { right_child = child; status_pointer = &right_child_status; } if ( child->get_n_children( ) > 0 ) { *status_pointer = 1; } else { *status_pointer = 2; } } tree_vector.push_back( left_child_status ); tree_vector.push_back( right_child_status ); if ( left_child_status == 1 ) { left_child->append_tree_structure_vector_recursively( tree_vector ); } if ( right_child_status == 1 ) { right_child->append_tree_structure_vector_recursively( tree_vector ); } } /** * Recursively traverses the implicitly given tree structure and constructs * a vector which contains the cluster bounds in the tree in the usual tree * format. * @param[out] cluster_bounds_vector Vector in which the cluster bounds are * stored. */ void append_cluster_bound_vector_recursively( std::vector< sc > & cluster_bounds_vector ) const { char left_child_status = 0; char right_child_status = 0; sc left_child_lower_bound( 0.0 ), left_child_upper_bound( 0.0 ); sc right_child_lower_bound( 0.0 ), right_child_upper_bound( 0.0 ); scheduling_time_cluster * left_child = nullptr; scheduling_time_cluster * right_child = nullptr; for ( auto child : *_children ) { // determine which child it is and remember its bounds and status. char * status_pointer; if ( child->get_configuration( ) == 0 ) { left_child = child; status_pointer = &left_child_status; left_child_lower_bound = child->get_center( ) - child->get_half_size( ); left_child_upper_bound = child->get_center( ) + child->get_half_size( ); } else { right_child = child; status_pointer = &right_child_status; right_child_lower_bound = child->get_center( ) - child->get_half_size( ); right_child_upper_bound = child->get_center( ) + child->get_half_size( ); } if ( child->get_n_children( ) > 0 ) { *status_pointer = 1; } else { *status_pointer = 2; } } // add the cluster bounds appropriately to the vector cluster_bounds_vector.push_back( left_child_lower_bound ); cluster_bounds_vector.push_back( left_child_upper_bound ); cluster_bounds_vector.push_back( right_child_lower_bound ); cluster_bounds_vector.push_back( right_child_upper_bound ); if ( left_child_status == 1 ) { left_child->append_cluster_bound_vector_recursively( cluster_bounds_vector ); } if ( right_child_status == 1 ) { right_child->append_cluster_bound_vector_recursively( cluster_bounds_vector ); } } /** * Returns a pointer to left neighbour. */ scheduling_time_cluster * get_left_neighbour( ) { if ( _parent == nullptr ) { // for the root cluster return nullptr; } if ( this == _parent->_children->back( ) ) { return _parent->_children->front( ); } else if ( ( _parent->get_left_neighbour( ) != nullptr ) && ( _parent->get_left_neighbour( )->_children != nullptr ) ) { return _parent->get_left_neighbour( )->_children->back( ); } else { return nullptr; } } /** * Determines whether the current cluster is the left child of its parent. * @note If the current cluster is the root of the tree \p false is returned. */ bool is_left_child( ) const { if ( _parent == nullptr ) return false; else return ( this == _parent->_children->front( ) ); } /** * Allocates an array containing all the moments of the associated * spacetime clusters. In addition, for each associated spacetime cluster it * sets the pointer to the appropriate moment. * @param[in] moment_size Size of the moment of a single space-time cluster. * @note Before calling this routine the spacetime clusters have to be * associated with this cluster. */ void allocate_associated_moments( const lou moment_size ) { if ( _associated_spacetime_clusters != nullptr ) { if ( _associated_moments == nullptr ) { _contribution_size = moment_size; _associated_moments = new sc[ moment_size * _associated_spacetime_clusters->size( ) ]; for ( lou i = 0; i < _associated_spacetime_clusters->size( ); ++i ) { general_spacetime_cluster * current_spacetime_cluster = ( *_associated_spacetime_clusters )[ i ]; current_spacetime_cluster->set_pointer_to_moment( &_associated_moments[ i * moment_size ] ); } } } } /** * Sets all associated moments to 0. */ void clear_associated_moments( ) { if ( _associated_moments != nullptr ) { for ( lou i = 0; i < _contribution_size * _associated_spacetime_clusters->size( ); ++i ) { _associated_moments[ i ] = 0.0; } } } /** * Returns a pointer to the associated moments. */ sc * get_associated_moments( ) { return _associated_moments; } /** * Allocates an array containing all the local contributions of the associated * spacetime clusters. In addition, for each associated spacetime cluster it * sets the pointer to the appropriate local contribution. * @param[in] contribution_size Size of the local contribution of a single * space-time cluster. * @note Before calling this routine the spacetime clusters have to be * associated with this cluster. */ void allocate_associated_local_contributions( const lou contribution_size ) { if ( _associated_spacetime_clusters != nullptr ) { if ( _associated_local_contributions == nullptr ) { _contribution_size = contribution_size; _associated_local_contributions = new sc[ contribution_size * _associated_spacetime_clusters->size( ) ]; for ( lou i = 0; i < _associated_spacetime_clusters->size( ); ++i ) { general_spacetime_cluster * current_spacetime_cluster = ( *_associated_spacetime_clusters )[ i ]; current_spacetime_cluster->set_pointer_to_local_contribution( &_associated_local_contributions[ i * contribution_size ] ); } } } } /** * Sets all associated local contributions to 0. */ void clear_associated_local_contributions( ) { if ( _associated_local_contributions != nullptr ) { for ( lou i = 0; i < _contribution_size * _associated_spacetime_clusters->size( ); ++i ) { _associated_local_contributions[ i ] = 0.0; } } } /** * Returns a pointer to the associated local contributions. */ sc * get_associated_local_contributions( ) { return _associated_local_contributions; } /** * Prints info of the object. */ void print( lo executing_process_id = -1 ) { std::cout << "level: " << _level << ", center: " << _center << ", half size: " << _half_size << ", global_index: " << _global_index << ", proc_id: " << _process_id; if ( _global_leaf_status ) { std::cout << ", is global leaf"; } // if ( _nearfield_list != nullptr ) { // std::cout << ", nearfield: "; // for ( lou i = 0; i < _nearfield_list->size( ); ++i ) { // std::cout << "(" << ( *_nearfield_list )[ i ]->get_level( ) << ", " // << ( *_nearfield_list )[ i ]->get_global_index( ) << "), "; // } // } // if ( _interaction_list != nullptr ) { // std::cout << "interaction_list: "; // for ( lou i = 0; i < _interaction_list->size( ); ++i ) { // std::cout << "(" << ( *_interaction_list )[ i ]->get_level( ) << ", " // << ( *_interaction_list )[ i ]->get_global_index( ) // << "), "; // } // } // if ( _send_list != nullptr ) { // std::cout << "send_list: "; // for ( lou i = 0; i < _send_list->size( ); ++i ) { // std::cout << "(" << ( *_send_list )[ i ]->get_level( ) << ", " // << ( *_send_list )[ i ]->get_global_index( ) // << "), "; // } // } // std::cout << ", upward_path_counter: " << _upward_path_counter; // std::cout << ", downward_path_status: " << (lo) _downward_path_status; // std::cout << ", m2l counter: " << _m2l_counter; if ( _associated_spacetime_clusters != nullptr ) { if ( _process_id == executing_process_id ) { std::cout << ", number of associated leaves: " << _n_associated_leaves << ", number of associated non-leaves: " << _associated_spacetime_clusters->size( ) - _n_associated_leaves; } else { std::cout << ", number of associated clusters: " << _associated_spacetime_clusters->size( ); } } if ( _time_slices != nullptr ) { std::cout << ", time slices: "; for ( auto idx : *_time_slices ) { std::cout << idx << ", "; } } std::cout << std::endl; } /** * Setter for the @ref _pos_in_m_list variable * @param[in] index Index of the cluster in the @ref * besthea::linear_algebra::distributed_pFMM_matrix::_m_list */ void set_pos_in_m_list( lo index ) { _pos_in_m_list = index; } /** * Returns position in @ref * besthea::linear_algebra::distributed_pFMM_matrix::_m_list */ lo get_pos_in_m_list( ) { return _pos_in_m_list; } /** * Setter for the @ref _pos_in_l_list variable * @param[in] index Index of the cluster in the @ref * besthea::linear_algebra::distributed_pFMM_matrix::_l_list */ void set_pos_in_l_list( lo index ) { _pos_in_l_list = index; } /** * Returns position in @ref * besthea::linear_algebra::distributed_pFMM_matrix::_l_list */ lo get_pos_in_l_list( ) { return _pos_in_l_list; } /** * Setter for the @ref _pos_in_m2l_list variable * @param[in] index Index of the cluster in the @ref * besthea::linear_algebra::distributed_pFMM_matrix::_m2l_list */ void set_pos_in_m2l_list( lo index ) { _pos_in_m2l_list = index; } /** * Returns position in @ref * besthea::linear_algebra::distributed_pFMM_matrix::_m2l_list */ lo get_pos_in_m2l_list( ) { return _pos_in_m2l_list; } private: sc _center; //!< Center of the cluster. sc _half_size; //!< Half size of the cluster. scheduling_time_cluster * _parent; //!< Parent of the cluster. short _left_right; //!< Indicates if the child is the left (0), or right (1) //!< child of its parent. std::vector< scheduling_time_cluster * > * _children; //!< Children of the cluster. lo _level; //!< Level within the cluster tree. lo _global_index; //!< Global index of the cluster. The children of a cluster //!< with index k have the indices 2k+1 and 2k+2. lo _process_id; //!< Id of the process to which the cluster is assigned. std::vector< lo > * _time_slices; //!< global indices of the cluster's time //!< slices (only set for leaf clusters) bool _global_leaf_status; //!< indicates whether the cluster is a leaf (1) or //!< non-leaf in a global tree structure bool _mesh_available; //!< Indicates whether the process who owns the cluster //!< has access to the corresponding mesh. Only relevant //!< in a distribution tree in a distributed spacetime //!< tensor mesh. It is set to true for leaf clusters //!< which are either local or in the nearfield of local //!< clusters. It is set in //!< @ref //!< distributed_spacetime_tensor_mesh::find_slices_to_load. std::vector< scheduling_time_cluster * > * _nearfield_list; //!< Nearfield of the cluster. std::vector< scheduling_time_cluster * > * _interaction_list; //!< Interaction list of the cluster. std::vector< scheduling_time_cluster * > * _send_list; //!< Contains all clusters in whose interaction list the //!< cluster is contained. char _essential_status; //!< Indicates the status of a cluster in a //!< distributed tree. Possible status are: //!< - 0: not essential //!< - 1: essential for time cluster only //!< - 2: essential for time and space-time cluster //!< - 3: local, i.e. directly essential //!< The status is assigned when the tree containing //!< the cluster is reduced to the locally essential //!< tree, see //!< @ref tree_structure::reduce_2_essential. bool _active_upward_path; //!< Indicates if the cluster is active in the //!< upward path of the FMM. bool _active_downward_path; //!< Indicates if the cluster is active in the //!< downward path of the FMM. lo _upward_path_counter; //!< Used to keep track of the dependencies in the //!< upward path. If it is 0, the dependencies are //!< fulfilled. slou _m2l_counter; //!< Used to keep track of the completed m2l operations. char _downward_path_status; //!< Used to keep track of the status in the //!< downward path. Three status are distinguished //!< - 0: L2L not executed, //!< - 1: L2L executed, local contributions not //!< ready, //!< - 2: local contributions ready. std::vector< general_spacetime_cluster * > * _associated_spacetime_clusters; //!< List of space-time clusters //!< associated to the scheduling time //!< cluster. lou _n_associated_leaves; //!< Number of associated space-time leaf clusters. //!< These are first in the list of associated //!< space-time clusters. sc * _associated_moments; //!< Array containing all the moments of the //!< associated general spacetime clusters. sc * _associated_local_contributions; //!< Array containing all the local //!< contributions of the associated //!< general spacetime clusters. lou _contribution_size; //!< Size of a single contribution (moments or local //!< contribution) in the array of associated //!< contributions //!< @todo Is there a better way to make this value //!< accessible for all clusters without storing it //!< in each instance separately? std::vector< sc * > _associated_moments_receive_buffers; //!< In case that moments have to be //!< received from other processes //!< they are written into these //!< buffers. std::map< lo, lou > * _map_to_moment_receive_buffers; //!< Map to access the correct position in //!< @p _associated_moments_receive_buffers //!< for extraneous children. lo _pos_in_m_list; //!< auxiliary variable storing position in the m list //!< used in @ref //!< besthea::linear_algebra::distributed_pFMM_matrix::apply lo _pos_in_l_list; //!< auxiliary variable storing position in the l list //!< used in @ref //!< besthea::linear_algebra::distributed_pFMM_matrix::apply lo _pos_in_m2l_list; //!< auxiliary variable storing position in the m2l list //!< used in @ref //!< besthea::linear_algebra::distributed_pFMM_matrix::apply lou _ready_interaction_list_size; //!< size of the ready interaction list //!< (stored as variable due to possible //!< data races) }; /** * Struct that realizes a comparison (<) between pairs consisting of process ids * (lo) and scheduling time clusters. */ struct compare_pairs_of_process_ids_and_scheduling_time_clusters { /** * Operator realizing the comparison < between pairs consisting of process ids * (lo) and scheduling time clusters * * (a, I) < (b, J) if the process ids satisfy a < b or * (a == b) and I's global index < J's global index * @param[in] first_pair First pair considered in the comparison * @param[in] second_pair Second pair considered in the comparison * @return True if first_pair is smaller than second pair. */ bool operator( )( const std::pair< lo, besthea::mesh::scheduling_time_cluster * > first_pair, const std::pair< lo, besthea::mesh::scheduling_time_cluster * > second_pair ) const { bool compare_value = false; if ( first_pair.first < second_pair.first || ( first_pair.first == second_pair.first && first_pair.second->get_global_index( ) < second_pair.second->get_global_index( ) ) ) { compare_value = true; } return compare_value; } }; #endif /* INCLUDE_BESTHEA_SCHEDULING_TIME_CLUSTER_H_ */
transform.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT RRRR AAA N N SSSSS FFFFF OOO RRRR M M % % T R R A A NN N SS F O O R R MM MM % % T RRRR AAAAA N N N SSS FFF O O RRRR M M M % % T R R A A N NN SS F O O R R M M % % T R R A A N N SSSSS F OOO R R M M % % % % % % MagickCore Image Transform Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/distort.h" #include "magick/draw.h" #include "magick/effect.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/memory_.h" #include "magick/layer.h" #include "magick/list.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-private.h" #include "magick/resource_.h" #include "magick/resize.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o O r i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoOrientImage() adjusts an image so that its orientation is suitable for % viewing (i.e. top-left orientation). % % The format of the AutoOrientImage method is: % % Image *AutoOrientImage(const Image *image, % const OrientationType orientation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image. % % o orientation: Current image orientation. % % o exception: Return any errors or warnings in this structure. % */ MagickExport Image *AutoOrientImage(const Image *image, const OrientationType orientation,ExceptionInfo *exception) { Image *orient_image; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); orient_image=(Image *) NULL; switch(orientation) { case UndefinedOrientation: case TopLeftOrientation: default: { orient_image=CloneImage(image,0,0,MagickTrue,exception); break; } case TopRightOrientation: { orient_image=FlopImage(image,exception); break; } case BottomRightOrientation: { orient_image=RotateImage(image,180.0,exception); break; } case BottomLeftOrientation: { orient_image=FlipImage(image,exception); break; } case LeftTopOrientation: { orient_image=TransposeImage(image,exception); break; } case RightTopOrientation: { orient_image=RotateImage(image,90.0,exception); break; } case RightBottomOrientation: { orient_image=TransverseImage(image,exception); break; } case LeftBottomOrientation: { orient_image=RotateImage(image,270.0,exception); break; } } if (orient_image != (Image *) NULL) orient_image->orientation=TopLeftOrientation; return(orient_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ChopImage() removes a region of an image and collapses the image to occupy % the removed portion. % % The format of the ChopImage method is: % % Image *ChopImage(const Image *image,const RectangleInfo *chop_info) % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o chop_info: Define the region of the image to chop. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info, ExceptionInfo *exception) { #define ChopImageTag "Chop/Image" CacheView *chop_view, *image_view; Image *chop_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo extent; ssize_t y; /* Check chop geometry. */ 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); assert(chop_info != (RectangleInfo *) NULL); if (((chop_info->x+(ssize_t) chop_info->width) < 0) || ((chop_info->y+(ssize_t) chop_info->height) < 0) || (chop_info->x > (ssize_t) image->columns) || (chop_info->y > (ssize_t) image->rows)) ThrowImageException(OptionWarning,"GeometryDoesNotContainImage"); extent=(*chop_info); if ((extent.x+(ssize_t) extent.width) > (ssize_t) image->columns) extent.width=(size_t) ((ssize_t) image->columns-extent.x); if ((extent.y+(ssize_t) extent.height) > (ssize_t) image->rows) extent.height=(size_t) ((ssize_t) image->rows-extent.y); if (extent.x < 0) { extent.width-=(size_t) (-extent.x); extent.x=0; } if (extent.y < 0) { extent.height-=(size_t) (-extent.y); extent.y=0; } chop_image=CloneImage(image,image->columns-extent.width,image->rows- extent.height,MagickTrue,exception); if (chop_image == (Image *) NULL) return((Image *) NULL); /* Extract chop image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); chop_view=AcquireAuthenticCacheView(chop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,chop_image,extent.y,1) #endif for (y=0; y < (ssize_t) extent.y; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict chop_indexes, *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(chop_view,0,y,chop_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); chop_indexes=GetCacheViewAuthenticIndexQueue(chop_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width))) { *q=(*p); if (indexes != (IndexPacket *) NULL) { if (chop_indexes != (IndexPacket *) NULL) *chop_indexes++=GetPixelIndex(indexes+x); } q++; } p++; } if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ChopImage) #endif proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } /* Extract chop image. */ #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-(extent.y+extent.height)); y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict chop_indexes, *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,extent.y+extent.height+y, image->columns,1,exception); q=QueueCacheViewAuthenticPixels(chop_view,0,extent.y+y,chop_image->columns, 1,exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); chop_indexes=GetCacheViewAuthenticIndexQueue(chop_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width))) { *q=(*p); if (indexes != (IndexPacket *) NULL) { if (chop_indexes != (IndexPacket *) NULL) *chop_indexes++=GetPixelIndex(indexes+x); } q++; } p++; } if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ChopImage) #endif proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } chop_view=DestroyCacheView(chop_view); image_view=DestroyCacheView(image_view); chop_image->type=image->type; if (status == MagickFalse) chop_image=DestroyImage(chop_image); return(chop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n s o l i d a t e C M Y K I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConsolidateCMYKImage() consolidates separate C, M, Y, and K planes into a % single image. % % The format of the ConsolidateCMYKImage method is: % % Image *ConsolidateCMYKImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConsolidateCMYKImages(const Image *images, ExceptionInfo *exception) { CacheView *cmyk_view, *image_view; Image *cmyk_image, *cmyk_images; register ssize_t i; ssize_t y; /* Consolidate separate C, M, Y, and K planes into a single image. */ 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); cmyk_images=NewImageList(); for (i=0; i < (ssize_t) GetImageListLength(images); i+=4) { cmyk_image=CloneImage(images,images->columns,images->rows,MagickTrue, exception); if (cmyk_image == (Image *) NULL) break; if (SetImageStorageClass(cmyk_image,DirectClass) == MagickFalse) break; (void) SetImageColorspace(cmyk_image,CMYKColorspace); image_view=AcquireVirtualCacheView(images,exception); cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception); for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception); q=QueueCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) images->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange-GetPixelIntensity(images,p))); p++; q++; } if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse) break; } cmyk_view=DestroyCacheView(cmyk_view); image_view=DestroyCacheView(image_view); images=GetNextImageInList(images); if (images == (Image *) NULL) break; image_view=AcquireVirtualCacheView(images,exception); cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception); for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception); q=GetCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) images->columns; x++) { q->green=ClampToQuantum(QuantumRange-GetPixelIntensity(images,p)); p++; q++; } if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse) break; } cmyk_view=DestroyCacheView(cmyk_view); image_view=DestroyCacheView(image_view); images=GetNextImageInList(images); if (images == (Image *) NULL) break; image_view=AcquireVirtualCacheView(images,exception); cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception); for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; register PixelPacket *magick_restrict q; p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception); q=GetCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) images->columns; x++) { q->blue=ClampToQuantum(QuantumRange-GetPixelIntensity(images,p)); p++; q++; } if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse) break; } cmyk_view=DestroyCacheView(cmyk_view); image_view=DestroyCacheView(image_view); images=GetNextImageInList(images); if (images == (Image *) NULL) break; image_view=AcquireVirtualCacheView(images,exception); cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception); for (y=0; y < (ssize_t) images->rows; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception); q=GetCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; indexes=GetCacheViewAuthenticIndexQueue(cmyk_view); for (x=0; x < (ssize_t) images->columns; x++) { SetPixelIndex(indexes+x,ClampToQuantum(QuantumRange- GetPixelIntensity(images,p))); p++; } if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse) break; } cmyk_view=DestroyCacheView(cmyk_view); image_view=DestroyCacheView(image_view); AppendImageToList(&cmyk_images,cmyk_image); images=GetNextImageInList(images); if (images == (Image *) NULL) break; } return(cmyk_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C r o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropImage() extracts a region of the image starting at the offset defined % by geometry. Region must be fully defined, and no special handling of % geometry flags is performed. % % The format of the CropImage method is: % % Image *CropImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to crop with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CropImage(const Image *image,const RectangleInfo *geometry, ExceptionInfo *exception) { #define CropImageTag "Crop/Image" CacheView *crop_view, *image_view; Image *crop_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo bounding_box, page; ssize_t y; /* Check crop geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); bounding_box=image->page; if ((bounding_box.width == 0) || (bounding_box.height == 0)) { bounding_box.width=image->columns; bounding_box.height=image->rows; } page=(*geometry); if (page.width == 0) page.width=bounding_box.width; if (page.height == 0) page.height=bounding_box.height; if (((bounding_box.x-page.x) >= (ssize_t) page.width) || ((bounding_box.y-page.y) >= (ssize_t) page.height) || ((page.x-bounding_box.x) > (ssize_t) image->columns) || ((page.y-bounding_box.y) > (ssize_t) image->rows)) { /* Crop is not within virtual canvas, return 1 pixel transparent image. */ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); crop_image=CloneImage(image,1,1,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(crop_image); crop_image->page=bounding_box; crop_image->page.x=(-1); crop_image->page.y=(-1); if (crop_image->dispose == BackgroundDispose) crop_image->dispose=NoneDispose; return(crop_image); } if ((page.x < 0) && (bounding_box.x >= 0)) { page.width+=page.x-bounding_box.x; page.x=0; } else { page.width-=bounding_box.x-page.x; page.x-=bounding_box.x; if (page.x < 0) page.x=0; } if ((page.y < 0) && (bounding_box.y >= 0)) { page.height+=page.y-bounding_box.y; page.y=0; } else { page.height-=bounding_box.y-page.y; page.y-=bounding_box.y; if (page.y < 0) page.y=0; } if ((page.x+(ssize_t) page.width) > (ssize_t) image->columns) page.width=image->columns-page.x; if ((geometry->width != 0) && (page.width > geometry->width)) page.width=geometry->width; if ((page.y+(ssize_t) page.height) > (ssize_t) image->rows) page.height=image->rows-page.y; if ((geometry->height != 0) && (page.height > geometry->height)) page.height=geometry->height; bounding_box.x+=page.x; bounding_box.y+=page.y; if ((page.width == 0) || (page.height == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); return((Image *) NULL); } /* Initialize crop image attributes. */ crop_image=CloneImage(image,page.width,page.height,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->page.width=image->page.width; crop_image->page.height=image->page.height; if (((ssize_t) (bounding_box.x+bounding_box.width) > (ssize_t) image->page.width) || ((ssize_t) (bounding_box.y+bounding_box.height) > (ssize_t) image->page.height)) { crop_image->page.width=bounding_box.width; crop_image->page.height=bounding_box.height; } crop_image->page.x=bounding_box.x; crop_image->page.y=bounding_box.y; /* Crop image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); crop_view=AcquireAuthenticCacheView(crop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,crop_image,crop_image->rows,1) #endif for (y=0; y < (ssize_t) crop_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict crop_indexes; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,page.x,page.y+y,crop_image->columns, 1,exception); q=QueueCacheViewAuthenticPixels(crop_view,0,y,crop_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); crop_indexes=GetCacheViewAuthenticIndexQueue(crop_view); (void) memcpy(q,p,(size_t) crop_image->columns*sizeof(*p)); if ((indexes != (IndexPacket *) NULL) && (crop_indexes != (IndexPacket *) NULL)) (void) memcpy(crop_indexes,indexes,(size_t) crop_image->columns* sizeof(*crop_indexes)); if (SyncCacheViewAuthenticPixels(crop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CropImage) #endif proceed=SetImageProgress(image,CropImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } crop_view=DestroyCacheView(crop_view); image_view=DestroyCacheView(image_view); crop_image->type=image->type; if (status == MagickFalse) crop_image=DestroyImage(crop_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C r o p I m a g e T o T i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropImageToTiles() crops a single image, into a possible list of tiles. % This may include a single sub-region of the image. This basically applies % all the normal geometry flags for Crop. % % Image *CropImageToTiles(const Image *image, % const RectangleInfo *crop_geometry, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image The transformed image is returned as this parameter. % % o crop_geometry: A crop geometry string. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } MagickExport Image *CropImageToTiles(const Image *image, const char *crop_geometry,ExceptionInfo *exception) { Image *next, *crop_image; MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); crop_image=NewImageList(); next=NewImageList(); flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception); if ((flags & AreaValue) != 0) { PointInfo delta, offset; RectangleInfo crop; size_t height, width; /* Crop into NxM tiles (@ flag). */ width=image->columns; height=image->rows; if (geometry.width == 0) geometry.width=1; if (geometry.height == 0) geometry.height=1; if ((flags & AspectValue) == 0) { width-=(geometry.x < 0 ? -1 : 1)*geometry.x; height-=(geometry.y < 0 ? -1 : 1)*geometry.y; } else { width+=(geometry.x < 0 ? -1 : 1)*geometry.x; height+=(geometry.y < 0 ? -1 : 1)*geometry.y; } delta.x=(double) width/geometry.width; delta.y=(double) height/geometry.height; if (delta.x < 1.0) delta.x=1.0; if (delta.y < 1.0) delta.y=1.0; for (offset.y=0; offset.y < (double) height; ) { if ((flags & AspectValue) == 0) { crop.y=(ssize_t) MagickRound((MagickRealType) (offset.y- (geometry.y > 0 ? 0 : geometry.y))); offset.y+=delta.y; /* increment now to find width */ crop.height=(size_t) MagickRound((MagickRealType) (offset.y+ (geometry.y < 0 ? 0 : geometry.y))); } else { crop.y=(ssize_t) MagickRound((MagickRealType) (offset.y- (geometry.y > 0 ? geometry.y : 0))); offset.y+=delta.y; /* increment now to find width */ crop.height=(size_t) MagickRound((MagickRealType) (offset.y+ (geometry.y < 0 ? geometry.y : 0))); } crop.height-=crop.y; crop.y+=image->page.y; for (offset.x=0; offset.x < (double) width; ) { if ((flags & AspectValue) == 0) { crop.x=(ssize_t) MagickRound((MagickRealType) (offset.x- (geometry.x > 0 ? 0 : geometry.x))); offset.x+=delta.x; /* increment now to find height */ crop.width=(size_t) MagickRound((MagickRealType) (offset.x+ (geometry.x < 0 ? 0 : geometry.x))); } else { crop.x=(ssize_t) MagickRound((MagickRealType) (offset.x- (geometry.x > 0 ? geometry.x : 0))); offset.x+=delta.x; /* increment now to find height */ crop.width=(size_t) MagickRound((MagickRealType) (offset.x+ (geometry.x < 0 ? geometry.x : 0))); } crop.width-=crop.x; crop.x+=image->page.x; next=CropImage(image,&crop,exception); if (next != (Image *) NULL) AppendImageToList(&crop_image,next); } } ClearMagickException(exception); return(crop_image); } if (((geometry.width == 0) && (geometry.height == 0)) || ((flags & XValue) != 0) || ((flags & YValue) != 0)) { /* Crop a single region at +X+Y. */ crop_image=CropImage(image,&geometry,exception); if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0)) { crop_image->page.width=geometry.width; crop_image->page.height=geometry.height; crop_image->page.x-=geometry.x; crop_image->page.y-=geometry.y; } return(crop_image); } if ((image->columns > geometry.width) || (image->rows > geometry.height)) { RectangleInfo page; size_t height, width; ssize_t x, y; /* Crop into tiles of fixed size WxH. */ page=image->page; if (page.width == 0) page.width=image->columns; if (page.height == 0) page.height=image->rows; width=geometry.width; if (width == 0) width=page.width; height=geometry.height; if (height == 0) height=page.height; next=NewImageList(); for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height) { for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width) { geometry.width=width; geometry.height=height; geometry.x=x; geometry.y=y; next=CropImage(image,&geometry,exception); if (next == (Image *) NULL) break; AppendImageToList(&crop_image,next); } if (next == (Image *) NULL) break; } return(crop_image); } return(CloneImage(image,0,0,MagickTrue,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x c e r p t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExcerptImage() returns a excerpt of the image as defined by the geometry. % % The format of the ExcerptImage method is: % % Image *ExcerptImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to extend with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ExcerptImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define ExcerptImageTag "Excerpt/Image" CacheView *excerpt_view, *image_view; Image *excerpt_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate excerpt image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); excerpt_image=CloneImage(image,geometry->width,geometry->height,MagickTrue, exception); if (excerpt_image == (Image *) NULL) return((Image *) NULL); /* Excerpt each row. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); excerpt_view=AcquireAuthenticCacheView(excerpt_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,excerpt_image,excerpt_image->rows,1) #endif for (y=0; y < (ssize_t) excerpt_image->rows; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict excerpt_indexes, *magick_restrict indexes; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,geometry->x,geometry->y+y, geometry->width,1,exception); q=GetCacheViewAuthenticPixels(excerpt_view,0,y,excerpt_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } (void) memcpy(q,p,(size_t) excerpt_image->columns*sizeof(*q)); indexes=GetCacheViewAuthenticIndexQueue(image_view); if (indexes != (IndexPacket *) NULL) { excerpt_indexes=GetCacheViewAuthenticIndexQueue(excerpt_view); if (excerpt_indexes != (IndexPacket *) NULL) (void) memcpy(excerpt_indexes,indexes,(size_t) excerpt_image->columns*sizeof(*excerpt_indexes)); } if (SyncCacheViewAuthenticPixels(excerpt_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ExcerptImage) #endif proceed=SetImageProgress(image,ExcerptImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } excerpt_view=DestroyCacheView(excerpt_view); image_view=DestroyCacheView(image_view); excerpt_image->type=image->type; if (status == MagickFalse) excerpt_image=DestroyImage(excerpt_image); return(excerpt_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x t e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExtentImage() extends the image as defined by the geometry, gravity, and % image background color. Set the (x,y) offset of the geometry to move the % original image relative to the extended image. % % The format of the ExtentImage method is: % % Image *ExtentImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to extend with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ExtentImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { Image *extent_image; /* Allocate extent image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == geometry->width) && (image->rows == geometry->height) && (geometry->x == 0) && (geometry->y == 0)) return(CloneImage(image,0,0,MagickTrue,exception)); extent_image=CloneImage(image,geometry->width,geometry->height,MagickTrue, exception); if (extent_image == (Image *) NULL) return((Image *) NULL); (void) SetImageBackgroundColor(extent_image); (void) CompositeImage(extent_image,image->compose,image,-geometry->x, -geometry->y); return(extent_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlipImage() creates a vertical mirror image by reflecting the pixels % around the central x-axis. % % The format of the FlipImage method is: % % Image *FlipImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *FlipImage(const Image *image,ExceptionInfo *exception) { #define FlipImageTag "Flip/Image" CacheView *flip_view, *image_view; Image *flip_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); flip_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (flip_image == (Image *) NULL) return((Image *) NULL); /* Flip image. */ status=MagickTrue; progress=0; page=image->page; image_view=AcquireVirtualCacheView(image,exception); flip_view=AcquireAuthenticCacheView(flip_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,flip_image,flip_image->rows,1) #endif for (y=0; y < (ssize_t) flip_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict flip_indexes; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(flip_view,0,(ssize_t) (flip_image->rows-y- 1),flip_image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } (void) memcpy(q,p,(size_t) image->columns*sizeof(*q)); indexes=GetCacheViewVirtualIndexQueue(image_view); if (indexes != (const IndexPacket *) NULL) { flip_indexes=GetCacheViewAuthenticIndexQueue(flip_view); if (flip_indexes != (IndexPacket *) NULL) (void) memcpy(flip_indexes,indexes,(size_t) image->columns* sizeof(*flip_indexes)); } if (SyncCacheViewAuthenticPixels(flip_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FlipImage) #endif proceed=SetImageProgress(image,FlipImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } flip_view=DestroyCacheView(flip_view); image_view=DestroyCacheView(image_view); flip_image->type=image->type; if (page.height != 0) page.y=(ssize_t) (page.height-flip_image->rows-page.y); flip_image->page=page; if (status == MagickFalse) flip_image=DestroyImage(flip_image); return(flip_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlopImage() creates a horizontal mirror image by reflecting the pixels % around the central y-axis. % % The format of the FlopImage method is: % % Image *FlopImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *FlopImage(const Image *image,ExceptionInfo *exception) { #define FlopImageTag "Flop/Image" CacheView *flop_view, *image_view; Image *flop_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); flop_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (flop_image == (Image *) NULL) return((Image *) NULL); /* Flop each row. */ status=MagickTrue; progress=0; page=image->page; image_view=AcquireVirtualCacheView(image,exception); flop_view=AcquireAuthenticCacheView(flop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,flop_image,flop_image->rows,1) #endif for (y=0; y < (ssize_t) flop_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict flop_indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(flop_view,0,y,flop_image->columns,1, exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } q+=flop_image->columns; indexes=GetCacheViewVirtualIndexQueue(image_view); flop_indexes=GetCacheViewAuthenticIndexQueue(flop_view); for (x=0; x < (ssize_t) flop_image->columns; x++) { (*--q)=(*p++); if ((indexes != (const IndexPacket *) NULL) && (flop_indexes != (IndexPacket *) NULL)) SetPixelIndex(flop_indexes+flop_image->columns-x-1, GetPixelIndex(indexes+x)); } if (SyncCacheViewAuthenticPixels(flop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FlopImage) #endif proceed=SetImageProgress(image,FlopImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } flop_view=DestroyCacheView(flop_view); image_view=DestroyCacheView(image_view); flop_image->type=image->type; if (page.width != 0) page.x=(ssize_t) (page.width-flop_image->columns-page.x); flop_image->page=page; if (status == MagickFalse) flop_image=DestroyImage(flop_image); return(flop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RollImage() offsets an image as defined by x_offset and y_offset. % % The format of the RollImage method is: % % Image *RollImage(const Image *image,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x_offset: the number of columns to roll in the horizontal direction. % % o y_offset: the number of rows to roll in the vertical direction. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CopyImageRegion(Image *destination,const Image *source, const size_t columns,const size_t rows,const ssize_t sx,const ssize_t sy, const ssize_t dx,const ssize_t dy,ExceptionInfo *exception) { CacheView *source_view, *destination_view; MagickBooleanType status; ssize_t y; if (columns == 0) return(MagickTrue); status=MagickTrue; source_view=AcquireVirtualCacheView(source,exception); destination_view=AcquireAuthenticCacheView(destination,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source,destination,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict destination_indexes; register PixelPacket *magick_restrict q; /* Transfer scanline. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,sx,sy+y,columns,1,exception); q=GetCacheViewAuthenticPixels(destination_view,dx,dy+y,columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(source_view); (void) memcpy(q,p,(size_t) columns*sizeof(*p)); if (indexes != (IndexPacket *) NULL) { destination_indexes=GetCacheViewAuthenticIndexQueue(destination_view); if (destination_indexes != (IndexPacket *) NULL) (void) memcpy(destination_indexes,indexes,(size_t) columns*sizeof(*indexes)); } sync=SyncCacheViewAuthenticPixels(destination_view,exception); if (sync == MagickFalse) status=MagickFalse; } destination_view=DestroyCacheView(destination_view); source_view=DestroyCacheView(source_view); return(status); } MagickExport Image *RollImage(const Image *image,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define RollImageTag "Roll/Image" Image *roll_image; MagickStatusType status; RectangleInfo offset; /* Initialize roll image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); roll_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (roll_image == (Image *) NULL) return((Image *) NULL); offset.x=x_offset; offset.y=y_offset; while (offset.x < 0) offset.x+=(ssize_t) image->columns; while (offset.x >= (ssize_t) image->columns) offset.x-=(ssize_t) image->columns; while (offset.y < 0) offset.y+=(ssize_t) image->rows; while (offset.y >= (ssize_t) image->rows) offset.y-=(ssize_t) image->rows; /* Roll image. */ status=CopyImageRegion(roll_image,image,(size_t) offset.x, (size_t) offset.y,(ssize_t) image->columns-offset.x,(ssize_t) image->rows- offset.y,0,0,exception); (void) SetImageProgress(image,RollImageTag,0,3); status&=CopyImageRegion(roll_image,image,image->columns-offset.x, (size_t) offset.y,0,(ssize_t) image->rows-offset.y,offset.x,0, exception); (void) SetImageProgress(image,RollImageTag,1,3); status&=CopyImageRegion(roll_image,image,(size_t) offset.x,image->rows- offset.y,(ssize_t) image->columns-offset.x,0,0,offset.y,exception); (void) SetImageProgress(image,RollImageTag,2,3); status&=CopyImageRegion(roll_image,image,image->columns-offset.x,image->rows- offset.y,0,0,offset.x,offset.y,exception); (void) SetImageProgress(image,RollImageTag,3,3); roll_image->type=image->type; if (status == MagickFalse) roll_image=DestroyImage(roll_image); return(roll_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShaveImage() shaves pixels from the image edges. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ShaveImage method is: % % Image *ShaveImage(const Image *image,const RectangleInfo *shave_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o shave_image: Method ShaveImage returns a pointer to the shaved % image. A null image is returned if there is a memory shortage or % if the image width or height is zero. % % o image: the image. % % o shave_info: Specifies a pointer to a RectangleInfo which defines the % region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShaveImage(const Image *image, const RectangleInfo *shave_info,ExceptionInfo *exception) { Image *shave_image; RectangleInfo geometry; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (((2*shave_info->width) >= image->columns) || ((2*shave_info->height) >= image->rows)) ThrowImageException(OptionWarning,"GeometryDoesNotContainImage"); SetGeometry(image,&geometry); geometry.width-=2*shave_info->width; geometry.height-=2*shave_info->height; geometry.x=(ssize_t) shave_info->width+image->page.x; geometry.y=(ssize_t) shave_info->height+image->page.y; shave_image=CropImage(image,&geometry,exception); if (shave_image == (Image *) NULL) return((Image *) NULL); shave_image->page.width-=2*shave_info->width; shave_image->page.height-=2*shave_info->height; shave_image->page.x-=(ssize_t) shave_info->width; shave_image->page.y-=(ssize_t) shave_info->height; return(shave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p l i c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpliceImage() splices a solid color into the image as defined by the % geometry. % % The format of the SpliceImage method is: % % Image *SpliceImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to splice with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpliceImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define SpliceImageTag "Splice/Image" CacheView *image_view, *splice_view; Image *splice_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo splice_geometry; ssize_t columns, y; /* Allocate splice image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); splice_geometry=(*geometry); splice_image=CloneImage(image,image->columns+splice_geometry.width, image->rows+splice_geometry.height,MagickTrue,exception); if (splice_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(splice_image,DirectClass) == MagickFalse) { InheritException(exception,&splice_image->exception); splice_image=DestroyImage(splice_image); return((Image *) NULL); } (void) SetImageBackgroundColor(splice_image); /* Respect image geometry. */ switch (image->gravity) { default: case UndefinedGravity: case NorthWestGravity: break; case NorthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; break; } case NorthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; break; } case WestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.width/2; break; } case StaticGravity: case CenterGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case EastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case SouthWestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } } /* Splice image. */ status=MagickTrue; progress=0; columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns); image_view=AcquireVirtualCacheView(image,exception); splice_view=AcquireAuthenticCacheView(splice_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,splice_image,splice_geometry.y,1) #endif for (y=0; y < (ssize_t) splice_geometry.y; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes, *magick_restrict splice_indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); splice_indexes=GetCacheViewAuthenticIndexQueue(splice_view); for (x=0; x < columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); if (image->colorspace == CMYKColorspace) SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes)); indexes++; p++; q++; } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q++; for ( ; x < (ssize_t) splice_image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); if (image->colorspace == CMYKColorspace) SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes)); indexes++; p++; q++; } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,splice_image,splice_image->rows,1) #endif for (y=(ssize_t) (splice_geometry.y+splice_geometry.height); y < (ssize_t) splice_image->rows; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes, *magick_restrict splice_indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; if ((y < 0) || (y >= (ssize_t)splice_image->rows)) continue; p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height, splice_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); splice_indexes=GetCacheViewAuthenticIndexQueue(splice_view); for (x=0; x < columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); if (image->colorspace == CMYKColorspace) SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes)); indexes++; p++; q++; } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q++; for ( ; x < (ssize_t) splice_image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); if (image->colorspace == CMYKColorspace) SetPixelIndex(splice_indexes+x,GetPixelIndex(indexes)); indexes++; p++; q++; } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } splice_view=DestroyCacheView(splice_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) splice_image=DestroyImage(splice_image); return(splice_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformImage() is a convenience method that behaves like ResizeImage() or % CropImage() but accepts scaling and/or cropping information as a region % geometry specification. If the operation fails, the original image handle % is left as is. % % This should only be used for single images. % % The format of the TransformImage method is: % % MagickBooleanType TransformImage(Image **image,const char *crop_geometry, % const char *image_geometry) % % A description of each parameter follows: % % o image: the image The transformed image is returned as this parameter. % % o crop_geometry: A crop geometry string. This geometry defines a % subregion of the image to crop. % % o image_geometry: An image geometry string. This geometry defines the % final size of the image. % */ /* DANGER: This function destroys what it assumes to be a single image list. If the input image is part of a larger list, all other images in that list will be simply 'lost', not destroyed. Also if the crop generates a list of images only the first image is resized. And finally if the crop succeeds and the resize failed, you will get a cropped image, as well as a 'false' or 'failed' report. This function and should probably be deprecated in favor of direct calls to CropImageToTiles() or ResizeImage(), as appropriate. */ MagickExport MagickBooleanType TransformImage(Image **image, const char *crop_geometry,const char *image_geometry) { Image *resize_image, *transform_image; MagickStatusType flags; RectangleInfo geometry; assert(image != (Image **) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); transform_image=(*image); if (crop_geometry != (const char *) NULL) { Image *crop_image; /* Crop image to a user specified size. */ crop_image=CropImageToTiles(*image,crop_geometry,&(*image)->exception); if (crop_image == (Image *) NULL) transform_image=CloneImage(*image,0,0,MagickTrue,&(*image)->exception); else { transform_image=DestroyImage(transform_image); transform_image=GetFirstImageInList(crop_image); } *image=transform_image; } if (image_geometry == (const char *) NULL) return(MagickTrue); /* Scale image to a user specified size. */ flags=ParseRegionGeometry(transform_image,image_geometry,&geometry, &(*image)->exception); (void) flags; if ((transform_image->columns == geometry.width) && (transform_image->rows == geometry.height)) return(MagickTrue); resize_image=ResizeImage(transform_image,geometry.width,geometry.height, transform_image->filter,transform_image->blur,&(*image)->exception); if (resize_image == (Image *) NULL) return(MagickFalse); transform_image=DestroyImage(transform_image); transform_image=resize_image; *image=transform_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformImages() calls TransformImage() on each image of a sequence. % % The format of the TransformImage method is: % % MagickBooleanType TransformImages(Image **image, % const char *crop_geometry,const char *image_geometry) % % A description of each parameter follows: % % o image: the image The transformed image is returned as this parameter. % % o crop_geometry: A crop geometry string. This geometry defines a % subregion of the image to crop. % % o image_geometry: An image geometry string. This geometry defines the % final size of the image. % */ MagickExport MagickBooleanType TransformImages(Image **images, const char *crop_geometry,const char *image_geometry) { Image *image, **image_list, *transform_images; MagickStatusType status; register ssize_t i; assert(images != (Image **) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); image_list=ImageListToArray(*images,&(*images)->exception); if (image_list == (Image **) NULL) return(MagickFalse); status=MagickTrue; transform_images=NewImageList(); for (i=0; image_list[i] != (Image *) NULL; i++) { image=image_list[i]; status&=TransformImage(&image,crop_geometry,image_geometry); AppendImageToList(&transform_images,image); } *images=transform_images; image_list=(Image **) RelinquishMagickMemory(image_list); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p o s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransposeImage() creates a horizontal mirror image by reflecting the pixels % around the central y-axis while rotating them by 90 degrees. % % The format of the TransposeImage method is: % % Image *TransposeImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TransposeImage(const Image *image,ExceptionInfo *exception) { #define TransposeImageTag "Transpose/Image" CacheView *image_view, *transpose_view; Image *transpose_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); transpose_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); if (transpose_image == (Image *) NULL) return((Image *) NULL); /* Transpose image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); transpose_view=AcquireAuthenticCacheView(transpose_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,transpose_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict transpose_indexes, *magick_restrict indexes; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-y-1, image->columns,1,exception); q=QueueCacheViewAuthenticPixels(transpose_view,(ssize_t) (image->rows-y-1), 0,1,transpose_image->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } (void) memcpy(q,p,(size_t) image->columns*sizeof(*q)); indexes=GetCacheViewAuthenticIndexQueue(image_view); if (indexes != (IndexPacket *) NULL) { transpose_indexes=GetCacheViewAuthenticIndexQueue(transpose_view); if (transpose_indexes != (IndexPacket *) NULL) (void) memcpy(transpose_indexes,indexes,(size_t) image->columns*sizeof(*transpose_indexes)); } if (SyncCacheViewAuthenticPixels(transpose_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,TransposeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } transpose_view=DestroyCacheView(transpose_view); image_view=DestroyCacheView(image_view); transpose_image->type=image->type; page=transpose_image->page; Swap(page.width,page.height); Swap(page.x,page.y); transpose_image->page=page; if (status == MagickFalse) transpose_image=DestroyImage(transpose_image); return(transpose_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s v e r s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransverseImage() creates a vertical mirror image by reflecting the pixels % around the central x-axis while rotating them by 270 degrees. % % The format of the TransverseImage method is: % % Image *TransverseImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TransverseImage(const Image *image,ExceptionInfo *exception) { #define TransverseImageTag "Transverse/Image" CacheView *image_view, *transverse_view; Image *transverse_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); transverse_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); if (transverse_image == (Image *) NULL) return((Image *) NULL); /* Transverse image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); transverse_view=AcquireAuthenticCacheView(transverse_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,transverse_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict transverse_indexes, *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(transverse_view,(ssize_t) (image->rows-y- 1),0,1,transverse_image->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } q+=image->columns; for (x=0; x < (ssize_t) image->columns; x++) *--q=(*p++); indexes=GetCacheViewAuthenticIndexQueue(image_view); if (indexes != (IndexPacket *) NULL) { transverse_indexes=GetCacheViewAuthenticIndexQueue(transverse_view); if (transverse_indexes != (IndexPacket *) NULL) for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(transverse_indexes+image->columns-x-1, GetPixelIndex(indexes+x)); } sync=SyncCacheViewAuthenticPixels(transverse_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransverseImage) #endif proceed=SetImageProgress(image,TransverseImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } transverse_view=DestroyCacheView(transverse_view); image_view=DestroyCacheView(image_view); transverse_image->type=image->type; page=transverse_image->page; Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-transverse_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-transverse_image->rows-page.y); transverse_image->page=page; if (status == MagickFalse) transverse_image=DestroyImage(transverse_image); return(transverse_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r i m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TrimImage() trims pixels from the image edges. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the TrimImage method is: % % Image *TrimImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TrimImage(const Image *image,ExceptionInfo *exception) { RectangleInfo geometry; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); geometry=GetImageBoundingBox(image,exception); if ((geometry.width == 0) || (geometry.height == 0)) { Image *crop_image; crop_image=CloneImage(image,1,1,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(crop_image); crop_image->page=image->page; crop_image->page.x=(-1); crop_image->page.y=(-1); return(crop_image); } geometry.x+=image->page.x; geometry.y+=image->page.y; return(CropImage(image,&geometry,exception)); }
main.c
/* Основной файл для запуска с функцией main. Разбор параметров запуска и основной DataFlow */ // #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #ifndef FIM_H #include "fim.h" #endif void run_overall(char *design_file, char *faults_file, int first_tst_num, int iter_num, int tst_num, int min_el, int max_el, int threshold) { struct fault_descr *fl = NULL; struct circuit *circ = NULL; struct circuit **fcirc = NULL; Abc_Ntk_t **fcircNtk = NULL; // int numthreads; int omp = 0; int maxNode; int flnum = 0; int design_type = -1; int i; int *obvious_faults = NULL; int *pregroup_faults = NULL; int *final_faults = NULL; char *out_file = "identical_fault_pairs.txt"; clock_t t0 = clock(); clock_t t1, t2; /* numthreads = omp_get_num_procs() - 1; if (numthreads < 1) numthreads = 1; */ printf("Reading faults list: %s\n", faults_file); read_fault_list(faults_file, &fl, &flnum); printf("Number of faults: %d\n", flnum); // flnum - содержит число ошибок, все последующие массивы имеют столько элементов printf("Reading design: %s\n", design_file); circ = read_initial_circuit(design_file); maxNode = get_max_node_number(circ); /* Abc_Ntk_t *etalon, *bench, *logic = NULL; bench = Cir_2_Ntk(circ); //CONVERTING TO LOGIC logic = Abc_NtkToLogic(bench); //STRUCTURALLY HASHING etalon = Abc_NtkStrash(logic, 1, 1, 1); // SWEEP OUT Abc_NtkDelete(bench); Abc_NtkDelete(logic); */ print_circuit_statistics(circ); int seq = get_design_type(design_file); t1 = clock(); printf("Reading time: %.2lf sec\n", (double)(((double)t1 - (double)t0) / CLOCKS_PER_SEC)); printf("Inject faults...\n"); fcirc = calloc(flnum, sizeof(struct circuit *)); // #pragma omp parallel num_threads(numthreads) for (i = 0; i < flnum; i++) { fcirc[i] = inject_fault(circ, fl[i], maxNode+1); } t2 = clock(); printf("Inject faults time: %.2lf sec\n", (double)(((double)t2 - (double)t1) / CLOCKS_PER_SEC)); // print_circuit_structure_in_file(fcirc[0], "debug.txt"); // fcirc - массив со схемами и внедренной ошибкой. printf("Create obvious pairs...\n"); // Получить массив очевидных пар идентичных ошибок // В позиции i хранится индекс j - позиция fault'а с которой данная ошибка идентична. // В остальных позициях хранится -1 obvious_faults = get_obvious_pairs(fl, flnum, circ); t1 = clock(); printf("Create obvious pairs time: %.2lf sec\n", (double)(((double)t1 - (double)t2) / CLOCKS_PER_SEC)); printf("Create Ntk circuits from our format...\n"); // Здесь нужен Димин код по генерации Ntk схем из fcirc массива // на выходе Ntk массив fcircNtk // не генерировать их для очевидных ошибок (obvious_faults) // Места где obvious_faults == True, оставляем схему равной NULL, что бы пропускать такие в следующих функциях fcircNtk = generate_ntk_circuits_array(fcirc, flnum, obvious_faults); t2 = clock(); printf("Create Ntk circuits time: %.2lf sec\n", (double)(((double)t2 - (double)t1) / CLOCKS_PER_SEC)); //printf("Detect group of masked faults...\n"); //masked_errors(fcircNtk, flnum, obvious_faults, etalon, seq); printf("Pregroup faults...\n"); // Передается толкьо набор Ntk схем и их количество // pregroup_faults - массив в котором напротив каждой схемы указан ID: группы к которой схема относится (от 0 до N-1 - где N число групп) // для пропущенных схем указан -1 int dima = 2; if (dima == 1) { int group_num = 0; pregroup_faults = gen_pregroup_faults(fcircNtk, flnum, 200, 310, &group_num); } else if (dima == 2) { // SMART GROUPING pregroup_faults = gen_pregroup_faults_iter(fcircNtk, flnum, first_tst_num, tst_num, iter_num, min_el, max_el, threshold); //int group_num = 0; //pregroup_faults = gen_pregroup_faults(fcircNtk, flnum, 100, 310, &group_num); } else { pregroup_faults = calloc(flnum, sizeof(int)); for (i = 0; i < flnum; i++) pregroup_faults[i] = -1; matrix_pregroup_faults(fcircNtk, flnum, 400, pregroup_faults, 200); } t1 = clock(); printf("Pregroup faults time: %.2lf sec\n", (double)(((double)t1 - (double)t2) / CLOCKS_PER_SEC)); //for (int i = 0; i < flnum; i++) //{ // printf("%d) %d ", i, pregroup_faults[i]); //} //printf("\n\n"); printf("All faults...\n"); // Передается набор Ntk схем и их количество, а также массив предразбиения // Возвращается финальный массив c разбиениям по группам if (omp == 1) final_faults = gen_final_faults_omp(pregroup_faults, fcircNtk, flnum, seq); else final_faults = gen_final_faults(pregroup_faults, fcircNtk, flnum, flnum, seq); //for (int i = 0; i < flnum; i++) //{ // printf("%d) %d ", i, final_faults[i]); //} t2 = clock(); printf("All faults time: %.2lf sec\n", (double)(((double)t2 - (double)t1) / CLOCKS_PER_SEC)); printf("Merge obvious faults and final faults arrays...\n"); // printf("Testing: %d %d\n", final_faults[217], final_faults[218]); // В final_faults копируются obvious_faults (простейшая функция на несколько строчек) merge_obvious_and_final_faults(obvious_faults, final_faults, flnum); t1 = clock(); printf("Merge faults time: %.2lf sec\n", (double)(((double)t1 - (double)t2) / CLOCKS_PER_SEC)); printf("Create fault pairs file...\n"); // Записываем результат в файл create_faults_pair_file(out_file, final_faults, fl, flnum); t2 = clock(); printf("Create file time: %.2lf sec\n", (double)(((double)t2 - (double)t1) / CLOCKS_PER_SEC)); printf("Free data...\n"); free_circuit(circ); for (i = 0; i < flnum; i++) { free_circuit(fcirc[i]); } free(obvious_faults); free(pregroup_faults); free(final_faults); free(fcirc); free(fl); free_ntk_circuits(fcircNtk, flnum); t1 = clock(); printf("Overall run time: %.2lf sec\n", (double)(((double)t1 - (double)t0) / CLOCKS_PER_SEC)); } int main(int argc, char * argv[]) { // МИСТИЧЕСКАЯ СТРОЧКА //__________________________________ Extra_ProgressBarStart(stdout, 101); //__________________________________ //int res = check_sch("01_ckt//97.bench", "01_ckt//193.bench", 1); //printf("EQ : %d\n", res); //run_overall("Case_05//design_05.isc", "Case_05//fault_description.txt", 50, 10, 100, 5, 30, 3); if (argc < 2) { printf("Wrong number of command-line arguments.\n"); return 1; } // DEFAULT RUN if (argc == 3) { char *design_file = argv[1]; char *faults_file = argv[2]; int first_tst_num = 50; // число тестов для первого предразбиения int iter_num = 50; // число итераций после которых завершается предгрупировка int tst_num = 50; // число тестов для остальных итераций int min_el = 5; // если число элементов в группе меньше этого значения, группа не рассматривается int max_el = 20; // если все группы состоят из меньшего числа элементов - предгрупировка завершается int threshold = 3; // если такое число итераций подряд группа не разбилась - группа больше не рассматривается run_overall(design_file, faults_file, first_tst_num, iter_num, tst_num, min_el, max_el, threshold); return 0; } // EXPLICIT RUN else if (argc == 9) { char *design_file = argv[1]; char *faults_file = argv[2]; int first_tst_num = atoi(argv[3]); // число тестов для первого предразбиения int iter_num = atoi(argv[4]); // число итераций после которых завершается предгрупировка int tst_num = atoi(argv[5]); // число тестов для остальных итераций int min_el = atoi(argv[6]); // если число элементов в группе меньше этого значения, группа не рассматривается int max_el = atoi(argv[7]); // если все группы состоят из меньшего числа элементов - предгрупировка завершается int threshold = atoi(argv[8]); // если такое число итераций подряд группа не разбилась - группа больше не рассматривается run_overall(design_file, faults_file, first_tst_num, iter_num, tst_num, min_el, max_el, threshold); return 0; } else { //IDENTICAL FAULTS EXHAUSTIVE SEARCH if (atoi(argv[1]) == 0) { if (argc != 4) { printf("Wrong number of command-line arguments.\n"); return 1; } int faults = atoi(argv[2]); char * dir = argv[3]; identical_sch_pairs(faults, dir); return 0; } //SIGNATURES EVALUATION if (atoi(argv[1]) == 1) { if (argc != 5) { printf("Wrong number of command-line arguments.\n"); return 1; } int faults = atoi(argv[2]); int tests = atoi(argv[3]); char * dir = argv[4]; pregroup2(faults, tests, dir); return 0; } //VERIFICATION OF TWO CIRCUITS if (atoi(argv[1]) == 2) { if (argc != 6) { printf("Wrong number of command-line arguments.\n"); return 1; } int sc1 = atoi(argv[2]); int sc2 = atoi(argv[3]); char * dir = argv[4]; int tst_num = atoi(argv[5]); verify(sc1, sc2, dir, tst_num); return 0; } } }
static_general_builder_and_solver.h
// // Project Name: Kratos // Last Modified by: $Author: mpetracca $ // Date: $Date: 2013-06-06 10:37:00 $ // Revision: $Revision: 1.00 $ // // #if !defined(KRATOS_STATIC_GENERAL_BUILDER_AND_SOLVER ) #define KRATOS_STATIC_GENERAL_BUILDER_AND_SOLVER /* System includes */ #include <set> #include <iomanip> #ifdef _OPENMP #define STATIC_GENERAL_BUILDER_AND_SOLVER_USES_OPENMP #endif #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_USES_OPENMP #include <omp.h> #endif #define STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION /* External includes */ #include "boost/smart_ptr.hpp" #include "utilities/timer.h" /* Project includes */ #include "multiscale_application_variables.h" #include "includes/define.h" #include "solving_strategies/builder_and_solvers/builder_and_solver.h" #include "includes/model_part.h" namespace Kratos { /** Short class definition. Detail class definition. Current class provides an implementation for standard builder and solving operations. the RHS is constituted by the unbalanced loads (residual) Degrees of freedom are reordered putting the restrained degrees of freedom at the end of the system ordered in reverse order with respect to the DofSet. Imposition of the dirichlet conditions is naturally dealt with as the residual already contains this information. Calculation of the reactions involves a cost very similiar to the calculation of the total residual */ template<class TSparseSpace,class TDenseSpace,class TLinearSolver> class StaticGeneralBuilderAndSolver : public BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver > { public: KRATOS_CLASS_POINTER_DEFINITION(StaticGeneralBuilderAndSolver); typedef BuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType; typedef typename BaseType::TSchemeType TSchemeType; typedef typename BaseType::TDataType TDataType; 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 typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType; typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType; typedef typename BaseType::NodesArrayType NodesArrayType; typedef typename BaseType::ElementsArrayType ElementsArrayType; typedef typename BaseType::ConditionsArrayType ConditionsArrayType; typedef typename BaseType::ElementsContainerType ElementsContainerType; public: StaticGeneralBuilderAndSolver(typename TLinearSolver::Pointer pNewLinearSystemSolver) : BuilderAndSolver< TSparseSpace, TDenseSpace, TLinearSolver >(pNewLinearSystemSolver) { mTotalBuildTime = 0.0; mTotalSolutionTime = 0.0; mTotalBuildTime_accum = 0.0; mTotalSolutionTime_accum = 0.0; #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION mDoFactorization = false; #endif // STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION } virtual ~StaticGeneralBuilderAndSolver() { } public: void Build(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& b) { double time_begin = Timer::GetTime(); if (!pScheme) KRATOS_THROW_ERROR( std::runtime_error, "No scheme provided!", "" ) //getting the elements from the model ElementsArrayType& pElements = r_model_part.Elements(); //getting the array of the conditions ConditionsArrayType& ConditionsArray = r_model_part.Conditions(); //resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); // assemble all elements #ifndef STATIC_GENERAL_BUILDER_AND_SOLVER_USES_OPENMP //vector containing the localization in the system of the different terms Element::EquationIdVectorType EquationId; //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) { //calculate elemental contribution pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS(A, LHS_Contribution, EquationId); AssembleRHS(b, RHS_Contribution, EquationId); // clean local elemental memory pScheme->CleanMemory(*it); } LHS_Contribution.resize(0, 0, false); RHS_Contribution.resize(0, false); // assemble all conditions for (typename ConditionsArrayType::ptr_iterator it = ConditionsArray.ptr_begin(); it != ConditionsArray.ptr_end(); ++it) { //calculate elemental contribution pScheme->Condition_CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS(A, LHS_Contribution, EquationId); AssembleRHS(b, RHS_Contribution, EquationId); } #else //creating an array of lock variables of the size of the system matrix std::vector< omp_lock_t > lock_array(A.size1()); int A_size = A.size1(); for (int i = 0; i < A_size; i++) omp_init_lock(&lock_array[i]); //create a partition of the element array int number_of_threads = omp_get_max_threads(); vector<unsigned int> element_partition; CreatePartition(number_of_threads, pElements.size(), element_partition); if( this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) { KRATOS_WATCH( number_of_threads ) KRATOS_WATCH( element_partition ) } double start_prod = omp_get_wtime(); #pragma omp parallel for for (int k = 0; k < number_of_threads; k++) { //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); typename ElementsArrayType::ptr_iterator it_begin = pElements.ptr_begin() + element_partition[k]; typename ElementsArrayType::ptr_iterator it_end = pElements.ptr_begin() + element_partition[k + 1]; // assemble all elements for (typename ElementsArrayType::ptr_iterator it = it_begin; it != it_end; ++it) { //calculate elemental contribution #pragma omp critical { pScheme->CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); } //assemble the elemental contribution Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, lock_array); // clean local elemental memory pScheme->CleanMemory(*it); } } vector<unsigned int> condition_partition; CreatePartition(number_of_threads, ConditionsArray.size(), condition_partition); #pragma omp parallel for for (int k = 0; k < number_of_threads; k++) { //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Condition::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); typename ConditionsArrayType::ptr_iterator it_begin = ConditionsArray.ptr_begin() + condition_partition[k]; typename ConditionsArrayType::ptr_iterator it_end = ConditionsArray.ptr_begin() + condition_partition[k + 1]; // assemble all elements for (typename ConditionsArrayType::ptr_iterator it = it_begin; it != it_end; ++it) { //calculate elemental contribution pScheme->Condition_CalculateSystemContributions(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, lock_array); } } double stop_prod = omp_get_wtime(); if (this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) std::cout << "time: " << stop_prod - start_prod << std::endl; for (int i = 0; i < A_size; i++) omp_destroy_lock(&lock_array[i]); if( this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) KRATOS_WATCH( "finished parallel building" ) #endif mTotalBuildTime += Timer::GetTime() - time_begin; #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION mDoFactorization = true; #endif // STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION } void BuildLHS(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A) { double time_begin = Timer::GetTime(); //getting the elements from the model ElementsArrayType& pElements = r_model_part.Elements(); //getting the array of the conditions ConditionsArrayType& ConditionsArray = r_model_part.Conditions(); //resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); // assemble all elements for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) { //calculate elemental contribution pScheme->Calculate_LHS_Contribution(*it, LHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS(A, LHS_Contribution, EquationId); // clean local elemental memory pScheme->CleanMemory(*it); } LHS_Contribution.resize(0, 0, false); // assemble all conditions for (typename ConditionsArrayType::ptr_iterator it = ConditionsArray.ptr_begin(); it != ConditionsArray.ptr_end(); ++it) { //calculate elemental contribution pScheme->Condition_Calculate_LHS_Contribution(*it, LHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS(A, LHS_Contribution, EquationId); } mTotalBuildTime += Timer::GetTime() - time_begin; #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION mDoFactorization = true; #endif // STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION } void BuildLHS_CompleteOnFreeRows(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A) { double time_begin = Timer::GetTime(); //getting the elements from the model ElementsArrayType& pElements = r_model_part.Elements(); //getting the array of the conditions ConditionsArrayType& ConditionsArray = r_model_part.Conditions(); ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); //resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; // assemble all elements for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) { //calculate elemental contribution pScheme->Calculate_LHS_Contribution(*it, LHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS_CompleteOnFreeRows(A, LHS_Contribution, EquationId); // clean local elemental memory pScheme->CleanMemory(*it); } LHS_Contribution.resize(0, 0, false); // assemble all conditions for (typename ConditionsArrayType::ptr_iterator it = ConditionsArray.ptr_begin(); it != ConditionsArray.ptr_end(); ++it) { //calculate elemental contribution pScheme->Condition_Calculate_LHS_Contribution(*it, LHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleLHS_CompleteOnFreeRows(A, LHS_Contribution, EquationId); } mTotalBuildTime += Timer::GetTime() - time_begin; #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION mDoFactorization = true; #endif // STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION } void SystemSolve(TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { double time_begin = Timer::GetTime(); double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION if(mDoFactorization) { BaseType::mpLinearSystemSolver->InitializeSolutionStep(A, Dx, b); BaseType::mpLinearSystemSolver->PerformSolutionStep(A, Dx, b); mDoFactorization = false; } else { BaseType::mpLinearSystemSolver->PerformSolutionStep(A, Dx, b); } #else BaseType::mpLinearSystemSolver->Solve(A, Dx, b); #endif // STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION } else TSparseSpace::SetToZero(Dx); mTotalSolutionTime += Timer::GetTime() - time_begin; } void SystemSolveWithPhysics(TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b, ModelPart& r_model_part) { double time_begin = Timer::GetTime(); double norm_b; if (TSparseSpace::Size(b) != 0) norm_b = TSparseSpace::TwoNorm(b); else norm_b = 0.00; if (norm_b != 0.00) { if(BaseType::mpLinearSystemSolver->AdditionalPhysicalDataIsNeeded() ) BaseType::mpLinearSystemSolver->ProvideAdditionalData(A, Dx, b, BaseType::mDofSet, r_model_part); #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION if(mDoFactorization) { BaseType::mpLinearSystemSolver->InitializeSolutionStep(A, Dx, b); BaseType::mpLinearSystemSolver->PerformSolutionStep(A, Dx, b); mDoFactorization = false; } else { BaseType::mpLinearSystemSolver->PerformSolutionStep(A, Dx, b); } #else BaseType::mpLinearSystemSolver->Solve(A, Dx, b); #endif // STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION } else { TSparseSpace::SetToZero(Dx); if( this->GetEchoLevel() > 0 && r_model_part.GetCommunicator().MyPID() == 0) std::cout << "ATTENTION! setting the RHS to zero!" << std::endl; } mTotalSolutionTime += Timer::GetTime() - time_begin; } void BuildAndSolve(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { bool CalculateReactionsFlag = BaseType::mCalculateReactionsFlag; BaseType::mCalculateReactionsFlag = false; this->Build(pScheme, r_model_part, A, b); BaseType::mCalculateReactionsFlag = CalculateReactionsFlag; SystemSolveWithPhysics(A, Dx, b, r_model_part); } void BuildRHSAndSolve(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { bool CalculateReactionsFlag = BaseType::mCalculateReactionsFlag; BaseType::mCalculateReactionsFlag = false; this->BuildRHS(pScheme, r_model_part, b); BaseType::mCalculateReactionsFlag = CalculateReactionsFlag; SystemSolve(A, Dx, b); } void BuildRHS(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemVectorType& b) { double time_begin = Timer::GetTime(); if (!pScheme) KRATOS_THROW_ERROR( std::runtime_error, "No scheme provided!", "" ) //getting the elements from the model ElementsArrayType& pElements = r_model_part.Elements(); //getting the array of the conditions ConditionsArrayType& ConditionsArray = r_model_part.Conditions(); //resetting to zero the vector of reactions TSparseSpace::SetToZero(*(BaseType::mpReactionsVector)); // assemble all elements #ifndef STATIC_GENERAL_BUILDER_AND_SOLVER_USES_OPENMP //contributions to the system LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0); LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); //vector containing the localization in the system of the different terms Element::EquationIdVectorType EquationId; for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) { //calculate elemental Right Hand Side Contribution pScheme->Calculate_RHS_Contribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } LHS_Contribution.resize(0, 0, false); RHS_Contribution.resize(0, false); // assemble all conditions for (typename ConditionsArrayType::ptr_iterator it = ConditionsArray.ptr_begin(); it != ConditionsArray.ptr_end(); ++it) { //calculate elemental contribution pScheme->Condition_Calculate_RHS_Contribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId); } #else //creating an array of lock variables of the size of the system vector /*std::vector< omp_lock_t > lock_array(b.size());*/ int total_size = b.size(); if (BaseType::mCalculateReactionsFlag) total_size += (*BaseType::mpReactionsVector).size(); std::vector< omp_lock_t > lock_array(total_size); //int b_size = b.size(); for (int i = 0; i < total_size; i++) omp_init_lock(&lock_array[i]); //create a partition of the element array int number_of_threads = omp_get_max_threads(); vector<unsigned int> element_partition; CreatePartition(number_of_threads, pElements.size(), element_partition); if( this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) { KRATOS_WATCH( number_of_threads ) KRATOS_WATCH( element_partition ) } double start_prod = omp_get_wtime(); #pragma omp parallel for for (int k = 0; k < number_of_threads; k++) { //contributions to the system LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); //vector containing the localization in the system of the different //terms Element::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); typename ElementsArrayType::ptr_iterator it_begin = pElements.ptr_begin() + element_partition[k]; typename ElementsArrayType::ptr_iterator it_end = pElements.ptr_begin() + element_partition[k + 1]; // assemble all elements for (typename ElementsArrayType::ptr_iterator it = it_begin; it != it_end; ++it) { //calculate elemental contribution #pragma omp critical { pScheme->Calculate_RHS_Contribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo); } //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId, lock_array); // clean local elemental memory pScheme->CleanMemory(*it); } } vector<unsigned int> condition_partition; CreatePartition(number_of_threads, ConditionsArray.size(), condition_partition); #pragma omp parallel for for (int k = 0; k < number_of_threads; k++) { //contributions to the system LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0); Condition::EquationIdVectorType EquationId; ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); typename ConditionsArrayType::ptr_iterator it_begin = ConditionsArray.ptr_begin() + condition_partition[k]; typename ConditionsArrayType::ptr_iterator it_end = ConditionsArray.ptr_begin() + condition_partition[k + 1]; // assemble all elements for (typename ConditionsArrayType::ptr_iterator it = it_begin; it != it_end; ++it) { //calculate elemental contribution pScheme->Condition_Calculate_RHS_Contribution(*it, RHS_Contribution, EquationId, CurrentProcessInfo); //assemble the elemental contribution AssembleRHS(b, RHS_Contribution, EquationId, lock_array); } } double stop_prod = omp_get_wtime(); if (this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) std::cout << "time: " << stop_prod - start_prod << std::endl; for (int i = 0; i < total_size; i++) omp_destroy_lock(&lock_array[i]); if( this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) { KRATOS_WATCH( "finished parallel building" ) } #endif mTotalBuildTime += Timer::GetTime() - time_begin; } void SetUpDofSet(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part) { KRATOS_TRY; if( this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) std::cout << " Setting up the dofs " << std::endl; ElementsArrayType& pElements = r_model_part.Elements(); Element::DofsVectorType ElementalDofList; ProcessInfo& CurrentProcessInfo = r_model_part.GetProcessInfo(); DofsArrayType Doftemp; BaseType::mDofSet = DofsArrayType(); for (typename ElementsArrayType::ptr_iterator it = pElements.ptr_begin(); it != pElements.ptr_end(); ++it) { pScheme->GetElementalDofList(*it, ElementalDofList, CurrentProcessInfo); for (typename Element::DofsVectorType::iterator i = ElementalDofList.begin(); i != ElementalDofList.end(); ++i) Doftemp.push_back(i->get()); } ConditionsArrayType& pConditions = r_model_part.Conditions(); for (typename ConditionsArrayType::ptr_iterator it = pConditions.ptr_begin(); it != pConditions.ptr_end(); ++it) { pScheme->GetConditionDofList(*it, ElementalDofList, CurrentProcessInfo); for (typename Element::DofsVectorType::iterator i = ElementalDofList.begin(); i != ElementalDofList.end(); ++i) Doftemp.push_back(i->get()); } Doftemp.Unique(); BaseType::mDofSet = Doftemp; if (BaseType::mDofSet.size() == 0) KRATOS_THROW_ERROR( std::logic_error, "No degrees of freedom!", "" ) BaseType::mDofSetIsInitialized = true; if( this->GetEchoLevel() > 2 && r_model_part.GetCommunicator().MyPID() == 0) std::cout << "finished setting up the dofs" << std::endl; KRATOS_CATCH( "" ) } void SetUpSystem(ModelPart& r_model_part) { // Set equation id for degrees of freedom // the free degrees of freedom are positioned at the beginning of the system, // while the fixed one are at the end (in opposite order). // // that means that if the EquationId is greater than "mEquationSystemSize" // the pointed degree of freedom is restrained // int free_id = 0; int fix_id = BaseType::mDofSet.size(); for (typename DofsArrayType::iterator dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) if (dof_iterator->IsFixed()) dof_iterator->SetEquationId(--fix_id); else dof_iterator->SetEquationId(free_id++); BaseType::mEquationSystemSize = fix_id; } void ResizeAndInitializeVectors( typename TSchemeType::Pointer pScheme,TSystemMatrixPointerType& pA, TSystemVectorPointerType& pDx, TSystemVectorPointerType& pb, ModelPart& rModelPart) { KRATOS_TRY if (pA == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemMatrixPointerType pNewA = TSystemMatrixPointerType(new TSystemMatrixType(0, 0)); pA.swap(pNewA); } if (pDx == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewDx = TSystemVectorPointerType(new TSystemVectorType(0)); pDx.swap(pNewDx); } if (pb == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewb = TSystemVectorPointerType(new TSystemVectorType(0)); pb.swap(pNewb); } if (BaseType::mpReactionsVector == NULL) //if the pointer is not initialized initialize it to an empty matrix { TSystemVectorPointerType pNewReactionsVector = TSystemVectorPointerType(new TSystemVectorType(0)); BaseType::mpReactionsVector.swap(pNewReactionsVector); } TSystemMatrixType& A = *pA; TSystemVectorType& Dx = *pDx; TSystemVectorType& b = *pb; //resizing the system vectors and matrix if (A.size1() == 0 || BaseType::GetReshapeMatrixFlag() == true) //if the matrix is not initialized { A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, false); ConstructMatrixStructure(pScheme, A, rModelPart.Elements(), rModelPart.Conditions(), rModelPart.GetProcessInfo()); } else { if (A.size1() != BaseType::mEquationSystemSize || A.size2() != BaseType::mEquationSystemSize) { KRATOS_WATCH( "it should not come here!!!!!!!! ... this is SLOW" ) A.resize(BaseType::mEquationSystemSize, BaseType::mEquationSystemSize, true); ConstructMatrixStructure(pScheme, A, rModelPart.Elements(), rModelPart.Conditions(), rModelPart.GetProcessInfo()); } } if (Dx.size() != BaseType::mEquationSystemSize) Dx.resize(BaseType::mEquationSystemSize, false); if (b.size() != BaseType::mEquationSystemSize) b.resize(BaseType::mEquationSystemSize, false); //if needed resize the vector for the calculation of reactions if (BaseType::mCalculateReactionsFlag == true) { unsigned int ReactionsVectorSize = BaseType::mDofSet.size() - BaseType::mEquationSystemSize; if (BaseType::mpReactionsVector->size() != ReactionsVectorSize) BaseType::mpReactionsVector->resize(ReactionsVectorSize, false); } KRATOS_CATCH( "" ) } void InitializeSolutionStep(ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { mTotalBuildTime = 0.0; mTotalSolutionTime = 0.0; } void FinalizeSolutionStep(ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { mTotalBuildTime_accum += mTotalBuildTime; mTotalSolutionTime_accum += mTotalSolutionTime; if( this->GetEchoLevel() > 0 && r_model_part.GetCommunicator().MyPID() == 0) PromptStatistics(r_model_part.GetProcessInfo()); } void CalculateReactions(typename TSchemeType::Pointer pScheme, ModelPart& r_model_part, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b) { ////refresh RHS to have the correct reactions //this->BuildRHS(pScheme, r_model_part, b); int i; int systemsize = BaseType::mDofSet.size() - TSparseSpace::Size(*BaseType::mpReactionsVector); typename DofsArrayType::ptr_iterator it2; // KRATOS_WATCH( *BaseType::mpReactionsVector ) //updating variables TSystemVectorType& ReactionsVector = *BaseType::mpReactionsVector; int num=1; for (it2 = BaseType::mDofSet.ptr_begin(); it2 != BaseType::mDofSet.ptr_end(); ++it2) { if ((*it2)->IsFixed()) { i = (*it2)->EquationId(); i -= systemsize; (*it2)->GetSolutionStepReactionValue() = ReactionsVector[i]; } num++; } } void Clear() { this->mDofSet = DofsArrayType(); if (this->mpReactionsVector != NULL) TSparseSpace::Clear((this->mpReactionsVector)); this->mpLinearSystemSolver->Clear(); } virtual int Check(ModelPart& r_model_part) { return 0; } protected: virtual void ConstructMatrixStructure( typename TSchemeType::Pointer pScheme,TSystemMatrixType& A, ModelPart& rModelPart) { std::size_t equation_size = A.size1(); std::vector<std::vector<std::size_t> > indices(equation_size); Element::EquationIdVectorType ids(3, 0); for (typename ElementsContainerType::iterator i_element = rModelPart.ElementsBegin(); i_element != rModelPart.ElementsEnd(); i_element++) { pScheme->EquationId( *(i_element.base()) , ids, CurrentProcessInfo); for (std::size_t i = 0; i < ids.size(); i++) if (ids[i] < equation_size) { std::vector<std::size_t>& row_indices = indices[ids[i]]; for (std::size_t j = 0; j < ids.size(); j++) if (ids[j] < equation_size) { AddUnique(row_indices, ids[j]); } } } for (typename ConditionsArrayType::iterator i_condition = rModelPart.ConditionsBegin(); i_condition != rModelPart.ConditionsEnd(); i_condition++) { pScheme->Condition_EquationId( *(i_condition.base()), ids, CurrentProcessInfo); for (std::size_t i = 0; i < ids.size(); i++) if (ids[i] < equation_size) { std::vector<std::size_t>& row_indices = indices[ids[i]]; for (std::size_t j = 0; j < ids.size(); j++) if (ids[j] < equation_size) { AddUnique(row_indices, ids[j]); } } } //allocating the memory needed int data_size = 0; for (std::size_t i = 0; i < indices.size(); i++) { data_size += indices[i].size(); } A.reserve(data_size, false); //filling with zero the matrix (creating the structure) Timer::Start("MatrixStructure"); #ifndef STATIC_GENERAL_BUILDER_AND_SOLVER_USES_OPENMP for (std::size_t i = 0; i < indices.size(); i++) { std::vector<std::size_t>& row_indices = indices[i]; std::sort(row_indices.begin(), row_indices.end()); for (std::vector<std::size_t>::iterator it = row_indices.begin(); it != row_indices.end(); it++) { A.push_back(i, *it, 0.00); } row_indices.clear(); } #else int number_of_threads = omp_get_max_threads(); vector<unsigned int> matrix_partition; CreatePartition(number_of_threads, indices.size(), matrix_partition); if (this->GetEchoLevel() > 2) { KRATOS_WATCH( matrix_partition ) } for (int k = 0; k < number_of_threads; k++) { #pragma omp parallel if (omp_get_thread_num() == k) { for (std::size_t i = matrix_partition[k]; i < matrix_partition[k + 1]; i++) { std::vector<std::size_t>& row_indices = indices[i]; std::sort(row_indices.begin(), row_indices.end()); for (std::vector<std::size_t>::iterator it = row_indices.begin(); it != row_indices.end(); it++) { A.push_back(i, *it, 0.00); } row_indices.clear(); } } } #endif Timer::Stop("MatrixStructure"); } void AssembleLHS(TSystemMatrixType& A, LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } void AssembleRHS(TSystemVectorType& b, LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId) { unsigned int local_size = RHS_Contribution.size(); if (BaseType::mCalculateReactionsFlag == false) //if we don't need to calculate reactions { for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //on "free" DOFs { // ASSEMBLING THE SYSTEM VECTOR b[i_global] += RHS_Contribution[i_local]; } } } else //when the calculation of reactions is needed { TSystemVectorType& ReactionsVector = *BaseType::mpReactionsVector; for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //on "free" DOFs { // ASSEMBLING THE SYSTEM VECTOR b[i_global] += RHS_Contribution[i_local]; } else //on "fixed" DOFs { // Assembling the Vector of REACTIONS ReactionsVector[i_global - BaseType::mEquationSystemSize] -= RHS_Contribution[i_local]; } } } } void AssembleLHS_CompleteOnFreeRows(TSystemMatrixType& A, LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { for (unsigned int j_local = 0; j_local < local_size; j_local++) { int j_global = EquationId[j_local]; A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } } } inline void AddUnique(std::vector<std::size_t>& v, const std::size_t& candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while (i != endit && (*i) != candidate) { i++; } if (i == endit) { v.push_back(candidate); } } 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; } private: double mTotalBuildTime; double mTotalSolutionTime; double mTotalBuildTime_accum; double mTotalSolutionTime_accum; unsigned int mNumberOfFreeDofs; #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION bool mDoFactorization; #endif // STATIC_GENERAL_BUILDER_AND_SOLVER_OPTIMIZE_SOLUTION private: inline void PromptStatistics(const ProcessInfo & rCurrentProcessInfo) { std::stringstream ss; ss << " Total Build Time: \t" << mTotalBuildTime << " seconds" << std::endl; ss << " Total Solution Time: \t" << mTotalSolutionTime << " seconds" << std::endl; int nit = rCurrentProcessInfo[NL_ITERATION_NUMBER]; double dnit = nit == 0.0 ? 1.0 : (double)nit; ss << " Number of Iterations:\t" << nit << std::endl; ss << " Mean Build Time: \t" << mTotalBuildTime / dnit << " seconds" << std::endl; ss << " Mean Solution Time: \t" << mTotalSolutionTime / dnit << " seconds" << std::endl; ss << " Total Build Time from start: " << mTotalBuildTime_accum << " seconds" << std::endl; ss << " Total Solution Time from start: " << mTotalSolutionTime_accum << " seconds" << std::endl; ss << " Total Time from start: " << mTotalSolutionTime_accum + mTotalBuildTime_accum << " seconds" << std::endl; std::cout << ss.str(); } #ifdef STATIC_GENERAL_BUILDER_AND_SOLVER_USES_OPENMP void Assemble(TSystemMatrixType& A, TSystemVectorType& b, const LocalSystemMatrixType& LHS_Contribution, const LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, std::vector< omp_lock_t >& lock_array) { unsigned int local_size = RHS_Contribution.size(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { omp_set_lock(&lock_array[i_global]); b[i_global] += RHS_Contribution(i_local); for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) { A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } omp_unset_lock(&lock_array[i_global]); } } } void AssembleLHS(TSystemMatrixType& A, const LocalSystemMatrixType& LHS_Contribution, Element::EquationIdVectorType& EquationId, std::vector< omp_lock_t >& lock_array) { unsigned int local_size = LHS_Contribution.size1(); for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { omp_set_lock(&lock_array[i_global]); for (unsigned int j_local = 0; j_local < local_size; j_local++) { unsigned int j_global = EquationId[j_local]; if (j_global < BaseType::mEquationSystemSize) { A(i_global, j_global) += LHS_Contribution(i_local, j_local); } } omp_unset_lock(&lock_array[i_global]); } } } void AssembleRHS(TSystemVectorType& b, const LocalSystemVectorType& RHS_Contribution, Element::EquationIdVectorType& EquationId, std::vector< omp_lock_t >& lock_array) { unsigned int local_size = RHS_Contribution.size(); if (BaseType::mCalculateReactionsFlag == false) { for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) { omp_set_lock(&lock_array[i_global]); b[i_global] += RHS_Contribution(i_local); omp_unset_lock(&lock_array[i_global]); } } } else { TSystemVectorType& ReactionsVector = *BaseType::mpReactionsVector; for (unsigned int i_local = 0; i_local < local_size; i_local++) { unsigned int i_global = EquationId[i_local]; if (i_global < BaseType::mEquationSystemSize) //on "free" DOFs { omp_set_lock(&lock_array[i_global]); b[i_global] += RHS_Contribution[i_local]; omp_unset_lock(&lock_array[i_global]); } else //on "fixed" DOFs { // bug fixed: lock_array now has dimension(=num_free + num_fixed) if // calculate reaction is needed omp_set_lock(&lock_array[i_global/* - BaseType::mEquationSystemSize*/]); ReactionsVector[i_global - BaseType::mEquationSystemSize] -= RHS_Contribution[i_local]; omp_unset_lock(&lock_array[i_global/* - BaseType::mEquationSystemSize*/]); } } } } #endif }; } #endif /* KRATOS_STATIC_GENERAL_BUILDER_AND_SOLVER defined */
util.c
#include <stdio.h> #include <stdlib.h> #include <math.h> void zero4d(int dim1, int dim2, int dim3, int dim4, double * a) { int i; #pragma omp parallel for private(i) schedule(static) for (i=0;i<(dim1*dim2*dim3*dim4);i++) a[i] = 0.0; return; } void rand4d(int dim1, int dim2, int dim3, int dim4, double * a) { printf("begin rand4d\n"); for (int i=0;i<(dim1*dim2*dim3*dim4);i++) a[i] = (double) rand()/RAND_MAX; printf(" end rand4d\n"); fflush(stdout); return; } void copy4d(int dim1, int dim2, int dim3, int dim4, double * in, double * out) { for (int i=0;i<(dim1*dim2*dim3*dim4);i++) out[i] = in[i]; return; } void init4d(int dim1, int dim2, int dim3, int dim4, double * a) { double shift1, shift2, shift3; if (dim1<100 && dim2<100 && dim3<100 && dim4<100) shift1 = 0.001; else shift1 = 0.0001; shift2 = shift1*shift1; shift3 = shift2*shift1; for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l] = (double) (i + j*shift1 + k*shift2 + l*shift3); return; } double diff4d(int dim1, int dim2, int dim3, int dim4, double * a, double * b) { double error = 0.0; for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { error += fabs( a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l] - b[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); } return error; } void print4d(int dim1, int dim2, int dim3, int dim4, double * a) { for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { printf("[%2d,%2d,%2d,%2d] = ",i,j,k,l); printf("%20.14lf ",a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("\n"); } return; } void print4d2(int dim1, int dim2, int dim3, int dim4, double * a, double * b) { for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { printf("[%2d,%2d,%2d,%2d] = ",i,j,k,l); printf("%20.14lf ",a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("%20.14lf ",b[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("\n"); } return; } void print4d3(int dim1, int dim2, int dim3, int dim4, double * a, double * b, double * c) { for (int i=0;i<dim1;i++) for (int j=0;j<dim2;j++) for (int k=0;k<dim3;k++) for (int l=0;l<dim4;l++) { printf("[%2d,%2d,%2d,%2d] = ",i,j,k,l); printf("%20.14lf ",a[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("%20.14lf ",b[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("%20.14lf ",c[i*dim2*dim3*dim4 + j*dim3*dim4 + k*dim4 + l]); printf("\n"); } return; }
imd_forces_eam2.c
/****************************************************************************** * * IMD -- The ITAP Molecular Dynamics Program * * Copyright 1996-2004 Institute for Theoretical and Applied Physics, * University of Stuttgart, D-70550 Stuttgart * ******************************************************************************/ /****************************************************************************** * * do_forces for ASYMPOT, and second force loop for EAM2 * ******************************************************************************/ /****************************************************************************** * $Revision$ * $Date$ ******************************************************************************/ #include "imd.h" #include "potaccess.h" /****************************************************************************** * * special version of do_forces for asymmetric core potentials * ******************************************************************************/ #ifdef ASYMPOT void do_forces(cell *p, cell *q, vektor pbc, real *Epot, real *Virial, real *Vir_xx, real *Vir_yy, real *Vir_zz, real *Vir_yz, real *Vir_zx, real *Vir_xy) { int i,j,k; vektor d; vektor tmp_d; vektor force; real r2, rho_h; real tmp_virial; real pot_zwi, pot_grad; int col1, col2, is_short=0, inc = ntypes * ntypes; int jstart, q_typ, p_typ; real *qptr, *pfptr, *qfptr, *qpdptr, *ppdptr, *qpoptr, *ppoptr; tmp_virial = 0.0; /* for each atom in first cell */ for (i=0; i<p->n; ++i) { tmp_d.x = ORT(p,i,X) - pbc.x; tmp_d.y = ORT(p,i,Y) - pbc.y; tmp_d.z = ORT(p,i,Z) - pbc.z; p_typ = SORTE(p,i); jstart = (((p==q) && (pbc.x==0) && (pbc.y==0) && (pbc.z==0)) ? i+1 : 0); qptr = &ORT(q,jstart,X); /* for each atom in neighbouring cell */ for (j = jstart; j < q->n; ++j) { /* calculate distance */ d.x = *qptr - tmp_d.x; ++qptr; d.y = *qptr - tmp_d.y; ++qptr; d.z = *qptr - tmp_d.z; ++qptr; q_typ = SORTE(q,j); col1 = p_typ * ntypes + q_typ; col2 = q_typ * ntypes + p_typ; r2 = SPROD(d,d); #ifdef DEBUG if (0==r2) { char msgbuf[256]; sprintf(msgbuf, "Distance is zero between particles %d and %d!\n", NUMMER(p,i), NUMMER(q,j)); error(msgbuf); } #endif /* compute pair interactions, first on particle i */ if (r2 <= pair_pot.end[col1]) { PAIR_INT(pot_zwi, pot_grad, pair_pot, col1, inc, r2, is_short) /* store force in temporary variable */ force.x = d.x * pot_grad; force.y = d.y * pot_grad; force.z = d.z * pot_grad; /* accumulate forces */ pfptr = &KRAFT(p,i,X); *pfptr += force.x; *(++pfptr) += force.y; *(++pfptr) += force.z; /* the first half of the pot. energy of this bond */ pot_zwi *= 0.5; *Epot += pot_zwi; POTENG(p,i) += pot_zwi; /* for the virial, we take the mean forces on the two particles */ force.x *= 0.5; force.y *= 0.5; force.z *= 0.5; pot_grad *= 0.5; tmp_virial -= r2 * pot_grad; #ifdef STRESS_TENS if (do_press_calc) { PRESSTENS(p,i,xx) -= d.x * force.x; PRESSTENS(p,i,yy) -= d.y * force.y; PRESSTENS(p,i,zz) -= d.z * force.z; PRESSTENS(p,i,yz) -= d.y * force.z; PRESSTENS(p,i,zx) -= d.z * force.x; PRESSTENS(p,i,xy) -= d.x * force.y; } #endif } /* compute pair interactions, now on particle j */ if (r2 <= pair_pot.end[col2]) { if (col1!=col2) { PAIR_INT(pot_zwi, pot_grad, pair_pot, col2, inc, r2, is_short); } /* store force in temporary variable */ force.x = d.x * pot_grad; force.y = d.y * pot_grad; force.z = d.z * pot_grad; /* accumulate forces */ qfptr = &KRAFT(q,j,X); *qfptr -= force.x; *(++qfptr) -= force.y; *(++qfptr) -= force.z; /* the second half of the pot. energy of this bond */ pot_zwi *= 0.5; *Epot += pot_zwi; POTENG(q,j) += pot_zwi; /* for the virial, we take the mean forces on the two particles */ force.x *= 0.5; force.y *= 0.5; force.z *= 0.5; pot_grad *= 0.5; tmp_virial -= r2 * pot_grad; #ifdef STRESS_TENS if (do_press_calc) { PRESSTENS(q,j,xx) -= d.x * force.x; PRESSTENS(q,j,yy) -= d.y * force.y; PRESSTENS(q,j,zz) -= d.z * force.z; PRESSTENS(q,j,yz) -= d.y * force.z; PRESSTENS(q,j,zx) -= d.z * force.x; PRESSTENS(q,j,xy) -= d.x * force.y; } #endif } /* compute host electron density */ if (r2 < rho_h_tab.end[col1]) { VAL_FUNC(rho_h, rho_h_tab, col1, inc, r2, is_short); EAM_RHO(p,i) += rho_h; #ifdef EEAM EAM_P(p,i) += rho_h*rho_h; #endif } if (r2 < rho_h_tab.end[col2]) { if (col1!=col2) { VAL_FUNC(rho_h, rho_h_tab, col2, inc, r2, is_short); } EAM_RHO(q,j) += rho_h; #ifdef EEAM EAM_P(q,j) += rho_h*rho_h; #endif } } /* for j */ } /* for i */ if (is_short==1) { printf("\nproc:%d,steps:%d,Short distance\n",myid,steps); } *Virial += tmp_virial; } #endif /* ASYMPOT */ /****************************************************************************** * * compute embedding energy and its derivative for all atoms * ******************************************************************************/ void do_embedding_energy(void) { int k; #ifdef _OPENMP #pragma omp parallel for schedule(runtime) reduction(+:tot_pot_energy) #endif for (k=0; k<NCELLS; k++) { int i, idummy=0; real pot; cell *p; p = CELLPTR(k); for (i=0; i<p->n; i++) { PAIR_INT( pot, EAM_DF(p,i), embed_pot, SORTE(p,i), ntypes, EAM_RHO(p,i), idummy); POTENG(p,i) += pot; tot_pot_energy += pot; #ifdef EEAM PAIR_INT( pot, EAM_DM(p,i), emod_pot, SORTE(p,i), ntypes, EAM_P(p,i), idummy); POTENG(p,i) += pot; tot_pot_energy += pot; #endif } } } /****************************************************************************** * * second force loop, calculates the force and the energy * caused by the embedding electron density * uses Phi(r2), Rho(r2), F(rho) and its derivatives * also used for EEAM * ******************************************************************************/ void do_forces_eam2(cell *p, cell *q, vektor pbc, real *Virial, real *Vir_xx, real *Vir_yy, real *Vir_zz, real *Vir_yz, real *Vir_zx, real *Vir_xy) { int i,j,k,same_cell; vektor d, tmp_d, force; real r2; int is_short=0, idummy=0; int jstart, q_typ, p_typ; int col1, col2, inc=ntypes*ntypes; real *qptr, *pfptr, *qfptr, *qpdptr, *ppdptr, *qpoptr, *ppoptr; real tmp_virial=0.0; real eam2_force, rho_i_strich, rho_j_strich; #ifdef EEAM real rho_i, rho_j; #endif /* for each atom in first cell */ for (i=0; i<p->n; ++i) { tmp_d.x = ORT(p,i,X) - pbc.x; tmp_d.y = ORT(p,i,Y) - pbc.y; tmp_d.z = ORT(p,i,Z) - pbc.z; p_typ = SORTE(p,i); same_cell = ((p==q) && (pbc.x==0) && (pbc.y==0) && (pbc.z==0)); jstart = (same_cell ? i+1 : 0); qptr = &ORT(q,jstart,X); /* for each atom in neighbouring cell */ for (j=jstart; j<q->n; ++j) { /* calculate distance */ d.x = *qptr - tmp_d.x; ++qptr; d.y = *qptr - tmp_d.y; ++qptr; d.z = *qptr - tmp_d.z; ++qptr; q_typ = SORTE(q,j); r2 = SPROD(d,d); col1 = q_typ * ntypes + p_typ; col2 = p_typ * ntypes + q_typ; if ((r2 < rho_h_tab.end[col1]) || (r2 < rho_h_tab.end[col2])) { /* take care: particle i gets its rho from particle j. This is tabulated in column p_typ*ntypes+q_typ. Here we need the giving part from column q_typ*ntypes+p_typ. */ /* rho_strich_i(r_ij) */ #ifndef EEAM DERIV_FUNC(rho_i_strich, rho_h_tab, col1, inc, r2, is_short); #else /* rho_strich_i(r_ij) and rho_i(r_ij) */ PAIR_INT(rho_i, rho_i_strich, rho_h_tab, col1, inc, r2, is_short); #endif /* rho_strich_j(r_ij) */ if (col1==col2) { rho_j_strich = rho_i_strich; #ifdef EEAM rho_j = rho_i; #endif } else { #ifndef EEAM DERIV_FUNC(rho_j_strich, rho_h_tab, col2, inc, r2, is_short); #else PAIR_INT(rho_j, rho_j_strich, rho_h_tab, col2, inc, r2, is_short); #endif } /* put together (dF_i and dF_j are by 0.5 too big) */ eam2_force = 0.5 * (EAM_DF(p,i)*rho_j_strich+EAM_DF(q,j)*rho_i_strich); #ifdef EEAM /* 0.5 times 2 from derivative simplified to 1 */ eam2_force += (EAM_DM(p,i) * rho_j * rho_j_strich + + EAM_DM(q,j) * rho_i * rho_i_strich); #endif /* store force in temporary variable */ force.x = d.x * eam2_force; force.y = d.y * eam2_force; force.z = d.z * eam2_force; /* accumulate forces */ pfptr = &KRAFT(p,i,X); qfptr = &KRAFT(q,j,X); *pfptr += force.x; *qfptr -= force.x; *(++pfptr) += force.y; *(++qfptr) -= force.y; *(++pfptr) += force.z; *(++qfptr) -= force.z; tmp_virial -= r2 * eam2_force; #ifdef STRESS_TENS if (do_press_calc) { /* avoid double counting of the virial */ force.x *= 0.5; force.y *= 0.5; force.z *= 0.5; PRESSTENS(p,i,xx) -= d.x * force.x; PRESSTENS(p,i,yy) -= d.y * force.y; PRESSTENS(p,i,zz) -= d.z * force.z; PRESSTENS(p,i,yz) -= d.y * force.z; PRESSTENS(p,i,zx) -= d.z * force.x; PRESSTENS(p,i,xy) -= d.x * force.y; PRESSTENS(q,j,xx) -= d.x * force.x; PRESSTENS(q,j,yy) -= d.y * force.y; PRESSTENS(q,j,zz) -= d.z * force.z; PRESSTENS(q,j,yz) -= d.y * force.z; PRESSTENS(q,j,zx) -= d.z * force.x; PRESSTENS(q,j,xy) -= d.x * force.y; } #endif } /* if in the cutoff range */ } /* for j */ } /* for i */ /* print warning if short distance occurred */ /*MY MOD: Hier stand fprintf(stderr,...) */ if (is_short==1) printf("\nproc:%d,steps:%d,Short distance!\n",myid,steps); *Virial += tmp_virial; } /* do_forces_eam2 */
GB_unop__identity_int8_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int8_fp32) // op(A') function: GB (_unop_tran__identity_int8_fp32) // C type: int8_t // A type: float // cast: int8_t cij = GB_cast_to_int8_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int8_t z = GB_cast_to_int8_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int8_t z = GB_cast_to_int8_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT8 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int8_fp32) ( int8_t *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; int8_t z = GB_cast_to_int8_t ((double) (aij)) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; int8_t z = GB_cast_to_int8_t ((double) (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int8_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_select_phase2.c
//------------------------------------------------------------------------------ // GB_select_phase2: C=select(A,thunk) //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ { //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; // if A is iso and the op is user-defined, Ax [0] is passed to the user // selectop const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ; size_t asize = A->type->size ; int64_t avlen = A->vlen ; int64_t avdim = A->vdim ; // if A is bitmap, the bitmap selector is always used instead ASSERT (!GB_IS_BITMAP (A)) ; #ifndef GB_DIAG_SELECTOR // if A is full, all opcodes except DIAG use the bitmap selector instead ASSERT (!GB_IS_FULL (A)) ; #endif const int64_t *restrict kfirst_Aslice = A_ek_slicing ; const int64_t *restrict klast_Aslice = A_ek_slicing + A_ntasks ; const int64_t *restrict pstart_Aslice = A_ek_slicing + A_ntasks * 2 ; //-------------------------------------------------------------------------- // C = select (A) //-------------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(A_nthreads) schedule(dynamic,1) for (tid = 0 ; tid < A_ntasks ; tid++) { // if kfirst > klast then task tid does no work at all int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; //---------------------------------------------------------------------- // selection from vectors kfirst to klast //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of A(:,k) to be operated on by this task //------------------------------------------------------------------ int64_t pA_start, pA_end, pC ; GB_get_pA_and_pC (&pA_start, &pA_end, &pC, tid, k, kfirst, klast, pstart_Aslice, Cp_kfirst, Cp, avlen, Ap, avlen) ; //------------------------------------------------------------------ // compact Ai and Ax [pA_start ... pA_end-1] into Ci and Cx //------------------------------------------------------------------ #if defined ( GB_ENTRY_SELECTOR ) int64_t j = GBH (Ah, k) ; for (int64_t pA = pA_start ; pA < pA_end ; pA++) { // A is never full; that case is now handled by the // bitmap selector instead. ASSERT (Ai != NULL) ; int64_t i = Ai [pA] ; GB_TEST_VALUE_OF_ENTRY (keep, pA) ; if (keep) { ASSERT (pC >= Cp [k] && pC < Cp [k+1]) ; Ci [pC] = i ; // Cx [pC] = Ax [pA] ; GB_SELECT_ENTRY (Cx, pC, Ax, pA) ; pC++ ; } } #elif defined ( GB_TRIL_SELECTOR ) || \ defined ( GB_ROWGT_SELECTOR ) // keep Zp [k] to pA_end-1 int64_t p = GB_IMAX (Zp [k], pA_start) ; int64_t mynz = pA_end - p ; if (mynz > 0) { // A and C are both sparse or hypersparse ASSERT (pA_start <= p && p + mynz <= pA_end) ; ASSERT (pC >= Cp [k] && pC + mynz <= Cp [k+1]) ; ASSERT (Ai != NULL) ; memcpy (Ci +pC, Ai +p, mynz*sizeof (int64_t)) ; #if !GB_ISO_SELECT memcpy (Cx +pC*asize, Ax +p*asize, mynz*asize) ; #endif } #elif defined ( GB_TRIU_SELECTOR ) || \ defined ( GB_ROWLE_SELECTOR ) // keep pA_start to Zp[k]-1 int64_t p = GB_IMIN (Zp [k], pA_end) ; int64_t mynz = p - pA_start ; if (mynz > 0) { // A and C are both sparse or hypersparse ASSERT (pC >= Cp [k] && pC + mynz <= Cp [k+1]) ; ASSERT (Ai != NULL) ; memcpy (Ci +pC, Ai +pA_start, mynz*sizeof (int64_t)) ; #if !GB_ISO_SELECT memcpy (Cx +pC*asize, Ax +pA_start*asize, mynz*asize) ; #endif } #elif defined ( GB_DIAG_SELECTOR ) // task that owns the diagonal entry does this work // A can be sparse or full, but not bitmap int64_t p = Zp [k] ; if (pA_start <= p && p < pA_end) { ASSERT (pC >= Cp [k] && pC + 1 <= Cp [k+1]) ; Ci [pC] = GBI (Ai, p, avlen) ; #if !GB_ISO_SELECT memcpy (Cx +pC*asize, Ax +p*asize, asize) ; #endif } #elif defined ( GB_OFFDIAG_SELECTOR ) || \ defined ( GB_ROWINDEX_SELECTOR ) // keep pA_start to Zp[k]-1 int64_t p = GB_IMIN (Zp [k], pA_end) ; int64_t mynz = p - pA_start ; if (mynz > 0) { // A and C are both sparse or hypersparse ASSERT (pC >= Cp [k] && pC + mynz <= Cp [k+1]) ; ASSERT (Ai != NULL) ; memcpy (Ci +pC, Ai +pA_start, mynz*sizeof (int64_t)) ; #if !GB_ISO_SELECT memcpy (Cx +pC*asize, Ax +pA_start*asize, mynz*asize) ; #endif pC += mynz ; } // keep Zp[k]+1 to pA_end-1 p = GB_IMAX (Zp [k]+1, pA_start) ; mynz = pA_end - p ; if (mynz > 0) { // A and C are both sparse or hypersparse ASSERT (pA_start <= p && p < pA_end) ; ASSERT (pC >= Cp [k] && pC + mynz <= Cp [k+1]) ; ASSERT (Ai != NULL) ; memcpy (Ci +pC, Ai +p, mynz*sizeof (int64_t)) ; #if !GB_ISO_SELECT memcpy (Cx +pC*asize, Ax +p*asize, mynz*asize) ; #endif } #endif } } }
GB_binop__max_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__max_int8) // A.*B function (eWiseMult): GB (_AemultB_01__max_int8) // A.*B function (eWiseMult): GB (_AemultB_02__max_int8) // A.*B function (eWiseMult): GB (_AemultB_03__max_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__max_int8) // A*D function (colscale): GB (_AxD__max_int8) // D*A function (rowscale): GB (_DxB__max_int8) // C+=B function (dense accum): GB (_Cdense_accumB__max_int8) // C+=b function (dense accum): GB (_Cdense_accumb__max_int8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__max_int8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__max_int8) // C=scalar+B GB (_bind1st__max_int8) // C=scalar+B' GB (_bind1st_tran__max_int8) // C=A+scalar GB (_bind2nd__max_int8) // C=A'+scalar GB (_bind2nd_tran__max_int8) // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = GB_IMAX (aij, bij) #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,A_iso) \ int8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // 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,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMAX (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MAX || GxB_NO_INT8 || GxB_NO_MAX_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__max_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__max_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__max_int8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__max_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__max_int8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__max_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 *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__max_int8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__max_int8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__max_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__max_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__max_int8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__max_int8) ( 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 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 < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMAX (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__max_int8) ( 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 ; 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++) { if (!GBB (Ab, p)) continue ; int8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMAX (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMAX (x, aij) ; \ } GrB_Info GB (_bind1st_tran__max_int8) ( 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 \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_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) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMAX (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__max_int8) ( 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 int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp.c
#include "stdio.h" int main() { #pragma omp parallel { printf("Hello, world.\n"); } return 0; }
omp_hello.c
/****************************************************************************** * FILE: omp_hello.c * DESCRIPTION: * OpenMP Example - Hello World - C/C++ Version * In this simple example, the master thread forks a parallel region. * All threads in the team obtain their unique thread number and print it. * The master thread only prints the total number of threads. Two OpenMP * library routines are used to obtain the number of threads and each * thread's number. * AUTHOR: Blaise Barney 5/99 * LAST REVISED: 04/06/05 ******************************************************************************/ #include <omp.h> #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int nthreads, tid; nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); /* 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 */ }
MatrixFreeSolver.h
#ifndef __MatrixFreeSolver_H__ #define __MatrixFreeSolver_H__ #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/Sparse> using SystemMatrixType = Eigen::SparseMatrix<Real>; namespace SPH { class MatrixReplacement; } namespace Eigen { namespace internal { template<> struct traits<SPH::MatrixReplacement> : public Eigen::internal::traits<SystemMatrixType> {}; } } namespace SPH { /** Replacement of the matrix in the linear system which is required for a * matrix-free solver. */ class MatrixReplacement : public Eigen::EigenBase<MatrixReplacement> { public: // Required typedefs, constants, and method: typedef Real Scalar; typedef Real RealScalar; typedef int StorageIndex; typedef void(*MatrixVecProdFct) (const Real*, Real*, void *); enum { ColsAtCompileTime = Eigen::Dynamic, MaxColsAtCompileTime = Eigen::Dynamic, IsRowMajor = false }; Index rows() const { return m_dim; } Index cols() const { return m_dim; } template<typename Rhs> Eigen::Product<MatrixReplacement, Rhs, Eigen::AliasFreeProduct> operator*(const Eigen::MatrixBase<Rhs>& x) const { return Eigen::Product<MatrixReplacement, Rhs, Eigen::AliasFreeProduct>(*this, x.derived()); } MatrixReplacement(const unsigned int dim, MatrixVecProdFct fct, void *userData) : m_dim(dim), m_matrixVecProdFct(fct), m_userData(userData) {} void * getUserData() { return m_userData; } MatrixVecProdFct getMatrixVecProdFct() { return m_matrixVecProdFct; } protected: unsigned int m_dim; void *m_userData; /** matrix vector product callback */ MatrixVecProdFct m_matrixVecProdFct; }; /** Matrix-free Jacobi preconditioner */ template <typename _Scalar> class JacobiPreconditioner { public: typedef typename SystemMatrixType::StorageIndex StorageIndex; typedef void(*DiagonalMatrixElementFct) (const unsigned int, Real&, void *); enum { ColsAtCompileTime = Eigen::Dynamic, MaxColsAtCompileTime = Eigen::Dynamic }; JacobiPreconditioner() {} void init(const unsigned int dim, DiagonalMatrixElementFct fct, void *userData) { m_dim = dim; m_diagonalElementFct = fct; m_userData = userData; } Eigen::Index rows() const { return m_dim; } Eigen::Index cols() const { return m_dim; } Eigen::ComputationInfo info() { return Eigen::Success; } template<typename MatType> JacobiPreconditioner& analyzePattern(const MatType&) { return *this; } template<typename MatType> JacobiPreconditioner& factorize(const MatType& mat) { return *this; } template<typename MatType> JacobiPreconditioner& compute(const MatType& mat) { m_invDiag.resize(m_dim); #pragma omp parallel default(shared) { #pragma omp for schedule(static) for (int i = 0; i < (int)m_dim; i++) { Real res; m_diagonalElementFct(i, res, m_userData); m_invDiag[i] = 1.0 / res; } } return *this; } template<typename Rhs, typename Dest> void _solve_impl(const Rhs& b, Dest& x) const { x = m_invDiag.array() * b.array(); } template<typename Rhs> inline const Eigen::Solve<JacobiPreconditioner, Rhs> solve(const Eigen::MatrixBase<Rhs>& b) const { return Eigen::Solve<JacobiPreconditioner, Rhs>(*this, b.derived()); } protected: unsigned int m_dim; /** diagonal matrix element callback */ DiagonalMatrixElementFct m_diagonalElementFct; void *m_userData; Eigen::VectorXd m_invDiag; }; } namespace Eigen { namespace internal { using namespace SPH; /** Implementation of the matrix-free matrix vector product */ template<typename Rhs> struct generic_product_impl<MatrixReplacement, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for generic matrix-vector : generic_product_impl_base<MatrixReplacement, Rhs, generic_product_impl<MatrixReplacement, Rhs> > { typedef typename Product<MatrixReplacement, Rhs>::Scalar Scalar; template<typename Dest> static void scaleAndAddTo(Dest& dst, const MatrixReplacement& lhs, const Rhs& rhs, const Scalar& alpha) { // This method should implement "dst += alpha * lhs * rhs" inplace, // however, for iterative solvers, alpha is always equal to 1, so let's not bother about it. assert(alpha == Scalar(1) && "scaling is not implemented"); const Real *vec = &rhs(0); Real *res = &dst(0); MatrixReplacement& lhs_ = const_cast<MatrixReplacement&>(lhs); lhs_.getMatrixVecProdFct()(vec, res, lhs_.getUserData()); } }; } } #endif
IntegralOrbitals.c
/* CoulombOrbitals.c */ /********************************************************************************************************** Copyright (c) 2002-2013 Abdul-Rahman Allouche. All rights reserved Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Gabedit), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************************************************/ #include "../../Config.h" #include "../Display/GlobalOrb.h" #ifdef ENABLE_OMP #include <omp.h> #endif #include "../Utils/Vector3d.h" #include "../Utils/GTF.h" #include "../Display/GLArea.h" #include "../Display/Orbitals.h" #include "../Display/OrbitalsMolpro.h" #include "../Display/OrbitalsGamess.h" #include "../Display/OrbitalsQChem.h" #include "../Display/GeomOrbXYZ.h" #include "../Display/BondsOrb.h" #include "../Display/UtilsOrb.h" #include "../Display/TriangleDraw.h" #include "../Utils/Utils.h" #include "../Utils/UtilsInterface.h" #include "../Utils/Constants.h" #include "../Utils/GabeditTextEdit.h" #include "../Files/FileChooser.h" #include "../Common/Windows.h" #include "../Display/Vibration.h" #include "../Display/ContoursPov.h" #include "../Display/PlanesMappedPov.h" #include "../Display/LabelsGL.h" #include "../Display/StatusOrb.h" #define WIDTHSCR 0.3 typedef gboolean (*FuncCompCoulomb)(gint N[],GridLimits limits, gint typeOrbi, gint i, gint typeOrbj, gint j, gdouble* pInteg, gdouble* pNorm, gdouble* pNormj, gdouble* pOverlap); /********************************************************************************/ /* <ii|delta(r_i,r_j)|jj>*/ gdouble compute_spatial_overlap_analytic(gint typeOrbi, gint i, gint typeOrbj, gint j, gdouble schwarzCutOff) { gdouble** CoefI = CoefAlphaOrbitals; gdouble** CoefJ = CoefAlphaOrbitals; gint k,kp; gint l,lp; gdouble scal; gchar tmp[BSIZE]; gint* p; gint* q; gdouble* cci; gdouble* ccj; gint kk; gint ll; gulong delta = 0; gint pos = 0; gdouble cc = 0; gulong nAll = 0; gdouble integ; gint N; gdouble pqrs; gdouble* mnmn; gulong nComp = 0; integ = 0; if(typeOrbi != typeOrbj ) { /* stop calculation */ CancelCalcul = TRUE; return integ ; } if(typeOrbi == 2) CoefI = CoefBetaOrbitals; if(typeOrbj == 2) CoefJ = CoefBetaOrbitals; N = NAOrb*(NAOrb+1)/2; if(N<1)return -1.0; mnmn = g_malloc(N*sizeof(gdouble)); p = g_malloc(N*sizeof(gint)); q = g_malloc(N*sizeof(gint)); cci = g_malloc(N*sizeof(gdouble)); ccj = g_malloc(N*sizeof(gdouble)); sprintf(tmp,_("Computing of <%d %d|delta(ri,rj)| %d %d>.... Please wait"),i+1,i+1,j+1,j+1); setTextInProgress(tmp); kk = 0; for(k=0;k<NAOrb;k++) for(kp=k;kp<NAOrb;kp++) { p[kk] = k; q[kk] = kp; cci[kk] = 2*CoefI[i][k]*CoefI[i][kp]/((k==kp)?2:1); ccj[kk] = 2*CoefJ[j][k]*CoefJ[j][kp]/((k==kp)?2:1); mnmn[kk] = 0.0; kk++; } scal = 0.01; delta = (gint)(N*(N+1.0)/2.0*scal); if(delta<1) delta = N*(N+1)/20; if(delta<1) delta = 1; pos = delta; /* printf("delta = %ld\n",delta);*/ progress_orb_txt(0,"tmp",TRUE); /* For do a Schwarz screening */ #ifdef ENABLE_OMP #ifdef G_OS_WIN32 setTextInProgress(_("Computing of spatial integrale, pleasse wait...")); #endif #pragma omp parallel for private(k,kp,kk,pqrs) reduction(+:integ,nAll,nComp,pos) #endif for(kk=0;kk<N;kk++) { k = p[kk]; kp = q[kk]; pqrs = overlap4CGTF(&AOrb[k],&AOrb[kp],&AOrb[k],&AOrb[kp]); integ += (cci[kk]*ccj[kk])*pqrs; mnmn[kk] = sqrt(fabs(pqrs)); nAll++; nComp++; if(nAll>=pos) { pos += delta; #ifdef ENABLE_OMP #ifndef G_OS_WIN32 #pragma omp critical progress_orb_txt(scal,tmp,FALSE); #endif #else progress_orb_txt(scal,tmp,FALSE); #endif } } #ifdef ENABLE_OMP #ifdef G_OS_WIN32 setTextInProgress(_("Computing of spatial integrale, pleasse wait...")); #endif #pragma omp parallel for private(k,kp,l,lp,kk,ll,pqrs,cc) reduction(+:integ,nAll,nComp,pos) #endif for(kk=0;kk<N;kk++) { k = p[kk]; kp = q[kk]; if(!CancelCalcul) for(ll=0;ll<kk;ll++) { if(!CancelCalcul) { l = p[ll]; lp = q[ll]; nAll++; if(nAll>=pos) { pos += delta; #ifdef ENABLE_OMP #ifndef G_OS_WIN32 #pragma omp critical progress_orb_txt(scal,tmp,FALSE); #endif #else progress_orb_txt(scal,tmp,FALSE); #endif } cc = (cci[kk]*ccj[ll]+cci[ll]*ccj[kk]); if(fabs(cc*mnmn[kk]*mnmn[ll])>=schwarzCutOff) { pqrs = overlap4CGTF(&AOrb[k],&AOrb[kp],&AOrb[l],&AOrb[lp]); integ += cc*pqrs; nComp++; } } } } sprintf(tmp,"# of all <pq|rs> = %ld, # of computed <pq|rs> %ld\n",nAll, nComp); progress_orb_txt(0,tmp,TRUE); g_free(mnmn); g_free(p); g_free(q); g_free(cci); g_free(ccj); return integ; } /********************************************************************************/ void compute_transition_matrix_analytic(gint typeOrbi, gint i, gint typeOrbj, gint j, gdouble integ[]) { gint k; gint l; gdouble** CoefI = CoefAlphaOrbitals; gdouble** CoefJ = CoefAlphaOrbitals; gdouble s = 0; integ[0] = 0; integ[1] = 0; integ[2] = 0; if(typeOrbi != typeOrbj ) return; if(typeOrbi == 2) CoefI = CoefBetaOrbitals; if(typeOrbj == 2) CoefJ = CoefBetaOrbitals; s = 0; #ifdef ENABLE_OMP printf("# proc = %d\n", omp_get_num_procs ()); #pragma omp parallel for private(k) reduction(+:s) #endif for(k=0;k<NAOrb;k++) s += CoefI[i][k]*CoefJ[j][k]*CGTFxyzCGTF(&AOrb[k],&AOrb[k],1,0,0); s = 0; integ[0] += s; #ifdef ENABLE_OMP #pragma omp parallel for private(k) reduction(+:s) #endif for(k=0;k<NAOrb;k++) s += CoefI[i][k]*CoefJ[j][k]*CGTFxyzCGTF(&AOrb[k],&AOrb[k],0,1,0); integ[1] += s; s = 0; #ifdef ENABLE_OMP #pragma omp parallel for private(k) reduction(+:s) #endif for(k=0;k<NAOrb;k++) s += CoefI[i][k]*CoefJ[j][k]*CGTFxyzCGTF(&AOrb[k],&AOrb[k],0,0,1); integ[2] += s; s = 0; #ifdef ENABLE_OMP #pragma omp parallel for private(k,l) reduction(+:s) #endif for(k=0;k<NAOrb;k++) for(l=k+1;l<NAOrb;l++) s += (CoefI[i][k]*CoefJ[j][l]+CoefI[i][l]*CoefJ[j][k])*CGTFxyzCGTF(&AOrb[k],&AOrb[l],1,0,0); integ[0] += s; s = 0; #ifdef ENABLE_OMP #pragma omp parallel for private(k,l) reduction(+:s) #endif for(k=0;k<NAOrb;k++) for(l=k+1;l<NAOrb;l++) s += (CoefI[i][k]*CoefJ[j][l]+CoefI[i][l]*CoefJ[j][k])*CGTFxyzCGTF(&AOrb[k],&AOrb[l],0,1,0); integ[1] += s; s = 0; #ifdef ENABLE_OMP #pragma omp parallel for private(k,l) reduction(+:s) #endif for(k=0;k<NAOrb;k++) for(l=k+1;l<NAOrb;l++) s += (CoefI[i][k]*CoefJ[j][l]+CoefI[i][l]*CoefJ[j][k])*CGTFxyzCGTF(&AOrb[k],&AOrb[l],0,0,1); integ[2] += s; } /********************************************************************************/ gdouble get_overlap_analytic(gint typeOrbi, gint i, gint typeOrbj, gint j) { gint k; gint l; gdouble v=0.0; gdouble** CoefI = CoefAlphaOrbitals; gdouble** CoefJ = CoefAlphaOrbitals; if(typeOrbi != typeOrbj ) return 0.0; if(typeOrbi == 2) CoefI = CoefBetaOrbitals; if(typeOrbj == 2) CoefJ = CoefBetaOrbitals; #ifdef ENABLE_OMP #pragma omp parallel for private(k) reduction(+:v) #endif for(k=0;k<NAOrb;k++) v += CoefI[i][k]*CoefJ[j][k]*overlapCGTF(&AOrb[k],&AOrb[k]); #ifdef ENABLE_OMP #pragma omp parallel for private(k,l) reduction(+:v) #endif for(k=0;k<NAOrb;k++) for(l=k+1;l<NAOrb;l++) v += (CoefI[i][k]*CoefJ[j][l]+CoefI[i][l]*CoefJ[j][k])*overlapCGTF(&AOrb[k],&AOrb[l]); return v; } /********************************************************************************/ /* gdouble get_coulomb_analytic(gint typeOrbi, gint i, gint typeOrbj, gint j) { gint k,kp; gint l,lp; gdouble v=0.0; gdouble** CoefI = CoefAlphaOrbitals; gdouble** CoefJ = CoefAlphaOrbitals; gdouble d,eri; gdouble scal; gint N = NAOrb*(NAOrb+1)/2; gint* p = g_malloc(N*sizeof(gint)); gint* q = g_malloc(N*sizeof(gint)); gint* dpq = g_malloc(N*sizeof(gint)); gdouble* cci = g_malloc(N*sizeof(gdouble)); gdouble* ccj = g_malloc(N*sizeof(gdouble)); gint kk; gint ll; gint dkkll; scal = (gdouble)1.01/N; if(typeOrbi == 2) CoefI = CoefBetaOrbitals; if(typeOrbj == 2) CoefJ = CoefBetaOrbitals; kk = 0; for(k=0;k<NAOrb;k++) for(kp=k;kp<NAOrb;kp++) { p[kk] = k; q[kk] = kp; dpq[kk] =(k==kp)?2:1; cci[kk] = CoefI[i][k]*CoefI[i][kp]; ccj[kk] = CoefJ[j][k]*CoefJ[j][kp]; kk++; } progress_orb(0,GABEDIT_PROGORB_COMPINTEG,TRUE); for(kk=0;kk<N;kk++) { k = p[kk]; kp = q[kk]; progress_orb(scal,GABEDIT_PROGORB_COMPINTEG,FALSE); if(CancelCalcul) { progress_orb(0,GABEDIT_PROGORB_COMPINTEG,TRUE); break; } if(fabs(cci[kk])<1e-12 && fabs(ccj[kk])<1e-12 )continue; if(!CancelCalcul) for(ll=kk;ll<N;ll++) { l = p[ll]; lp = q[ll]; if(CancelCalcul) break; if(fabs(cci[ll])<1e-12 && fabs(ccj[ll])<1e-12 )continue; dkkll=(kk==ll)?2:1; d = dpq[kk]*dpq[ll]*dkkll; eri = ERICGTF(&AOrb[k],&AOrb[kp],&AOrb[l],&AOrb[lp]); v += 4*(cci[kk]*ccj[ll]+cci[ll]*ccj[kk])*eri/d; } } progress_orb(0,GABEDIT_PROGORB_COMPINTEG,TRUE); g_free(p); g_free(q); g_free(dpq); g_free(cci); g_free(ccj); if(CancelCalcul) return -1.0; return v; } */ /********************************************************************************/ /* gdouble get_coulomb_analytic(gint typeOrbi, gint i, gint typeOrbj, gint j) { gint k,kp; gint l,lp; gdouble v=0.0; gdouble** CoefI = CoefAlphaOrbitals; gdouble** CoefJ = CoefAlphaOrbitals; gdouble a,b,eri; gdouble scal; scal = (gdouble)2.02/NAOrb/(NAOrb+1); gdouble cci = 0; gdouble ccj = 0; if(typeOrbi == 2) CoefI = CoefBetaOrbitals; if(typeOrbj == 2) CoefJ = CoefBetaOrbitals; progress_orb(0,GABEDIT_PROGORB_COMPINTEG,TRUE); for(k=0;k<NAOrb;k++) for(kp=k;kp<NAOrb;kp++) { cci = CoefI[i][k]*CoefI[i][kp]; progress_orb(scal,GABEDIT_PROGORB_COMPINTEG,FALSE); if(CancelCalcul) { progress_orb(0,GABEDIT_PROGORB_COMPINTEG,TRUE); break; } if(fabs(cci)<1e-12)continue; a=(k==kp)?1:2; if(!CancelCalcul) for(l=0;l<NAOrb;l++) for(lp=l;lp<NAOrb;lp++) { if(CancelCalcul) break; ccj = CoefJ[j][l]*CoefJ[j][lp]; if(fabs(ccj)<1e-12)continue; b=(l==lp)?1:2; eri = ERICGTF(&AOrb[k],&AOrb[kp],&AOrb[l],&AOrb[lp]); v += cci*ccj*eri*a*b; } } progress_orb(0,GABEDIT_PROGORB_COMPINTEG,TRUE); if(CancelCalcul) return -1.0; return v; } */ /********************************************************************************/ gdouble get_coulomb_analytic(gint typeOrbi, gint i, gint typeOrbj, gint j, gdouble schwarzCutOff) { gint k,kp; gint l,lp; gdouble v=0.0; gdouble** CoefI = CoefAlphaOrbitals; gdouble** CoefJ = CoefAlphaOrbitals; gdouble eri = 0; gdouble scal; gchar tmp[BSIZE]; gint N = NAOrb*(NAOrb+1)/2; gint* p = g_malloc(N*sizeof(gint)); gint* q = g_malloc(N*sizeof(gint)); gdouble* cci = g_malloc(N*sizeof(gdouble)); gdouble* ccj = g_malloc(N*sizeof(gdouble)); gdouble* mnmn = g_malloc(N*sizeof(gdouble)); gint kk; gint ll; gulong delta = 0; gint pos = 0; TTABLES** Ttables = NULL; gdouble cc = 0; gdouble ccmn = 0; gulong nAll = 0; gulong nComp = 0; if(N<1)return -1.0; setTextInProgress(_("Creation of T1 and T2 tables... Please wait")); Ttables = createTTables(AOrb, NAOrb, 1e-9); if(!Ttables) return -1.0; sprintf(tmp,_("Computing of <%d %d|1/r12| %d %d>.... Please wait"),i+1,i+1,j+1,j+1); if(typeOrbi == 2) CoefI = CoefBetaOrbitals; if(typeOrbj == 2) CoefJ = CoefBetaOrbitals; kk = 0; for(k=0;k<NAOrb;k++) for(kp=k;kp<NAOrb;kp++) { p[kk] = k; q[kk] = kp; cci[kk] = 2*CoefI[i][k]*CoefI[i][kp]/((k==kp)?2:1); ccj[kk] = 2*CoefJ[j][k]*CoefJ[j][kp]/((k==kp)?2:1); mnmn[kk] = 0.0; kk++; } scal = 0.01; delta = (gint)(N*(N+1.0)/2.0*scal); if(delta<1) delta = N*(N+1)/20; if(delta<1) delta = 1; pos = delta; /* printf("delta = %ld\n",delta);*/ progress_orb_txt(0,_("Computing of 2 centers Coulomb integrals... Please wait"),TRUE); /* For do a Schwarz screening */ #ifdef ENABLE_OMP #ifdef G_OS_WIN32 setTextInProgress(_("Computing of eri, pleasse wait...")); #endif #pragma omp parallel for private(k,kp,kk,eri) reduction(+:v,nAll,nComp,pos) #endif for(kk=0;kk<N;kk++) { k = p[kk]; kp = q[kk]; eri = ERICTABLES(k,kp,k,kp,Ttables); v += (cci[kk]*ccj[kk])*eri; mnmn[kk] = sqrt(fabs(eri)); nAll++; nComp++; if(nAll>=pos) { pos += delta; #ifdef ENABLE_OMP #ifndef G_OS_WIN32 #pragma omp critical progress_orb_txt(scal,tmp,FALSE); #endif #else progress_orb_txt(scal,tmp,FALSE); #endif } } #ifdef ENABLE_OMP #ifdef G_OS_WIN32 setTextInProgress(_("Computing of eri, pleasse wait...")); #endif #pragma omp parallel for private(k,kp,l,lp,kk,ll,eri,cc,ccmn) reduction(+:v,nAll,nComp,pos) #endif for(kk=0;kk<N;kk++) { k = p[kk]; kp = q[kk]; if(!CancelCalcul) for(ll=0;ll<kk;ll++) { if(!CancelCalcul) { l = p[ll]; lp = q[ll]; nAll++; if(nAll>=pos) { pos += delta; #ifdef ENABLE_OMP #ifndef G_OS_WIN32 #pragma omp critical progress_orb_txt(scal,tmp,FALSE); #endif #else progress_orb_txt(scal,tmp,FALSE); #endif } cc = (cci[kk]*ccj[ll]+cci[ll]*ccj[kk]); /* Schwarz screening */ ccmn = cc*mnmn[kk]*mnmn[ll]; if(fabs(ccmn)<schwarzCutOff) { continue; } eri = ERICTABLES(k,kp,l,lp,Ttables); v += cc*eri; nComp++; } } } sprintf(tmp,_("# of all ERI = %ld, # of computed ERI = %ld"),nAll, nComp); freeTTables(NAOrb,Ttables); progress_orb_txt(0,tmp,TRUE); g_free(p); g_free(q); g_free(cci); g_free(ccj); g_free(mnmn); if(CancelCalcul) return -1.0; return v; } /********************************************************************************/ static gint* get_num_of_selected_orbitals(GtkWidget *gtklist, gint* n) { gint* numOrbs = NULL; *n = 0; if (gtklist == NULL) return NULL; if(!GTK_IS_TREE_VIEW(gtklist)) return NULL; { GtkTreeSelection *selection; GtkTreeModel *model; GList *selected_rows = NULL; GList *row; GtkTreePath *path = NULL; gint* indices = NULL; gint i = 0; selection = gtk_tree_view_get_selection (GTK_TREE_VIEW(gtklist)); if(selection) selected_rows = gtk_tree_selection_get_selected_rows (selection, &model); *n = gtk_tree_selection_count_selected_rows(selection); if(*n<1) return numOrbs; numOrbs = g_malloc(*n*sizeof(gint)); i =0; for (row = g_list_first (selected_rows); row != NULL; row = g_list_next (row)) { path = (GtkTreePath *)(row->data); indices = gtk_tree_path_get_indices(path); numOrbs[i++] = indices[0]; if(i>=*n) break; } } return numOrbs; } /********************************************************************************/ static void numeriButtonClicked(GtkWidget *numericButton,gpointer data) { GtkWidget* frameGrid = g_object_get_data (G_OBJECT (numericButton), "FrameGrid"); GtkWidget* labelSchwarz = g_object_get_data (G_OBJECT (numericButton), "LabelSchwarz"); GtkWidget* entrySchwarz = g_object_get_data (G_OBJECT (numericButton), "EntrySchwarz"); gboolean checked = GTK_TOGGLE_BUTTON (numericButton)->active; if(GTK_IS_WIDGET(frameGrid))gtk_widget_set_sensitive(frameGrid, checked); if(GTK_IS_WIDGET(labelSchwarz)) gtk_widget_set_sensitive(labelSchwarz, !checked); if(GTK_IS_WIDGET(entrySchwarz))gtk_widget_set_sensitive(entrySchwarz, !checked); } /********************************************************************************/ static void apply_coulomb_orbitals(GtkWidget *Win,gpointer data) { GtkWidget** entriestmp = NULL; G_CONST_RETURN gchar* temp; gchar* dump; gint i; gint j; GridLimits limitstmp; gint NumPointstmp[3]; GtkWidget *entries[3][6]; gdouble V[3][3]; GtkWidget* alphaList = g_object_get_data (G_OBJECT (Win), "AlphaList"); GtkWidget* betaList = g_object_get_data (G_OBJECT (Win), "BetaList"); GtkWidget* numericButton = g_object_get_data (G_OBJECT (Win), "NumericButton"); GtkWidget* entrySchwarz = g_object_get_data (G_OBJECT (Win), "EntrySchwarz"); gint* numAlphaOrbs = NULL; gint* numBetaOrbs = NULL; gint nAlpha = 0; gint nBeta = 0; gdouble integ, normi, normj, overlap; gchar* result = NULL; FuncCompCoulomb compute_coulomb = compute_coulomb_integrale_iijj_poisson; gboolean numeric = FALSE; gdouble schwarzCutOff = 1e-8; if(GTK_IS_WIDGET(Win)) { entriestmp = (GtkWidget **)g_object_get_data(G_OBJECT (Win), "Entries"); } else return; if(entriestmp==NULL) return; if(!GTK_IS_WIDGET(numericButton)) return; numeric = GTK_TOGGLE_BUTTON (numericButton)->active; if(!numeric) { if(!GTK_IS_WIDGET(entrySchwarz)) return; schwarzCutOff = atof(gtk_entry_get_text(GTK_ENTRY(entrySchwarz))); } destroy_win_list(); if(numeric) { for(i=0;i<3;i++) for(j=0;j<6;j++) entries[i][j] = entriestmp[i*6+j]; for(i=0;i<3;i++) { for(j=3;j<5;j++) { temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { limitstmp.MinMax[j-3][i] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } temp = gtk_entry_get_text(GTK_ENTRY(entries[i][5])); NumPointstmp[i] = atoi(temp); if(NumPointstmp[i] <=2) { GtkWidget* message = Message(_("Error : The number of points should be > 2. "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { if( limitstmp.MinMax[0][i]> limitstmp.MinMax[1][i]) { GtkWidget* message = Message(_("Error : The minimal value should be smaller than the maximal value "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { V[i][j] = 0; temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { V[i][j] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } } for(i=0;i<3;i++) { gdouble norm = 0.0; for(j=0;j<3;j++) norm += V[i][j]*V[i][j]; if(fabs(norm)<1e-8) { GtkWidget* message = Message(_("Error : the norm is equal to 0 "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } for(j=0;j<3;j++) V[i][j] /= sqrt(norm); } for(j=0;j<3;j++) originOfCube[j] = 0; for(j=0;j<3;j++) firstDirection[j] = V[0][j]; for(j=0;j<3;j++) secondDirection[j] = V[1][j]; for(j=0;j<3;j++) thirdDirection[j] = V[2][j]; for(i=0;i<3;i++) { NumPoints[i] =NumPointstmp[i] ; for(j=0;j<2;j++) limits.MinMax[j][i] =limitstmp.MinMax[j][i]; } } /* end if numeric */ CancelCalcul = FALSE; /* printf("DirName = %s\n",dirName);*/ numAlphaOrbs = get_num_of_selected_orbitals(alphaList, &nAlpha); numBetaOrbs = get_num_of_selected_orbitals(betaList, &nBeta); if(nAlpha+nBeta<1) { GtkWidget* message = Message(_("Error : You should select at last one orbital"),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } else if(nAlpha+nBeta==1) { gint i = -1; gint typeOrb = -1; delete_child(Win); if(nAlpha==1 && numAlphaOrbs) { typeOrb = 1; i = numAlphaOrbs[0]; } else if(nBeta==1 && numBetaOrbs) { typeOrb = 2; i = numBetaOrbs[0]; } if(i>-1 && typeOrb>0) { gint ii = i+1; if(numeric) { if(compute_coulomb( NumPoints,limits, typeOrb, i, typeOrb, i, &integ, &normi, &normj, &overlap) ) result = g_strdup_printf( "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, ii,ii,ii,ii,integ); else result = g_strdup_printf("Canceled? !\n If not see your terminal "); } else { setTextInProgress(_("Analytic computing of coulomb integral")); integ = get_coulomb_analytic(typeOrb, i, typeOrb, i, schwarzCutOff); normi = get_overlap_analytic(typeOrb, i, typeOrb, i); result = g_strdup_printf( "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, ii,ii,ii,ii,integ); } } } else { gint typeOrbi = 1; gint typeOrbj = 1; delete_child(Win); if(numAlphaOrbs) for(i=0;i<nAlpha;i++) for(j=i+1;j<nAlpha;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numAlphaOrbs[j]; if(CancelCalcul) break; if(numeric && compute_coulomb( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, &integ, &normi, &normj, &overlap) ) { ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, jj,jj,normj, ii,jj,overlap, ii,ii,jj,jj, integ); } else if(!numeric) { setTextInProgress(_("Analytic computing of coulomb integral")); integ = get_coulomb_analytic(typeOrbi, ii, typeOrbj, jj, schwarzCutOff); normi = get_overlap_analytic(typeOrbi, ii, typeOrbi, ii); normj = get_overlap_analytic(typeOrbj, jj, typeOrbj, jj); overlap = get_overlap_analytic(typeOrbi, ii, typeOrbj, jj); ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, jj,jj,normj, ii,jj,overlap, ii,ii,jj,jj, integ); } if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 2; typeOrbj = 2; if(numBetaOrbs) for(i=0;i<nBeta;i++) for(j=i+1;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numBetaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; if(numeric && compute_coulomb( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, &integ, &normi, &normj, &overlap) ) { ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, jj,jj,normj, ii,jj,overlap, ii,ii,jj,jj, integ); } else if(!numeric) { setTextInProgress(_("Analytic computing of coulomb integral")); integ = get_coulomb_analytic(typeOrbi, ii, typeOrbj, jj, schwarzCutOff); normi = get_overlap_analytic(typeOrbi, ii, typeOrbi, ii); normj = get_overlap_analytic(typeOrbj, jj, typeOrbj, jj); overlap = get_overlap_analytic(typeOrbi, ii, typeOrbj, jj); ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, jj,jj,normj, ii,jj,overlap, ii,ii,jj,jj, integ); } if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 1; typeOrbj = 2; if(numAlphaOrbs && numBetaOrbs) for(i=0;i<nAlpha;i++) for(j=0;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; if(numeric && compute_coulomb( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, &integ, &normi, &normj, &overlap) ) { ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, jj,jj,normj, ii,jj,overlap, ii,ii,jj,jj, integ); } else if(!numeric) { setTextInProgress(_("Analytic computing of coulomb integral")); integ = get_coulomb_analytic(typeOrbi, ii, typeOrbj, jj, schwarzCutOff); normi = get_overlap_analytic(typeOrbi, ii, typeOrbi, ii); normj = get_overlap_analytic(typeOrbj, jj, typeOrbj, jj); overlap = get_overlap_analytic(typeOrbi, ii, typeOrbj, jj); ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|1/r12|%d %d> = %0.12lf Hartree\n", ii,ii,normi, jj,jj,normj, ii,jj,overlap, ii,ii,jj,jj, integ); } if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } } if(result && !CancelCalcul) { GtkWidget* message = MessageTxt(result,_("Result")); gtk_window_set_modal (GTK_WINDOW (message), TRUE); gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } /* printf("Selected alpha orbitals : "); for(i=0;i<nAlpha;i++) printf("%d ",numAlphaOrbs[i]); printf("\n"); printf("Selected beta orbitals : "); for(i=0;i<nBeta;i++) printf("%d ",numBetaOrbs[i]); printf("\n"); */ set_label_title(NULL,0,0); if(numAlphaOrbs) g_free(numAlphaOrbs); if(numBetaOrbs) g_free(numBetaOrbs); if(CancelCalcul) CancelCalcul = FALSE; } /********************************************************************************/ static void select_row(GtkWidget* list, gint row) { GtkTreePath *path; gchar* tmp = g_strdup_printf("%d",row); path = gtk_tree_path_new_from_string (tmp); g_free(tmp); if(!list) return; gtk_tree_selection_select_path (gtk_tree_view_get_selection (GTK_TREE_VIEW (list)), path); gtk_tree_view_scroll_to_cell(GTK_TREE_VIEW (list), path, NULL, FALSE,0.5,0.5); gtk_tree_path_free(path); } /********************************************************************************/ static GtkWidget* new_gtk_list_orbitals(gint N,gdouble* Energies,gdouble* Occ,gchar** sym, gint* widall) { gint i; gint j; GtkWidget* gtklist = NULL; gint *Width = NULL; gint NlistTitle = 4; gchar* Titles[] = {"Nr","Energy","Occ.","Sym."}; gchar* List[4]; GtkListStore *store; GtkTreeModel *model; GtkCellRenderer *renderer; GtkTreeViewColumn *column; GtkTreeSelection *select; GtkTreeIter iter; GType* types; Width = g_malloc(NlistTitle*sizeof(gint)); for (j=0;j<NlistTitle;j++) Width[j] = strlen(Titles[j]); types = g_malloc(NlistTitle*sizeof(GType)); for (i=0;i<NlistTitle;i++) types[i] = G_TYPE_STRING; store = gtk_list_store_newv (NlistTitle, types); g_free(types); model = GTK_TREE_MODEL (store); Width[0] = (gint)(Width[0]*10); Width[1] = (gint)(Width[1]*12); Width[2] = (gint)(Width[2]*8); Width[3] = (gint)(Width[3]*14); *widall = 0; for (j=0;j<NlistTitle;j++) *widall += Width[j]; *widall += 60; gtklist = gtk_tree_view_new_with_model (model); gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (gtklist), TRUE); gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (gtklist), TRUE); gtk_tree_view_set_reorderable(GTK_TREE_VIEW (gtklist), FALSE); for (i=0;i<NlistTitle;i++) { column = gtk_tree_view_column_new (); gtk_tree_view_column_set_title (column, Titles[i]); renderer = gtk_cell_renderer_text_new (); gtk_tree_view_column_pack_start (column, renderer, TRUE); gtk_tree_view_column_set_min_width(column, Width[i]); gtk_tree_view_column_set_attributes (column, renderer, "text", i, NULL); gtk_tree_view_append_column (GTK_TREE_VIEW (gtklist), column); } g_free( Width); select = gtk_tree_view_get_selection (GTK_TREE_VIEW (gtklist)); gtk_tree_selection_set_mode (select, GTK_SELECTION_MULTIPLE); for(i=0;i<N;i++) { if(strcmp(sym[i],"DELETED")==0)continue; List[0] = g_strdup_printf("%i",i+1); List[1] = g_strdup_printf("%lf",Energies[i]); List[2] = g_strdup_printf("%lf",Occ[i]); List[3] = g_strdup(sym[i]); gtk_list_store_append(store, &iter); for(j=0;j<4;j++) gtk_list_store_set (store, &iter, j, List[j], -1); for(j=0;j<4;j++) g_free(List[j]); } return gtklist; } /********************************************************************************/ static GtkWidget* new_alpha_list(GtkWidget *hboxall) { GtkWidget *frame; GtkWidget *scr; GtkWidget *vbox; GtkWidget *gtklist; gint i; gint N; gdouble* Energies; gdouble* Occ; gchar** sym; static gint type = 1; gint widall = 0; N = NAlphaOrb; Energies = g_malloc(N*sizeof(gdouble)); Occ = g_malloc(N*sizeof(gdouble)); sym = g_malloc(N*sizeof(gchar*)); for(i=0;i<N;i++) { Energies[i] = EnerAlphaOrbitals[i]; Occ[i] = OccAlphaOrbitals[i]; sym[i] = g_strdup(SymAlphaOrbitals[i]); } gtklist = new_gtk_list_orbitals(N,Energies,Occ,sym,&widall); g_object_set_data(G_OBJECT (gtklist), "Type",&type); frame = gtk_frame_new (_("Alpha Orbitals")); gtk_container_set_border_width (GTK_CONTAINER (frame), 1); gtk_frame_set_shadow_type( GTK_FRAME(frame),GTK_SHADOW_ETCHED_OUT); gtk_box_pack_start (GTK_BOX (hboxall), frame, TRUE, TRUE, 0); gtk_widget_show (frame); vbox = create_vbox(frame); scr=gtk_scrolled_window_new(NULL,NULL); gtk_widget_set_size_request(scr,widall,(gint)(ScreenHeight*WIDTHSCR)); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr),GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_box_pack_start(GTK_BOX (vbox), scr,TRUE, TRUE, 1); gtk_container_add(GTK_CONTAINER(scr),gtklist); set_base_style(gtklist,55000,55000,55000); for(i=0;i<N;i++) g_free(sym[i]); g_free(Energies); g_free(Occ); g_free(sym); g_object_set_data(G_OBJECT (hboxall), "AlphaList",gtklist); return frame; } /********************************************************************************/ static GtkWidget* new_beta_list(GtkWidget *hboxall) { GtkWidget *frame; GtkWidget *scr; GtkWidget *vbox; GtkWidget *gtklist; gint i; gint N; gdouble* Energies; gdouble* Occ; gchar** sym; static gint type = 2; gint widall = 0; N = NBetaOrb; Energies = g_malloc(N*sizeof(gdouble)); Occ = g_malloc(N*sizeof(gdouble)); sym = g_malloc(N*sizeof(gchar*)); for(i=0;i<N;i++) { Energies[i] = EnerBetaOrbitals[i]; Occ[i] = OccBetaOrbitals[i]; sym[i] = g_strdup(SymBetaOrbitals[i]); } gtklist = new_gtk_list_orbitals(N,Energies,Occ,sym,&widall); g_object_set_data(G_OBJECT (gtklist), "Type",&type); frame = gtk_frame_new (_("Beta Orbitals")); gtk_container_set_border_width (GTK_CONTAINER (frame), 1); gtk_frame_set_shadow_type( GTK_FRAME(frame),GTK_SHADOW_ETCHED_OUT); gtk_box_pack_start (GTK_BOX (hboxall), frame, TRUE, TRUE, 0); gtk_widget_show (frame); vbox = create_vbox(frame); scr=gtk_scrolled_window_new(NULL,NULL); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr),GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_widget_set_size_request(scr,widall,(gint)(ScreenHeight*WIDTHSCR)); gtk_box_pack_start(GTK_BOX (vbox), scr,TRUE, TRUE, 1); gtk_container_add(GTK_CONTAINER(scr),gtklist); set_base_style(gtklist,55000,55000,55000); gtk_widget_show (scr); gtk_widget_show (gtklist); for(i=0;i<N;i++) g_free(sym[i]); g_free(Energies); g_free(Occ); g_free(sym); g_object_set_data(G_OBJECT (hboxall), "BetaList",gtklist); return frame; } /********************************************************************************/ static GtkWidget *create_orbitals_list( GtkWidget *vboxall) { GtkWidget *hbox; hbox = gtk_hbox_new (TRUE, 0); gtk_box_pack_start (GTK_BOX (vboxall), hbox, TRUE, TRUE, 0); new_alpha_list(hbox); new_beta_list(hbox); return hbox; } /********************************************************************************/ void coulomb_orbitals_dlg() { GtkWidget *Win; GtkWidget *frameGrid; GtkWidget *frameMethod; GtkWidget *alphaList; GtkWidget *betaList; GtkWidget *hbox; GtkWidget *vboxall; GtkWidget *vboxwin; GtkWidget *button; GtkWidget *label; GtkWidget** entries; GtkWidget* numericButton = NULL; GtkWidget* vbox = NULL; GtkWidget* entrySchwarz = NULL; GtkWidget* table = NULL; if(!GeomOrb) { Message(_("Sorry, Please load a file before\n"),_("Error"),TRUE); return; } if(!CoefAlphaOrbitals) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOrb && !SAOrb) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOAvailable &&(TypeGrid == GABEDIT_TYPEGRID_DDENSITY || TypeGrid == GABEDIT_TYPEGRID_ADENSITY)) { Message(_("Sorry, No atomic orbitals available.\nPlease use a gabedit file for load : \n" "Geometry, Molecular and Atomic Orbitals\n"),_("Error"),TRUE); return; } Win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(Win),"Comlomb energy <ii|1/r12|jj>"); gtk_window_set_position(GTK_WINDOW(Win),GTK_WIN_POS_CENTER); gtk_container_set_border_width (GTK_CONTAINER (Win), 5); gtk_window_set_transient_for(GTK_WINDOW(Win),GTK_WINDOW(PrincipalWindow)); gtk_window_set_modal (GTK_WINDOW (Win), TRUE); add_glarea_child(Win,"Grid "); vboxall = create_vbox(Win); vboxwin = vboxall; hbox = gtk_hbox_new (TRUE, 0); gtk_box_pack_start (GTK_BOX (vboxall), hbox, TRUE, TRUE, 0); label = gtk_label_new(""); gtk_label_set_markup(GTK_LABEL(label), "<span foreground=\"#FF0000\"><big>Use mouse + the Ctrl key (or the shift key) to select several orbitals</big></span>\n"); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); hbox = create_orbitals_list(vboxall); alphaList = g_object_get_data (G_OBJECT (hbox), "AlphaList"); g_object_set_data (G_OBJECT (Win), "AlphaList",alphaList); betaList = g_object_get_data (G_OBJECT (hbox), "BetaList"); g_object_set_data (G_OBJECT (Win), "BetaList",betaList); gtk_box_pack_start (GTK_BOX (vboxall), gtk_hseparator_new(), TRUE, TRUE, 5); frameMethod = gtk_frame_new(_("Method")); gtk_box_pack_start (GTK_BOX (vboxall), frameMethod, TRUE, TRUE, 2); vbox = create_vbox(frameMethod); gtk_widget_show_all (vbox); table = gtk_table_new(2,2,FALSE); gtk_container_add(GTK_CONTAINER(vbox),table); gtk_widget_show (table); numericButton = gtk_check_button_new_with_label ( _("Numerical computing of the Coulomb integral (Large box is recommended)")); gtk_table_attach(GTK_TABLE(table),numericButton,0,0+2,0,0+1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), 1,1); g_signal_connect(G_OBJECT(numericButton), "clicked",(GCallback)numeriButtonClicked,NULL); g_object_set_data (G_OBJECT (Win), "NumericButton",numericButton); label = gtk_label_new(_(" Schwarz cutoff : ")); gtk_table_attach(GTK_TABLE(table),label,0,0+1,1,1+1, (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), 1,1); g_object_set_data (G_OBJECT (Win), "LabelSchwarz",label); g_object_set_data (G_OBJECT (numericButton), "LabelSchwarz",label); entrySchwarz = gtk_entry_new(); gtk_entry_set_text(GTK_ENTRY(entrySchwarz),"1e-8"); gtk_table_attach(GTK_TABLE(table),entrySchwarz,1,1+1,1,1+1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), 1,1); g_object_set_data (G_OBJECT (Win), "EntrySchwarz",entrySchwarz); g_object_set_data (G_OBJECT (numericButton), "EntrySchwarz",entrySchwarz); frameGrid = create_grid_frame(vboxall,"Box & Grid"); entries = (GtkWidget**) g_object_get_data (G_OBJECT (frameGrid), "Entries"); g_object_set_data (G_OBJECT (Win), "Entries",entries); g_object_set_data (G_OBJECT (Win), "FrameGrid",frameGrid); g_object_set_data (G_OBJECT (numericButton), "FrameGrid",frameGrid); gtk_widget_set_sensitive(frameGrid, GTK_TOGGLE_BUTTON (numericButton)->active); if(!AOrb && SAOrb) { gtk_button_clicked (GTK_BUTTON (numericButton)); gtk_widget_set_sensitive(numericButton, FALSE); } hbox = create_hbox_false(vboxwin); gtk_widget_realize(Win); button = create_button(Win,_("OK")); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); gtk_widget_show (button); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)apply_coulomb_orbitals,G_OBJECT(Win)); button = create_button(Win,_("Cancel")); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)delete_child, G_OBJECT(Win)); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)gtk_widget_destroy,G_OBJECT(Win)); gtk_widget_show (button); gtk_widget_show_all (Win); if(NAlphaOcc-1>=0) { select_row(alphaList,NAlphaOcc-1); if(NAlphaOcc+1<=NOrb) select_row(alphaList,NAlphaOcc); } else { select_row(alphaList,0); if(2<=NOrb) select_row(alphaList,1); } } /********************************************************************************/ void compute_overlap_matrix(gint typeOrb) { gint i,j,k,l; gchar* result = NULL; gdouble** matrix = NULL; gdouble** CoefI = CoefAlphaOrbitals; gdouble** CoefJ = CoefAlphaOrbitals; gchar* tmp = NULL; gdouble o; gint nAll = 0; gint delta = 0; gint pos = 0; gdouble scal; gchar str[BSIZE]; if(typeOrb != 1) { CoefI = CoefBetaOrbitals; CoefJ = CoefBetaOrbitals; } if(NAOrb<1) { GtkWidget* message = Message(_("Error : You should read orbitals"),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(!AOrb && !SAOrb) { GtkWidget* message = Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(!AOrb && SAOrb) { GtkWidget* message = Message(_("Sorry, That does not work with Slater basis set\n"),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } destroy_win_list(); sprintf(str,_("Computing of overlap matrix between orbitals... Please wait")); setTextInProgress(str); scal = 0.01; delta = (gint)(NAOrb*(NAOrb+1)/2*scal); if(delta<1) delta = 1; pos = delta; matrix = g_malloc(NAOrb*sizeof(gdouble*)); for(i=0;i<NAOrb;i++) { matrix[i] = g_malloc((i+1)*sizeof(gdouble)); for(j=0;j<=i;j++) matrix[i][j] = 0; } progress_orb_txt(0,str,TRUE); for(k=0;k<NAOrb;k++) { if(CancelCalcul) break; o = overlapCGTF(&AOrb[k],&AOrb[k]); nAll++; /* printf("k=%d o = %lf\n",k,o);*/ for(i=0;i<NAOrb;i++) for(j=0;j<=i;j++) matrix[i][j] += CoefI[i][k]*CoefJ[j][k]*o; if(nAll>=pos) { pos += delta; progress_orb_txt(scal,str,FALSE); } } for(k=0;k<NAOrb;k++) { /* printf("---->k=%d \n",k);*/ for(l=k+1;l<NAOrb;l++) { if(CancelCalcul) break; o = overlapCGTF(&AOrb[k],&AOrb[l]); nAll++; for(i=0;i<NAOrb;i++) for(j=0;j<=i;j++) matrix[i][j] += (CoefI[i][k]*CoefJ[j][l]+CoefI[i][l]*CoefJ[j][k])*o; if(nAll>=pos) { pos += delta; progress_orb_txt(scal,str,FALSE); } } if(CancelCalcul) break; } progress_orb_txt(0," ",TRUE); result = g_malloc(NAOrb*(NAOrb+1)/2*100*sizeof(gchar)); tmp = g_malloc(BSIZE*sizeof(gchar)); if(typeOrb == 1) sprintf(result," Alpha overlap matrix\n"); else sprintf(result," Beta overlap matrix\n"); setTextInProgress(_("Preparation of text to show... Please wait")); for(i=0;i<NAOrb;i++) for(j=0;j<=i;j++) { if(CancelCalcul) break; sprintf(tmp,"<%d|%d> = %lf\n",i+1,j+1,matrix[i][j]); strcat(result,tmp); if(CancelCalcul) break; } g_free(tmp); progress_orb_txt(0," ",TRUE); if(result && !CancelCalcul) { GtkWidget* message = MessageTxt(result,_("Overlap matrix")); gtk_window_set_modal (GTK_WINDOW (message), TRUE); gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } if(matrix) { for(i=0;i<NAOrb;i++) if(matrix[i]) g_free(matrix[i]); g_free(matrix); } g_free(result); } /********************************************************************************/ gchar* compute_transition_matrix(gint N[],GridLimits limits, gint typeOrbi, gint ii, gint typeOrbj, gint jj, gdouble* integ, gdouble* pNormi, gdouble* pNormj, gdouble* pOverlap, gboolean numeric) { gchar* tmp = NULL; gdouble m = 0; if(numeric && compute_transition_matrix_numeric( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, pNormi, pNormj, pOverlap) ) { ii++; jj++; m = sqrt(integ[0]*integ[0]+integ[1]*integ[1]+integ[2]*integ[2]); tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|vec r|%d> = %lf %lf %lf au (Magnitude=%lf)\n" "<%d|vec r|%d> = %lf %lf %lf Debye (Magnitude=%lf)\n\n", ii,ii,*pNormi, jj,jj,*pNormj, ii,jj,*pOverlap, ii,jj, integ[0], integ[1], integ[2], m, ii,jj, integ[0]*AUTODEB, integ[1]*AUTODEB, integ[2]*AUTODEB, m*AUTODEB ); } else if(!numeric) { setTextInProgress(_("Analytic computing of coulomb integral")); compute_transition_matrix_analytic(typeOrbi, ii, typeOrbj, jj, integ); *pNormi = get_overlap_analytic(typeOrbi, ii, typeOrbi, ii); *pNormj = get_overlap_analytic(typeOrbj, jj, typeOrbj, jj); *pOverlap = get_overlap_analytic(typeOrbi, ii, typeOrbj, jj); ii++; jj++; m = sqrt(integ[0]*integ[0]+integ[1]*integ[1]+integ[2]*integ[2]); tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|vec r|%d> = %lf %lf %lf au (Magnitude=%lf)\n" "<%d|vec r|%d> = %lf %lf %lf Debye (Magnitude=%lf)\n\n", ii,ii,*pNormi, jj,jj,*pNormj, ii,jj,*pOverlap, ii,jj, integ[0], integ[1], integ[2], m, ii,jj, integ[0]*AUTODEB, integ[1]*AUTODEB, integ[2]*AUTODEB, m*AUTODEB ); } return tmp; } /********************************************************************************/ static void apply_transition_matrix(GtkWidget *Win,gpointer data) { GtkWidget** entriestmp = NULL; G_CONST_RETURN gchar* temp; gchar* dump; gint i; gint j; GridLimits limitstmp; gint NumPointstmp[3]; GtkWidget *entries[3][6]; gdouble V[3][3]; GtkWidget* alphaList = g_object_get_data (G_OBJECT (Win), "AlphaList"); GtkWidget* betaList = g_object_get_data (G_OBJECT (Win), "BetaList"); GtkWidget* numericButton = g_object_get_data (G_OBJECT (Win), "NumericButton"); gint* numAlphaOrbs = NULL; gint* numBetaOrbs = NULL; gint nAlpha = 0; gint nBeta = 0; gdouble integ[3], normi, normj, overlap; gchar* result = NULL; gboolean numeric = FALSE; if(GTK_IS_WIDGET(Win)) { entriestmp = (GtkWidget **)g_object_get_data(G_OBJECT (Win), "Entries"); } else return; if(entriestmp==NULL) return; if(!GTK_IS_WIDGET(numericButton)) return; numeric = GTK_TOGGLE_BUTTON (numericButton)->active; destroy_win_list(); if(numeric) { for(i=0;i<3;i++) for(j=0;j<6;j++) entries[i][j] = entriestmp[i*6+j]; for(i=0;i<3;i++) { for(j=3;j<5;j++) { temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { limitstmp.MinMax[j-3][i] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } temp = gtk_entry_get_text(GTK_ENTRY(entries[i][5])); NumPointstmp[i] = atoi(temp); if(NumPointstmp[i] <=2) { GtkWidget* message = Message(_("Error : The number of points should be > 2. "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { if( limitstmp.MinMax[0][i]> limitstmp.MinMax[1][i]) { GtkWidget* message = Message(_("Error : The minimal value should be smaller than the maximal value "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { V[i][j] = 0; temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { V[i][j] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } } for(i=0;i<3;i++) { gdouble norm = 0.0; for(j=0;j<3;j++) norm += V[i][j]*V[i][j]; if(fabs(norm)<1e-8) { GtkWidget* message = Message(_("Error : the norm is equal to 0 "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } for(j=0;j<3;j++) V[i][j] /= sqrt(norm); } for(j=0;j<3;j++) originOfCube[j] = 0; for(j=0;j<3;j++) firstDirection[j] = V[0][j]; for(j=0;j<3;j++) secondDirection[j] = V[1][j]; for(j=0;j<3;j++) thirdDirection[j] = V[2][j]; for(i=0;i<3;i++) { NumPoints[i] =NumPointstmp[i] ; for(j=0;j<2;j++) limits.MinMax[j][i] =limitstmp.MinMax[j][i]; } } /* end if numeric */ CancelCalcul = FALSE; /* printf("DirName = %s\n",dirName);*/ numAlphaOrbs = get_num_of_selected_orbitals(alphaList, &nAlpha); numBetaOrbs = get_num_of_selected_orbitals(betaList, &nBeta); if(nAlpha+nBeta<1) { GtkWidget* message = Message(_("Error : You should select at last one orbital"),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } else if(nAlpha+nBeta==1) { gint i = -1; gint typeOrb = -1; delete_child(Win); if(nAlpha==1 && numAlphaOrbs) { typeOrb = 1; i = numAlphaOrbs[0]; } else if(nBeta==1 && numBetaOrbs) { typeOrb = 2; i = numBetaOrbs[0]; } if(i>-1 && typeOrb>0) { result = compute_transition_matrix( NumPoints,limits, typeOrb, i, typeOrb, i, integ, &normi, &normj, &overlap, numeric); } } else { gint typeOrbi = 1; gint typeOrbj = 1; delete_child(Win); if(numAlphaOrbs) for(i=0;i<nAlpha;i++) for(j=i+1;j<nAlpha;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numAlphaOrbs[j]; if(CancelCalcul) break; tmp = compute_transition_matrix( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap, numeric); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 2; typeOrbj = 2; if(numBetaOrbs) for(i=0;i<nBeta;i++) for(j=i+1;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numBetaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; tmp = compute_transition_matrix( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap, numeric); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 1; typeOrbj = 2; if(numAlphaOrbs && numBetaOrbs) for(i=0;i<nAlpha;i++) for(j=0;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; tmp = compute_transition_matrix( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap, numeric); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } } if(result && !CancelCalcul) { GtkWidget* message = MessageTxt(result,_("Result")); gtk_window_set_default_size (GTK_WINDOW(message),(gint)(ScreenWidth*0.8),-1); gtk_widget_set_size_request(message,(gint)(ScreenWidth*0.45),-1); /* gtk_window_set_modal (GTK_WINDOW (message), TRUE);*/ gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } /* printf("Selected alpha orbitals : "); for(i=0;i<nAlpha;i++) printf("%d ",numAlphaOrbs[i]); printf("\n"); printf("Selected beta orbitals : "); for(i=0;i<nBeta;i++) printf("%d ",numBetaOrbs[i]); printf("\n"); */ set_label_title(NULL,0,0); if(numAlphaOrbs) g_free(numAlphaOrbs); if(numBetaOrbs) g_free(numBetaOrbs); if(CancelCalcul) CancelCalcul = FALSE; } /********************************************************************************/ void transition_matrix_orbitals_dlg() { GtkWidget *Win; GtkWidget *frameGrid; GtkWidget *frameMethod; GtkWidget *alphaList; GtkWidget *betaList; GtkWidget *hbox; GtkWidget *vboxall; GtkWidget *vboxwin; GtkWidget *button; GtkWidget *label; GtkWidget** entries; GtkWidget* numericButton = NULL; GtkWidget* vbox = NULL; GtkWidget* table = NULL; if(!GeomOrb) { Message(_("Sorry, Please load a file before\n"),_("Error"),TRUE); return; } if(!CoefAlphaOrbitals) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOrb && !SAOrb) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOAvailable &&(TypeGrid == GABEDIT_TYPEGRID_DDENSITY || TypeGrid == GABEDIT_TYPEGRID_ADENSITY)) { Message(_("Sorry, No atomic orbitals available.\nPlease use a gabedit file for load : \n" "Geometry, Molecular and Atomic Orbitals\n"),_("Error"),TRUE); return; } Win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(Win),"transition matrix element <i|vec r|j>"); gtk_window_set_position(GTK_WINDOW(Win),GTK_WIN_POS_CENTER); gtk_container_set_border_width (GTK_CONTAINER (Win), 5); gtk_window_set_transient_for(GTK_WINDOW(Win),GTK_WINDOW(PrincipalWindow)); gtk_window_set_modal (GTK_WINDOW (Win), TRUE); add_glarea_child(Win,"Grid "); vboxall = create_vbox(Win); vboxwin = vboxall; hbox = gtk_hbox_new (TRUE, 0); gtk_box_pack_start (GTK_BOX (vboxall), hbox, TRUE, TRUE, 0); label = gtk_label_new(""); gtk_label_set_markup(GTK_LABEL(label), "<span foreground=\"#FF0000\"><big>Use mouse + the Ctrl key (or the shift key) to select several orbitals</big></span>\n"); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); hbox = create_orbitals_list(vboxall); alphaList = g_object_get_data (G_OBJECT (hbox), "AlphaList"); g_object_set_data (G_OBJECT (Win), "AlphaList",alphaList); betaList = g_object_get_data (G_OBJECT (hbox), "BetaList"); g_object_set_data (G_OBJECT (Win), "BetaList",betaList); gtk_box_pack_start (GTK_BOX (vboxall), gtk_hseparator_new(), TRUE, TRUE, 5); frameMethod = gtk_frame_new(_("Method")); gtk_box_pack_start (GTK_BOX (vboxall), frameMethod, TRUE, TRUE, 2); vbox = create_vbox(frameMethod); gtk_widget_show_all (vbox); table = gtk_table_new(2,2,FALSE); gtk_container_add(GTK_CONTAINER(vbox),table); gtk_widget_show (table); numericButton = gtk_check_button_new_with_label ( _("Numerical computing (Large box is recommended)")); gtk_table_attach(GTK_TABLE(table),numericButton,0,0+2,0,0+1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), 1,1); g_signal_connect(G_OBJECT(numericButton), "clicked",(GCallback)numeriButtonClicked,NULL); g_object_set_data (G_OBJECT (Win), "NumericButton",numericButton); frameGrid = create_grid_frame(vboxall,"Box & Grid"); entries = (GtkWidget**) g_object_get_data (G_OBJECT (frameGrid), "Entries"); g_object_set_data (G_OBJECT (Win), "Entries",entries); g_object_set_data (G_OBJECT (Win), "FrameGrid",frameGrid); g_object_set_data (G_OBJECT (numericButton), "FrameGrid",frameGrid); gtk_widget_set_sensitive(frameGrid, GTK_TOGGLE_BUTTON (numericButton)->active); if(!AOrb && SAOrb) { gtk_button_clicked (GTK_BUTTON (numericButton)); gtk_widget_set_sensitive(numericButton, FALSE); } hbox = create_hbox_false(vboxwin); gtk_widget_realize(Win); button = create_button(Win,_("OK")); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); gtk_widget_show (button); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)apply_transition_matrix,G_OBJECT(Win)); button = create_button(Win,_("Cancel")); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)delete_child, G_OBJECT(Win)); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)gtk_widget_destroy,G_OBJECT(Win)); gtk_widget_show (button); gtk_widget_show_all (Win); if(NAlphaOcc-1>=0) { select_row(alphaList,NAlphaOcc-1); if(NAlphaOcc+1<=NOrb) select_row(alphaList,NAlphaOcc); } else { select_row(alphaList,0); if(2<=NOrb) select_row(alphaList,1); } } /********************************************************************************/ gchar* compute_spatial_overlapiijj(gint N[],GridLimits limits, gint typeOrbi, gint ii, gint typeOrbj, gint jj, gdouble* integ, gdouble* pNormi, gdouble* pNormj, gdouble* pOverlap, gboolean numeric, gdouble schwarzCutOff) { gchar* tmp = NULL; if(numeric) { if(!compute_spatial_overlapiijj_numeric(N, limits, typeOrbi, ii, typeOrbj, jj, integ, pNormi, pNormj, pOverlap)) return tmp; if(CancelCalcul) return tmp; ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|delta(ri,rj)|%d %d> = %0.12lf\n", ii,ii,*pNormi, jj,jj,*pNormj, ii,jj,*pOverlap, ii,ii,jj,jj, *integ ); } else if(!numeric) { setTextInProgress(_("Analytic computing of spatial overlap <ii|delta(ri,rj)|jj> integral")); *integ = compute_spatial_overlap_analytic(typeOrbi, ii, typeOrbj, jj,schwarzCutOff); if(CancelCalcul) return tmp; *pNormi = get_overlap_analytic(typeOrbi, ii, typeOrbi, ii); *pNormj = get_overlap_analytic(typeOrbj, jj, typeOrbj, jj); *pOverlap = get_overlap_analytic(typeOrbi, ii, typeOrbj, jj); ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d %d|delta(ri,rj)|%d %d> = %0.12lf\n", ii,ii,*pNormi, jj,jj,*pNormj, ii,jj,*pOverlap, ii,ii,jj,jj, *integ ); } return tmp; } /********************************************************************************/ static void apply_spatial_overlapiijj(GtkWidget *Win,gpointer data) { GtkWidget** entriestmp = NULL; G_CONST_RETURN gchar* temp; gchar* dump; gint i; gint j; GridLimits limitstmp; gint NumPointstmp[3]; GtkWidget *entries[3][6]; gdouble V[3][3]; GtkWidget* alphaList = NULL; GtkWidget* betaList = NULL; GtkWidget* numericButton = NULL; GtkWidget* entrySchwarz = NULL; gint* numAlphaOrbs = NULL; gint* numBetaOrbs = NULL; gint nAlpha = 0; gint nBeta = 0; gdouble integ[3], normi, normj, overlap; gchar* result = NULL; gboolean numeric = FALSE; gdouble schwarzCutOff; if(GTK_IS_WIDGET(Win)) { entriestmp = (GtkWidget **)g_object_get_data(G_OBJECT (Win), "Entries"); alphaList = g_object_get_data (G_OBJECT (Win), "AlphaList"); betaList = g_object_get_data (G_OBJECT (Win), "BetaList"); numericButton = g_object_get_data (G_OBJECT (Win), "NumericButton"); entrySchwarz = g_object_get_data (G_OBJECT (Win), "EntrySchwarz"); } else return; if(entriestmp==NULL) return; if(!GTK_IS_WIDGET(numericButton)) return; if(!GTK_IS_WIDGET(entrySchwarz)) return; temp = gtk_entry_get_text(GTK_ENTRY(entrySchwarz)); schwarzCutOff = atof(temp); numeric = GTK_TOGGLE_BUTTON (numericButton)->active; destroy_win_list(); if(numeric) { for(i=0;i<3;i++) for(j=0;j<6;j++) entries[i][j] = entriestmp[i*6+j]; for(i=0;i<3;i++) { for(j=3;j<5;j++) { temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { limitstmp.MinMax[j-3][i] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } temp = gtk_entry_get_text(GTK_ENTRY(entries[i][5])); NumPointstmp[i] = atoi(temp); if(NumPointstmp[i] <=2) { GtkWidget* message = Message(_("Error : The number of points should be > 2. "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { if( limitstmp.MinMax[0][i]> limitstmp.MinMax[1][i]) { GtkWidget* message = Message(_("Error : The minimal value should be smaller than the maximal value "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { V[i][j] = 0; temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { V[i][j] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } } for(i=0;i<3;i++) { gdouble norm = 0.0; for(j=0;j<3;j++) norm += V[i][j]*V[i][j]; if(fabs(norm)<1e-8) { GtkWidget* message = Message(_("Error : the norm is equal to 0 "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } for(j=0;j<3;j++) V[i][j] /= sqrt(norm); } for(j=0;j<3;j++) originOfCube[j] = 0; for(j=0;j<3;j++) firstDirection[j] = V[0][j]; for(j=0;j<3;j++) secondDirection[j] = V[1][j]; for(j=0;j<3;j++) thirdDirection[j] = V[2][j]; for(i=0;i<3;i++) { NumPoints[i] =NumPointstmp[i] ; for(j=0;j<2;j++) limits.MinMax[j][i] =limitstmp.MinMax[j][i]; } } /* end if numeric */ CancelCalcul = FALSE; /* printf("DirName = %s\n",dirName);*/ numAlphaOrbs = get_num_of_selected_orbitals(alphaList, &nAlpha); numBetaOrbs = get_num_of_selected_orbitals(betaList, &nBeta); if(nAlpha+nBeta<1) { GtkWidget* message = Message(_("Error : You should select at last one orbital"),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } else if(nAlpha+nBeta==1) { gint i = -1; gint typeOrb = -1; delete_child(Win); if(nAlpha==1 && numAlphaOrbs) { typeOrb = 1; i = numAlphaOrbs[0]; } else if(nBeta==1 && numBetaOrbs) { typeOrb = 2; i = numBetaOrbs[0]; } if(i>-1 && typeOrb>0) { result = compute_spatial_overlapiijj( NumPoints,limits, typeOrb, i, typeOrb, i, integ, &normi, &normj, &overlap, numeric, schwarzCutOff); } } else { gint typeOrbi = 1; gint typeOrbj = 1; delete_child(Win); if(numAlphaOrbs) for(i=0;i<nAlpha;i++) for(j=i+1;j<nAlpha;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numAlphaOrbs[j]; if(CancelCalcul) break; tmp = compute_spatial_overlapiijj( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap, numeric, schwarzCutOff); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 2; typeOrbj = 2; if(numBetaOrbs) for(i=0;i<nBeta;i++) for(j=i+1;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numBetaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; tmp = compute_spatial_overlapiijj( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap, numeric,schwarzCutOff); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 1; typeOrbj = 2; if(numAlphaOrbs && numBetaOrbs) for(i=0;i<nAlpha;i++) for(j=0;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; tmp = compute_spatial_overlapiijj( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap, numeric,schwarzCutOff); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } } if(result && !CancelCalcul) { GtkWidget* message = MessageTxt(result,_("Result")); gtk_window_set_default_size (GTK_WINDOW(message),(gint)(ScreenWidth*0.8),-1); gtk_widget_set_size_request(message,(gint)(ScreenWidth*0.45),-1); /* gtk_window_set_modal (GTK_WINDOW (message), TRUE);*/ gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } /* printf("Selected alpha orbitals : "); for(i=0;i<nAlpha;i++) printf("%d ",numAlphaOrbs[i]); printf("\n"); printf("Selected beta orbitals : "); for(i=0;i<nBeta;i++) printf("%d ",numBetaOrbs[i]); printf("\n"); */ set_label_title(NULL,0,0); if(numAlphaOrbs) g_free(numAlphaOrbs); if(numBetaOrbs) g_free(numBetaOrbs); if(CancelCalcul) CancelCalcul = FALSE; } /********************************************************************************/ void spatial_overlapiijj_orbitals_dlg() { GtkWidget *Win; GtkWidget *frameGrid; GtkWidget *frameMethod; GtkWidget *alphaList; GtkWidget *betaList; GtkWidget *hbox; GtkWidget *vboxall; GtkWidget *vboxwin; GtkWidget *button; GtkWidget *label; GtkWidget** entries; GtkWidget* numericButton = NULL; GtkWidget* vbox = NULL; GtkWidget* table = NULL; GtkWidget* entrySchwarz = NULL; if(!GeomOrb) { Message(_("Sorry, Please load a file before\n"),_("Error"),TRUE); return; } if(!CoefAlphaOrbitals) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOrb && !SAOrb) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOAvailable &&(TypeGrid == GABEDIT_TYPEGRID_DDENSITY || TypeGrid == GABEDIT_TYPEGRID_ADENSITY)) { Message(_("Sorry, No atomic orbitals available.\nPlease use a gabedit file for load : \n" "Geometry, Molecular and Atomic Orbitals\n"),_("Error"),TRUE); return; } Win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(Win),"Spatial Overlap element <ii|delta(ri,rj)|jj>"); gtk_window_set_position(GTK_WINDOW(Win),GTK_WIN_POS_CENTER); gtk_container_set_border_width (GTK_CONTAINER (Win), 5); gtk_window_set_transient_for(GTK_WINDOW(Win),GTK_WINDOW(PrincipalWindow)); gtk_window_set_modal (GTK_WINDOW (Win), TRUE); add_glarea_child(Win,"Grid "); vboxall = create_vbox(Win); vboxwin = vboxall; hbox = gtk_hbox_new (TRUE, 0); gtk_box_pack_start (GTK_BOX (vboxall), hbox, TRUE, TRUE, 0); label = gtk_label_new(""); gtk_label_set_markup(GTK_LABEL(label), "<span foreground=\"#FF0000\"><big>Use mouse + the Ctrl key (or the shift key) to select several orbitals</big></span>\n"); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); hbox = create_orbitals_list(vboxall); alphaList = g_object_get_data (G_OBJECT (hbox), "AlphaList"); g_object_set_data (G_OBJECT (Win), "AlphaList",alphaList); betaList = g_object_get_data (G_OBJECT (hbox), "BetaList"); g_object_set_data (G_OBJECT (Win), "BetaList",betaList); gtk_box_pack_start (GTK_BOX (vboxall), gtk_hseparator_new(), TRUE, TRUE, 5); frameMethod = gtk_frame_new(_("Method")); gtk_box_pack_start (GTK_BOX (vboxall), frameMethod, TRUE, TRUE, 2); vbox = create_vbox(frameMethod); gtk_widget_show_all (vbox); table = gtk_table_new(2,2,FALSE); gtk_container_add(GTK_CONTAINER(vbox),table); gtk_widget_show (table); numericButton = gtk_check_button_new_with_label ( _("Numerical computing (Large box is recommended)")); gtk_table_attach(GTK_TABLE(table),numericButton,0,0+2,0,0+1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), 1,1); g_signal_connect(G_OBJECT(numericButton), "clicked",(GCallback)numeriButtonClicked,NULL); g_object_set_data (G_OBJECT (Win), "NumericButton",numericButton); label = gtk_label_new(_(" Schwarz cutoff : ")); gtk_table_attach(GTK_TABLE(table),label,0,0+1,1,1+1, (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), 1,1); g_object_set_data (G_OBJECT (Win), "LabelSchwarz",label); g_object_set_data (G_OBJECT (numericButton), "LabelSchwarz",label); entrySchwarz = gtk_entry_new(); gtk_entry_set_text(GTK_ENTRY(entrySchwarz),"1e-8"); gtk_table_attach(GTK_TABLE(table),entrySchwarz,1,1+1,1,1+1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), (GtkAttachOptions)(GTK_FILL | GTK_SHRINK), 1,1); g_object_set_data (G_OBJECT (Win), "EntrySchwarz",entrySchwarz); g_object_set_data (G_OBJECT (numericButton), "EntrySchwarz",entrySchwarz); frameGrid = create_grid_frame(vboxall,"Box & Grid"); entries = (GtkWidget**) g_object_get_data (G_OBJECT (frameGrid), "Entries"); g_object_set_data (G_OBJECT (Win), "Entries",entries); g_object_set_data (G_OBJECT (Win), "FrameGrid",frameGrid); g_object_set_data (G_OBJECT (numericButton), "FrameGrid",frameGrid); gtk_widget_set_sensitive(frameGrid, GTK_TOGGLE_BUTTON (numericButton)->active); if(!AOrb && SAOrb) { gtk_button_clicked (GTK_BUTTON (numericButton)); gtk_widget_set_sensitive(numericButton, FALSE); } hbox = create_hbox_false(vboxwin); gtk_widget_realize(Win); button = create_button(Win,_("OK")); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); gtk_widget_show (button); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)apply_spatial_overlapiijj,G_OBJECT(Win)); button = create_button(Win,_("Cancel")); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)delete_child, G_OBJECT(Win)); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)gtk_widget_destroy,G_OBJECT(Win)); gtk_widget_show (button); gtk_widget_show_all (Win); if(NAlphaOcc-1>=0) { select_row(alphaList,NAlphaOcc-1); if(NAlphaOcc+1<=NOrb) select_row(alphaList,NAlphaOcc); } else { select_row(alphaList,0); if(2<=NOrb) select_row(alphaList,1); } } /********************************************************************************/ gchar* compute_spatial_overlapij(gint N[],GridLimits limits, gint typeOrbi, gint ii, gint typeOrbj, gint jj, gdouble* integ, gdouble* pNormi, gdouble* pNormj, gdouble* pOverlap) { gchar* tmp = NULL; if(!compute_spatial_overlapij_numeric(N, limits, typeOrbi, ii, typeOrbj, jj, integ, pNormi, pNormj, pOverlap)) return tmp; if(CancelCalcul) return tmp; ii++; jj++; tmp = g_strdup_printf( "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "<%d|%d> = %lf\n" "< |%d| | |%d|> = %0.12lf\n", ii,ii,*pNormi, jj,jj,*pNormj, ii,jj,*pOverlap, ii,jj, *integ ); return tmp; } /********************************************************************************/ static void apply_spatial_overlapij(GtkWidget *Win,gpointer data) { GtkWidget** entriestmp = NULL; G_CONST_RETURN gchar* temp; gchar* dump; gint i; gint j; GridLimits limitstmp; gint NumPointstmp[3]; GtkWidget *entries[3][6]; gdouble V[3][3]; GtkWidget* alphaList = NULL; GtkWidget* betaList = NULL; gint* numAlphaOrbs = NULL; gint* numBetaOrbs = NULL; gint nAlpha = 0; gint nBeta = 0; gdouble integ[3], normi, normj, overlap; gchar* result = NULL; if(GTK_IS_WIDGET(Win)) { entriestmp = (GtkWidget **)g_object_get_data(G_OBJECT (Win), "Entries"); alphaList = g_object_get_data (G_OBJECT (Win), "AlphaList"); betaList = g_object_get_data (G_OBJECT (Win), "BetaList"); } else return; if(entriestmp==NULL) return; destroy_win_list(); for(i=0;i<3;i++) for(j=0;j<6;j++) entries[i][j] = entriestmp[i*6+j]; for(i=0;i<3;i++) { for(j=3;j<5;j++) { temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { limitstmp.MinMax[j-3][i] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } temp = gtk_entry_get_text(GTK_ENTRY(entries[i][5])); NumPointstmp[i] = atoi(temp); if(NumPointstmp[i] <=2) { GtkWidget* message = Message(_("Error : The number of points should be > 2. "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { if( limitstmp.MinMax[0][i]> limitstmp.MinMax[1][i]) { GtkWidget* message = Message(_("Error : The minimal value should be smaller than the maximal value "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { V[i][j] = 0; temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { V[i][j] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } } for(i=0;i<3;i++) { gdouble norm = 0.0; for(j=0;j<3;j++) norm += V[i][j]*V[i][j]; if(fabs(norm)<1e-8) { GtkWidget* message = Message(_("Error : the norm is equal to 0 "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } for(j=0;j<3;j++) V[i][j] /= sqrt(norm); } for(j=0;j<3;j++) originOfCube[j] = 0; for(j=0;j<3;j++) firstDirection[j] = V[0][j]; for(j=0;j<3;j++) secondDirection[j] = V[1][j]; for(j=0;j<3;j++) thirdDirection[j] = V[2][j]; for(i=0;i<3;i++) { NumPoints[i] =NumPointstmp[i] ; for(j=0;j<2;j++) limits.MinMax[j][i] =limitstmp.MinMax[j][i]; } CancelCalcul = FALSE; /* printf("DirName = %s\n",dirName);*/ numAlphaOrbs = get_num_of_selected_orbitals(alphaList, &nAlpha); numBetaOrbs = get_num_of_selected_orbitals(betaList, &nBeta); if(nAlpha+nBeta<1) { GtkWidget* message = Message(_("Error : You should select at last one orbital"),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } else if(nAlpha+nBeta==1) { gint i = -1; gint typeOrb = -1; delete_child(Win); if(nAlpha==1 && numAlphaOrbs) { typeOrb = 1; i = numAlphaOrbs[0]; } else if(nBeta==1 && numBetaOrbs) { typeOrb = 2; i = numBetaOrbs[0]; } if(i>-1 && typeOrb>0) { result = compute_spatial_overlapij( NumPoints,limits, typeOrb, i, typeOrb, i, integ, &normi, &normj, &overlap); } } else { gint typeOrbi = 1; gint typeOrbj = 1; delete_child(Win); if(numAlphaOrbs) for(i=0;i<nAlpha;i++) for(j=i+1;j<nAlpha;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numAlphaOrbs[j]; if(CancelCalcul) break; tmp = compute_spatial_overlapij( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 2; typeOrbj = 2; if(numBetaOrbs) for(i=0;i<nBeta;i++) for(j=i+1;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numBetaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; tmp = compute_spatial_overlapij( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } typeOrbi = 1; typeOrbj = 2; if(numAlphaOrbs && numBetaOrbs) for(i=0;i<nAlpha;i++) for(j=0;j<nBeta;j++) { gchar* tmp = NULL; gint ii = numAlphaOrbs[i]; gint jj = numBetaOrbs[j]; if(CancelCalcul) break; tmp = compute_spatial_overlapij( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap); if(tmp) { gchar* old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } } } if(result && !CancelCalcul) { GtkWidget* message = MessageTxt(result,_("Result")); gtk_window_set_default_size (GTK_WINDOW(message),(gint)(ScreenWidth*0.8),-1); gtk_widget_set_size_request(message,(gint)(ScreenWidth*0.45),-1); /* gtk_window_set_modal (GTK_WINDOW (message), TRUE);*/ gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } /* printf("Selected alpha orbitals : "); for(i=0;i<nAlpha;i++) printf("%d ",numAlphaOrbs[i]); printf("\n"); printf("Selected beta orbitals : "); for(i=0;i<nBeta;i++) printf("%d ",numBetaOrbs[i]); printf("\n"); */ set_label_title(NULL,0,0); if(numAlphaOrbs) g_free(numAlphaOrbs); if(numBetaOrbs) g_free(numBetaOrbs); if(CancelCalcul) CancelCalcul = FALSE; } /********************************************************************************/ void spatial_overlapij_orbitals_dlg() { GtkWidget *Win; GtkWidget *frameGrid; GtkWidget *alphaList; GtkWidget *betaList; GtkWidget *hbox; GtkWidget *vboxall; GtkWidget *vboxwin; GtkWidget *button; GtkWidget *label; GtkWidget** entries; if(!GeomOrb) { Message(_("Sorry, Please load a file before\n"),_("Error"),TRUE); return; } if(!CoefAlphaOrbitals) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOrb && !SAOrb) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOAvailable &&(TypeGrid == GABEDIT_TYPEGRID_DDENSITY || TypeGrid == GABEDIT_TYPEGRID_ADENSITY)) { Message(_("Sorry, No atomic orbitals available.\nPlease use a gabedit file for load : \n" "Geometry, Molecular and Atomic Orbitals\n"),_("Error"),TRUE); return; } Win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(Win),"Spatial Overlap element < |i| | |j|>"); gtk_window_set_position(GTK_WINDOW(Win),GTK_WIN_POS_CENTER); gtk_container_set_border_width (GTK_CONTAINER (Win), 5); gtk_window_set_transient_for(GTK_WINDOW(Win),GTK_WINDOW(PrincipalWindow)); gtk_window_set_modal (GTK_WINDOW (Win), TRUE); add_glarea_child(Win,"Grid "); vboxall = create_vbox(Win); vboxwin = vboxall; hbox = gtk_hbox_new (TRUE, 0); gtk_box_pack_start (GTK_BOX (vboxall), hbox, TRUE, TRUE, 0); label = gtk_label_new(""); gtk_label_set_markup(GTK_LABEL(label), "<span foreground=\"#FF0000\"><big>Use mouse + the Ctrl key (or the shift key) to select several orbitals</big></span>\n"); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); hbox = create_orbitals_list(vboxall); alphaList = g_object_get_data (G_OBJECT (hbox), "AlphaList"); g_object_set_data (G_OBJECT (Win), "AlphaList",alphaList); betaList = g_object_get_data (G_OBJECT (hbox), "BetaList"); g_object_set_data (G_OBJECT (Win), "BetaList",betaList); gtk_box_pack_start (GTK_BOX (vboxall), gtk_hseparator_new(), TRUE, TRUE, 5); frameGrid = create_grid_frame(vboxall,"Box & Grid"); entries = (GtkWidget**) g_object_get_data (G_OBJECT (frameGrid), "Entries"); g_object_set_data (G_OBJECT (Win), "Entries",entries); g_object_set_data (G_OBJECT (Win), "FrameGrid",frameGrid); gtk_widget_set_sensitive(frameGrid, TRUE); hbox = create_hbox_false(vboxwin); gtk_widget_realize(Win); button = create_button(Win,_("OK")); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); gtk_widget_show (button); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)apply_spatial_overlapij,G_OBJECT(Win)); button = create_button(Win,_("Cancel")); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)delete_child, G_OBJECT(Win)); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)gtk_widget_destroy,G_OBJECT(Win)); gtk_widget_show (button); gtk_widget_show_all (Win); if(NAlphaOcc-1>=0) { select_row(alphaList,NAlphaOcc-1); if(NAlphaOcc+1<=NOrb) select_row(alphaList,NAlphaOcc); } else { select_row(alphaList,0); if(2<=NOrb) select_row(alphaList,1); } } /************************************************************************************************************/ static void setPartialChargesToCalculated(GtkWidget *win) { gint i; gdouble* charges = NULL; if(GTK_IS_WIDGET(win)) charges = g_object_get_data(G_OBJECT (win), "Charges"); if(!charges) return; for(i=0;i<Ncenters;i++) GeomOrb[i].partialCharge = charges[i]; glarea_rafresh(GLArea); } /************************************************************************************************************/ static void destroyCalculatedChargesDlg(GtkWidget *win) { gdouble* charges = NULL; if(GTK_IS_WIDGET(win)) charges = g_object_get_data(G_OBJECT (win), "Charges"); if(charges) g_free(charges); if(GTK_IS_WIDGET(win)) delete_child(win); if(GTK_IS_WIDGET(win)) gtk_widget_destroy(win); } /********************************************************************************/ static GtkWidget* showCalculatedChargesDlg(gchar *message,gchar *title,gdouble* charges) { GtkWidget *dlgWin = NULL; GtkWidget *frame; GtkWidget *vboxframe; GtkWidget *txtWid; GtkWidget *button; dlgWin = gtk_dialog_new(); gtk_widget_realize(GTK_WIDGET(dlgWin)); gtk_window_set_title(GTK_WINDOW(dlgWin),title); gtk_window_set_position(GTK_WINDOW(dlgWin),GTK_WIN_POS_CENTER); gtk_window_set_modal (GTK_WINDOW (dlgWin), TRUE); gtk_window_set_transient_for(GTK_WINDOW(dlgWin),GTK_WINDOW(PrincipalWindow)); g_signal_connect(G_OBJECT(dlgWin), "delete_event", (GCallback)destroyCalculatedChargesDlg, NULL); frame = gtk_frame_new (NULL); gtk_frame_set_shadow_type( GTK_FRAME(frame),GTK_SHADOW_ETCHED_OUT); gtk_container_set_border_width (GTK_CONTAINER (frame), 5); gtk_box_pack_start( GTK_BOX(GTK_DIALOG(dlgWin)->vbox), frame,TRUE,TRUE,0); gtk_widget_show (frame); vboxframe = create_vbox(frame); txtWid = create_text_widget(vboxframe,NULL,&frame); if(message) gabedit_text_insert (GABEDIT_TEXT(txtWid), NULL, NULL, NULL,message,-1); gtk_box_set_homogeneous (GTK_BOX( GTK_DIALOG(dlgWin)->action_area), FALSE); button = create_button(dlgWin,_("Partial charges of molecule <= Calculated charges")); gtk_box_pack_end (GTK_BOX( GTK_DIALOG(dlgWin)->action_area), button, FALSE, TRUE, 5); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); g_signal_connect_swapped(G_OBJECT(button), "clicked", (GCallback)setPartialChargesToCalculated, GTK_OBJECT(dlgWin)); button = create_button(dlgWin,"Close"); gtk_box_pack_end (GTK_BOX( GTK_DIALOG(dlgWin)->action_area), button, FALSE, TRUE, 5); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); g_signal_connect_swapped(G_OBJECT(button), "clicked", (GCallback)destroyCalculatedChargesDlg, GTK_OBJECT(dlgWin)); add_button_windows(title,dlgWin); gtk_window_set_default_size (GTK_WINDOW(dlgWin), (gint)(ScreenHeight*0.6), (gint)(ScreenHeight*0.5)); gtk_widget_show_all(dlgWin); g_object_set_data(G_OBJECT (dlgWin), "Charges",charges); return dlgWin; } /********************************************************************************/ void compute_mulliken_charges() { gint i,k,l; gchar* result = NULL; gdouble* charges = NULL; gchar* tmp = NULL; gdouble o; gint nAll = 0; gint delta = 0; gint pos = 0; gdouble scal; gchar str[BSIZE]; gint kk=0; if(Ncenters<1) return; if(!AOrb && (!SAOrb || !SOverlaps)) return; destroy_win_list(); sprintf(str,_("Computing of mulliken charges... Please wait")); setTextInProgress(str); scal = 0.01; delta = (gint)(NAOrb*(NAOrb+1)/2*scal); if(delta<1) delta = 1; pos = delta; charges = g_malloc(Ncenters*sizeof(gdouble)); for(i=0;i<Ncenters;i++) charges[i] = GeomOrb[i].nuclearCharge; progress_orb_txt(0,str,TRUE); kk = 0; for(k=0;k<NAOrb;k++) { gint ic = (AOrb)?AOrb[k].NumCenter:SAOrb[k].NumCenter; for(l=0;l<=k;l++) { gint jc = (AOrb)?AOrb[l].NumCenter:SAOrb[l].NumCenter; gint fact = 1; if(CancelCalcul) break; if(AOrb) o = overlapCGTF(&AOrb[k],&AOrb[l])*fact; else o = SOverlaps[kk++]*fact; /* printf("k=%d o = %lf\n",k,o);*/ for(i=0;i<NAlphaOcc;i++) charges[ic] -= OccAlphaOrbitals[i]*CoefAlphaOrbitals[i][k]*CoefAlphaOrbitals[i][l]*o; for(i=0;i<NBetaOcc;i++) charges[ic] -= OccBetaOrbitals[i]*CoefBetaOrbitals[i][k]*CoefBetaOrbitals[i][l]*o; if(k!=l) { for(i=0;i<NAlphaOcc;i++) charges[jc] -= OccAlphaOrbitals[i]*CoefAlphaOrbitals[i][k]*CoefAlphaOrbitals[i][l]*o; for(i=0;i<NBetaOcc;i++) charges[jc] -= OccBetaOrbitals[i]*CoefBetaOrbitals[i][k]*CoefBetaOrbitals[i][l]*o; } nAll++; if(nAll>=pos) { pos += delta; progress_orb_txt(scal,str,FALSE); } } } progress_orb_txt(0," ",TRUE); result = g_malloc(Ncenters*100*sizeof(gchar)); tmp = g_malloc(BSIZE*sizeof(gchar)); sprintf(result," Mulliken charges\n"); setTextInProgress(_("Preparation of text to show... Please wait")); for(i=0;i<Ncenters;i++) { if(CancelCalcul) break; sprintf(tmp,"Atom# %d : %lf\n",i+1,charges[i]); strcat(result,tmp); if(CancelCalcul) break; } g_free(tmp); progress_orb_txt(0," ",TRUE); if(result && !CancelCalcul) { GtkWidget* message = showCalculatedChargesDlg(result,"Mulliken charges",charges); gtk_window_set_modal (GTK_WINDOW (message), TRUE); gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } g_free(result); } /************************************************************************************************************/ static void setBondOrdersToCalculated(GtkWidget *win) { gint i; gint j; gdouble* bondOrders = NULL; if(GTK_IS_WIDGET(win)) bondOrders = g_object_get_data(G_OBJECT (win), "BondOrders"); if(!bondOrders) return; freeBondsOrb(); if(Ncenters<1) return ; for(i = 0;i<Ncenters;i++) { for(j=i+1;j<Ncenters;j++) { gint ii = i*Ncenters + j - i*(i+1)/2; if(i>j) ii = j*Ncenters + i - j*(j+1)/2; if((gint)(bondOrders[ii]+0.5)==1) { BondType* A=g_malloc(sizeof(BondType)); A->n1 = i; A->n2 = j; A->bondType = GABEDIT_BONDTYPE_SINGLE; BondsOrb = g_list_append(BondsOrb,A); } else if((gint)(bondOrders[ii]+0.5)==2) { BondType* A=g_malloc(sizeof(BondType)); A->n1 = i; A->n2 = j; A->bondType = GABEDIT_BONDTYPE_DOUBLE; BondsOrb = g_list_append(BondsOrb,A); } else if((gint)(bondOrders[ii]+0.5)==3) { BondType* A=g_malloc(sizeof(BondType)); A->n1 = i; A->n2 = j; A->bondType = GABEDIT_BONDTYPE_TRIPLE; BondsOrb = g_list_append(BondsOrb,A); } else if(ShowHBondOrb && hbonded(i,j)) { BondType* A=g_malloc(sizeof(BondType)); A->n1 = i; A->n2 = j; A->bondType = GABEDIT_BONDTYPE_HYDROGEN; BondsOrb = g_list_append(BondsOrb,A); } } } RebuildGeom = TRUE; glarea_rafresh(GLArea); } /************************************************************************************************************/ static void destroyCalculatedBondOrdersDlg(GtkWidget *win) { gdouble* bondOrders = NULL; if(GTK_IS_WIDGET(win)) bondOrders = g_object_get_data(G_OBJECT (win), "BondOrders"); if(bondOrders) g_free(bondOrders); if(GTK_IS_WIDGET(win)) delete_child(win); if(GTK_IS_WIDGET(win)) gtk_widget_destroy(win); } /********************************************************************************/ static GtkWidget* showCalculatedBondOrdersDlg(gchar *message,gchar *title,gdouble* bondOrders) { GtkWidget *dlgWin = NULL; GtkWidget *frame; GtkWidget *vboxframe; GtkWidget *txtWid; GtkWidget *button; dlgWin = gtk_dialog_new(); gtk_widget_realize(GTK_WIDGET(dlgWin)); gtk_window_set_title(GTK_WINDOW(dlgWin),title); gtk_window_set_position(GTK_WINDOW(dlgWin),GTK_WIN_POS_CENTER); gtk_window_set_modal (GTK_WINDOW (dlgWin), TRUE); gtk_window_set_transient_for(GTK_WINDOW(dlgWin),GTK_WINDOW(PrincipalWindow)); g_signal_connect(G_OBJECT(dlgWin), "delete_event", (GCallback)destroyCalculatedBondOrdersDlg, NULL); frame = gtk_frame_new (NULL); gtk_frame_set_shadow_type( GTK_FRAME(frame),GTK_SHADOW_ETCHED_OUT); gtk_container_set_border_width (GTK_CONTAINER (frame), 5); gtk_box_pack_start( GTK_BOX(GTK_DIALOG(dlgWin)->vbox), frame,TRUE,TRUE,0); gtk_widget_show (frame); vboxframe = create_vbox(frame); txtWid = create_text_widget(vboxframe,NULL,&frame); if(message) gabedit_text_insert (GABEDIT_TEXT(txtWid), NULL, NULL, NULL,message,-1); gtk_box_set_homogeneous (GTK_BOX( GTK_DIALOG(dlgWin)->action_area), FALSE); button = create_button(dlgWin,_("Multiple bonds <= Calculated bondOrders")); gtk_box_pack_end (GTK_BOX( GTK_DIALOG(dlgWin)->action_area), button, FALSE, TRUE, 5); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); g_signal_connect_swapped(G_OBJECT(button), "clicked", (GCallback)setBondOrdersToCalculated, GTK_OBJECT(dlgWin)); button = create_button(dlgWin,"Close"); gtk_box_pack_end (GTK_BOX( GTK_DIALOG(dlgWin)->action_area), button, FALSE, TRUE, 5); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); g_signal_connect_swapped(G_OBJECT(button), "clicked", (GCallback)destroyCalculatedBondOrdersDlg, GTK_OBJECT(dlgWin)); add_button_windows(title,dlgWin); gtk_window_set_default_size (GTK_WINDOW(dlgWin), (gint)(ScreenHeight*0.6), (gint)(ScreenHeight*0.5)); gtk_widget_show_all(dlgWin); g_object_set_data(G_OBJECT (dlgWin), "BondOrders",bondOrders); return dlgWin; } /********************************************************************************/ void compute_bondOrders() { gint i,j,k,l,m; gchar* result = NULL; gdouble* bondOrders = NULL; gchar* tmp = NULL; gdouble o; gint nAll = 0; gint delta = 0; gint pos = 0; gdouble scal; gchar str[BSIZE]; gdouble** S = NULL; gdouble** Pa = NULL; gdouble** Pb = NULL; gdouble** PS = NULL; gint n2 = Ncenters*(Ncenters+1)/2; gint kk; if(Ncenters<1) return; if(!AOrb && (!SAOrb || !SOverlaps)) return; destroy_win_list(); sprintf(str,_("Computing of bond order matrix... Please wait")); setTextInProgress(str); scal = 0.01; delta = (gint)(NAOrb*(NAOrb+1)/2*scal); if(delta<1) delta = 1; pos = delta; bondOrders = g_malloc(n2*sizeof(gdouble)); for(i=0;i<n2;i++) bondOrders[i] = 0; S = g_malloc(NAOrb*sizeof(gdouble*)); for(i=0;i<NAOrb;i++) S[i] = g_malloc(NAOrb*sizeof(gdouble)); for(i=0;i<NAOrb;i++) for(j=0;j<NAOrb;j++) S[i][j] = 0; Pa = g_malloc(NAOrb*sizeof(gdouble*)); for(i=0;i<NAOrb;i++) Pa[i] = g_malloc(NAOrb*sizeof(gdouble)); for(i=0;i<NAOrb;i++) for(j=0;j<NAOrb;j++) Pa[i][j] = 0; Pb = g_malloc(NAOrb*sizeof(gdouble*)); for(i=0;i<NAOrb;i++) Pb[i] = g_malloc(NAOrb*sizeof(gdouble)); for(i=0;i<NAOrb;i++) for(j=0;j<NAOrb;j++) Pb[i][j] = 0; PS = g_malloc(NAOrb*sizeof(gdouble*)); for(i=0;i<NAOrb;i++) PS[i] = g_malloc(NAOrb*sizeof(gdouble)); for(i=0;i<NAOrb;i++) for(j=0;j<NAOrb;j++) PS[i][j] = 0; progress_orb_txt(0,str,TRUE); kk = 0; for(k=0;k<NAOrb;k++) { for(l=0;l<=k;l++) { double s = 0; if(CancelCalcul) break; if(AOrb) o = overlapCGTF(&AOrb[k],&AOrb[l]); else o = SOverlaps[kk++]; S[k][l] = o; if(k!=l) S[l][k] = S[k][l]; s = 0; for(i=0;i<NAOrb;i++) s += OccAlphaOrbitals[i]*CoefAlphaOrbitals[i][k]*CoefAlphaOrbitals[i][l]; Pa[k][l] += s; if(k!=l) Pa[l][k] += s; s = 0; for(i=0;i<NAOrb;i++) s += OccBetaOrbitals[i]*CoefBetaOrbitals[i][k]*CoefBetaOrbitals[i][l]; Pb[k][l] += s; if(k!=l) Pb[l][k] += s; nAll++; if(nAll>=pos) { pos += delta; progress_orb_txt(scal,str,FALSE); } } } for(k=0;k<NAOrb;k++) for(l=0;l<NAOrb;l++) { PS[k][l] = 0; for(m=0;m<NAOrb;m++) PS[k][l] += Pa[k][m]*S[m][l]; } /* printf("Density matrix alpha\n"); for(k=0;k<NAOrb;k++) {for(l=0;l<=k;l++) printf("%f ",PS[k][l]); printf("\n");} */ double s1 = 0; for(k=0;k<NAOrb;k++) { gint i = (AOrb)?AOrb[k].NumCenter:SAOrb[k].NumCenter; for(l=0;l<NAOrb;l++) { gint j = (AOrb)?AOrb[l].NumCenter:SAOrb[l].NumCenter; gint ii = i*Ncenters + j - i*(i+1)/2; if(i>j) ii = j*Ncenters + i - j*(j+1)/2; bondOrders[ii] += PS[k][l]*PS[l][k]; } /* printf(" k %d %f\n",i, PS[k][k]);*/ s1 += PS[k][k]; } /* printf(" s1 = %f\n",s1);*/ for(k=0;k<NAOrb;k++) for(l=0;l<NAOrb;l++) { PS[k][l] = 0; for(m=0;m<NAOrb;m++) PS[k][l] += Pb[k][m]*S[m][l]; } /* printf("Density matrix beta\n"); for(k=0;k<NAOrb;k++) {for(l=0;l<=k;l++) printf("%f ",2*PS[k][l]); printf("\n");} */ double s2 = 0; for(k=0;k<NAOrb;k++) { gint i = (AOrb)?AOrb[k].NumCenter:SAOrb[k].NumCenter; for(l=0;l<NAOrb;l++) { gint j = (AOrb)?AOrb[l].NumCenter:SAOrb[l].NumCenter; gint ii = i*Ncenters + j - i*(i+1)/2; if(i>j) ii = j*Ncenters + i - j*(j+1)/2; bondOrders[ii] += PS[k][l]*PS[l][k]; } /* printf(" k %d %f\n",i, PS[k][k]);*/ s2 += PS[k][k]; } /* printf(" s2 = %f\n",s2);*/ progress_orb_txt(0," ",TRUE); for(i=0;i<NAOrb;i++) g_free(S[i]); g_free(S); for(i=0;i<NAOrb;i++) g_free(Pa[i]); g_free(Pa); for(i=0;i<NAOrb;i++) g_free(Pb[i]); g_free(Pb); for(i=0;i<NAOrb;i++) g_free(PS[i]); g_free(PS); result = g_malloc(n2*100*sizeof(gchar)); tmp = g_malloc(BSIZE*sizeof(gchar)); sprintf(result," BondOrders\n"); setTextInProgress(_("Preparation of text to show... Please wait")); for(i=0;i<Ncenters;i++) for(j=i+1;j<Ncenters;j++) { gint ii = i*Ncenters + j - i*(i+1)/2; if(i>j) ii = j*Ncenters + i - j*(j+1)/2; if(CancelCalcul) break; sprintf(tmp,"Bond %d-%d : %lf\n",i+1,j+1,bondOrders[ii]); strcat(result,tmp); if(CancelCalcul) break; } g_free(tmp); progress_orb_txt(0," ",TRUE); if(result && !CancelCalcul) { GtkWidget* message = showCalculatedBondOrdersDlg(result,"Bond orders ",bondOrders); gtk_window_set_modal (GTK_WINDOW (message), TRUE); gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } g_free(result); } /********************************************************************************/ static void messageErrorTrans(gchar* fileName) { gchar buffer[BSIZE]; sprintf(buffer,_("Sorry, I can not read transition properties from '%s' file\n"),fileName); Message(buffer,_("Error"),TRUE); } /********************************************************************************/ /* static gboolean read_tansition_properties(GabeditFileChooser *SelecFile, gint response_id) { gchar t[BSIZE]; gchar type1[20]; gchar type2[20]; gint i1; gint i2; gdouble coef; gboolean OK = TRUE; gint numberOfTransitions = 0; gint* fromI = NULL; gint* toI = NULL; gchar** fromType = NULL; gchar** toType = NULL; gdouble* coefficients = NULL; gchar *FileName; FILE *fd; int ne = 0; if(response_id != GTK_RESPONSE_OK) return FALSE; FileName = gabedit_file_chooser_get_current_file(SelecFile); fd = FOpen(FileName, "rb"); if(!fd) return FALSE; while(!feof(fd)) { if(!fgets(t,BSIZE,fd))break; ne = sscanf(t,"%d %s %d %s %lf",&i1,type1, &i2, type2, &coef); if(ne==5 && i1<=NAOrb && i2<=NAOrb && i1>0 && i2>0) { numberOfTransitions++; coefficients = g_realloc(coefficients, numberOfTransitions*sizeof(gdouble)); fromI = g_realloc(fromI, numberOfTransitions*sizeof(gint)); toI = g_realloc(toI, numberOfTransitions*sizeof(gint)); fromType = g_realloc(fromType, numberOfTransitions*sizeof(gchar*)); toType = g_realloc(toType, numberOfTransitions*sizeof(gchar*)); coefficients[numberOfTransitions-1] = coef; fromI[numberOfTransitions-1] = i1; toI[numberOfTransitions-1] = i2; fromType[numberOfTransitions-1] = g_strdup(type1); toType[numberOfTransitions-1] = g_strdup(type2); printf("t=%s\n",t); } else { OK= FALSE; break;} } if(numberOfTransitions>0 && OK) { //createIRSpectrumWin(numberOfFrequencies, frequencies, intensities); } else { OK = FALSE; messageErrorTrans(FileName); } if(coefficients) g_free(coefficients); if(fromType) { gint i; for(i=0;i<numberOfTransitions;i++) if(fromType[i]) g_free(fromType[i]); g_free(fromType); } if(toType) { gint i; for(i=0;i<numberOfTransitions;i++) if(toType[i]) g_free(toType[i]); g_free(toType); } if(fromI) g_free(fromI); if(toI) g_free(toI); fclose(fd); return OK; } */ /********************************************************************************/ /* void lambda_diagnostic_dlg() { GtkWidget* filesel = file_chooser_open(read_tansition_properties, _("Read transition properties from a sample file(5columns : num1 type(alpha or beta) num2 type coffeifient)"), GABEDIT_TYPEFILE_TXT,GABEDIT_TYPEWIN_OTHER); gtk_window_set_modal (GTK_WINDOW (filesel), TRUE); } */ /********************************************************************************/ static void apply_lambda_diagnostic(GtkWidget *Win,gpointer data) { GtkWidget** entriestmp = NULL; G_CONST_RETURN gchar* temp; gchar* dump; gint i; gint j; GridLimits limitstmp; gint NumPointstmp[3]; GtkWidget *entries[3][6]; gdouble V[3][3]; GtkWidget* buttonFileSelector = NULL; gdouble integ[3], normi, normj, overlap; gchar* result = NULL; gchar t[BSIZE]; gchar type1[20]; gchar type2[20]; gint i1; gint i2; gdouble coef; gboolean OK = TRUE; gint numberOfTransitions = 0; gint* fromI = NULL; gint* toI = NULL; gint* fromType = NULL; gint* toType = NULL; gdouble* coefficients = NULL; gchar *FileName; FILE *fd; int ne = 0; if(GTK_IS_WIDGET(Win)) { entriestmp = (GtkWidget **)g_object_get_data(G_OBJECT (Win), "Entries"); buttonFileSelector = g_object_get_data (G_OBJECT (Win), "ButtonFileSelector"); } else return; if(entriestmp==NULL) return; if(!buttonFileSelector) return; for(i=0;i<3;i++) for(j=0;j<6;j++) entries[i][j] = entriestmp[i*6+j]; for(i=0;i<3;i++) { for(j=3;j<5;j++) { temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { limitstmp.MinMax[j-3][i] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } temp = gtk_entry_get_text(GTK_ENTRY(entries[i][5])); NumPointstmp[i] = atoi(temp); if(NumPointstmp[i] <=2) { GtkWidget* message = Message(_("Error : The number of points should be > 2. "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { if( limitstmp.MinMax[0][i]> limitstmp.MinMax[1][i]) { GtkWidget* message = Message(_("Error : The minimal value should be smaller than the maximal value "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { V[i][j] = 0; temp = gtk_entry_get_text(GTK_ENTRY(entries[i][j])); dump = NULL; if(temp && strlen(temp)>0) { dump = g_strdup(temp); delete_first_spaces(dump); delete_last_spaces(dump); } if(dump && strlen(dump)>0 && this_is_a_real(dump)) { V[i][j] = atof(dump); } else { GtkWidget* message = Message(_("Error : an entry is not a float "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } if(dump) g_free(dump); } } for(i=0;i<3;i++) { gdouble norm = 0.0; for(j=0;j<3;j++) norm += V[i][j]*V[i][j]; if(fabs(norm)<1e-8) { GtkWidget* message = Message(_("Error : the norm is equal to 0 "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } for(j=0;j<3;j++) V[i][j] /= sqrt(norm); } for(j=0;j<3;j++) originOfCube[j] = 0; for(j=0;j<3;j++) firstDirection[j] = V[0][j]; for(j=0;j<3;j++) secondDirection[j] = V[1][j]; for(j=0;j<3;j++) thirdDirection[j] = V[2][j]; for(i=0;i<3;i++) { NumPoints[i] =NumPointstmp[i] ; for(j=0;j<2;j++) limits.MinMax[j][i] =limitstmp.MinMax[j][i]; } CancelCalcul = FALSE; /* printf("DirName = %s\n",dirName);*/ FileName = gabedit_file_chooser_get_current_file(GABEDIT_FILE_CHOOSER(buttonFileSelector)); fd = FOpen(FileName, "rb"); if(!fd) { GtkWidget* message = Message(_("I cannot open the data file "),_("Error"),TRUE); gtk_window_set_modal (GTK_WINDOW (message), TRUE); return; } while(!feof(fd)) { gdouble scale = 1.0; if(!fgets(t,BSIZE,fd))break; ne = sscanf(t,"%d %s %d %s %lf",&i1,type1, &i2, type2, &coef); if(ne!=5 ) { ne = sscanf(t,"%d %d %lf",&i1, &i2, &coef); ne=5; sprintf(type1,"A"); sprintf(type2,"A"); scale = sqrt(2.0);} if(ne==5 && i1<=NAOrb && i2<=NAOrb && i1>0 && i2>0) { numberOfTransitions++; coefficients = g_realloc(coefficients, numberOfTransitions*sizeof(gdouble)); fromI = g_realloc(fromI, numberOfTransitions*sizeof(gint)); toI = g_realloc(toI, numberOfTransitions*sizeof(gint)); fromType = g_realloc(fromType, numberOfTransitions*sizeof(gchar*)); toType = g_realloc(toType, numberOfTransitions*sizeof(gchar*)); coefficients[numberOfTransitions-1] = coef*scale; fromI[numberOfTransitions-1] = i1-1; toI[numberOfTransitions-1] = i2-1; fromType[numberOfTransitions-1] = 1; toType[numberOfTransitions-1] = 1; if(strstr(type1,"B") || strstr(type1,"b")) fromType[numberOfTransitions-1] = 2; if(strstr(type2,"B") || strstr(type2,"b")) toType[numberOfTransitions-1] = 2; printf("t=%s\n",t); } else { OK= FALSE; break;} } if(numberOfTransitions==0 || !OK) { messageErrorTrans(FileName); if(coefficients) g_free(coefficients); if(fromType) g_free(fromType); if(toType) g_free(toType); if(fromI) g_free(fromI); if(toI) g_free(toI); return; } fclose(fd); /* computing */ { gint typeOrbi = 1; gint typeOrbj = 1; gdouble lambda = 0.0; gdouble sum = 0.0; gdouble cc = 0.0; gchar* old; delete_child(Win); for(i=0;i<numberOfTransitions;i++) { gchar* tmp = NULL; gint ii = fromI[i]; gint jj = toI[i]; typeOrbi = fromType[i]; typeOrbj = toType[i]; if(CancelCalcul) break; tmp = compute_spatial_overlapij( NumPoints,limits, typeOrbi, ii, typeOrbj, jj, integ, &normi, &normj, &overlap); if(tmp) { old = result; if(old) { result = g_strdup_printf("%s%s",old,tmp); g_free(old); } else result = g_strdup_printf("%s",tmp); } cc = coefficients[i]*coefficients[i]; sum += cc; lambda += *integ*cc; } if(sum>0) lambda /= sum; /* put result in result variable */ old = result; if(old) { result = g_strdup_printf("%s\nSum = %f\nLambda = %f\n",old,sum,lambda); g_free(old); } else result = g_strdup_printf("Sum = %f\nLambda = %f\n",sum,lambda); } if(result && !CancelCalcul) { GtkWidget* message = MessageTxt(result,_("Result")); gtk_window_set_default_size (GTK_WINDOW(message),(gint)(ScreenWidth*0.8),-1); gtk_widget_set_size_request(message,(gint)(ScreenWidth*0.45),-1); /* gtk_window_set_modal (GTK_WINDOW (message), TRUE);*/ gtk_window_set_transient_for(GTK_WINDOW(message),GTK_WINDOW(PrincipalWindow)); } set_label_title(NULL,0,0); if(CancelCalcul) CancelCalcul = FALSE; if(coefficients) g_free(coefficients); if(fromType) g_free(fromType); if(toType) g_free(toType); if(fromI) g_free(fromI); if(toI) g_free(toI); } /***************************************************************************/ static void help_trans_prop() { gchar temp[BSIZE]; GtkWidget* win; sprintf(temp, _(" Lambda is calculated as in M.J.G. Peach et al. J. Chem. Phys. 128, 044118 (2008).\n\n" " You must select the file containing the transition properties. \n\n" " The text file must contain 5 columns by line.\n" " First line : an integer. The electron is excited from this orbital.\n" " second line : a character B or A. The spin of electron.\n" " Third line : an integer. The electron is excited to this orbital.\n" " Forth line : a character B or A. The spin of electron.\n" " Fifth line : a float. The largest coefficients in the CI expansion.\n\n" " Example :\n" " 5 B 6 B 0.401\n" " 4 A 7 B 0.205\n\n" " A text file with 3 columns by line is also accepted.\n" " Example :\n" " 5 6 0.401\n" " 4 7 0.205\n\n" ) ); win = Message(temp,_(" Info "),FALSE); gtk_window_set_modal (GTK_WINDOW (win), TRUE); } /********************************************************************************/ void lambda_diagnostic_dlg() { GtkWidget *Win; GtkWidget *frameGrid; GtkWidget *hbox; GtkWidget *vboxall; GtkWidget *vboxwin; GtkWidget *button; /* GtkWidget *label;*/ GtkWidget** entries; GtkWidget *buttonFileSelector; G_CONST_RETURN gchar* temp; static gboolean first = TRUE; if(!GeomOrb) { Message(_("Sorry, Please read the MO before\n"),_("Error"),TRUE); return; } if(!CoefAlphaOrbitals) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOrb && !SAOrb) { Message(_("Sorry, Please load the MO before\n"),_("Error"),TRUE); return; } if(!AOAvailable &&(TypeGrid == GABEDIT_TYPEGRID_DDENSITY || TypeGrid == GABEDIT_TYPEGRID_ADENSITY)) { Message(_("Sorry, No atomic orbitals available.\nPlease use a gabedit file for load : \n" "Geometry, Molecular and Atomic Orbitals\n"),_("Error"),TRUE); return; } Win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(Win),"Lambda diagnostic"); gtk_window_set_position(GTK_WINDOW(Win),GTK_WIN_POS_CENTER); gtk_container_set_border_width (GTK_CONTAINER (Win), 5); gtk_window_set_transient_for(GTK_WINDOW(Win),GTK_WINDOW(PrincipalWindow)); gtk_window_set_modal (GTK_WINDOW (Win), TRUE); add_glarea_child(Win,"Grid "); vboxall = create_vbox(Win); vboxwin = vboxall; hbox = gtk_hbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (vboxall), hbox, TRUE, TRUE, 0); /* label = gtk_label_new(_("File containing the transition properties :")); gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); */ buttonFileSelector = gtk_file_chooser_button_new(_("select the file containing the transition properties(5columns : num1 type(alpha or beta) num2 type coefficient)"), GTK_FILE_CHOOSER_ACTION_OPEN); g_object_set_data (G_OBJECT (Win), "ButtonFileSelector",buttonFileSelector); gtk_box_pack_start (GTK_BOX (hbox), buttonFileSelector, TRUE, TRUE, 5); button = create_button(Win,_("Help")); gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 5); gtk_widget_show (button); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)help_trans_prop,G_OBJECT(Win)); gtk_box_pack_start (GTK_BOX (vboxall), gtk_hseparator_new(), TRUE, TRUE, 5); frameGrid = create_grid_frame(vboxall,"Box & Grid"); entries = (GtkWidget**) g_object_get_data (G_OBJECT (frameGrid), "Entries"); if(first) { temp = gtk_entry_get_text(GTK_ENTRY(entries[3])); if(temp && strlen(temp)>0) { gchar* newval = g_strdup_printf("%f",atof(temp)*5); gtk_entry_set_text(GTK_ENTRY(entries[3]),newval); } first = FALSE; } g_object_set_data (G_OBJECT (Win), "Entries",entries); g_object_set_data (G_OBJECT (Win), "FrameGrid",frameGrid); gtk_widget_set_sensitive(frameGrid, TRUE); hbox = create_hbox_false(vboxwin); gtk_widget_realize(Win); button = create_button(Win,_("OK")); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_widget_grab_default(button); gtk_widget_show (button); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)apply_lambda_diagnostic,G_OBJECT(Win)); button = create_button(Win,_("Cancel")); GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT); gtk_box_pack_end (GTK_BOX( hbox), button, FALSE, TRUE, 3); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)delete_child, G_OBJECT(Win)); g_signal_connect_swapped(G_OBJECT(button), "clicked",(GCallback)gtk_widget_destroy,G_OBJECT(Win)); gtk_widget_show (button); gtk_widget_show_all (Win); }
irbuilder_unroll_partial_factor_for.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 #ifndef HEADER #define HEADER // CHECK-LABEL: define {{.*}}@unroll_partial_heuristic_for( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[N_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: %[[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 i32 %[[N:.+]], i32* %[[N_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 i32 0, 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, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 1 // CHECK-NEXT: store i32* %[[N_ADDR]], i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP2:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[TMP2]], 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: %[[TMP4:.+]] = udiv i32 %[[DOTCOUNT]], 13 // CHECK-NEXT: %[[TMP5:.+]] = urem i32 %[[DOTCOUNT]], 13 // CHECK-NEXT: %[[TMP6:.+]] = icmp ne i32 %[[TMP5]], 0 // CHECK-NEXT: %[[TMP7:.+]] = zext i1 %[[TMP6]] to i32 // CHECK-NEXT: %[[OMP_FLOOR0_TRIPCOUNT:.+]] = add nuw i32 %[[TMP4]], %[[TMP7]] // CHECK-NEXT: br label %[[OMP_FLOOR0_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_PREHEADER]]: // CHECK-NEXT: store i32 0, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP8:.+]] = sub i32 %[[OMP_FLOOR0_TRIPCOUNT]], 1 // CHECK-NEXT: store i32 %[[TMP8]], 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_for_static_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 34, i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]], i32 1, i32 0) // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: %[[TMP11:.+]] = sub i32 %[[TMP10]], %[[TMP9]] // CHECK-NEXT: %[[TMP12:.+]] = add i32 %[[TMP11]], 1 // CHECK-NEXT: br label %[[OMP_FLOOR0_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_HEADER]]: // CHECK-NEXT: %[[OMP_FLOOR0_IV:.+]] = phi i32 [ 0, %[[OMP_FLOOR0_PREHEADER]] ], [ %[[OMP_FLOOR0_NEXT:.+]], %[[OMP_FLOOR0_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_FLOOR0_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_COND]]: // CHECK-NEXT: %[[OMP_FLOOR0_CMP:.+]] = icmp ult i32 %[[OMP_FLOOR0_IV]], %[[TMP12]] // CHECK-NEXT: br i1 %[[OMP_FLOOR0_CMP]], label %[[OMP_FLOOR0_BODY:.+]], label %[[OMP_FLOOR0_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_BODY]]: // CHECK-NEXT: %[[TMP13:.+]] = add i32 %[[OMP_FLOOR0_IV]], %[[TMP9]] // CHECK-NEXT: %[[TMP14:.+]] = icmp eq i32 %[[TMP13]], %[[OMP_FLOOR0_TRIPCOUNT]] // CHECK-NEXT: %[[TMP15:.+]] = select i1 %[[TMP14]], i32 %[[TMP5]], i32 13 // CHECK-NEXT: br label %[[OMP_TILE0_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_PREHEADER]]: // CHECK-NEXT: br label %[[OMP_TILE0_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_HEADER]]: // CHECK-NEXT: %[[OMP_TILE0_IV:.+]] = phi i32 [ 0, %[[OMP_TILE0_PREHEADER]] ], [ %[[OMP_TILE0_NEXT:.+]], %[[OMP_TILE0_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_TILE0_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_COND]]: // CHECK-NEXT: %[[OMP_TILE0_CMP:.+]] = icmp ult i32 %[[OMP_TILE0_IV]], %[[TMP15]] // CHECK-NEXT: br i1 %[[OMP_TILE0_CMP]], label %[[OMP_TILE0_BODY:.+]], label %[[OMP_TILE0_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_BODY]]: // CHECK-NEXT: %[[TMP16:.+]] = mul nuw i32 13, %[[TMP13]] // CHECK-NEXT: %[[TMP17:.+]] = add nuw i32 %[[TMP16]], %[[OMP_TILE0_IV]] // CHECK-NEXT: br label %[[OMP_LOOP_BODY:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[TMP17]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP18:.+]] = load float*, float** %[[B_ADDR]], align 8 // CHECK-NEXT: %[[TMP19:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = sext i32 %[[TMP19]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP18]], i64 %[[IDXPROM]] // CHECK-NEXT: %[[TMP20:.+]] = load float, float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: %[[TMP21:.+]] = load float*, float** %[[C_ADDR]], align 8 // CHECK-NEXT: %[[TMP22:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM2:.+]] = sext i32 %[[TMP22]] to i64 // CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP21]], i64 %[[IDXPROM2]] // CHECK-NEXT: %[[TMP23:.+]] = load float, float* %[[ARRAYIDX3]], align 4 // CHECK-NEXT: %[[MUL:.+]] = fmul float %[[TMP20]], %[[TMP23]] // CHECK-NEXT: %[[TMP24:.+]] = load float*, float** %[[D_ADDR]], align 8 // CHECK-NEXT: %[[TMP25:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM4:.+]] = sext i32 %[[TMP25]] to i64 // CHECK-NEXT: %[[ARRAYIDX5:.+]] = getelementptr inbounds float, float* %[[TMP24]], i64 %[[IDXPROM4]] // CHECK-NEXT: %[[TMP26:.+]] = load float, float* %[[ARRAYIDX5]], align 4 // CHECK-NEXT: %[[MUL6:.+]] = fmul float %[[MUL]], %[[TMP26]] // CHECK-NEXT: %[[TMP27:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP28:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM7:.+]] = sext i32 %[[TMP28]] to i64 // CHECK-NEXT: %[[ARRAYIDX8:.+]] = getelementptr inbounds float, float* %[[TMP27]], i64 %[[IDXPROM7]] // CHECK-NEXT: store float %[[MUL6]], float* %[[ARRAYIDX8]], align 4 // CHECK-NEXT: br label %[[OMP_TILE0_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_INC]]: // CHECK-NEXT: %[[OMP_TILE0_NEXT]] = add nuw i32 %[[OMP_TILE0_IV]], 1 // CHECK-NEXT: br label %[[OMP_TILE0_HEADER]], !llvm.loop ![[LOOP3:[0-9]+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_EXIT]]: // CHECK-NEXT: br label %[[OMP_TILE0_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_AFTER]]: // CHECK-NEXT: br label %[[OMP_FLOOR0_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_INC]]: // CHECK-NEXT: %[[OMP_FLOOR0_NEXT]] = add nuw i32 %[[OMP_FLOOR0_IV]], 1 // CHECK-NEXT: br label %[[OMP_FLOOR0_HEADER]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_EXIT]]: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]]) // 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_FLOOR0_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_AFTER]]: // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-NEXT: } void unroll_partial_heuristic_for(int n, float *a, float *b, float *c, float *d) { #pragma omp for #pragma omp unroll partial(13) for (int i = 0; i < n; i++) { 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: %[[TMP4:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 1 // CHECK-NEXT: %[[TMP5:.+]] = load i32*, i32** %[[TMP4]], align 8 // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[TMP5]], align 4 // CHECK-NEXT: store i32 %[[TMP6]], i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 1, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp slt i32 %[[TMP7]], %[[TMP8]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub nsw i32 %[[TMP9]], %[[TMP10]] // CHECK-NEXT: %[[TMP11:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP11]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]] // CHECK-NEXT: %[[TMP12:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP12]] // 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: %[[TMP13:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP13]], 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 1, %[[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 51} // CHECK: ![[META2:[0-9]+]] = // CHECK: ![[LOOP3]] = distinct !{![[LOOP3]], ![[LOOPPROP4:[0-9]+]], ![[LOOPPROP5:[0-9]+]]} // CHECK: ![[LOOPPROP4]] = !{!"llvm.loop.unroll.enable"} // CHECK: ![[LOOPPROP5]] = !{!"llvm.loop.unroll.count", i32 13}
omp-hello-world.c
/***************************************************************************** Example : omp-hello-world.c Objective : OpenMP program to print "Hello World" This example demonstrates the use of omp_get_thread_num() omp_get_num_threads() calls Input : Set the number of threads to use by means of the OMP_NUM_THREADS environment variable. For C shell use command : setenv OMP_NUM_THREADS 4 For bash shell use command : export OMP_NUM_THREADS=4. Output : Each thread prints a message "Hello World" and its identifier. Created : Aug 2011 Author : RarchK *********************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<omp.h> /* Main Program */ int main(int argc , char **argv) { int Threadid, Noofthreads; printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Email : RarchK"); printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Objective : OpenMP program to print \"Hello World\" using OpenMP PARALLEL directives\n "); printf("\n\t\t..........................................................................\n"); /* Set the number of threads */ /* omp_set_num_threads(4); */ /* OpenMP Parallel Construct : Fork a team of threads */ #pragma omp parallel private(Threadid) { /* Obtain the thread id */ Threadid = omp_get_thread_num(); printf("\n\t\t Hello World is being printed by the thread : %d\n", Threadid); /* Master Thread Has Its Threadid 0 */ if (Threadid == 0) { Noofthreads = omp_get_num_threads(); printf("\n\t\t Master thread printing total number of threads for this execution are : %d\n", Noofthreads); } }/* All thread join Master thread */ return 0; }
openssl_enc_fmt_plug.c
/* OpenSSL "enc" cracker for JtR. * * This software is Copyright (c) 2013, Dhiru Kholia <dhiru at openwall.com> * * $ openssl enc -aes-256-cbc -p -e -a -salt -in hello.txt -out hello.txt.enc * enter aes-256-cbc encryption password: * Verifying - enter aes-256-cbc encryption password: * salt=305CEDC2A0521011 * key=E08A1E6E1493BD3D3DAA25E112259D1688F7A0302AC8C16208DBDCEF179765F0 * iv =582FDDF9603B9B03A54FC0BB34370DDE * * $ cat hello.txt * 123456789012 * * Input Format: * * $openssl$cipher$md$salt-size$salt$last-chunks$inlined$known-plaintext$plaintext * $openssl$cipher$md$salt-size$salt$last-chunks$0$datalen$data$known-plaintext$plaintext */ #if FMT_EXTERNS_H extern struct fmt_main fmt_openssl; #elif FMT_REGISTERS_H john_register_one(&fmt_openssl); #else #if AC_BUILT #include "autoconfig.h" #endif #ifdef __CYGWIN__ // cygwin has HORRIBLE performance GOMP for this format it runs at 1/#cpu's the speed of OMP_NUM_THREADS=1 or non-GMP build #undef _OPENMP #undef FMT_OMP #undef FMT_OMP_BAD #define FMT_OMP 0 #define FMT_OMP_BAD 0 #endif #include <string.h> #include <errno.h> #if !AC_BUILT || HAVE_FCNTL_H #include <fcntl.h> #endif #include <stdlib.h> #include "stdint.h" #include <sys/types.h> #include <openssl/evp.h> #include "aes.h" #include "md5.h" #include "arch.h" #include "misc.h" #include "params.h" #include "common.h" #include "formats.h" #include "jumbo.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 8 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "openssl-enc" #define FORMAT_NAME "OpenSSL \"enc\" encryption" #define ALGORITHM_NAME "32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 0 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN sizeof(int) #define MIN_KEYS_PER_CRYPT 8 #define MAX_KEYS_PER_CRYPT 8 #define PLAINTEXT_LENGTH 125 #define FORMAT_TAG "$openssl$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked; static struct custom_salt { unsigned int saltlen; unsigned char salt[16]; int cipher; int md; int inlined; int kpa; int datalen; unsigned char kpt[256]; unsigned char data[16 * 16]; unsigned char last_chunks[32]; } *cur_salt; static struct fmt_tests openssl_tests[] = { {"$openssl$1$0$8$a1a5e529c8d92da5$8de763bf61377d365243993137ad9729$1$0", "password"}, {"$openssl$1$1$8$844527fb2f5d7ad5$ebccb1fcd2b1b30c5c3624d4016978ea$1$0", "password"}, {"$openssl$0$0$8$305cedc2a0521011$bf11609a01e78ec3f50f0cc483e636f9$1$0", "password"}, {"$openssl$0$0$8$305cedc2a0521011$bf11609a01e78ec3f50f0cc483e636f9$1$1$123456", "password"}, {"$openssl$0$0$8$3993671be477e8f0$95384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$0$256$9bbbc2af64ba27444370e3b3db6f4077a5b83c099a9b0a13d0c03dbc89185aad078266470bb15c44e7b35aef66f456ba7f44fb0f60824331f5b598347cd471c6745374c7dbecf49a1dd0378e938bb9d3d68703e3038805fb3c7bf0623222bcc8e9375b10853aa7c991ddd086b8e2a97dd9ddd351ee0facde9bc3529742f0ffab990db046f5a64765d7a4b1c83b0290acae3eaa09278933cddcf1fed0ab14d408cd43fb73d830237dcd681425cd878bf4b542c108694b90e82f912c4aa4de02bd002dce975c2bb308aad933bfcfd8375d91837048d110f007ba3852dbb498a54595384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$0", "password"}, {"$openssl$0$0$8$3993671be477e8f0$95384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$0$256$9bbbc2af64ba27444370e3b3db6f4077a5b83c099a9b0a13d0c03dbc89185aad078266470bb15c44e7b35aef66f456ba7f44fb0f60824331f5b598347cd471c6745374c7dbecf49a1dd0378e938bb9d3d68703e3038805fb3c7bf0623222bcc8e9375b10853aa7c991ddd086b8e2a97dd9ddd351ee0facde9bc3529742f0ffab990db046f5a64765d7a4b1c83b0290acae3eaa09278933cddcf1fed0ab14d408cd43fb73d830237dcd681425cd878bf4b542c108694b90e82f912c4aa4de02bd002dce975c2bb308aad933bfcfd8375d91837048d110f007ba3852dbb498a54595384ad4fb11d737dc7ba884ccece94698b46d68d28c5cc4297ce37aea91064e$1$00000000", "password"}, {NULL} }; static void init(struct fmt_main *self) { #if defined (_OPENMP) int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); cracked = mem_calloc(self->params.max_keys_per_crypt, sizeof(*cracked)); } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } //#define DEBUG_VALID #ifdef DEBUG_VALID // Awesome debug macro for valid() #define return if(printf("\noriginal: %s\n",ciphertext)+printf("fail line %u: '%s' p=%p q=%p q-p-1=%u\n",__LINE__,p,p,q,(unsigned int)(q-p-1)))return #endif static int valid(char *ciphertext, struct fmt_main *self) { char *p = ciphertext, *q = NULL; int len; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH) != 0) return 0; p += TAG_LENGTH; // cipher q = strchr(p, '$'); if (!q) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1') return 0; p = q; q = strchr(p, '$'); // md if (!q) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1') return 0; p = q; q = strchr(p, '$'); // salt-size if (!q) return 0; q = q + 1; len = strspn(p, DIGITCHARS); if (len < 1 || len > 2 || len != q - p - 1) return 0; len = atoi(p); if (len < 1 || len > sizeof(cur_salt->salt)) return 0; p = q; q = strchr(p, '$'); // salt if (!q) return 0; q = q + 1; if (2 * len != q - p - 1 || 2 * len != strspn(p, HEXCHARS_lc)) return 0; p = q; q = strchr(p, '$'); // last-chunks if (!q) return 0; q = q + 1; len = strspn(p, HEXCHARS_lc); if (len != q - p - 1 || len < 2 || (len & 1) || len/2 > sizeof(cur_salt->last_chunks)) return 0; p = q; q = strchr(p, '$'); // inlined if (!q) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1') return 0; if (*p == '0') { p = q; q = strchr(p, '$'); // datalen if (!q) return 0; q = q + 1; len = strspn(p, DIGITCHARS); if (len < 1 || len > 3 || len != q - p - 1) return 0; len = atoi(p); if (len < 1 || len > sizeof(cur_salt->data)) return 0; p = q; q = strchr(p, '$'); // data if (!q) return 0; q = q + 1; if (2 * len != q - p - 1 || 2 * len != strspn(p, HEXCHARS_all)) return 0; } p = q; q = strchr(p, '$'); // known-plaintext if (!q) return !strcmp(p, "0"); if(strlen(q) == 1) return 0; q = q + 1; if ((q - p - 1) != 1) return 0; if (*p != '0' && *p != '1') return 0; if (strlen(q) > sizeof(cur_salt->kpt) - 1) return 0; #ifdef DEBUG_VALID #undef return #endif return 1; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i, res; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += TAG_LENGTH; p = strtokm(ctcopy, "$"); cs.cipher = atoi(p); p = strtokm(NULL, "$"); cs.md = atoi(p); p = strtokm(NULL, "$"); cs.saltlen = atoi(p); p = strtokm(NULL, "$"); for (i = 0; i < cs.saltlen; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); res = strlen(p) / 2; for (i = 0; i < res; i++) cs.last_chunks[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); cs.inlined = atoi(p); if (cs.inlined) { p = strtokm(NULL, "$"); cs.kpa = atoi(p); if (cs.kpa) { p = strtokm(NULL, "$"); strncpy((char*)cs.kpt, p, 255); } } else { p = strtokm(NULL, "$"); cs.datalen = atoi(p); p = strtokm(NULL, "$"); for (i = 0; i < cs.datalen; i++) cs.data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); cs.kpa = atoi(p); if (cs.kpa) { p = strtokm(NULL, "$"); strncpy((char*)cs.kpt, p, 255); } } MEM_FREE(keeptr); return (void *)&cs; } static int kpa(unsigned char *key, unsigned char *iv, int inlined) { AES_KEY akey; unsigned char out[16*16]; if(AES_set_decrypt_key(key, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n"); } if (inlined) { AES_cbc_encrypt(cur_salt->last_chunks, out, 16, &akey, iv, AES_DECRYPT); if (memmem(out, 16, cur_salt->kpt, strlen((char*)cur_salt->kpt))) return 0; } else { AES_cbc_encrypt(cur_salt->data, out, cur_salt->datalen, &akey, iv, AES_DECRYPT); if (memmem(out, cur_salt->datalen, cur_salt->kpt, strlen((char*)cur_salt->kpt))) return 0; } return -1; } static int decrypt(char *password) { unsigned char out[16]; AES_KEY akey; unsigned char iv[16]; unsigned char biv[16]; unsigned char key[32]; int nrounds = 1; // FIXME handle more stuff switch(cur_salt->cipher) { case 0: switch(cur_salt->md) { case 0: EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 256, &akey); break; case 1: EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 256, &akey); break; } break; case 1: switch(cur_salt->md) { case 0: EVP_BytesToKey(EVP_aes_128_cbc(), EVP_md5(), cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 128, &akey); break; case 1: EVP_BytesToKey(EVP_aes_128_cbc(), EVP_sha1(), cur_salt->salt, (unsigned char*)password, strlen(password), nrounds, key, iv); AES_set_decrypt_key(key, 128, &akey); break; } break; } memcpy(biv, iv, 16); if (cur_salt->inlined) AES_cbc_encrypt(cur_salt->last_chunks, out, 16, &akey, iv, AES_DECRYPT); else { memcpy(iv, cur_salt->last_chunks, 16); AES_cbc_encrypt(cur_salt->last_chunks + 16, out, 16, &akey, iv, AES_DECRYPT); } // now check padding if (check_pkcs_pad(out, 16, 16) < 0) return -1; if(cur_salt->kpa) return kpa(key, biv, cur_salt->inlined); return 0; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static void openssl_set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { if (decrypt(saved_key[index]) == 0) cracked[index] = 1; else cracked[index] = 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; } struct fmt_main fmt_openssl = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD | FMT_NOT_EXACT, /* * FIXME: if there wouldn't be so many false positives, * it would be useful to report some tunable costs */ { NULL }, { FORMAT_TAG }, openssl_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, openssl_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
relax.c
/*BHEADER********************************************************************** * Copyright (c) 2006 The Regents of the University of California. * Produced at the Lawrence Livermore National Laboratory. * Written by the HYPRE team. UCRL-CODE-222953. * All rights reserved. * * This file is part of HYPRE (see http://www.llnl.gov/CASC/hypre/). * Please see the COPYRIGHT_and_LICENSE file for the copyright notice, * disclaimer, contact information and the GNU Lesser General Public License. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License (as published by the Free Software * Foundation) version 2.1 dated February 1999. * * HYPRE 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 terms and conditions of the GNU General * Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Revision: 2.8 $ ***********************************************************************EHEADER*/ /****************************************************************************** * * Relaxation scheme * *****************************************************************************/ #include "headers.h" #include "omp.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGSeqRelax *--------------------------------------------------------------------------*/ int hypre_BoomerAMGSeqRelax( hypre_CSRMatrix *A, hypre_Vector *f, hypre_Vector *u) { double *A_diag_data = hypre_CSRMatrixData(A); int *A_diag_i = hypre_CSRMatrixI(A); int *A_diag_j = hypre_CSRMatrixJ(A); int n = hypre_CSRMatrixNumRows(A); double *u_data = hypre_VectorData(u); double *f_data = hypre_VectorData(f); double *tmp_data; double res; int i, j; int ii, jj; int ns, ne, size, rest; int relax_error = 0; // int index, start; int num_threads; num_threads = hypre_NumThreads(); /*----------------------------------------------------------------------- * Switch statement to direct control based on relax_type: * relax_type = 3 -> hybrid: SOR-J mix off-processor, SOR on-processor * with outer relaxation parameters (forward solve) *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ if (1) { tmp_data = hypre_CTAlloc(double,n); #pragma omp parallel private(num_threads) { num_threads = omp_get_num_threads(); #pragma omp for private(i) schedule(dynamic, n/16) //#pragma omp for private(i) schedule(dynamic) for (i = 0; i < n; i++) tmp_data[i] = u_data[i]; #pragma omp for private(i,ii,j,jj,ns,ne,res,rest,size) schedule(dynamic,1) for (j = 0; j < num_threads; j++) { size = n/num_threads; rest = n - size*num_threads; if (j < rest) { ns = j*size+j; ne = (j+1)*size+j+1; } else { ns = j*size+rest; ne = (j+1)*size+rest; } for (i = ns; i < ne; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != 0.0) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii >= ns && ii < ne) res -= A_diag_data[jj] * u_data[ii]; else res -= A_diag_data[jj] * tmp_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } } hypre_TFree(tmp_data); } else { for (i = 0; i < n; i++) /* interior points first */ { /*----------------------------------------------------------- * If diagonal is nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( A_diag_data[A_diag_i[i]] != 0.0) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } } return(relax_error); }
perftest.c
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2015. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "libperf.h" #include "libperf_int.h" #include <ucs/sys/string.h> #include <ucs/sys/sys.h> #include <ucs/debug/log.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <getopt.h> #include <string.h> #include <sys/types.h> #include <locale.h> #if HAVE_MPI # include <mpi.h> #elif HAVE_RTE # include<rte.h> #endif #define MAX_BATCH_FILES 32 enum { TEST_FLAG_PRINT_RESULTS = UCS_BIT(0), TEST_FLAG_PRINT_TEST = UCS_BIT(1), TEST_FLAG_SET_AFFINITY = UCS_BIT(8), TEST_FLAG_NUMERIC_FMT = UCS_BIT(9), TEST_FLAG_PRINT_FINAL = UCS_BIT(10), TEST_FLAG_PRINT_CSV = UCS_BIT(11) }; typedef struct sock_rte_group { int is_server; int connfd; } sock_rte_group_t; typedef struct test_type { const char *name; ucx_perf_api_t api; ucx_perf_cmd_t command; ucx_perf_test_type_t test_type; const char *desc; } test_type_t; struct perftest_context { ucx_perf_params_t params; const char *server_addr; int port; #if HAVE_MPI int mpi; #endif unsigned cpu; unsigned flags; unsigned num_batch_files; char *batch_files[MAX_BATCH_FILES]; char *test_names[MAX_BATCH_FILES]; sock_rte_group_t sock_rte_group; }; #define TEST_PARAMS_ARGS "t:n:s:W:O:w:D:i:H:oSCqM:T:d:x:A:B" test_type_t tests[] = { {"am_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG, "active message latency"}, {"put_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency"}, {"add_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG, "atomic add latency"}, {"get", UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate"}, {"fadd", UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / message rate"}, {"swap", UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / message rate"}, {"cswap", UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / message rate"}, {"am_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI, "active message bandwidth / message rate"}, {"put_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth / message rate"}, {"add_mr", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add message rate"}, {"tag_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_PINGPONG, "UCP tag match latency"}, {"tag_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP tag match bandwidth"}, {"ucp_put_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "UCP put latency"}, {"ucp_put_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP put bandwidth"}, {"ucp_get", UCX_PERF_API_UCP, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP get latency / bandwidth / message rate"}, {"ucp_add", UCX_PERF_API_UCP, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic add bandwidth / message rate"}, {"ucp_fadd", UCX_PERF_API_UCP, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic fetch-and-add latency / bandwidth / message rate"}, {"ucp_swap", UCX_PERF_API_UCP, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic swap latency / bandwidth / message rate"}, {"ucp_cswap", UCX_PERF_API_UCP, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP atomic compare-and-swap latency / bandwidth / message rate"}, {"stream_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_STREAM_UNI, "UCP stream bandwidth"}, {"stream_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_PINGPONG, "UCP stream latency"}, {NULL} }; static int safe_send(int sock, void *data, size_t size) { size_t total = 0; int ret; while (total < size) { ret = send(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("send() failed: %m"); return -1; } total += ret; } return 0; } static int safe_recv(int sock, void *data, size_t size) { size_t total = 0; int ret; while (total < size) { ret = recv(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("recv() failed: %m"); return -1; } total += ret; } return 0; } static void print_progress(char **test_names, unsigned num_names, const ucx_perf_result_t *result, unsigned flags, int final) { static const char *fmt_csv = "%.0f,%.3f,%.3f,%.3f,%.2f,%.2f,%.0f,%.0f\n"; static const char *fmt_numeric = "%'14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %'11.0f %'11.0f\n"; static const char *fmt_plain = "%14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %11.0f %11.0f\n"; unsigned i; if (!(flags & TEST_FLAG_PRINT_RESULTS) || (!final && (flags & TEST_FLAG_PRINT_FINAL))) { return; } if (flags & TEST_FLAG_PRINT_CSV) { for (i = 0; i < num_names; ++i) { printf("%s,", test_names[i]); } } printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv : (flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric : fmt_plain, (double)result->iters, result->latency.typical * 1000000.0, result->latency.moment_average * 1000000.0, result->latency.total_average * 1000000.0, result->bandwidth.moment_average / (1024.0 * 1024.0), result->bandwidth.total_average / (1024.0 * 1024.0), result->msgrate.moment_average, result->msgrate.total_average); fflush(stdout); } static void print_header(struct perftest_context *ctx) { const char *test_api_str; const char *test_data_str; test_type_t *test; unsigned i; if (ctx->flags & TEST_FLAG_PRINT_TEST) { for (test = tests; test->name; ++test) { if ((test->command == ctx->params.command) && (test->test_type == ctx->params.test_type)) { break; } } if (test->name != NULL) { if (test->api == UCX_PERF_API_UCT) { test_api_str = "transport layer"; switch (ctx->params.uct.data_layout) { case UCT_PERF_DATA_LAYOUT_SHORT: test_data_str = "short"; break; case UCT_PERF_DATA_LAYOUT_BCOPY: test_data_str = "bcopy"; break; case UCT_PERF_DATA_LAYOUT_ZCOPY: test_data_str = "zcopy"; break; default: test_data_str = "(undefined)"; break; } } else if (test->api == UCX_PERF_API_UCP) { test_api_str = "protocol layer"; test_data_str = "(automatic)"; /* TODO contig/stride/stream */ } else { return; } printf("+------------------------------------------------------------------------------------------+\n"); printf("| API: %-60s |\n", test_api_str); printf("| Test: %-60s |\n", test->desc); printf("| Data layout: %-60s |\n", test_data_str); printf("| Message size: %-60zu |\n", ucx_perf_get_message_size(&ctx->params)); } } if (ctx->flags & TEST_FLAG_PRINT_CSV) { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { for (i = 0; i < ctx->num_batch_files; ++i) { printf("%s,", basename(ctx->batch_files[i])); } printf("iterations,typical_lat,avg_lat,overall_lat,avg_bw,overall_bw,avg_mr,overall_mr\n"); } } else { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("+--------------+-----------------------------+---------------------+-----------------------+\n"); printf("| | latency (usec) | bandwidth (MB/s) | message rate (msg/s) |\n"); printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); printf("| # iterations | typical | average | overall | average | overall | average | overall |\n"); printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); } else if (ctx->flags & TEST_FLAG_PRINT_TEST) { printf("+------------------------------------------------------------------------------------------+\n"); } } } static void print_test_name(struct perftest_context *ctx) { char buf[200]; unsigned i, pos; if (!(ctx->flags & TEST_FLAG_PRINT_CSV) && (ctx->num_batch_files > 0)) { strcpy(buf, "+--------------+---------+---------+---------+----------+----------+-----------+-----------+"); pos = 1; for (i = 0; i < ctx->num_batch_files; ++i) { if (i != 0) { buf[pos++] = '/'; } memcpy(&buf[pos], ctx->test_names[i], ucs_min(strlen(ctx->test_names[i]), sizeof(buf) - pos - 1)); pos += strlen(ctx->test_names[i]); } if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("%s\n", buf); } } } static void usage(struct perftest_context *ctx, const char *program) { test_type_t *test; printf("Usage: %s [ server-hostname ] [ options ]\n", program); printf("\n"); #if HAVE_MPI printf("This test can be also launched as an MPI application\n"); #elif HAVE_RTE printf("This test can be also launched as an libRTE application\n"); #endif printf(" Common options:\n"); printf("\n"); printf(" Test options:\n"); printf(" -t <test> Test to run.\n"); for (test = tests; test->name; ++test) { printf(" %11s : %s.\n", test->name, test->desc); } printf("\n"); printf(" -D <layout>[,<layout>] Data layout. Default is \"short\" in UCT," " \"contig\" in UCP and previous one " "in batch mode. Second parameter is for " "receive side in UCP only.\n"); printf(" short : Use short messages API (cannot used for get).\n"); printf(" bcopy : Use copy-out API (cannot used for atomics).\n"); printf(" zcopy : Use zero-copy API (cannot used for atomics).\n"); printf(" contig : Use continuous datatype in UCP tests.\n"); printf(" iov : Use IOV datatype in UCP tests.\n"); printf("\n"); printf(" -d <device> Device to use for testing.\n"); printf(" -x <tl> Transport to use for testing.\n"); printf(" -c <cpu> Set affinity to this CPU. (off)\n"); printf(" -n <iters> Number of iterations to run. (%ld)\n", ctx->params.max_iter); printf(" -s <size> List of buffer sizes separated by comma, which " "make up a single message. Default is (%zu). " "For example, \"-s 16,48,8192,8192,14\"\n", ctx->params.msg_size_list[0]); printf(" -H <size> AM Header size. (%zu)\n", ctx->params.am_hdr_size); printf(" -w <iters> Number of warm-up iterations. (%zu)\n", ctx->params.warmup_iter); printf(" -W <count> Flow control window size, for active messages. (%u)\n", ctx->params.uct.fc_window); printf(" -O <count> Maximal number of uncompleted outstanding sends. (%u)\n", ctx->params.max_outstanding); printf(" -i <count> Distance between starting address of consecutive " "IOV entries. The same as UCT uct_iov_t stride.\n"); printf(" -N Use numeric formatting - thousands separator.\n"); printf(" -f Print only final numbers.\n"); printf(" -v Print CSV-formatted output.\n"); printf(" -p <port> TCP port to use for data exchange. (%d)\n", ctx->port); printf(" -b <batchfile> Batch mode. Read and execute tests from a file.\n"); printf(" Every line of the file is a test to run. " "The first word is the\n"); printf(" test name, and the rest are command-line " "arguments for the test.\n"); printf(" -M <thread> Thread support level for progress engine (single).\n"); printf(" single : Only the master thread can access.\n"); printf(" serialized : One thread can access at a time.\n"); printf(" multi : Multiple threads can access.\n"); printf(" -T <threads> Number of threads in the test (1); " "also implies \"-M multi\".\n"); printf(" -A <mode> Async progress mode. (thread)\n"); printf(" thread : Use separate progress thread.\n"); printf(" signal : Use signal based timer.\n"); printf(" -B Register memory with NONBLOCK flag.\n"); printf(" -C Use wildcard for tag tests.\n"); printf(" -S Use synchronous mode for tag sends.\n"); #if HAVE_MPI printf(" -P <0|1> Disable/enable MPI mode (%d)\n", ctx->mpi); #endif printf(" -h Show this help message.\n"); printf("\n"); } static const char *__basename(const char *path) { const char *p = strrchr(path, '/'); return (p == NULL) ? path : p; } static ucs_status_t parse_ucp_datatype_params(const char *optarg, ucp_perf_datatype_t *datatype) { const char *iov_type = "iov"; const size_t iov_type_size = strlen("iov"); const char *contig_type = "contig"; const size_t contig_type_size = strlen("contig"); if (0 == strncmp(optarg, iov_type, iov_type_size)) { *datatype = UCP_PERF_DATATYPE_IOV; } else if (0 == strncmp(optarg, contig_type, contig_type_size)) { *datatype = UCP_PERF_DATATYPE_CONTIG; } else { return UCS_ERR_INVALID_PARAM; } return UCS_OK; } static ucs_status_t parse_message_sizes_params(const char *optarg, ucx_perf_params_t *params) { char *optarg_ptr, *optarg_ptr2; size_t token_num, token_it; const char delim = ','; optarg_ptr = (char *)optarg; token_num = 0; /* count the number of given message sizes */ while ((optarg_ptr = strchr(optarg_ptr, delim)) != NULL) { ++optarg_ptr; ++token_num; } ++token_num; free(params->msg_size_list); /* free previously allocated buffer */ params->msg_size_list = malloc(sizeof(*params->msg_size_list) * token_num); if (NULL == params->msg_size_list) { return UCS_ERR_NO_MEMORY; } optarg_ptr = (char *)optarg; errno = 0; for (token_it = 0; token_it < token_num; ++token_it) { params->msg_size_list[token_it] = strtoul(optarg_ptr, &optarg_ptr2, 10); if (((ERANGE == errno) && (ULONG_MAX == params->msg_size_list[token_it])) || ((errno != 0) && (params->msg_size_list[token_it] == 0)) || (optarg_ptr == optarg_ptr2)) { free(params->msg_size_list); params->msg_size_list = NULL; /* prevent double free */ ucs_error("Invalid option substring argument at position %lu", token_it); return UCS_ERR_INVALID_PARAM; } optarg_ptr = optarg_ptr2 + 1; } params->msg_size_cnt = token_num; return UCS_OK; } static void init_test_params(ucx_perf_params_t *params) { params->api = UCX_PERF_API_LAST; params->command = UCX_PERF_CMD_LAST; params->test_type = UCX_PERF_TEST_TYPE_LAST; params->thread_mode = UCS_THREAD_MODE_SINGLE; params->thread_count = 1; params->async_mode = UCS_ASYNC_MODE_THREAD; params->wait_mode = UCX_PERF_WAIT_MODE_LAST; params->max_outstanding = 1; params->warmup_iter = 10000; params->am_hdr_size = 8; params->alignment = ucs_get_page_size(); params->max_iter = 1000000l; params->max_time = 0.0; params->report_interval = 1.0; params->flags = UCX_PERF_TEST_FLAG_VERBOSE; params->uct.fc_window = UCT_PERF_TEST_MAX_FC_WINDOW; params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; params->msg_size_cnt = 1; params->iov_stride = 0; params->ucp.send_datatype = UCP_PERF_DATATYPE_CONTIG; params->ucp.recv_datatype = UCP_PERF_DATATYPE_CONTIG; strcpy(params->uct.dev_name, "<none>"); strcpy(params->uct.tl_name, "<none>"); params->msg_size_list = malloc(sizeof(*params->msg_size_list) * params->msg_size_cnt); params->msg_size_list[0] = 8; } static ucs_status_t parse_test_params(ucx_perf_params_t *params, char opt, const char *optarg) { test_type_t *test; char *optarg2 = NULL; /* TODO: currently, UCP supports only ucp_stream_recv_data_nb path, * add option when ucp_stream_recv_nb is implemented */ params->flags |= UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; switch (opt) { case 'd': ucs_snprintf_zero(params->uct.dev_name, sizeof(params->uct.dev_name), "%s", optarg); return UCS_OK; case 'x': ucs_snprintf_zero(params->uct.tl_name, sizeof(params->uct.tl_name), "%s", optarg); return UCS_OK; case 't': for (test = tests; test->name; ++test) { if (!strcmp(optarg, test->name)) { params->api = test->api; params->command = test->command; params->test_type = test->test_type; break; } } if (test->name == NULL) { ucs_error("Invalid option argument for -t"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'D': if (0 == strcmp(optarg, "short")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; } else if (0 == strcmp(optarg, "bcopy")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_BCOPY; } else if (0 == strcmp(optarg, "zcopy")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_ZCOPY; } else if (UCS_OK == parse_ucp_datatype_params(optarg, &params->ucp.send_datatype)) { optarg2 = strchr(optarg, ','); if (optarg2) { if (UCS_OK != parse_ucp_datatype_params(optarg2 + 1, &params->ucp.recv_datatype)) { return -1; } } } else { ucs_error("Invalid option argument for -D"); return -1; } return UCS_OK; case 'i': params->iov_stride = atol(optarg); return UCS_OK; case 'n': params->max_iter = atol(optarg); return UCS_OK; case 's': return parse_message_sizes_params(optarg, params); case 'H': params->am_hdr_size = atol(optarg); return UCS_OK; case 'W': params->uct.fc_window = atoi(optarg); return UCS_OK; case 'O': params->max_outstanding = atoi(optarg); return UCS_OK; case 'w': params->warmup_iter = atol(optarg); return UCS_OK; case 'o': params->flags |= UCX_PERF_TEST_FLAG_ONE_SIDED; return UCS_OK; case 'B': params->flags |= UCX_PERF_TEST_FLAG_MAP_NONBLOCK; return UCS_OK; case 'q': params->flags &= ~UCX_PERF_TEST_FLAG_VERBOSE; return UCS_OK; case 'C': params->flags |= UCX_PERF_TEST_FLAG_TAG_WILDCARD; return UCS_OK; case 'S': params->flags |= UCX_PERF_TEST_FLAG_TAG_SYNC; return UCS_OK; case 'M': if (0 == strcmp(optarg, "single")) { params->thread_mode = UCS_THREAD_MODE_SINGLE; return UCS_OK; } else if (0 == strcmp(optarg, "serialized")) { params->thread_mode = UCS_THREAD_MODE_SERIALIZED; return UCS_OK; } else if (0 == strcmp(optarg, "multi")) { params->thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; } else { ucs_error("Invalid option argument for -M"); return UCS_ERR_INVALID_PARAM; } case 'T': params->thread_count = atoi(optarg); params->thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; case 'A': if (0 == strcmp(optarg, "thread")) { params->async_mode = UCS_ASYNC_MODE_THREAD; return UCS_OK; } else if (0 == strcmp(optarg, "signal")) { params->async_mode = UCS_ASYNC_MODE_SIGNAL; return UCS_OK; } else { ucs_error("Invalid option argument for -A"); return UCS_ERR_INVALID_PARAM; } default: return UCS_ERR_INVALID_PARAM; } } static ucs_status_t read_batch_file(FILE *batch_file, ucx_perf_params_t *params, char** test_name_p) { #define MAX_SIZE 256 #define MAX_ARG_SIZE 2048 ucs_status_t status; char buf[MAX_ARG_SIZE]; int argc; char *argv[MAX_SIZE + 1]; int c; char *p; do { if (fgets(buf, sizeof(buf) - 1, batch_file) == NULL) { return UCS_ERR_NO_ELEM; } argc = 0; p = strtok(buf, " \t\n\r"); while (p && (argc < MAX_SIZE)) { argv[argc++] = p; p = strtok(NULL, " \t\n\r"); } argv[argc] = NULL; } while ((argc == 0) || (argv[0][0] == '#')); optind = 1; while ((c = getopt (argc, argv, TEST_PARAMS_ARGS)) != -1) { status = parse_test_params(params, c, optarg); if (status != UCS_OK) { ucs_error("Invalid argument in batch file: -%c, status(%d):\"%s\"", c, status, ucs_status_string(status)); return status; } } *test_name_p = strdup(argv[0]); return UCS_OK; } static ucs_status_t parse_opts(struct perftest_context *ctx, int argc, char **argv) { ucs_status_t status; int c; ucs_trace_func(""); init_test_params(&ctx->params); ctx->server_addr = NULL; ctx->num_batch_files = 0; ctx->port = 13337; ctx->flags = 0; #if HAVE_MPI ctx->mpi = !isatty(0); #endif optind = 1; while ((c = getopt (argc, argv, "p:b:Nfvc:P:h" TEST_PARAMS_ARGS)) != -1) { switch (c) { case 'p': ctx->port = atoi(optarg); break; case 'b': if (ctx->num_batch_files < MAX_BATCH_FILES) { ctx->batch_files[ctx->num_batch_files++] = strdup(optarg); } break; case 'N': ctx->flags |= TEST_FLAG_NUMERIC_FMT; break; case 'f': ctx->flags |= TEST_FLAG_PRINT_FINAL; break; case 'v': ctx->flags |= TEST_FLAG_PRINT_CSV; break; case 'c': ctx->flags |= TEST_FLAG_SET_AFFINITY; ctx->cpu = atoi(optarg); break; case 'P': #if HAVE_MPI ctx->mpi = atoi(optarg); break; #endif case 'h': usage(ctx, __basename(argv[0])); return UCS_ERR_CANCELED; default: status = parse_test_params(&ctx->params, c, optarg); if (status != UCS_OK) { usage(ctx, __basename(argv[0])); return status; } break; } } if (optind < argc) { ctx->server_addr = argv[optind]; } return UCS_OK; } static unsigned sock_rte_group_size(void *rte_group) { return 2; } static unsigned sock_rte_group_index(void *rte_group) { sock_rte_group_t *group = rte_group; return group->is_server ? 0 : 1; } static void sock_rte_barrier(void *rte_group) { #pragma omp master { sock_rte_group_t *group = rte_group; const unsigned magic = 0xdeadbeef; unsigned sync; sync = magic; safe_send(group->connfd, &sync, sizeof(unsigned)); sync = 0; safe_recv(group->connfd, &sync, sizeof(unsigned)); ucs_assert(sync == magic); } #pragma omp barrier } static void sock_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { sock_rte_group_t *group = rte_group; size_t size; int i; size = 0; for (i = 0; i < iovcnt; ++i) { size += iovec[i].iov_len; } safe_send(group->connfd, &size, sizeof(size)); for (i = 0; i < iovcnt; ++i) { safe_send(group->connfd, iovec[i].iov_base, iovec[i].iov_len); } } static void sock_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { sock_rte_group_t *group = rte_group; int group_index; size_t size; group_index = sock_rte_group_index(rte_group); if (src == group_index) { return; } ucs_assert_always(src == (1 - group_index)); safe_recv(group->connfd, &size, sizeof(size)); ucs_assert_always(size <= max); safe_recv(group->connfd, buffer, size); } static void sock_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t sock_rte = { .group_size = sock_rte_group_size, .group_index = sock_rte_group_index, .barrier = sock_rte_barrier, .post_vec = sock_rte_post_vec, .recv = sock_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = sock_rte_report, }; static ucs_status_t setup_sock_rte(struct perftest_context *ctx) { struct sockaddr_in inaddr; struct hostent *he; ucs_status_t status; int optval = 1; int sockfd, connfd; int ret; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ucs_error("socket() failed: %m"); status = UCS_ERR_IO_ERROR; goto err; } if (ctx->server_addr == NULL) { optval = 1; ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (ret < 0) { ucs_error("setsockopt(SO_REUSEADDR) failed: %m"); status = UCS_ERR_INVALID_PARAM; goto err_close_sockfd; } inaddr.sin_family = AF_INET; inaddr.sin_port = htons(ctx->port); inaddr.sin_addr.s_addr = INADDR_ANY; memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = bind(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("bind() failed: %m"); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } ret = listen(sockfd, 10); if (ret < 0) { ucs_error("listen() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } printf("Waiting for connection...\n"); /* Accept next connection */ connfd = accept(sockfd, NULL, NULL); if (connfd < 0) { ucs_error("accept() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } close(sockfd); safe_recv(connfd, &ctx->params, sizeof(ctx->params)); if (ctx->params.msg_size_cnt) { ctx->params.msg_size_list = malloc(sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt); if (NULL == ctx->params.msg_size_list) { status = UCS_ERR_NO_MEMORY; goto err_close_connfd; } safe_recv(connfd, ctx->params.msg_size_list, sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt); } ctx->sock_rte_group.connfd = connfd; ctx->sock_rte_group.is_server = 1; } else { he = gethostbyname(ctx->server_addr); if (he == NULL || he->h_addr_list == NULL) { ucs_error("host %s not found: %s", ctx->server_addr, hstrerror(h_errno)); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } inaddr.sin_family = he->h_addrtype; inaddr.sin_port = htons(ctx->port); ucs_assert(he->h_length == sizeof(inaddr.sin_addr)); memcpy(&inaddr.sin_addr, he->h_addr_list[0], he->h_length); memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = connect(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("connect() failed: %m"); status = UCS_ERR_UNREACHABLE; goto err_close_sockfd; } safe_send(sockfd, &ctx->params, sizeof(ctx->params)); if (ctx->params.msg_size_cnt) { safe_send(sockfd, ctx->params.msg_size_list, sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt); } ctx->sock_rte_group.connfd = sockfd; ctx->sock_rte_group.is_server = 0; } if (ctx->sock_rte_group.is_server) { ctx->flags |= TEST_FLAG_PRINT_TEST; } else { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = &ctx->sock_rte_group; ctx->params.rte = &sock_rte; ctx->params.report_arg = ctx; return UCS_OK; err_close_connfd: close(connfd); goto err; err_close_sockfd: close(sockfd); err: return status; } static ucs_status_t cleanup_sock_rte(struct perftest_context *ctx) { close(ctx->sock_rte_group.connfd); return UCS_OK; } #if HAVE_MPI static unsigned mpi_rte_group_size(void *rte_group) { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); return size; } static unsigned mpi_rte_group_index(void *rte_group) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); return rank; } static void mpi_rte_barrier(void *rte_group) { #pragma omp master MPI_Barrier(MPI_COMM_WORLD); #pragma omp barrier } static void mpi_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { int group_size; int my_rank; int dest, i; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); for (dest = 0; dest < group_size; ++dest) { if (dest == my_rank) { continue; } for (i = 0; i < iovcnt; ++i) { MPI_Send(iovec[i].iov_base, iovec[i].iov_len, MPI_BYTE, dest, i == (iovcnt - 1), /* Send last iov with tag == 1 */ MPI_COMM_WORLD); } } *req = (void*)(uintptr_t)1; } static void mpi_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { MPI_Status status; size_t offset; int my_rank; int count; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if (src == my_rank) { return; } offset = 0; do { ucs_assert_always(offset < max); MPI_Recv(buffer + offset, max - offset, MPI_BYTE, src, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_BYTE, &count); offset += count; } while (status.MPI_TAG != 1); } static void mpi_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t mpi_rte = { .group_size = mpi_rte_group_size, .group_index = mpi_rte_group_index, .barrier = mpi_rte_barrier, .post_vec = mpi_rte_post_vec, .recv = mpi_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = mpi_rte_report, }; #elif HAVE_RTE static unsigned ext_rte_group_size(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_size(group); } static unsigned ext_rte_group_index(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_rank(group); } static void ext_rte_barrier(void *rte_group) { #pragma omp master { rte_group_t group = (rte_group_t)rte_group; int rc; rc = rte_barrier(group); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_barrier"); } } #pragma omp barrier } static void ext_rte_post_vec(void *rte_group, const struct iovec* iovec, int iovcnt, void **req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session; rte_iovec_t *r_vec; int i, rc; rc = rte_srs_session_create(group, 0, &session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_create"); } r_vec = calloc(iovcnt, sizeof(rte_iovec_t)); if (r_vec == NULL) { return; } for (i = 0; i < iovcnt; ++i) { r_vec[i].iov_base = iovec[i].iov_base; r_vec[i].type = rte_datatype_uint8_t; r_vec[i].count = iovec[i].iov_len; } rc = rte_srs_set_data(session, "KEY_PERF", r_vec, iovcnt); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_set_data"); } *req = session; free(r_vec); } static void ext_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session = (rte_srs_session_t)req; void *rte_buffer = NULL; rte_iovec_t r_vec; uint32_t offset; int size; int rc; rc = rte_srs_get_data(session, rte_group_index_to_ec(group, src), "KEY_PERF", &rte_buffer, &size); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_get_data"); return; } r_vec.iov_base = buffer; r_vec.type = rte_datatype_uint8_t; r_vec.count = max; offset = 0; rte_unpack(&r_vec, rte_buffer, &offset); rc = rte_srs_session_destroy(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_destroy"); } free(rte_buffer); } static void ext_rte_exchange_vec(void *rte_group, void * req) { rte_srs_session_t session = (rte_srs_session_t)req; int rc; rc = rte_srs_exchange_data(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_exchange_data"); } } static void ext_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t ext_rte = { .group_size = ext_rte_group_size, .group_index = ext_rte_group_index, .barrier = ext_rte_barrier, .report = ext_rte_report, .post_vec = ext_rte_post_vec, .recv = ext_rte_recv, .exchange_vec = ext_rte_exchange_vec, }; #endif static ucs_status_t setup_mpi_rte(struct perftest_context *ctx) { ucs_trace_func(""); #if HAVE_MPI int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); if (size != 2) { ucs_error("This test should run with exactly 2 processes (actual: %d)", size); return UCS_ERR_INVALID_PARAM; } MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 1) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = NULL; ctx->params.rte = &mpi_rte; ctx->params.report_arg = ctx; #elif HAVE_RTE rte_group_t group; rte_init(NULL, NULL, &group); if (1 == rte_group_rank(group)) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = group; ctx->params.rte = &ext_rte; ctx->params.report_arg = ctx; #endif return UCS_OK; } static ucs_status_t cleanup_mpi_rte(struct perftest_context *ctx) { #if HAVE_MPI MPI_Finalize(); #elif HAVE_RTE rte_finalize(); #endif return UCS_OK; } static ucs_status_t check_system(struct perftest_context *ctx) { cpu_set_t cpuset; unsigned i, count, nr_cpus; int ret; ucs_trace_func(""); ret = sysconf(_SC_NPROCESSORS_CONF); if (ret < 0) { ucs_error("failed to get local cpu count: %m"); return UCS_ERR_INVALID_PARAM; } nr_cpus = ret; memset(&cpuset, 0, sizeof(cpuset)); if (ctx->flags & TEST_FLAG_SET_AFFINITY) { if (ctx->cpu >= nr_cpus) { ucs_error("cpu (%u) ot of range (0..%u)", ctx->cpu, nr_cpus - 1); return UCS_ERR_INVALID_PARAM; } CPU_SET(ctx->cpu, &cpuset); ret = sched_setaffinity(0, sizeof(cpuset), &cpuset); if (ret) { ucs_warn("sched_setaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } } else { ret = sched_getaffinity(0, sizeof(cpuset), &cpuset); if (ret) { ucs_warn("sched_getaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } count = 0; for (i = 0; i < CPU_SETSIZE; ++i) { if (CPU_ISSET(i, &cpuset)) { ++count; } } if (count > 2) { ucs_warn("CPU affinity is not set (bound to %u cpus)." " Performance may be impacted.", count); } } return UCS_OK; } static ucs_status_t run_test_recurs(struct perftest_context *ctx, ucx_perf_params_t *parent_params, unsigned depth) { ucx_perf_params_t params; ucx_perf_result_t result; ucs_status_t status; FILE *batch_file; ucs_trace_func("depth=%u, num_files=%u", depth, ctx->num_batch_files); if (depth >= ctx->num_batch_files) { print_test_name(ctx); return ucx_perf_run(parent_params, &result); } batch_file = fopen(ctx->batch_files[depth], "r"); if (batch_file == NULL) { ucs_error("Failed to open batch file '%s': %m", ctx->batch_files[depth]); return UCS_ERR_IO_ERROR; } params = *parent_params; while ((status = read_batch_file(batch_file, &params, &ctx->test_names[depth])) == UCS_OK) { status = run_test_recurs(ctx, &params, depth + 1); free(ctx->test_names[depth]); if ((NULL == parent_params->msg_size_list) && (NULL != params.msg_size_list)) { free(params.msg_size_list); params.msg_size_list = NULL; } } fclose(batch_file); return UCS_OK; } static ucs_status_t run_test(struct perftest_context *ctx) { ucs_status_t status; ucs_trace_func(""); setlocale(LC_ALL, "en_US"); print_header(ctx); status = run_test_recurs(ctx, &ctx->params, 0); if (status != UCS_OK) { ucs_error("Failed to run test: %s", ucs_status_string(status)); } return status; } int main(int argc, char **argv) { struct perftest_context ctx; ucs_status_t status; int rte = 0; int ret; /* Parse command line */ if (parse_opts(&ctx, argc, argv) != UCS_OK) { ret = -127; goto out; } #ifdef __COVERITY__ /* coverity[dont_call] */ rte = rand(); /* Shut up deadcode error */ #endif #if HAVE_MPI /* Don't try MPI when running interactively */ if (ctx.mpi && (MPI_Init(&argc, &argv) == 0)) { rte = 1; } #elif HAVE_RTE rte = 1; #endif status = check_system(&ctx); if (status != UCS_OK) { ret = -1; goto out; } /* Create RTE */ status = (rte) ? setup_mpi_rte(&ctx) : setup_sock_rte(&ctx); if (status != UCS_OK) { ret = -1; goto out; } /* Run the test */ status = run_test(&ctx); if (status != UCS_OK) { ret = -1; goto out_cleanup_rte; } ret = 0; out_cleanup_rte: (rte) ? cleanup_mpi_rte(&ctx) : cleanup_sock_rte(&ctx); out: if (ctx.params.msg_size_list) { free(ctx.params.msg_size_list); } return ret; }
multipleCBQuantizedLQPFeatures.h
/* Copyright (c) 2013, Sibt ul Hussain <sibt.ul.hussain at gmail dot com> All rights reserved. Released under BSD License ------------------------- For license terms please see license.lic */ #ifndef MULTIPLECBQUANTIZEDLQPFEATURES_H_ #define MULTIPLECBQUANTIZEDLQPFEATURES_H_ #include "encodedPatchFeatures.h" #include "omp.h" /// LQP Quantization, Features are quantized against each cell codebook class MultipleCBQuantizeLQPFeatures: public EncodedPatchFeatures { public: MultipleCBQuantizeLQPFeatures(const LBPParams &lbpparam, UINT width_, UINT height_, UINT nplevels, ProcessImage &pim_, const PatchParams& pparam) : EncodedPatchFeatures(lbpparam, width_, height_, nplevels, pim_, pparam) { // Histogram Parameters delete codeinfo; codeinfo = NULL; // to be used for dellocation of memory char tvar[2525]; string patchtype = PatchParams::GetPatchType(ptype); ostringstream oss; oss << "MCBQ-CI-Pos" << patchtype << "-" << patchsize << "-" << ncenters; cifilename = oss.str(); oss.str(""); oss << "MCBQ-CB-Pos" << patchtype << "-" << patchsize << "-" << ncenters; cbfilename = oss.str(); // for negative side lqp oss.str(""); oss << "MCBQ-CI-Neg" << patchtype << "-" << patchsize << "-" << ncenters; ncifilename = oss.str(); oss.str(""); oss << "MCBQ-CB-Neg" << patchtype << "-" << patchsize << "-" << ncenters; ncbfilename = oss.str(); switch (cbtype) { case CBT_PosCropNegSampled: case CBT_PosPyramidNegSampled: case CBT_MultiClass: ncbs = 2; featdim = ncbs * ncenters; break; case CBT_ConstantPosCellNeg: case CBT_PosCellNeg: case CBT_PosCellNegSep: case CBT_ConstantPosCellNegSingleQuantization: // see the inherited class MultipleCBQuantizeLQPFeaturesHistogram // featdim = ncenters * 2;/*dim of each cell because it is mapped against its own codebook &-ve cb*/ // only doing this during returning the features to classifiers, while doing computation // each cell is quantized against all the codebooks., so featdim for each cell is ncbs = cwidth * cheight + 1; featdim = ncenters * ncbs; case CBT_CellQuantizeAll: /// cell quantization doing against all the cells codebooks ncbs = cwidth * cheight; featdim = ncenters * ncbs; // each cell is quantized against all the codebooks } UINT *npmult = pparam.npmult; pcbooks.resize(ncbs, 0); /*Only LTP based CodeBooks are implemented...*/ if (petype == PET_SplitLTP) { ncbooks.resize(ncbs, 0); /*Only LTP based CodeBooks are implemented...*/ featdim = featdim * 2; for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter = ncbooks.begin(); iter != pcbooks.end(); ++iter, ++niter) { *iter = new ComputeCodeLBP(ltplevels, npoints * npmult[ptype], ncenters, softq, meanp, pparam.pcount); *niter = new ComputeCodeLBP(ltplevels, npoints * npmult[ptype], ncenters, softq, meanp, pparam.pcount); } } else { for (vector<ComputeCode*>::iterator iter = pcbooks.begin(); iter != pcbooks.end(); ++iter) *iter = new ComputeCodeLTP(ltplevels, npoints * npmult[ptype], ncenters, softq, meanp, pparam.pcount); } nwinsampled = cbparams->nwinsampled; // //----------------- Print Parameter Info ----------- cout << "\n ----------------- Mulitple CB Encoded Parameter Info " "----------- " << endl << "Number of CodeBooks = " << ncbs << endl << " Feature Dim = " << featdim << endl << " CodeBookFileName" << cbfilename << endl << " Number of Window Sampled =" << nwinsampled << "\n--------------------------------------------\n"; } // GetDim returns the size of feature in a window without considering offset... virtual ~MultipleCBQuantizeLQPFeatures() { for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter = ncbooks.begin(); iter != pcbooks.end(); ++iter, ++niter) { delete *iter; delete *niter; } } virtual UINT GetDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_); } virtual UINT GetHOGDim(UINT width_, UINT height_) const { return 0; } virtual UINT GetLBPDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_);; } virtual UINT GetFoldedLBPDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_);; } virtual UINT GetFoldedHOGDim(UINT width_, UINT height_) const { return 0; } virtual UINT GetFoldedDim(UINT width_, UINT height_) const { return GetFeatDim(width_, height_); } virtual void InitalizeMaps(Image &, PyramidType); virtual void InitalizeMaps(Image &image); virtual void InitalizeMaps(Pyramid & pyobj_, PyramidType); virtual void GetFeatures(UINT, int, int, int, int, vector<REAL>&); virtual void GetFeatures(UINT, int, int, int, int, REAL*); virtual void GetFoldedFeatures(UINT, int, int, int, int, vector<REAL>&); virtual void GetFoldedFeatures(UINT, int, int, int, int, REAL*); virtual UINT GetInitIndex() { return sspace == DoubleRes ? pyobj.GetInitIndex() : 0; } virtual void PadFeatureMap(UINT index, UINT padx, UINT pady); virtual void DotProduct(UINT index, UINT width, UINT height, vector<REAL>&, Store&response); virtual void DotProduct(UINT index, UINT width, UINT height, REAL *filter, Store&); void ComputeLTPMap(Image &image, LBPMap *tpmap, LBPMap *tnmap); void ComputeLBPFeatures(Image& imgref, UINT index, UINT winstride, UINT tlbpstride); void ComputeLBPFeatures(Image& imgref, vector<REAL> &features, UINT cxbmax, UINT cybmax, UINT winstride, UINT tlbpstride); void ComputeSplitLBPFeatures(Image& imgref, vector<REAL> &features, UINT cxbmax, UINT cybmax, UINT winstride, UINT tlbpstride); /*****Test Code ****/ // All the inputs are in Pixels ..... void ExtractPosCodeInfo(Image&image, vector<Coord>& ainfo); void ExtractNegCodeInfo(Image&image); void ExtractCodeInfo(Image &image, LBPMap *map, ComputeCode *cbook); void GenerateCodeBookInfo(LBPMap *map, UINT xmin, UINT ymin, ComputeCode* cbook); // for a single code book void GenerateCodeBookInfo(LBPMap *map, UINT xmin, UINT ymin, vector<ComputeCode*> & cbook); // for complete codebook // void GenerateCodeBookInfo(Image & image, ComputeCode * cbook); void GenerateCodeBookInfo(LBPMap *pmap, LBPMap *nmap, UINT xmin, UINT ymin); bool ExistPosCodeInfo() { UINT count = 1; for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter = ncbooks.begin(); iter != pcbooks.end(); ++iter, ++niter) { ostringstream oss; oss << cifilename << "-" << count << ".txt"; if (!(*iter)->ExistCodeBook(oss.str())) return false; oss.str(""); oss << ncifilename << "-" << count << ".txt"; if (!(*niter)->ExistCodeBook(oss.str())) return false; } return true; } bool ExistPosCodeBook() { UINT count = 1; for (vector<ComputeCode*>::iterator iter = pcbooks.begin(), niter = ncbooks.begin(); iter != pcbooks.end(); ++iter, ++count, ++niter) { ostringstream oss; oss << cbfilename << "-" << count << ".txt"; if (!(*iter)->ExistCodeBook(oss.str())) return false; oss.str(""); oss << ncbfilename << "-" << count << ".txt"; if (!(*niter)->ExistCodeBook(oss.str())) return false; } return true; } virtual void GenerateCodeBook() { if (ExistPosCodeBook()) return; if (cbparams->cbtype == CBT_NegativeThenPosCrop) { // first generate the negative code book // and use it as initialization for the +ve cell based codebooks string cifname = cifilename + "Neg"; ExtractNegCBInfo(cifname); ConstructNegCodeBook(NULL); REAL *ncluster = new REAL[ncenters * pcbooks[ncbs - 1]->GetCodeLength()]; pcbooks[ncbs - 1]->CopyClusters(ncluster); // ExtractPosCodeInfo(); ExtractPosCBInfo(); ConstructPosCodeBook(ncluster); } else if (cbparams->cbtype == CBT_CellQuantizeAll) { if (!ExistPosCodeInfo()) { vector<string> imnames; ParseListFile(cbparams->vimgfname, imnames); Image image; for (UINT i = 0; i < imnames.size(); ++i) { cout << "\n Processing Image # = " << (i + 1) << " " << imnames[i]; image.read(imnames[i]); ExtractImageCodeInfo(image); } } ConstructPosCodeBook(NULL); } else { ExtractPosCBInfo(); ConstructPosCodeBook(NULL); ExtractNegCBInfo(cifilename); ConstructNegCodeBook(NULL); } } void ExtractImageCodeInfo(Image &image) { LBPMap pmap[3], nmap[3]; ExtractCodeBookInfo(image, pmap, nmap, false, true); UINT offset = GetMaxFeatureOffset(), minoffset = GetFeaturesOffset(), doffset = offset - minoffset; GenerateCodeBookInfo(pmap, nmap, doffset, doffset); image.flop(); // flipped image cout << " ------ Processing Flipped Version "; ExtractCodeBookInfo(image, pmap, nmap, false, true); GenerateCodeBookInfo(pmap, nmap, doffset, doffset); } void ExtractPosCBInfo() { if (ExistPosCodeInfo()) return; ClassInfo *ocinfo = cbparams->ocinfo; if (cbtype == CBT_PosPyramid || cbtype == CBT_PosPyramidNegSampled) { sspace = SingleRes; SetPyramidInterval(5); } else sspace = NoPyramid; /*if to use local space pyramid*/ cout << "\n Using Scale Space = " << GetPyramidType(sspace) << endl; string imname; Image image; vector<Coord> vcoord;// to contain the flipped features coordinates ocinfo->ResetCounter(); UINT count = 0; while (ocinfo->GetNextImageAnnotation(imname, vcoord)) { image.read(imname); cout << "Image " << ++count << ". Number of Annotations = " << vcoord.size() << endl; ExtractPosCodeInfo(image, vcoord); } } void ExtractNegCBInfo(const string &cifn) { ostringstream oss; oss << cifn << "-" << ncbs << ".txt"; if (pcbooks[ncbs - 1]->ExistCodeInfo(oss.str())) return; sspace = SingleRes; SetPyramidInterval(2); vector<string> imnames; if (cbtype == CBT_Complete)/*Use complete validation set*/ ParseListFile(cbparams->vimgfname, imnames); else ParseListFile(cbparams->nimgfname, imnames); Image image; for (UINT i = 0; i < imnames.size(); ++i) { cout << " Processing Image # = " << (i + 1) << " " << imnames[i] << endl; image.read(imnames[i]); ExtractNegCodeInfo(image); } } void ConstructPosCodeBook(REAL *initclusters) { char ci[2000], cb[2000]; UINT nclusrounds = cbparams->nclusrounds; ClusteringDistanceMetric dmetric = cbparams->dmetric; if (ExistPosCodeBook()) return; #pragma omp parallel for for (UINT count = 0; count < pcbooks.size(); ++count) { ostringstream ciss, cbss; ciss << cifilename << "-" << count + 1 << ".txt"; cbss << cbfilename << "-" << count + 1 << ".txt"; long initime = time(0); pcbooks[count]->GenerateCodeBook(ciss.str(), cbss.str(), dmetric, nclusrounds, initclusters); cout << " \n Time Taken For Positive Code Book Number " << count << "Generation =" << time(0) - initime << endl << flush; } #pragma omp parallel for for (UINT count = 0; count < pcbooks.size(); ++count) { ostringstream ciss, cbss; ciss << ncifilename << "-" << count + 1 << ".txt"; cbss << ncbfilename << "-" << count + 1 << ".txt"; long initime = time(0); ncbooks[count]->GenerateCodeBook(ciss.str(), cbss.str(), dmetric, nclusrounds, initclusters); cout << " \n Time Taken For Negative Code Book Number " << count << "Generation =" << time(0) - initime << endl << flush; } } void ConstructNegCodeBook(REAL *initclusters) { char ci[2000], cb[2000]; UINT count = ncbs, nclusrounds = cbparams->nclusrounds; ClusteringDistanceMetric dmetric = cbparams->dmetric; ostringstream ciss, cbss; ciss << cifilename << "-" << count << ".txt"; cbss << cbfilename << "-" << count << ".txt"; long initime = time(0); pcbooks[count - 1]->GenerateCodeBook(ciss.str(), cbss.str(), dmetric, nclusrounds, initclusters); cout << " \n Time Taken For Code Book Number " << count << "Generation =" << time(0) - initime << endl << flush; } private: UINT GetFeatDim(UINT width_, UINT height_) const { return (width_ / cellsize) * (height_ / cellsize) * featdim; } protected: UINT featdim; /// single cell feature dimension vector<ComputeCode*> pcbooks, ncbooks; UINT ncbs; string imgfname; }; #endif
gemtools_binding.c
/* GEMTools python binding utilities */ #include "gemtools_binding.h" #include <omp.h> bool gt_input_file_has_qualities(gt_input_file* file){ return (file->file_format == FASTA && file->fasta_type.fasta_format == F_FASTQ) || (file->file_format == MAP && file->map_type.contains_qualities); } void gt_write_stream(gt_output_file* output, gt_input_file** inputs, uint64_t num_inputs, bool append_extra, bool clean_id, bool interleave, uint64_t threads, bool write_map, bool remove_scores){ // prepare attributes gt_output_fasta_attributes* attributes = 0; gt_output_map_attributes* map_attributes = 0; if(!write_map){ attributes = gt_output_fasta_attributes_new(); gt_output_fasta_attributes_set_print_extra(attributes, append_extra); gt_output_fasta_attributes_set_print_casava(attributes, !clean_id); // check qualities if(!gt_input_file_has_qualities(inputs[0])){ gt_output_fasta_attributes_set_format(attributes, F_FASTA); } }else{ map_attributes = gt_output_map_attributes_new(); gt_output_map_attributes_set_print_extra(map_attributes, append_extra); gt_output_map_attributes_set_print_casava(map_attributes, !clean_id); gt_output_map_attributes_set_print_scores(map_attributes, !remove_scores); } // generic parser attributes gt_generic_parser_attributes* parser_attributes = gt_input_generic_parser_attributes_new(false); // do not force pairs pthread_mutex_t input_mutex = PTHREAD_MUTEX_INITIALIZER; if(interleave){ // main loop, interleave #pragma omp parallel num_threads(threads) { register uint64_t i = 0; register uint64_t c = 0; gt_buffered_output_file* buffered_output = gt_buffered_output_file_new(output); gt_buffered_input_file** buffered_input = malloc(num_inputs * sizeof(gt_buffered_input_file*)); for(i=0; i<num_inputs; i++){ buffered_input[i] = gt_buffered_input_file_new(inputs[i]); } // attache first input to output gt_buffered_input_file_attach_buffered_output(buffered_input[0], buffered_output); gt_template* template = gt_template_new(); gt_status status; i=0; while( gt_input_generic_parser_synch_blocks_a(&input_mutex, buffered_input, num_inputs, parser_attributes) == GT_STATUS_OK ){ for(i=0; i<num_inputs; i++){ if( (status = gt_input_generic_parser_get_template(buffered_input[i], template, parser_attributes)) == GT_STATUS_OK){ if(write_map){ gt_output_map_bofprint_template(buffered_output, template, map_attributes); }else{ gt_output_fasta_bofprint_template(buffered_output, template, attributes); } c++; } } } gt_buffered_output_file_close(buffered_output); for(i=0; i<num_inputs; i++){ gt_buffered_input_file_close(buffered_input[i]); } gt_template_delete(template); free(buffered_input); } }else{ // main loop, cat #pragma omp parallel num_threads(threads) { register uint64_t i = 0; register uint64_t c = 0; register uint64_t last_id = 0; gt_buffered_output_file* buffered_output = gt_buffered_output_file_new(output); gt_buffered_input_file** buffered_input = malloc(1 * sizeof(gt_buffered_input_file*)); gt_buffered_input_file* current_input = 0; gt_template* template = gt_template_new(); gt_status status = 0; for(i=0; i<num_inputs;i++){ // create input buffer if(i>0){ gt_buffered_input_file_close(current_input); inputs[i]->processed_id = last_id; } current_input = gt_buffered_input_file_new(inputs[i]); buffered_input[0] = current_input; // attache the buffer gt_buffered_input_file_attach_buffered_output(current_input, buffered_output); // read while( gt_input_generic_parser_synch_blocks_a(&input_mutex, buffered_input, 1, parser_attributes) == GT_STATUS_OK ){ if( (status = gt_input_generic_parser_get_template(current_input, template, parser_attributes)) == GT_STATUS_OK){ if(write_map){ gt_output_map_bofprint_template(buffered_output, template, map_attributes); }else{ gt_output_fasta_bofprint_template(buffered_output, template, attributes); } c++; } } last_id = inputs[i]->processed_id; } gt_buffered_input_file_close(current_input); gt_buffered_output_file_close(buffered_output); gt_template_delete(template); free(buffered_input); } } if(attributes != NULL) gt_output_fasta_attributes_delete(attributes); if(map_attributes != NULL)gt_output_map_attributes_delete(map_attributes); gt_input_generic_parser_attributes_delete(parser_attributes); // register uint64_t i = 0; // for(i=0; i<num_inputs; i++){ // gt_input_file_close(inputs[i]); // } // gt_output_file_close(output); }
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % 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/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; size_t columns, number_channels, rows; ssize_t y; 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); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images->next,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } image->depth=32UL; AppendImageToList(&complex_images,image); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { complex_images=DestroyImageList(complex_images); return(complex_images); } /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(images,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; number_channels=MagickMin(MagickMin(MagickMin( Ar_image->number_channels,Ai_image->number_channels),MagickMin( Br_image->number_channels,Bi_image->number_channels)),MagickMin( Cr_image->number_channels,Ci_image->number_channels)); Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; columns=MagickMin(Cr_image->columns,Ci_image->columns); rows=MagickMin(Cr_image->rows,Ci_image->rows); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,rows,1L) #endif for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; Quantum *magick_restrict Ci, *magick_restrict Cr; ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) columns; x++) { ssize_t i; for (i=0; i < (ssize_t) number_channels; i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=QuantumRange*PerceptibleReciprocal(QuantumScale*Br[i]*Br[i]+ QuantumScale*Bi[i]*Bi[i]+snr); Cr[i]=gamma*(QuantumScale*Ar[i]*Br[i]+QuantumScale*Ai[i]*Bi[i]); Ci[i]=gamma*(QuantumScale*Ai[i]*Br[i]-QuantumScale*Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(QuantumScale*Ar[i]*Ar[i]+QuantumScale*Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=(QuantumScale*Ar[i]*Br[i]-QuantumScale*Ai[i]*Bi[i]); Ci[i]=(QuantumScale*Ai[i]*Br[i]+QuantumScale*Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) memcpy(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; Quantum *q; ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) memset(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) memset(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; const Quantum *p; ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); memset(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"forward") == 0) { double gamma; /* Normalize forward transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; const Quantum *p; ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) memcpy(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; Quantum *q; ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
displacement_lagrangemultiplier_mixed_contact_criteria.h
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: StructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_CONTACT_CRITERIA_H) #define KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_CONTACT_CRITERIA_H /* System includes */ /* External includes */ /* Project includes */ #include "utilities/table_stream_utility.h" #include "solving_strategies/convergencecriterias/convergence_criteria.h" #include "utilities/color_utilities.h" #include "utilities/constraint_utilities.h" namespace Kratos { ///@addtogroup ContactStructuralMechanicsApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@name Kratos Classes ///@{ /** * @class DisplacementLagrangeMultiplierMixedContactCriteria * @ingroup ContactStructuralMechanicsApplication * @brief Convergence criteria for contact problems * @details This class implements a convergence control based on nodal displacement and * lagrange multiplier values. The error is evaluated separately for each of them, and * relative and absolute tolerances for both must be specified. * @author Vicente Mataix Ferrandiz */ template< class TSparseSpace, class TDenseSpace > class DisplacementLagrangeMultiplierMixedContactCriteria : public ConvergenceCriteria< TSparseSpace, TDenseSpace > { public: ///@name Type Definitions ///@{ /// Pointer definition of DisplacementLagrangeMultiplierMixedContactCriteria KRATOS_CLASS_POINTER_DEFINITION( DisplacementLagrangeMultiplierMixedContactCriteria ); /// Local Flags KRATOS_DEFINE_LOCAL_FLAG( ENSURE_CONTACT ); KRATOS_DEFINE_LOCAL_FLAG( PRINTING_OUTPUT ); KRATOS_DEFINE_LOCAL_FLAG( TABLE_IS_INITIALIZED ); KRATOS_DEFINE_LOCAL_FLAG( INITIAL_RESIDUAL_IS_SET ); /// The base class definition (and it subclasses) typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; /// The sparse space used typedef TSparseSpace SparseSpaceType; /// The r_table stream definition TODO: Replace by logger typedef TableStreamUtility::Pointer TablePrinterPointerType; /// The index type definition typedef std::size_t IndexType; /// The key type definition typedef std::size_t KeyType; /// The epsilon tolerance definition static constexpr double Tolerance = std::numeric_limits<double>::epsilon(); ///@} ///@name Life Cycle ///@{ /** * @brief Default constructor * @param DispRatioTolerance Relative tolerance for displacement residual error * @param DispAbsTolerance Absolute tolerance for displacement residual error * @param LMRatioTolerance Relative tolerance for lagrange multiplier residual error * @param LMAbsTolerance Absolute tolerance for lagrange multiplier residual error * @param EnsureContact To check if the contact is lost * @param pTable The pointer to the output r_table * @param PrintingOutput If the output is going to be printed in a txt file */ explicit DisplacementLagrangeMultiplierMixedContactCriteria( const TDataType DispRatioTolerance, const TDataType DispAbsTolerance, const TDataType LMRatioTolerance, const TDataType LMAbsTolerance, const bool EnsureContact = false, const bool PrintingOutput = false ) : BaseType() { // Set local flags mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::ENSURE_CONTACT, EnsureContact); mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::PRINTING_OUTPUT, PrintingOutput); mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::INITIAL_RESIDUAL_IS_SET, false); mDispRatioTolerance = DispRatioTolerance; mDispAbsTolerance = DispAbsTolerance; mLMRatioTolerance = LMRatioTolerance; mLMAbsTolerance = LMAbsTolerance; } /** * @brief Default constructor (parameters) * @param ThisParameters The configuration parameters */ explicit DisplacementLagrangeMultiplierMixedContactCriteria( Parameters ThisParameters = Parameters(R"({})")) : BaseType() { // The default parameters Parameters default_parameters = Parameters(R"( { "ensure_contact" : false, "print_convergence_criterion" : false, "residual_relative_tolerance" : 1.0e-4, "residual_absolute_tolerance" : 1.0e-9, "contact_displacement_relative_tolerance" : 1.0e-4, "contact_displacement_absolute_tolerance" : 1.0e-9 })" ); ThisParameters.ValidateAndAssignDefaults(default_parameters); // The displacement solution mDispRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble(); mDispAbsTolerance = ThisParameters["residual_absolute_tolerance"].GetDouble(); // The contact solution mLMRatioTolerance = ThisParameters["contact_displacement_relative_tolerance"].GetDouble(); mLMAbsTolerance = ThisParameters["contact_displacement_absolute_tolerance"].GetDouble(); // Set local flags mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::ENSURE_CONTACT, ThisParameters["ensure_contact"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::PRINTING_OUTPUT, ThisParameters["print_convergence_criterion"].GetBool()); mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::TABLE_IS_INITIALIZED, false); mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::INITIAL_RESIDUAL_IS_SET, false); } //* Copy constructor. DisplacementLagrangeMultiplierMixedContactCriteria( DisplacementLagrangeMultiplierMixedContactCriteria const& rOther ) :BaseType(rOther) ,mOptions(rOther.mOptions) ,mDispRatioTolerance(rOther.mDispRatioTolerance) ,mDispAbsTolerance(rOther.mDispAbsTolerance) ,mDispInitialResidualNorm(rOther.mDispInitialResidualNorm) ,mDispCurrentResidualNorm(rOther.mDispCurrentResidualNorm) ,mLMRatioTolerance(rOther.mLMRatioTolerance) ,mLMAbsTolerance(rOther.mLMAbsTolerance) { } /// Destructor. ~DisplacementLagrangeMultiplierMixedContactCriteria() override = default; ///@} ///@name Operators ///@{ /** * @brief Compute relative and absolute error. * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) * @return true if convergence is achieved, false otherwise */ bool PostCriteria( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { if (SparseSpaceType::Size(rb) != 0) { //if we are solving for something // Initialize TDataType disp_residual_solution_norm = 0.0, lm_solution_norm = 0.0, lm_increase_norm = 0.0; IndexType disp_dof_num(0),lm_dof_num(0); // First iterator const auto it_dof_begin = rDofSet.begin(); // Auxiliar values std::size_t dof_id = 0; TDataType residual_dof_value = 0.0, dof_value = 0.0, dof_incr = 0.0; // Loop over Dofs #pragma omp parallel for reduction(+:disp_residual_solution_norm,lm_solution_norm,lm_increase_norm,disp_dof_num,lm_dof_num,dof_id,residual_dof_value,dof_value,dof_incr) for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) { auto it_dof = it_dof_begin + i; dof_id = it_dof->EquationId(); if (mActiveDofs[dof_id]) { const auto curr_var = it_dof->GetVariable(); if ((curr_var == VECTOR_LAGRANGE_MULTIPLIER_X) || (curr_var == VECTOR_LAGRANGE_MULTIPLIER_Y) || (curr_var == VECTOR_LAGRANGE_MULTIPLIER_Z) || (curr_var == LAGRANGE_MULTIPLIER_CONTACT_PRESSURE)) { dof_value = it_dof->GetSolutionStepValue(0); dof_incr = rDx[dof_id]; lm_solution_norm += dof_value * dof_value; lm_increase_norm += dof_incr * dof_incr; lm_dof_num++; } else { residual_dof_value = rb[dof_id]; disp_residual_solution_norm += residual_dof_value * residual_dof_value; disp_dof_num++; } } } if(lm_increase_norm < Tolerance) lm_increase_norm = 1.0; KRATOS_ERROR_IF(mOptions.Is(DisplacementLagrangeMultiplierMixedContactCriteria::ENSURE_CONTACT) && lm_solution_norm < Tolerance) << "ERROR::CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl; mDispCurrentResidualNorm = disp_residual_solution_norm; const TDataType lm_ratio = lm_solution_norm > Tolerance ? std::sqrt(lm_increase_norm/lm_solution_norm) : 0.0; const TDataType lm_abs = std::sqrt(lm_increase_norm)/static_cast<TDataType>(lm_dof_num); TDataType residual_disp_ratio; // We initialize the solution if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::INITIAL_RESIDUAL_IS_SET)) { mDispInitialResidualNorm = (disp_residual_solution_norm < Tolerance) ? 1.0 : disp_residual_solution_norm; residual_disp_ratio = 1.0; mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::INITIAL_RESIDUAL_IS_SET, true); } // We calculate the ratio of the displacements residual_disp_ratio = mDispCurrentResidualNorm/mDispInitialResidualNorm; // We calculate the absolute norms TDataType residual_disp_abs = mDispCurrentResidualNorm/disp_dof_num; // The process info of the model part ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); // We print the results // TODO: Replace for the new log if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { std::cout.precision(4); TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << lm_ratio << mLMRatioTolerance << lm_abs << mLMAbsTolerance; } else { std::cout.precision(4); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::PRINTING_OUTPUT)) { KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << BOLDFONT("MIXED CONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific; KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << residual_disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << residual_disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << BOLDFONT("\tLAGRANGE MUL: RATIO = ") << lm_ratio << BOLDFONT(" EXP.RATIO = ") << mLMRatioTolerance << BOLDFONT(" ABS = ") << lm_abs << BOLDFONT(" EXP.ABS = ") << mLMAbsTolerance << std::endl; } else { KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << "MIXED CONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific; KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << "\tDISPLACEMENT: RATIO = " << residual_disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << residual_disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl; KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << "\tLAGRANGE MUL: RATIO = " << lm_ratio << " EXP.RATIO = " << mLMRatioTolerance << " ABS = " << lm_abs << " EXP.ABS = " << mLMAbsTolerance << std::endl; } } } r_process_info[CONVERGENCE_RATIO] = (residual_disp_ratio > lm_ratio) ? residual_disp_ratio : lm_ratio; r_process_info[RESIDUAL_NORM] = (lm_abs > mLMAbsTolerance) ? lm_abs : mLMAbsTolerance; // We check if converged const bool disp_converged = (residual_disp_ratio <= mDispRatioTolerance || residual_disp_abs <= mDispAbsTolerance); const bool lm_converged = (mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::ENSURE_CONTACT) && lm_solution_norm < Tolerance) ? true : (lm_ratio <= mLMRatioTolerance || lm_abs <= mLMAbsTolerance); if ( disp_converged && lm_converged ) { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FGRN(" Achieved")); else r_table << "Achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FGRN("achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << "\tConvergence is achieved" << std::endl; } } return true; } else { if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) { if (r_process_info.Has(TABLE_UTILITY)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::PRINTING_OUTPUT)) r_table << BOLDFONT(FRED(" Not achieved")); else r_table << "Not achieved"; } else { if (mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::PRINTING_OUTPUT)) KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << BOLDFONT("\tConvergence") << " is " << BOLDFONT(FRED(" not achieved")) << std::endl; else KRATOS_INFO("DisplacementLagrangeMultiplierMixedContactCriteria") << "\tConvergence is not achieved" << std::endl; } } return false; } } else // In this case all the displacements are imposed! return true; } /** * @brief This function initialize the convergence criteria * @param rModelPart Reference to the ModelPart containing the contact problem. (unused) */ void Initialize( ModelPart& rModelPart) override { BaseType::mConvergenceCriteriaIsInitialized = true; ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); if (r_process_info.Has(TABLE_UTILITY) && mOptions.IsNot(DisplacementLagrangeMultiplierMixedContactCriteria::TABLE_IS_INITIALIZED)) { TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY]; auto& r_table = p_table->GetTable(); r_table.AddColumn("DP RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); r_table.AddColumn("LM RATIO", 10); r_table.AddColumn("EXP. RAT", 10); r_table.AddColumn("ABS", 10); r_table.AddColumn("EXP. ABS", 10); r_table.AddColumn("CONVERGENCE", 15); mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::TABLE_IS_INITIALIZED, true); } } /** * @brief This function initializes the solution step * @param rModelPart Reference to the ModelPart containing the contact problem. * @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver) * @param rA System matrix (unused) * @param rDx Vector of results (variations on nodal variables) * @param rb RHS vector (residual) */ void InitializeSolutionStep( ModelPart& rModelPart, DofsArrayType& rDofSet, const TSystemMatrixType& rA, const TSystemVectorType& rDx, const TSystemVectorType& rb ) override { // Initialize flag mOptions.Set(DisplacementLagrangeMultiplierMixedContactCriteria::INITIAL_RESIDUAL_IS_SET, false); // Filling mActiveDofs when MPC exist ConstraintUtilities::ComputeActiveDofs(rModelPart, mActiveDofs, rDofSet); } ///@} ///@name Operations ///@{ ///@} ///@name Acces ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@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 ///@{ Flags mOptions; /// Local flags TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement residual TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement residual TDataType mDispInitialResidualNorm; /// The reference norm of the displacement residual TDataType mDispCurrentResidualNorm; /// The current norm of the displacement residual TDataType mLMRatioTolerance; /// The ratio threshold for the norm of the LM TDataType mLMAbsTolerance; /// The absolute value threshold for the norm of the LM std::vector<bool> mActiveDofs; /// This vector contains the dofs that are active ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Unaccessible methods ///@{ ///@} }; // Kratos DisplacementLagrangeMultiplierMixedContactCriteria ///@name Local flags creation ///@{ /// Local Flags template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::ENSURE_CONTACT(Kratos::Flags::Create(0)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::NOT_ENSURE_CONTACT(Kratos::Flags::Create(0, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::PRINTING_OUTPUT(Kratos::Flags::Create(1)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::NOT_PRINTING_OUTPUT(Kratos::Flags::Create(1, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::TABLE_IS_INITIALIZED(Kratos::Flags::Create(2)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::NOT_TABLE_IS_INITIALIZED(Kratos::Flags::Create(2, false)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(3)); template<class TSparseSpace, class TDenseSpace> const Kratos::Flags DisplacementLagrangeMultiplierMixedContactCriteria<TSparseSpace, TDenseSpace>::NOT_INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(3, false)); } #endif /* KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_MIXED_CONTACT_CRITERIA_H */
array_swap.c
#include<stdio.h> #include<omp.h> #include<stdlib.h> int main(int argc, char* argv[]) { int i, temp, n=5; int a[5] = {1, 2, 3, 4, 5}; int b[5] = {6, 7, 8, 9, 10}; #pragma omp parallel for private(temp) for (i=0;i<n;i++) { temp = a[i]; a[i] = b[i]; b[i] = temp; } printf("thread %d\n", omp_get_max_threads()); }
omp_rw_lock.h
/* @copyright Russell Standish 2000-2013 @author Russell Standish This file is part of EcoLab Open source licensed under the MIT license. See LICENSE for details. */ /**\file \brief A read/write lock pattern for OpenMP */ #ifndef OMP_RW_LOCK_H #define OMP_RW_LOCK_H #ifdef _OPENMP #include <omp.h> namespace ecolab { /// A read/write lock pattern for OpenMP class RWlock { /** stores which threads are read locked. Implies a maximum of 32 threads are supported on 32 bit machines ad 64 threads on 64 bit machines. */ volatile unsigned long read_mask; omp_lock_t write_lock; public: RWlock(): read_mask(0) {omp_init_lock(&write_lock);} ~RWlock() {omp_destroy_lock(&write_lock);} void lock_for_read() { omp_set_lock(&write_lock); #pragma omp atomic read_mask |= (1 << omp_get_thread_num()); omp_unset_lock(&write_lock); } void unlock_for_read() { #pragma omp atomic read_mask &= ~(1 << omp_get_thread_num()); } void lock_for_write() { unsigned long read_set = read_mask & (1 << omp_get_thread_num()); unlock_for_read(); omp_set_lock(&write_lock); //wait for read locks on other threads to be relinquished while (read_mask); #pragma omp atomic read_mask |= read_set; //reestablish previous read lock status. } void unlock_for_write() { omp_unset_lock(&write_lock); } }; /// apply a read lock to the current scope (prevents write lock from /// being taken) class read_lock { RWlock& lock; public: read_lock(RWlock& lock): lock(lock) {lock.lock_for_read();} ~read_lock() {lock.unlock_for_read();} }; /// apply a write lock (exclusive access) to the current scope class write_lock { RWlock& lock; public: write_lock(RWlock& lock): lock(lock) {lock.lock_for_write();} ~write_lock() {lock.unlock_for_write();} }; } #else //!_OPENMP namespace ecolab { class RWlock {}; struct read_lock { read_lock(RWlock& lock) {} }; struct write_lock { write_lock(RWlock& lock) {} }; } #endif #endif
test_nvector_openmpdev.c
/* ----------------------------------------------------------------- * Programmer(s): David J. Gardner @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, 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 * ----------------------------------------------------------------- * This is the testing routine to check the OpenMP 4.5 NVECTOR * module implementation. * -----------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <sundials/sundials_types.h> #include <nvector/nvector_openmpdev.h> #include <sundials/sundials_math.h> #include "test_nvector.h" #include <omp.h> /* OpenMPDEV vector specific tests */ int Test_N_VMake_OpenMPDEV(N_Vector X, sunindextype length, int myid); /* ---------------------------------------------------------------------- * Main NVector Testing Routine * --------------------------------------------------------------------*/ int main(int argc, char *argv[]) { int fails = 0; /* counter for test failures */ int retval; /* function return value */ sunindextype length; /* vector length */ N_Vector U, V, W, X, Y, Z; /* test vectors */ int print_timing; /* turn timing on/off */ /* check input and set vector length */ if (argc < 3){ printf("ERROR: TWO (2) Inputs required: vector length and print timing \n"); return(-1); } length = (sunindextype) atol(argv[1]); if (length <= 0) { printf("ERROR: length of vector must be a positive integer \n"); return(-1); } print_timing = atoi(argv[2]); SetTiming(print_timing, 0); printf("Testing the OpenMP DEV N_Vector \n"); printf("Vector length %ld \n", (long int) length); printf("\n omp_get_default_device = %d \n", omp_get_default_device()); printf("\n omp_get_num_devices = %d \n", omp_get_num_devices()); printf("\n omp_get_initial_device = %d \n", omp_get_initial_device()); printf("\n omp_is_initial_device = %d \n", omp_is_initial_device()); /* Create new vectors */ W = N_VNewEmpty_OpenMPDEV(length); if (W == NULL) { printf("FAIL: Unable to create a new empty vector \n\n"); return(1); } X = N_VNew_OpenMPDEV(length); if (X == NULL) { N_VDestroy(W); printf("FAIL: Unable to create a new vector \n\n"); return(1); } /* Check vector ID */ fails += Test_N_VGetVectorID(X, SUNDIALS_NVEC_OPENMPDEV, 0); /* Check vector length */ fails += Test_N_VGetLength(X, 0); /* Check vector communicator */ fails += Test_N_VGetCommunicator(X, NULL, 0); /* Test clone functions */ fails += Test_N_VCloneEmpty(X, 0); fails += Test_N_VClone(X, length, 0); fails += Test_N_VCloneEmptyVectorArray(5, X, 0); fails += Test_N_VCloneVectorArray(5, X, length, 0); /* Clone additional vectors for testing */ Y = N_VClone(X); if (Y == NULL) { N_VDestroy(W); N_VDestroy(X); printf("FAIL: Unable to create a new vector \n\n"); return(1); } Z = N_VClone(X); if (Z == NULL) { N_VDestroy(W); N_VDestroy(X); N_VDestroy(Y); printf("FAIL: Unable to create a new vector \n\n"); return(1); } /* Standard vector operation tests */ printf("\nTesting standard vector operations:\n\n"); fails += Test_N_VConst(X, length, 0); fails += Test_N_VLinearSum(X, Y, Z, length, 0); fails += Test_N_VProd(X, Y, Z, length, 0); fails += Test_N_VDiv(X, Y, Z, length, 0); fails += Test_N_VScale(X, Z, length, 0); fails += Test_N_VAbs(X, Z, length, 0); fails += Test_N_VInv(X, Z, length, 0); fails += Test_N_VAddConst(X, Z, length, 0); fails += Test_N_VDotProd(X, Y, length, 0); fails += Test_N_VMaxNorm(X, length, 0); fails += Test_N_VWrmsNorm(X, Y, length, 0); fails += Test_N_VWrmsNormMask(X, Y, Z, length, 0); fails += Test_N_VMin(X, length, 0); fails += Test_N_VWL2Norm(X, Y, length, 0); fails += Test_N_VL1Norm(X, length, 0); fails += Test_N_VCompare(X, Z, length, 0); fails += Test_N_VInvTest(X, Z, length, 0); fails += Test_N_VConstrMask(X, Y, Z, length, 0); fails += Test_N_VMinQuotient(X, Y, length, 0); /* Fused and vector array operations tests (disabled) */ printf("\nTesting fused and vector array operations (disabled):\n\n"); /* create vector and disable all fused and vector array operations */ U = N_VNew_OpenMPDEV(length); retval = N_VEnableFusedOps_OpenMPDEV(U, SUNFALSE); if (U == NULL || retval != 0) { N_VDestroy(W); N_VDestroy(X); N_VDestroy(Y); N_VDestroy(Z); printf("FAIL: Unable to create a new vector \n\n"); return(1); } /* fused operations */ fails += Test_N_VLinearCombination(U, length, 0); fails += Test_N_VScaleAddMulti(U, length, 0); fails += Test_N_VDotProdMulti(U, length, 0); /* vector array operations */ fails += Test_N_VLinearSumVectorArray(U, length, 0); fails += Test_N_VScaleVectorArray(U, length, 0); fails += Test_N_VConstVectorArray(U, length, 0); fails += Test_N_VWrmsNormVectorArray(U, length, 0); fails += Test_N_VWrmsNormMaskVectorArray(U, length, 0); fails += Test_N_VScaleAddMultiVectorArray(U, length, 0); fails += Test_N_VLinearCombinationVectorArray(U, length, 0); /* Fused and vector array operations tests (enabled) */ printf("\nTesting fused and vector array operations (enabled):\n\n"); /* create vector and enable all fused and vector array operations */ V = N_VNew_OpenMPDEV(length); retval = N_VEnableFusedOps_OpenMPDEV(V, SUNTRUE); if (V == NULL || retval != 0) { N_VDestroy(W); N_VDestroy(X); N_VDestroy(Y); N_VDestroy(Z); N_VDestroy(U); printf("FAIL: Unable to create a new vector \n\n"); return(1); } /* fused operations */ fails += Test_N_VLinearCombination(V, length, 0); fails += Test_N_VScaleAddMulti(V, length, 0); fails += Test_N_VDotProdMulti(V, length, 0); /* vector array operations */ fails += Test_N_VLinearSumVectorArray(V, length, 0); fails += Test_N_VScaleVectorArray(V, length, 0); fails += Test_N_VConstVectorArray(V, length, 0); fails += Test_N_VWrmsNormVectorArray(V, length, 0); fails += Test_N_VWrmsNormMaskVectorArray(V, length, 0); fails += Test_N_VScaleAddMultiVectorArray(V, length, 0); fails += Test_N_VLinearCombinationVectorArray(V, length, 0); /* local reduction operations */ printf("\nTesting local reduction operations:\n\n"); fails += Test_N_VDotProdLocal(X, Y, length, 0); fails += Test_N_VMaxNormLocal(X, length, 0); fails += Test_N_VMinLocal(X, length, 0); fails += Test_N_VL1NormLocal(X, length, 0); fails += Test_N_VWSqrSumLocal(X, Y, length, 0); fails += Test_N_VWSqrSumMaskLocal(X, Y, Z, length, 0); fails += Test_N_VInvTestLocal(X, Z, length, 0); fails += Test_N_VConstrMaskLocal(X, Y, Z, length, 0); fails += Test_N_VMinQuotientLocal(X, Y, length, 0); /* Free vectors */ N_VDestroy(U); N_VDestroy(V); N_VDestroy(W); N_VDestroy(X); N_VDestroy(Y); N_VDestroy(Z); /* Print result */ if (fails) { printf("FAIL: NVector module failed %i tests \n\n", fails); } else { printf("SUCCESS: NVector module passed all tests \n\n"); } return(fails); } /* ---------------------------------------------------------------------- * OpenMPDEV specific tests * --------------------------------------------------------------------*/ /* -------------------------------------------------------------------- * Test for the CUDA N_Vector N_VMake_OpenMPDEV function. Requires N_VConst * to check data. */ int Test_N_VMake_OpenMPDEV(N_Vector X, sunindextype length, int myid) { int failure = 0; realtype *h_data, *d_data; N_Vector Y; N_VConst(NEG_HALF, X); N_VCopyFromDevice_OpenMPDEV(X); h_data = N_VGetHostArrayPointer_OpenMPDEV(X); d_data = N_VGetDeviceArrayPointer_OpenMPDEV(X); /* Case 1: h_data and d_data are not null */ Y = N_VMake_OpenMPDEV(length, h_data, d_data); if (Y == NULL) { printf(">>> FAILED test -- N_VMake_OpenMPDEV, Proc %d \n", myid); printf(" Vector is NULL \n \n"); return(1); } if (N_VGetHostArrayPointer_OpenMPDEV(Y) == NULL) { printf(">>> FAILED test -- N_VMake_OpenMPDEV, Proc %d \n", myid); printf(" Vector host data == NULL \n \n"); N_VDestroy(Y); return(1); } if (N_VGetDeviceArrayPointer_OpenMPDEV(Y) == NULL) { printf(">>> FAILED test -- N_VMake_OpenMPDEV, Proc %d \n", myid); printf(" Vector device data -= NULL \n \n"); N_VDestroy(Y); return(1); } failure += check_ans(NEG_HALF, Y, length); if (failure) { printf(">>> FAILED test -- N_VMake_OpenMPDEV Case 1, Proc %d \n", myid); printf(" Failed N_VConst check \n \n"); N_VDestroy(Y); return(1); } if (myid == 0) { printf("PASSED test -- N_VMake_OpenMPDEV Case 1 \n"); } N_VDestroy(Y); /* Case 2: data is null */ Y = N_VMake_OpenMPDEV(length, NULL, NULL); if (Y != NULL) { printf(">>> FAILED test -- N_VMake_OpenMPDEV Case 2, Proc %d \n", myid); printf(" Vector is not NULL \n \n"); return(1); } if (myid == 0) { printf("PASSED test -- N_VMake_OpenMPDEV Case 2 \n"); } N_VDestroy(Y); return(failure); } /* ---------------------------------------------------------------------- * Implementation specific utility functions for vector tests * --------------------------------------------------------------------*/ int check_ans(realtype ans, N_Vector X, sunindextype local_length) { int failure = 0; sunindextype i; realtype *Xdata; N_VCopyFromDevice_OpenMPDEV(X); Xdata = N_VGetHostArrayPointer_OpenMPDEV(X); /* check vector data */ for (i = 0; i < local_length; i++) { failure += FNEQ(Xdata[i], ans); } return (failure > ZERO) ? (1) : (0); } booleantype has_data(N_Vector X) { realtype *Xdata = N_VGetHostArrayPointer_OpenMPDEV(X); if (Xdata == NULL) return SUNFALSE; else return SUNTRUE; } void set_element(N_Vector X, sunindextype i, realtype val) { set_element_range(X, i, i, val); } void set_element_range(N_Vector X, sunindextype is, sunindextype ie, realtype val) { realtype *xdev; int dev; sunindextype i; xdev = N_VGetDeviceArrayPointer_OpenMPDEV(X); dev = omp_get_default_device(); /* set elements [is,ie] of the data array */ #pragma omp target map(to:is,ie,val) is_device_ptr(xdev) device(dev) #pragma omp teams distribute parallel for schedule(static, 1) { for(i = is; i <= ie; i++) xdev[i] = val; } } realtype get_element(N_Vector X, sunindextype i) { realtype *data; N_VCopyFromDevice_OpenMPDEV(X); data = N_VGetHostArrayPointer_OpenMPDEV(X); return data[i]; } double max_time(N_Vector X, double time) { /* not running in parallel, just return input time */ return(time); } void sync_device() { /* not running on DEV, just return */ return; }
GB_unop__abs_fp64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__abs_fp64_fc64) // op(A') function: GB (_unop_tran__abs_fp64_fc64) // C type: double // A type: GxB_FC64_t // cast: GxB_FC64_t cij = (aij) // unaryop: cij = cabs (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cabs (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = (aij) ; \ Cx [pC] = cabs (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_FP64 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__abs_fp64_fc64) ( double *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = cabs (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = cabs (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__abs_fp64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
grid.c
#include "grid.h" #include "utils.h" #include <cmath> #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; void init_rhs( GRID u ) { #pragma omp parallel for for (int i=1; i<=u.n; i++) for (int j=1; j<=u.n; j++) for (int k=1; k<=u.n; k++) u.p[i][j][k] = 0.0; } void init_border( GRID u ) { for (int i=0; i<=u.n+1; i++) for (int j=0; j<=u.n+1; j++) { u.p[i][j][0] = 0.0; u.p[i][j][u.n+1] = 0.0; } for (int i=0; i<=u.n+1; i++) for (int k=0; k<=u.n+1; k++) { u.p[i][0][k] = 0.0; u.p[i][u.n+1][k] = 0.0; } for (int j=0; j<=u.n+1; j++) for (int k=0; k<=u.n+1; k++) { u.p[0][j][k] = 0.0; u.p[u.n+1][j][k] = 0.0; } } void init_solution( GRID u ) { zero_grid(u); } void create_grid( GRID *grid, int n ) { grid->n = n; grid->h = 1.0/(double)(n+1); grid->lda = n+2; #ifdef USE_MM_MALLOC grid->p = (double ***) _mm_malloc((n+2)*sizeof(double **),64); grid->p[0] = (double **) _mm_malloc((n+2)*(grid->lda)*sizeof(double *),64); grid->p[0][0] = (double *) _mm_malloc((n+2)*(grid->lda)*(grid->lda)*sizeof(double),64); #else grid->p = (double ***) malloc((n+2)*sizeof(double **)); grid->p[0] = (double **) malloc((n+2)*(grid->lda)*sizeof(double *)); grid->p[0][0] = (double *) malloc((n+2)*(grid->lda)*(grid->lda)*sizeof(double)); #endif for (int i=0; i<=n+1; i++) { grid->p[i] = grid->p[0] + i*grid->lda; for (int j=0; j<=n+1; j++) { grid->p[i][j] = grid->p[0][0] + j*grid->lda + i*grid->lda*grid->lda; } } zero_grid(*grid); } void free_grid( GRID *grid ) { #ifdef USE_MM_MALLOC _mm_free(grid->p[0][0]); _mm_free(grid->p[0]); _mm_free(grid->p); #else free(grid->p[0][0]); free(grid->p[0]); free(grid->p); #endif } void create_grid_list( GRIDLIST *list, int n, int lmax ) { *list = (GRID *) calloc(lmax+1,sizeof(GRID)); if(*list == NULL) print_msg("create_grid_list: not enough memory"); for (int i=0; i<=lmax; i++) { create_grid((*list)+i,n); n = 2*n+1; } } void free_grid_list( GRIDLIST *list, int lmax ) { for (int i=0; i<=lmax; i++) free_grid((*list)+i); free(*list); } void print_grid( GRID u ) { cout << "\n GRID \n"; for (int i=0; i<=u.n+1; i++) { for (int j=0; j<=u.n+1; j++) { for (int k=0; k<=u.n+1; k++) cout << u.p[i][j][k] << " "; cout << "\n"; } cout << "\n"; } cout << "\n"; } /* void print_grid( GRID u, char *c ) { */ /* printf("\n GRID %s\n",c); */ /* for (int j=u.n+1; j>=0; j--) { */ /* printf("\n row %d:\n ",j); */ /* for (int i=0; i<=u.n +1; i++) */ /* printf("%f ",u.p[i][j]); */ /* } */ /* printf("\n"); */ /* } */ void zero_grid( GRID u ) { #pragma omp parallel for for (int i=0; i<=u.n+1; i++) for (int j=0; j<=u.n+1; j++) for (int k=0; k<=u.n+1; k++) u.p[i][j][k] = 0; } void random_grid( GRID u ) { #pragma omp parallel for for (int i=0; i<=u.n+1; i++) for(int j=0; j<=u.n+1; j++) for(int k=0; k<=u.n+1; k++) u.p[i][j][k] = rand() / RAND_MAX; } void init_grid( GRID u, double a ) { #pragma omp parallel for for (int i=0; i<=u.n+1; i++) for(int j=0; j<=u.n+1; j++) for(int k=0; k<=u.n+1; k++) u.p[i][j][k] = a; } double error( GRID u1, GRID u2 ) { if (u1.n != u2.n) print_msg("error: wrong grid-sizes"); double tmp = 0.0; #pragma omp parallel for reduction(+:tmp) for (int i=1; i<=u1.n; i++) for(int j=1; j<=u1.n; j++) for(int k=1; k<=u1.n; k++) tmp += (u1.p[i][j][k]-u2.p[i][j][k])*(u1.p[i][j][k]-u2.p[i][j][k]); tmp = sqrt(tmp)/u1.n; return tmp; } //void correct( GRID u, GRID c ) { long long int correct( GRID u, GRID c ) { long long int count = 0; if (u.n != c.n) print_msg("correct: wrong grid sizes"); #pragma omp parallel for for (int i=1; i<=u.n; i++) for (int j=1; j<=u.n; j++) for (int k=1; k<=u.n; k++) u.p[i][j][k] += c.p[i][j][k]; //count++; return count; }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 4; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.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 const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; 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] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][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, "constant") #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(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
10_omp_empty.c
// clang-format off // RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | %apply-typeart -typeart-alloca -call-filter -S 2>&1 | FileCheck %s // REQUIRES: openmp // clang-format on #include "omp.h" // CHECK-NOT: {{.*}} __typeart_alloc void foo(int* x) { #pragma omp parallel // transformed to @__kmpc_fork_call { *x = -1; } #pragma omp parallel for for (int i = 0; i < x[10]; ++i) { x[i] = i; } } // Standard filter // CHECK: > Stack Memory // CHECK-NEXT: Alloca : // CHECK-NEXT: Stack call filtered % : 100.00
private_mapping.c
// RUN: %libomptarget-compile-run-and-check-aarch64-unknown-linux-gnu // RUN: %libomptarget-compile-run-and-check-powerpc64-ibm-linux-gnu // RUN: %libomptarget-compile-run-and-check-powerpc64le-ibm-linux-gnu // RUN: %libomptarget-compile-run-and-check-x86_64-pc-linux-gnu // RUN: %libomptarget-compile-run-and-check-nvptx64-nvidia-cuda #include <assert.h> #include <stdio.h> int main() { int data1[3] = {1}, data2[3] = {2}, data3[3] = {3}; int sum[16] = {0}; #pragma omp target teams distribute parallel for map(tofrom \ : sum) \ firstprivate(data1, data2, data3) for (int i = 0; i < 16; ++i) { for (int j = 0; j < 3; ++j) { sum[i] += data1[j]; sum[i] += data2[j]; sum[i] += data3[j]; } } for (int i = 0; i < 16; ++i) { assert(sum[i] == 6); } printf("PASS\n"); return 0; } // CHECK: PASS
GB_unaryop__lnot_fp64_uint16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_fp64_uint16 // op(A') function: GB_tran__lnot_fp64_uint16 // C type: double // A type: uint16_t // cast: double cij = (double) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint16_t #define GB_CTYPE \ double // 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 != 0) ; // casting #define GB_CASTING(z, x) \ double z = (double) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_FP64 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp64_uint16 ( double *restrict Cx, const uint16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_fp64_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
facedetectcnn.h
/* By downloading, copying, installing or using the software you agree to this license. If you do not agree to this license, do not download, install, copy or use the software. License Agreement For libfacedetection (3-clause BSD License) Copyright (c) 2018-2020, Shiqi Yu, all rights reserved. shiqi.yu@gmail.com 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 names of the copyright holders nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall copyright holders or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ #pragma once #include "facedetection_export.h" //#define _ENABLE_AVX512 //Please enable it if X64 CPU //#define _ENABLE_AVX2 //Please enable it if X64 CPU //#define _ENABLE_NEON //Please enable it if ARM CPU FACEDETECTION_EXPORT int * facedetect_cnn(unsigned char * result_buffer, //buffer memory for storing face detection results, !!its size must be 0x20000 Bytes!! unsigned char * rgb_image_data, int width, int height, int step); //input image, it must be BGR (three channels) insteed of RGB image! /* DO NOT EDIT the following code if you don't really understand it. */ #if defined(_ENABLE_AVX512) || defined(_ENABLE_AVX2) #include <immintrin.h> #endif #if defined(_ENABLE_NEON) #include "arm_neon.h" //NEON does not support UINT8*INT8 dot product //to conver the input data to range [0, 127], //and then use INT8*INT8 dot product #define _MAX_UINT8_VALUE 127 #else #define _MAX_UINT8_VALUE 255 #endif #if defined(_ENABLE_AVX512) #define _MALLOC_ALIGN 512 #elif defined(_ENABLE_AVX2) #define _MALLOC_ALIGN 256 #else #define _MALLOC_ALIGN 128 #endif #if defined(_ENABLE_AVX512)&& defined(_ENABLE_NEON) #error Cannot enable the two of AVX512 and NEON at the same time. #endif #if defined(_ENABLE_AVX2)&& defined(_ENABLE_NEON) #error Cannot enable the two of AVX and NEON at the same time. #endif #if defined(_ENABLE_AVX512)&& defined(_ENABLE_AVX2) #error Cannot enable the two of AVX512 and AVX2 at the same time. #endif #if defined(_OPENMP) #include <omp.h> #endif #include <string.h> #include <vector> #include <iostream> #include <typeinfo> using namespace std; void* myAlloc(size_t size); void myFree_(void* ptr); #define myFree(ptr) (myFree_(*(ptr)), *(ptr)=0); #ifndef MIN # define MIN(a,b) ((a) > (b) ? (b) : (a)) #endif #ifndef MAX # define MAX(a,b) ((a) < (b) ? (b) : (a)) #endif typedef struct FaceRect_ { float score; int x; int y; int w; int h; int lm[10]; }FaceRect; typedef struct ConvInfoStruct_ { int pad; int stride; int kernel_size; int channels; int num; float scale; signed char* pWeights; signed int* pBias; }ConvInfoStruct; template <class T> class CDataBlob { public: T * data; int width; int height; int channels; int channelStep; float scale; //when the datablob is a filter, the bias is 0 by default //if it is the filted data, the bias is 1 by default int bias; public: CDataBlob() { data = 0; width = 0; height = 0; channels = 0; channelStep = 0; scale = 1.0f; bias = 0; } CDataBlob(int w, int h, int c) { data = 0; create(w, h, c); } ~CDataBlob() { setNULL(); } void setNULL() { if (data) myFree(&data); width = height = channels = channelStep = 0; scale = 1.0f; } bool create(int w, int h, int c) { setNULL(); width = w; height = h; channels = c; bias = 0; //alloc space for int8 array int remBytes = (sizeof(T)* channels) % (_MALLOC_ALIGN / 8); if (remBytes == 0) this->channelStep = channels * sizeof(T); else this->channelStep = (channels * sizeof(T)) + (_MALLOC_ALIGN / 8) - remBytes; data = (T*)myAlloc(size_t(width) * height * this->channelStep); if (data == NULL) { cerr << "Failed to alloc memeory for uint8 data blob: " << width << "*" << height << "*" << channels << endl; return false; } //memset(data, 0, width * height * channelStep); //the following code is faster than memset //but not only the padding bytes are set to zero. //BE CAREFUL!!! //#if defined(_OPENMP) //#pragma omp parallel for //#endif for (int r = 0; r < this->height; r++) { for (int c = 0; c < this->width; c++) { int pixel_end = this->channelStep / sizeof(T); T * pI = (this->data + (size_t(r) * this->width + c) * this->channelStep /sizeof(T)); for (int ch = this->channels; ch < pixel_end; ch++) pI[ch] = 0; } } return true; } bool setInt8FilterData(signed char * pData, int bias, int dataWidth, int dataHeight, int dataChannels) { if (pData == NULL) { cerr << "The input image data is null." << endl; return false; } if (typeid(signed char) != typeid(T)) { cerr << "Data must be signed char, the same with the source data." << endl; return false; } if (dataWidth != this->width || dataHeight != this->height || dataChannels != this->channels) { cerr << "The dimension of the data can not match that of the Blob." << endl; return false; } for(int row = 0; row < height; row++) for (int col = 0; col < width; col++) { T * p = (this->data + (size_t(width) * row + col) * channelStep /sizeof(T)); for (int ch = 0; ch < channels; ch++) { p[ch] = pData[ch * height * width + row * width + col]; } } this->bias = bias; return true; } bool setDataFrom3x3S2P1to1x1S1P0FromImage(const unsigned char * imgData, int imgWidth, int imgHeight, int imgChannels, int imgWidthStep) { if (imgData == NULL) { cerr << "The input image data is null." << endl; return false; } if (typeid(unsigned char) != typeid(T)) { cerr << "Data must be unsigned char, the same with the source data." << endl; return false; } if (imgChannels != 3) { cerr << "The input image must be a 3-channel RGB image." << endl; return false; } create((imgWidth+1)/2, (imgHeight+1)/2, 27); //since the pixel assignment cannot fill all the elements in the blob. //some elements in the blob should be initialized to 0 memset(data, 0, size_t(width) * height * channelStep); #if defined(_OPENMP) #pragma omp parallel for #endif for (int r = 0; r < this->height; r++) { for (int c = 0; c < this->width; c++) { T * pData = (unsigned char*)this->data + (size_t(r) * this->width + c) * this->channelStep; for (int fy = -1; fy <= 1; fy++) { int srcy = r * 2 + fy; if (srcy < 0 || srcy >= imgHeight) //out of the range of the image continue; for (int fx = -1; fx <= 1; fx++) { int srcx = c * 2 + fx; if (srcx < 0 || srcx >= imgWidth) //out of the range of the image continue; const unsigned char * pImgData = imgData + size_t(imgWidthStep) * srcy + imgChannels * srcx; int output_channel_offset = ((fy + 1) * 3 + fx + 1) * 3; //3x3 filters, 3-channel image #if defined(_ENABLE_NEON) pData[output_channel_offset] = (pImgData[0] / 2); pData[output_channel_offset + 1] = (pImgData[1] / 2); pData[output_channel_offset + 2] = (pImgData[2] / 2); #else pData[output_channel_offset] = (pImgData[0]); pData[output_channel_offset+1] = (pImgData[1]); pData[output_channel_offset+2] = (pImgData[2]); #endif } } } } #if defined(_ENABLE_NEON) this->bias = 1; // 1/2 = 0 this->scale = 0.5f; #else this->bias = 1; this->scale = 1.0f; #endif return true; } T getElement(int x, int y, int channel) { if (this->data) { if (x >= 0 && x < this->width && y >= 0 && y < this->height && channel >= 0 && channel < this->channels) { T * p = this->data + (size_t(y) * this->width + x) * this->channelStep/sizeof(T); return (p[channel]); } } return (T)(0); } friend ostream &operator<<(ostream &output, const CDataBlob &dataBlob) { output << "DataBlob Size (Width, Height, Channel, scale) = (" << dataBlob.width << ", " << dataBlob.height << ", " << dataBlob.channels << ", " << dataBlob.scale << ", " << dataBlob.bias << ")" << endl; for (int ch = 0; ch < dataBlob.channels; ch++) { output << "Channel " << ch << ": " << endl; for (int row = 0; row < dataBlob.height; row++) { output << "("; for (int col = 0; col < dataBlob.width; col++) { T * p = (dataBlob.data + (dataBlob.width * row + col) * dataBlob.channelStep /sizeof(T) ); if(sizeof(T)<4) output << (int)(p[ch]); else output << p[ch]; if (col != dataBlob.width - 1) output << ", "; } output << ")" << endl; } } return output; } }; class Filters { public: vector<CDataBlob<signed char> *> filters; int pad; int stride; float scale; //element * scale = original value Filters() { pad = 0; stride = 0; scale = 0; } }; bool convertInt2Float(CDataBlob<int> * inputData, CDataBlob<float> * outputData); bool convolution(CDataBlob<unsigned char> *inputData, const Filters* filters, CDataBlob<int> *outputData); bool convolution_relu(CDataBlob<unsigned char> *inputData, const Filters* filters, CDataBlob<unsigned char> *outputData); bool maxpooling2x2S2(const CDataBlob<unsigned char> *inputData, CDataBlob<unsigned char> *outputData); bool priorbox(const CDataBlob<unsigned char> * featureData, int img_width, int img_height, int step, int num_sizes, float * pWinSizes, CDataBlob<float> * outputData); template<typename T> bool concat4(const CDataBlob<T> *inputData1, const CDataBlob<T> *inputData2, const CDataBlob<T> *inputData3, const CDataBlob<T> *inputData4, CDataBlob<T> *outputData); /* the input data for softmax must be a vector, the data stored in a multi-channel blob with size 1x1 */ template<typename T> bool blob2vector(const CDataBlob<T> * inputData, CDataBlob<T> * outputData); bool softmax1vector2class(CDataBlob<float> *inputOutputData); bool detection_output(const CDataBlob<float> * priorbox, const CDataBlob<float> * loc, const CDataBlob<float> * conf, float overlap_threshold, float confidence_threshold, int top_k, int keep_top_k, CDataBlob<float> * outputData); vector<FaceRect> objectdetect_cnn(unsigned char * rgbImageData, int with, int height, int step);
is.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 2.3 OpenMP C versions - IS This benchmark is an OpenMP C version of the NPB IS code. The OpenMP C versions are developed by RWCP and derived from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Send comments on the OpenMP C versions to pdp-openmp@rwcp.or.jp 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/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Author: M. Yarrow OpenMP C version: S. Satoh --------------------------------------------------------------------*/ #include "npbparams.h" #include <stdlib.h> #include <stdio.h> #if defined(_OPENMP) #include <omp.h> #endif /* _OPENMP */ /*****************************************************************/ /* For serial IS, buckets are not really req'd to solve NPB1 IS */ /* spec, but their use on some machines improves performance, on */ /* other machines the use of buckets compromises performance, */ /* probably because it is extra computation which is not req'd. */ /* (Note: Mechanism not understood, probably cache related) */ /* Example: SP2-66MhzWN: 50% speedup with buckets */ /* Example: SGI Indy5000: 50% slowdown with buckets */ /* Example: SGI O2000: 400% slowdown with buckets (Wow!) */ /*****************************************************************/ /* #define USE_BUCKETS */ /* buckets are not used in the OpenMP C version */ /******************/ /* default values */ /******************/ #ifndef CLASS #define CLASS 'S' #endif /*************/ /* CLASS S */ /*************/ #if CLASS == 'S' #define TOTAL_KEYS_LOG_2 16 #define MAX_KEY_LOG_2 11 #define NUM_BUCKETS_LOG_2 9 #endif /*************/ /* CLASS W */ /*************/ #if CLASS == 'W' #define TOTAL_KEYS_LOG_2 20 #define MAX_KEY_LOG_2 16 #define NUM_BUCKETS_LOG_2 10 #endif /*************/ /* CLASS A */ /*************/ #if CLASS == 'A' #define TOTAL_KEYS_LOG_2 23 #define MAX_KEY_LOG_2 19 #define NUM_BUCKETS_LOG_2 10 #endif /*************/ /* CLASS B */ /*************/ #if CLASS == 'B' #define TOTAL_KEYS_LOG_2 25 #define MAX_KEY_LOG_2 21 #define NUM_BUCKETS_LOG_2 10 #endif /*************/ /* CLASS C */ /*************/ #if CLASS == 'C' #define TOTAL_KEYS_LOG_2 27 #define MAX_KEY_LOG_2 23 #define NUM_BUCKETS_LOG_2 10 #endif #define TOTAL_KEYS (1 << TOTAL_KEYS_LOG_2) #define MAX_KEY (1 << MAX_KEY_LOG_2) #define NUM_BUCKETS (1 << NUM_BUCKETS_LOG_2) #define NUM_KEYS TOTAL_KEYS #define SIZE_OF_BUFFERS NUM_KEYS #define MAX_ITERATIONS 10 #define TEST_ARRAY_SIZE 5 /*************************************/ /* Typedef: if necessary, change the */ /* size of int here by changing the */ /* int type to, say, long */ /*************************************/ typedef int INT_TYPE; /********************/ /* Some global info */ /********************/ INT_TYPE *key_buff_ptr_global; /* used by full_verify to get */ /* copies of rank info */ int passed_verification; /************************************/ /* These are the three main arrays. */ /* See SIZE_OF_BUFFERS def above */ /************************************/ INT_TYPE key_array[SIZE_OF_BUFFERS], key_buff1[SIZE_OF_BUFFERS], key_buff2[SIZE_OF_BUFFERS], partial_verify_vals[TEST_ARRAY_SIZE]; #ifdef USE_BUCKETS INT_TYPE bucket_size[NUM_BUCKETS], bucket_ptrs[NUM_BUCKETS]; #endif /**********************/ /* Partial verif info */ /**********************/ INT_TYPE test_index_array[TEST_ARRAY_SIZE], test_rank_array[TEST_ARRAY_SIZE], S_test_index_array[TEST_ARRAY_SIZE] = {48427,17148,23627,62548,4431}, S_test_rank_array[TEST_ARRAY_SIZE] = {0,18,346,64917,65463}, W_test_index_array[TEST_ARRAY_SIZE] = {357773,934767,875723,898999,404505}, W_test_rank_array[TEST_ARRAY_SIZE] = {1249,11698,1039987,1043896,1048018}, A_test_index_array[TEST_ARRAY_SIZE] = {2112377,662041,5336171,3642833,4250760}, A_test_rank_array[TEST_ARRAY_SIZE] = {104,17523,123928,8288932,8388264}, B_test_index_array[TEST_ARRAY_SIZE] = {41869,812306,5102857,18232239,26860214}, B_test_rank_array[TEST_ARRAY_SIZE] = {33422937,10244,59149,33135281,99}, C_test_index_array[TEST_ARRAY_SIZE] = {44172927,72999161,74326391,129606274,21736814}, C_test_rank_array[TEST_ARRAY_SIZE] = {61147,882988,266290,133997595,133525895}; /***********************/ /* function prototypes */ /***********************/ double randlc( double *X, double *A ); void full_verify( void ); /* * FUNCTION RANDLC (X, A) * * This routine returns a uniform pseudorandom double precision number in the * range (0, 1) by using the linear congruential generator * * x_{k+1} = a x_k (mod 2^46) * * where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers * before repeating. The argument A is the same as 'a' in the above formula, * and X is the same as x_0. A and X must be odd double precision integers * in the range (1, 2^46). The returned value RANDLC is normalized to be * between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain * the new seed x_1, so that subsequent calls to RANDLC using the same * arguments will generate a continuous sequence. * * This routine should produce the same results on any computer with at least * 48 mantissa bits in double precision floating point data. On Cray systems, * double precision should be disabled. * * David H. Bailey October 26, 1990 * * IMPLICIT DOUBLE PRECISION (A-H, O-Z) * SAVE KS, R23, R46, T23, T46 * DATA KS/0/ * * If this is the first call to RANDLC, compute R23 = 2 ^ -23, R46 = 2 ^ -46, * T23 = 2 ^ 23, and T46 = 2 ^ 46. These are computed in loops, rather than * by merely using the ** operator, in order to insure that the results are * exact on all systems. This code assumes that 0.5D0 is represented exactly. */ /*****************************************************************/ /************* R A N D L C ************/ /************* ************/ /************* portable random number generator ************/ /*****************************************************************/ double randlc(X, A) double *X; double *A; { static int KS=0; static double R23, R46, T23, T46; double T1, T2, T3, T4; double A1; double A2; double X1; double X2; double Z; int i, j; if (KS == 0) { R23 = 1.0; R46 = 1.0; T23 = 1.0; T46 = 1.0; for (i=1; i<=23; i++) { R23 = 0.50 * R23; T23 = 2.0 * T23; } for (i=1; i<=46; i++) { R46 = 0.50 * R46; T46 = 2.0 * T46; } KS = 1; } /* Break A into two parts such that A = 2^23 * A1 + A2 and set X = N. */ T1 = R23 * *A; j = T1; A1 = j; A2 = *A - T23 * A1; /* Break X into two parts such that X = 2^23 * X1 + X2, compute Z = A1 * X2 + A2 * X1 (mod 2^23), and then X = 2^23 * Z + A2 * X2 (mod 2^46). */ T1 = R23 * *X; j = T1; X1 = j; X2 = *X - T23 * X1; T1 = A1 * X2 + A2 * X1; j = R23 * T1; T2 = j; Z = T1 - T23 * T2; T3 = T23 * Z + A2 * X2; j = R46 * T3; T4 = j; *X = T3 - T46 * T4; return(R46 * *X); } /*****************************************************************/ /************* C R E A T E _ S E Q ************/ /*****************************************************************/ void create_seq( double seed, double a ) { double x; int i, j, k; k = MAX_KEY/4; for (i=0; i<NUM_KEYS; i++) { x = randlc(&seed, &a); x += randlc(&seed, &a); x += randlc(&seed, &a); x += randlc(&seed, &a); key_array[i] = k*x; } } /*****************************************************************/ /************* F U L L _ V E R I F Y ************/ /*****************************************************************/ void full_verify() { INT_TYPE i, j; INT_TYPE k; INT_TYPE m, unique_keys; /* Now, finally, sort the keys: */ for( i=0; i<NUM_KEYS; i++ ) key_array[--key_buff_ptr_global[key_buff2[i]]] = key_buff2[i]; /* Confirm keys correctly sorted: count incorrectly sorted keys, if any */ j = 0; #pragma omp parallel for firstprivate(i ) reduction(+:j) for( i=1; i<NUM_KEYS; i++ ) if( key_array[i-1] > key_array[i] ) j++; if( j != 0 ) { printf( "Full_verify: number of keys out of sort: %d\n", j ); } else passed_verification++; } /*****************************************************************/ /************* R A N K ****************/ /*****************************************************************/ void rank( int iteration ) { INT_TYPE i, j, k; INT_TYPE l, m; INT_TYPE shift = MAX_KEY_LOG_2 - NUM_BUCKETS_LOG_2; INT_TYPE key; INT_TYPE min_key_val, max_key_val; INT_TYPE prv_buff1[MAX_KEY]; { key_array[iteration] = iteration; key_array[iteration+MAX_ITERATIONS] = MAX_KEY - iteration; /* Determine where the partial verify test keys are, load into */ /* top of array bucket_size */ #pragma omp parallel for firstprivate(i ) for( i=0; i<TEST_ARRAY_SIZE; i++ ) partial_verify_vals[i] = key_array[test_index_array[i]]; /* Clear the work array */ for( i=0; i<MAX_KEY; i++ ) key_buff1[i] = 0; } for (i=0; i<MAX_KEY; i++) prv_buff1[i] = 0; /* Copy keys into work array; keys in key_array will be reused each iter. */ #pragma omp for for( i=0; i<NUM_KEYS; i++ ) { key_buff2[i] = key_array[i]; /* Ranking of all keys occurs in this section: */ /* In this section, the keys themselves are used as their own indexes to determine how many of each there are: their individual population */ prv_buff1[key_buff2[i]]++; /* Now they have individual key */ } /* population */ for( i=0; i<MAX_KEY-1; i++ ) prv_buff1[i+1] += prv_buff1[i]; { #pragma omp parallel for firstprivate(i ) for( i=0; i<MAX_KEY; i++ ) key_buff1[i] += prv_buff1[i]; } /* To obtain ranks of each key, successively add the individual key population, not forgetting to add m, the total of lesser keys, to the first key population */ { /* This is the partial verify test section */ /* Observe that test_rank_array vals are */ /* shifted differently for different cases */ for( i=0; i<TEST_ARRAY_SIZE; i++ ) { k = partial_verify_vals[i]; /* test vals were put here */ if( 0 <= k && k <= NUM_KEYS-1 ) switch( CLASS ) { case 'S': if( i <= 2 ) { if( key_buff1[k-1] != test_rank_array[i]+iteration ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } else { if( key_buff1[k-1] != test_rank_array[i]-iteration ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } break; case 'W': if( i < 2 ) { if( key_buff1[k-1] != test_rank_array[i]+(iteration-2) ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } else { if( key_buff1[k-1] != test_rank_array[i]-iteration ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } break; case 'A': if( i <= 2 ) { if( key_buff1[k-1] != test_rank_array[i]+(iteration-1) ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } else { if( key_buff1[k-1] != test_rank_array[i]-(iteration-1) ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } break; case 'B': if( i == 1 || i == 2 || i == 4 ) { if( key_buff1[k-1] != test_rank_array[i]+iteration ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } else { if( key_buff1[k-1] != test_rank_array[i]-iteration ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } break; case 'C': if( i <= 2 ) { if( key_buff1[k-1] != test_rank_array[i]+iteration ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } else { if( key_buff1[k-1] != test_rank_array[i]-iteration ) { printf( "Failed partial verification: " "iteration %d, test key %d\n", iteration, i ); } else passed_verification++; } break; } } /* Make copies of rank info for use by full_verify: these variables in rank are local; making them global slows down the code, probably since they cannot be made register by compiler */ if( iteration == MAX_ITERATIONS ) key_buff_ptr_global = key_buff1; } /* end master */ } /*****************************************************************/ /************* M A I N ****************/ /*****************************************************************/ main( argc, argv ) int argc; char **argv; { int i, iteration, itemp; int nthreads = 1; double timecounter, maxtime; /* Initialize the verification arrays if a valid class */ #pragma omp parallel for firstprivate(i ) for( i=0; i<TEST_ARRAY_SIZE; i++ ) switch( CLASS ) { case 'S': test_index_array[i] = S_test_index_array[i]; test_rank_array[i] = S_test_rank_array[i]; break; case 'A': test_index_array[i] = A_test_index_array[i]; test_rank_array[i] = A_test_rank_array[i]; break; case 'W': test_index_array[i] = W_test_index_array[i]; test_rank_array[i] = W_test_rank_array[i]; break; case 'B': test_index_array[i] = B_test_index_array[i]; test_rank_array[i] = B_test_rank_array[i]; break; case 'C': test_index_array[i] = C_test_index_array[i]; test_rank_array[i] = C_test_rank_array[i]; break; }; /* Printout initial NPB info */ printf( "\n\n NAS Parallel Benchmarks 2.3 OpenMP C version" " - IS Benchmark\n\n" ); printf( " Size: %d (class %c)\n", TOTAL_KEYS, CLASS ); printf( " Iterations: %d\n", MAX_ITERATIONS ); /* Initialize timer */ timer_clear( 0 ); /* Generate random number sequence and subsequent keys on all procs */ create_seq( 314159265.00, /* Random number gen seed */ 1220703125.00 ); /* Random number gen mult */ /* Do one interation for free (i.e., untimed) to guarantee initialization of all data and code pages and respective tables */ rank( 1 ); /* Start verification counter */ passed_verification = 0; if( CLASS != 'S' ) printf( "\n iteration\n" ); /* Start timer */ timer_start( 0 ); /* This is the main iteration */ for( iteration=1; iteration<=MAX_ITERATIONS; iteration++ ) { if( CLASS != 'S' ) printf( " %d\n", iteration ); rank( iteration ); #if defined(_OPENMP) nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* End of timing, obtain maximum time of all processors */ timer_stop( 0 ); timecounter = timer_read( 0 ); /* This tests that keys are in sequence: sorting of last ranked key seq occurs here, but is an untimed operation */ full_verify(); /* The final printout */ if( passed_verification != 5*MAX_ITERATIONS + 1 ) passed_verification = 0; c_print_results( "IS", CLASS, TOTAL_KEYS, 0, 0, MAX_ITERATIONS, nthreads, timecounter, ((double) (MAX_ITERATIONS*TOTAL_KEYS)) /timecounter/1000000., "keys ranked", passed_verification, NPBVERSION, COMPILETIME, CC, CLINK, C_LIB, C_INC, CFLAGS, CLINKFLAGS, "randlc"); /**************************/ } /* E N D P R O G R A M */ /**************************/
bf16_vec_kernel.h
#include "vec_type_cvt.h" #if defined(CPU_CAPABILITY_AVX512) #include <immintrin.h> #else #include "csrc/cpu/vec512/ref/add_ker.h" #include "csrc/cpu/vec512/ref/mov_ker.h" using namespace torch_ipex::cpu::kernel; #endif #if defined(CPU_CAPABILITY_AVX512) inline __m512 pack_bf16_to_fp32(const __m256i top, const __m256i bot) { auto x1 = _mm512_cvtepu16_epi32(top); auto x2 = _mm512_cvtepu16_epi32(bot); auto y = _mm512_add_epi32(_mm512_bslli_epi128(x1, 2), x2); return _mm512_castsi512_ps(y); } #endif // Only support AVX512 impl at current stage. Will expand this impl to cover // AVX2 and other cases. inline void packed_bf16_add_ker( at::BFloat16* a1, at::BFloat16* a2, at::BFloat16* b, int len, float alpha) { #if defined(CPU_CAPABILITY_AVX512) auto vAlpha = _mm512_set1_ps(alpha); int i = 0; for (; i < len - 15; i += 16) { auto x1 = _mm256_loadu_si256((__m256i*)(a1 + i)); auto x2 = _mm256_loadu_si256((__m256i*)(a2 + i)); auto y1 = _mm256_loadu_si256((__m256i*)(b + i)); auto z1 = pack_bf16_to_fp32(x1, x2); auto z2 = cvt_bf16_to_fp32(y1); z1 = _mm512_fmadd_ps(vAlpha, z2, z1); // Update result back to split input tensors. _mm256_storeu_si256((__m256i*)(a1 + i), trunc_fp32_to_bf16(z1)); _mm256_storeu_si256( (__m256i*)(a2 + i), _mm512_cvtepi32_epi16(_mm512_castps_si512(z1))); } if (i < len) { __mmask16 mask = (1 << (len - i)) - 1; auto x1 = _mm256_maskz_loadu_epi16(mask, a1 + i); auto x2 = _mm256_maskz_loadu_epi16(mask, a2 + i); auto y1 = _mm256_maskz_loadu_epi16(mask, b + i); auto z1 = pack_bf16_to_fp32(x1, x2); auto z2 = cvt_bf16_to_fp32(y1); z1 = _mm512_fmadd_ps(vAlpha, z2, z1); // Update result back to split input tensors. _mm256_mask_storeu_epi16(a1 + i, mask, trunc_fp32_to_bf16(z1)); _mm256_mask_storeu_epi16( a2 + i, mask, _mm512_cvtepi32_epi16(_mm512_castps_si512(z1))); } #else for (int i = 0; i < len; i++) { uint32_t hi = (a1 + i)->x; uint32_t lo = (a2 + i)->x; uint32_t merge = hi << 16 | lo; float a_val = *((float*)&merge); float b_val = *(b + i); float res = a_val + b_val * alpha; (a1 + i)->x = (uint16_t)((*((uint32_t*)(&res))) >> 16); (a2 + i)->x = *((uint16_t*)(&res)); } #endif } inline void add_ker(at::BFloat16* inout, at::BFloat16* in, int len) { int i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(2) for (i = 0; i < len - 31; i += 32) { auto inout1 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(inout + i))); auto inout2 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(inout + i + 16))); auto in1 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(in + i))); auto in2 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(in + i + 16))); inout1 = _mm512_add_ps(inout1, in1); inout2 = _mm512_add_ps(inout2, in2); _mm256_storeu_si256((__m256i*)(inout + i), cvt_fp32_to_bf16(inout1)); _mm256_storeu_si256((__m256i*)(inout + i + 16), cvt_fp32_to_bf16(inout2)); } if (i < len - 15) { auto inout1 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(inout + i))); auto in1 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(in + i))); inout1 = _mm512_add_ps(inout1, in1); _mm256_storeu_si256((__m256i*)(inout + i), cvt_fp32_to_bf16(inout1)); i += 16; } if (i < len) { auto mask = (1 << (len - i)) - 1; auto inout1 = cvt_bf16_to_fp32(_mm256_maskz_loadu_epi16(mask, inout + i)); auto in1 = cvt_bf16_to_fp32(_mm256_maskz_loadu_epi16(mask, in + i)); inout1 = _mm512_add_ps(inout1, in1); _mm256_mask_storeu_epi16(inout + i, mask, cvt_fp32_to_bf16(inout1)); } #else ref::add_ker(inout, in, len); #endif } static inline void add_ker(float* inout, float* in, int len) { int i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(2) for (i = 0; i < len - 31; i += 32) { auto out1 = _mm512_loadu_ps(inout + i); auto out2 = _mm512_loadu_ps(inout + i + 16); auto in1 = _mm512_loadu_ps(in + i); auto in2 = _mm512_loadu_ps(in + i + 16); out1 = _mm512_add_ps(out1, in1); out2 = _mm512_add_ps(out2, in2); _mm512_storeu_ps(inout + i, out1); _mm512_storeu_ps(inout + i + 16, out2); } if (i < len - 15) { auto out1 = _mm512_loadu_ps(inout + i); auto in1 = _mm512_loadu_ps(in + i); _mm512_storeu_ps(inout + i, _mm512_add_ps(out1, in1)); i += 16; } if (i < len) { auto mask = (1 << (len - i)) - 1; auto out1 = _mm512_maskz_loadu_ps(mask, inout + i); auto in1 = _mm512_maskz_loadu_ps(mask, in + i); _mm512_mask_storeu_ps(inout + i, mask, _mm512_add_ps(out1, in1)); } #else ref::add_ker(inout, in, len); #endif } static inline void add_ker(float* inout, at::BFloat16* in, int len) { int i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(2) for (i = 0; i < len - 31; i += 32) { auto in1 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(in + i))); auto in2 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(in + i + 16))); auto inout1 = _mm512_loadu_ps(inout + i); auto inout2 = _mm512_loadu_ps(inout + i + 16); inout1 = _mm512_add_ps(inout1, in1); inout2 = _mm512_add_ps(inout2, in2); _mm512_storeu_ps(inout + i, inout1); _mm512_storeu_ps(inout + i + 16, inout2); } if (i < len - 15) { auto in1 = cvt_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(in + i))); auto inout1 = _mm512_loadu_ps(inout + i); inout1 = _mm512_add_ps(inout1, in1); _mm512_storeu_ps(inout + i, inout1); i += 16; } if (i < len) { auto mask = (1 << (len - i)) - 1; auto in1 = cvt_bf16_to_fp32(_mm256_maskz_loadu_epi16(mask, in + i)); auto inout1 = _mm512_maskz_loadu_ps(mask, inout + i); inout1 = _mm512_add_ps(inout1, in1); _mm512_mask_storeu_ps(inout + i, mask, inout1); } #else ref::add_ker(inout, in, len); #endif } inline void add_ker(double* inout, double* in, int len) { #pragma omp simd for (int i = 0; i < len; i++) { *(inout + i) += *(in + i); } } static inline void move_ker(at::BFloat16* out, float* in, int64_t len) { int64_t i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(4) for (i = 0; i < len - 31; i += 32) { auto in0 = cvt_fp32_to_bf16(_mm512_loadu_ps(in + i)); auto in1 = cvt_fp32_to_bf16(_mm512_loadu_ps(in + i + 16)); _mm256_storeu_si256((__m256i*)(out + i), in0); _mm256_storeu_si256((__m256i*)(out + i + 16), in1); } if (i < len - 15) { auto in0 = cvt_fp32_to_bf16(_mm512_loadu_ps(in + i)); _mm256_storeu_si256((__m256i*)(out + i), in0); i += 16; } if (i < len) { auto mask = ((1 << (len - i)) - 1); auto in0 = cvt_fp32_to_bf16(_mm512_maskz_loadu_ps(mask, in + i)); _mm256_mask_storeu_epi16((__m256i*)(out + i), mask, in0); } #else ref::mov_ker(out, in, len); #endif } static inline void move_ker(float* out, const float* in, int64_t len) { int64_t i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(4) for (i = 0; i < len - 15; i += 16) { auto in0 = _mm512_loadu_ps(in + i); _mm512_storeu_ps(out + i, in0); } if (i < len) { auto mask = ((1 << (len - i)) - 1); auto in0 = _mm512_maskz_loadu_ps(mask, in + i); _mm512_mask_storeu_ps(out + i, mask, in0); } #else ref::mov_ker(out, in, len); #endif } static inline void move_ker( at::BFloat16* out, const at::BFloat16* in, int64_t len) { int64_t i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(4) for (i = 0; i < len - 31; i += 32) { auto in0 = _mm512_loadu_si512(in + i); _mm512_storeu_si512(out + i, in0); } if (i < len) { auto mask = (1 << (len - i)) - 1; auto in0 = _mm512_maskz_loadu_epi16(mask, in + i); _mm512_mask_storeu_epi16(out + i, mask, in0); } #else ref::mov_ker(out, in, len); #endif } static inline void move_ker(int64_t* out, int64_t* in, int64_t len) { int64_t i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(4) for (i = 0; i < len - 7; i += 8) { auto in0 = _mm512_loadu_pd(in + i); _mm512_storeu_pd(out + i, in0); } if (i < len) { auto mask = ((1 << (len - i)) - 1); auto in0 = _mm512_maskz_loadu_pd(mask, in + i); _mm512_mask_storeu_pd(out + i, mask, in0); } #else ref::mov_ker(out, in, len); #endif } static inline void move_ker(int32_t* out, const int32_t* in, int64_t len) { int64_t i = 0; #if defined(CPU_CAPABILITY_AVX512) #pragma unroll(4) for (i = 0; i < len - 15; i += 16) { auto in0 = _mm512_loadu_ps(in + i); _mm512_storeu_ps(out + i, in0); } if (i < len) { auto mask = ((1 << (len - i)) - 1); auto in0 = _mm512_maskz_loadu_ps(mask, in + i); _mm512_mask_storeu_ps(out + i, mask, in0); } #else ref::mov_ker(out, in, len); #endif } static inline void move_ker(double* out, double* in, int len) { #pragma omp simd for (int i = 0; i < len; i++) { *(out + i) = *(in + i); } } static inline void zero_ker(double* out, int len) { #pragma omp simd for (int i = 0; i < len; i++) { *(out + i) = 0; } } static inline void zero_ker(float* out, int64_t len) { int64_t i = 0; #if defined(CPU_CAPABILITY_AVX512) __m512 zero_512 = _mm512_setzero_ps(); #pragma unroll(4) for (i = 0; i < len - 15; i += 16) { _mm512_storeu_ps(out + i, zero_512); } if (i < len) { auto mask = ((1 << (len - i)) - 1); _mm512_mask_storeu_ps(out + i, mask, zero_512); } #else memset(out, 0, len * sizeof(float)); #endif } static inline void zero_ker(at::BFloat16* out, int64_t len) { int64_t i = 0; #if defined(CPU_CAPABILITY_AVX512) __m512i zero_512 = _mm512_setzero_si512(); #pragma unroll(4) for (i = 0; i < len - 31; i += 32) { _mm512_storeu_si512(out + i, zero_512); } if (i < len) { auto mask = ((1 << (len - i)) - 1); _mm512_mask_storeu_epi16(out + i, mask, zero_512); } #else memset(out, 0, len * sizeof(at::BFloat16)); #endif } #if defined(CPU_CAPABILITY_AVX512) inline __m512 convert_bf16_to_fp32(const __m256i src) { __m512i y = _mm512_cvtepu16_epi32(src); return _mm512_castsi512_ps(_mm512_bslli_epi128(y, 2)); } #endif template <typename T> inline float toFloat(T val) { float ret = float(val); return ret; } template <typename T1, typename T2> inline void madd_ker(T1* inout, T2* in, int len, float alpha) { #pragma omp simd for (long v = 0; v < len; v++) { inout[v] += toFloat(in[v]) * alpha; } } #if defined(CPU_CAPABILITY_AVX512) template <> inline void madd_ker(float* inout, at::BFloat16* in, int len, float alpha) { __m512 vAlpha = _mm512_set1_ps(alpha); int i = 0; for (; i < len - 15; i += 16) { __m512 y1 = _mm512_loadu_ps(inout + i); __m512 y2 = convert_bf16_to_fp32(_mm256_loadu_si256((__m256i*)(in + i))); y1 = _mm512_fmadd_ps(vAlpha, y2, y1); _mm512_storeu_ps(inout + i, y1); } if (i < len) { int rem = len - i; __mmask16 mask = (1 << rem) - 1; __m512 y1 = _mm512_maskz_loadu_ps(mask, inout + i); __m512 y2 = convert_bf16_to_fp32(_mm256_maskz_loadu_epi16(mask, in + i)); y1 = _mm512_fmadd_ps(vAlpha, y2, y1); _mm512_mask_storeu_ps(inout + i, mask, y1); } } #endif
mobilenet_32.c
/* Pretrained MobileNet Convolutional Neural Network in C language and OpenMP API GitHUB Page: https://github.com/jcanore/vgg16 Author: ZFTurbo/jocare Compilation: gcc -O3 MobileNet_CPU_cifar.c -lm -fopenmp -o MobileNet_CPU_cifar Usage: MobileNet_CPU_cifar <weights_path> <file_with_list_of_images> <output file> <output convolution features (optional)> Example: MobileNet_CPU_cifar ../../weights/weights.txt" ../../img/image_list.txt results_imagenet_conv.txt 1 */ #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <unistd.h> double get_seconds(struct timeval tStart, struct timeval tEnd) { return ((tEnd.tv_sec - tStart.tv_sec) * 1000000 + tEnd.tv_usec - tStart.tv_usec) / 1.e6; } #define SIZE 32 #define CONV_SIZE 3 #define CONV_LEVELS 27 //#define _CRT_SECURE_NO_WARNINGS 1 // precompile variables // assure default values if nothing provided #ifndef SPARSE_CONVOLUTIONS #define SPARSE_CONVOLUTIONS 0 // default dense convolutions #endif // SPARSE_CONVOLUTIONS #ifndef FIRST_CONV_SPARSE #define FIRST_CONV_SPARSE 0 // this is almost never 1 #endif // FIRST_CONV_SPARSE #ifndef SPARSE_FULLY_CONNECTED #define SPARSE_FULLY_CONNECTED 0 // this is not implemented yet #endif // SPARSE_FULLY_CONNECTED #ifndef FISHER_PRUNING #define FISHER_PRUNING \ 0 // set for fisher pruning, all previous variables changed to dense #endif // FISHER_PRUNING #ifndef NUMBER_OF_THREADS #define NUMBER_OF_THREADS 1 // number of threads to run on //#define NUMBER_OF_THREADS omp_get_num_procs() - 1 #endif // NUMBER_OF_THREADS static double pw_conv_time = 0.0; static double dense_time = 0.0; /****************************************************************************************************************************/ int im_sizes[27] = {32, 32, 16, 16, 16, 16, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 2}; int strides[26] = {1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1}; int mem_block_shape[3] = { 1024, 32, 32}; // allocate the absolute maximum amount of space we will need float ***block1; float ***block2; float *****wc; // weights convolution float ***wd; // weights dense float **bd; // biases dense float **batchnorm_weights; float **batchnorm_biases; float **batchnorm_means; // running mean and variance from training used to // estimate population statistics float **batchnorm_vars; int mem_block_dense_shape = { 1024 * 2 * 2}; // size of output from last convolutional layer float *mem_block1_dense; float *mem_block2_dense; #if SPARSE_CONVOLUTIONS // sparse conv csr_t ****wc_sparse; #endif // SPARSE_CONVOLUTIONS #if FISHER_PRUNING #define SPARSE_CONVOLUTIONS 0 // force dense convolutions /* // ORIGINAL FISHER EXPERIMENTS int cshape[27][4] = { { 32, 3, CONV_SIZE, CONV_SIZE }, { 32, 1, CONV_SIZE, CONV_SIZE }, { 43, 32, 1, 1 }, { 43, 1, CONV_SIZE, CONV_SIZE }, { 85, 43, 1, 1 }, { 85, 1, CONV_SIZE, CONV_SIZE }, { 70, 85, 1, 1 }, { 70, 1, CONV_SIZE, CONV_SIZE }, { 150, 70, 1, 1 }, { 150, 1, CONV_SIZE, CONV_SIZE }, { 69, 150, 1, 1 }, { 69, 1, CONV_SIZE, CONV_SIZE }, { 188, 69, 1, 1 }, { 188, 1, CONV_SIZE, CONV_SIZE }, { 72, 188, 1, 1 }, { 72, 1, CONV_SIZE, CONV_SIZE }, { 122, 72, 1, 1 }, { 122, 1, CONV_SIZE, CONV_SIZE }, { 106, 122, 1, 1 }, { 106, 1, CONV_SIZE, CONV_SIZE }, { 96, 106, 1, 1 }, { 96, 1, CONV_SIZE, CONV_SIZE }, { 81, 96, 1, 1 }, { 81, 1, CONV_SIZE, CONV_SIZE }, { 75, 81, 1, 1 }, { 75, 1, CONV_SIZE, CONV_SIZE }, { 100, 75, 1, 1 } }; int dshape[1][2]= { { 100, 10} }; */ // FIXED 90% ACCURACY EXPERIMENTS int cshape[27][4] = {{32, 3, CONV_SIZE, CONV_SIZE}, {32, 1, CONV_SIZE, CONV_SIZE}, {43, 32, 1, 1}, {43, 1, CONV_SIZE, CONV_SIZE}, {85, 43, 1, 1}, {85, 1, CONV_SIZE, CONV_SIZE}, {70, 85, 1, 1}, {70, 1, CONV_SIZE, CONV_SIZE}, {150, 70, 1, 1}, {150, 1, CONV_SIZE, CONV_SIZE}, {69, 150, 1, 1}, {69, 1, CONV_SIZE, CONV_SIZE}, {188, 69, 1, 1}, {188, 1, CONV_SIZE, CONV_SIZE}, {72, 188, 1, 1}, {72, 1, CONV_SIZE, CONV_SIZE}, {122, 72, 1, 1}, {122, 1, CONV_SIZE, CONV_SIZE}, {106, 122, 1, 1}, {106, 1, CONV_SIZE, CONV_SIZE}, {96, 106, 1, 1}, {96, 1, CONV_SIZE, CONV_SIZE}, {81, 96, 1, 1}, {81, 1, CONV_SIZE, CONV_SIZE}, {75, 81, 1, 1}, {75, 1, CONV_SIZE, CONV_SIZE}, {100, 75, 1, 1} }; int dshape[1][2] = {{100, 10}}; #else // PLAIN int cshape[27][4] = {{32, 3, CONV_SIZE, CONV_SIZE}, {32, 1, CONV_SIZE, CONV_SIZE}, {64, 32, 1, 1}, {64, 1, CONV_SIZE, CONV_SIZE}, {128, 64, 1, 1}, {128, 1, CONV_SIZE, CONV_SIZE}, {128, 128, 1, 1}, {128, 1, CONV_SIZE, CONV_SIZE}, {256, 128, 1, 1}, {256, 1, CONV_SIZE, CONV_SIZE}, {256, 256, 1, 1}, {256, 1, CONV_SIZE, CONV_SIZE}, {512, 256, 1, 1}, {512, 1, CONV_SIZE, CONV_SIZE}, {512, 512, 1, 1}, {512, 1, CONV_SIZE, CONV_SIZE}, {512, 512, 1, 1}, {512, 1, CONV_SIZE, CONV_SIZE}, {512, 512, 1, 1}, {512, 1, CONV_SIZE, CONV_SIZE}, {512, 512, 1, 1}, {512, 1, CONV_SIZE, CONV_SIZE}, {512, 512, 1, 1}, {512, 1, CONV_SIZE, CONV_SIZE}, {1024, 512, 1, 1}, {1024, 1, CONV_SIZE, CONV_SIZE}, {1024, 1024, 1, 1}}; int dshape[1][2] = {{1024, 10}}; #endif // FISHER_PRUNING /****************************************************************************************************************************/ void reset_mem_block(float ***mem) { int i, j, k; for (i = 0; i < mem_block_shape[0]; i++) { for (j = 0; j < mem_block_shape[1]; j++) { for (k = 0; k < mem_block_shape[2]; k++) { mem[i][j][k] = 0.0; } } } } /****************************************************************************************************************************/ void reset_mem_block_dense(float *mem) { int i; for (i = 0; i < mem_block_dense_shape; i++) { mem[i] = 0.0; } } /****************************************************************************************************************************/ void init_memory() { int i, j, k, l; int max_channels = 1024; int max_im_size = 32; block1 = malloc(max_channels * sizeof(float **)); block2 = malloc(max_channels * sizeof(float **)); // allocate block memory for (i = 0; i < max_channels; i++) { block1[i] = malloc(max_im_size * sizeof(float *)); block2[i] = malloc(max_im_size * sizeof(float *)); for (j = 0; j < max_im_size; j++) { block1[i][j] = malloc(max_im_size * sizeof(float)); block2[i][j] = malloc(max_im_size * sizeof(float)); } } #if SPARSE_CONVOLUTIONS wc_sparse = (csr_t ****)malloc(CONV_LEVELS * sizeof(csr_t ***)); for (l = 0; l < CONV_LEVELS; l++) { wc_sparse[l] = (csr_t ***)malloc(cshape[l][0] * sizeof(csr_t **)); for (i = 0; i < cshape[l][0]; i++) { wc_sparse[l][i] = (csr_t **)malloc(cshape[l][1] * sizeof(csr_t *)); } } // wc memory allocated below will be freed in read_weights if // SPARSE_CONVOLUTIONS #endif // SPARSE_CONVOLUTIONS wc = malloc(CONV_LEVELS * sizeof(float ****)); // allocate kernel memory for (l = 0; l < CONV_LEVELS; l++) { wc[l] = malloc(cshape[l][0] * sizeof(float ***)); for (i = 0; i < cshape[l][0]; i++) { wc[l][i] = malloc(cshape[l][1] * sizeof(float **)); for (j = 0; j < cshape[l][1]; j++) { wc[l][i][j] = malloc(cshape[l][2] * sizeof(float *)); for (k = 0; k < cshape[l][2]; k++) { wc[l][i][j][k] = malloc(cshape[l][3] * sizeof(float)); } } } } // allocate batchnorm memory batchnorm_weights = malloc(27 * sizeof(float *)); batchnorm_biases = malloc(27 * sizeof(float *)); batchnorm_means = malloc(27 * sizeof(float *)); batchnorm_vars = malloc(27 * sizeof(float *)); for (l = 0; l < CONV_LEVELS; l++) { batchnorm_weights[l] = malloc(cshape[l][0] * sizeof(float)); batchnorm_biases[l] = malloc(cshape[l][0] * sizeof(float)); batchnorm_means[l] = malloc(cshape[l][0] * sizeof(float)); batchnorm_vars[l] = malloc(cshape[l][0] * sizeof(float)); } wd = malloc(1 * sizeof(float **)); bd = malloc(1 * sizeof(float *)); for (l = 0; l < 1; l++) { wd[l] = malloc(dshape[l][0] * sizeof(float *)); for (i = 0; i < dshape[l][0]; i++) { wd[l][i] = malloc(dshape[l][1] * sizeof(float)); } bd[l] = malloc(dshape[l][1] * sizeof(float)); } // allocate dense memory mem_block1_dense = calloc(mem_block_dense_shape, sizeof(float)); mem_block2_dense = calloc(mem_block_dense_shape, sizeof(float)); } /****************************************************************************************************************************/ void free_memory() { int i, j, k, l; // Free convolution weights for (l = 0; l < CONV_LEVELS; l++) { #if SPARSE_CONVOLUTIONS for (i = 0; i < cshape[l][0]; i++) { for (j = 0; j < cshape[l][1]; j++) { free(wc_sparse[l][i][j]); } free(wc_sparse[l][i]); } free(wc_sparse[l]); #else for (i = 0; i < cshape[l][0]; i++) { for (j = 0; j < cshape[l][1]; j++) { for (k = 0; k < cshape[l][2]; k++) { free(wc[l][i][j][k]); } free(wc[l][i][j]); } free(wc[l][i]); } free(wc[l]); #endif } // free(wc); // free(bc); #if SPARSE_CONVOLUTIONS free(wc_sparse); #else free(wc); #endif // SPARSE_CONVOLUTIONS // Free dense weights for (l = 0; l < 1; l++) { for (i = 0; i < dshape[l][0]; i++) { free(wd[l][i]); } free(wd[l]); free(bd[l]); } free(wd); free(bd); // Free memblocks for (i = 0; i < mem_block_shape[0]; i++) { for (j = 0; j < mem_block_shape[1]; j++) { free(block1[i][j]); free(block2[i][j]); } free(block1[i]); free(block2[i]); } free(block1); free(block2); free(mem_block1_dense); free(mem_block2_dense); } /****************************************************************************************************************************/ void read_weights(char *in_file, int lvls) { float dval; int i, j, k, l, m, z; FILE *iin; int total_lvls_read = 0; // printf("\nin_file es: %s\n\n", in_file); iin = fopen(in_file, "r"); if (iin == NULL) { printf("Weights file %s absent\n", in_file); exit(1); } // Reading convolution weights (store them flipped from begining) // no biases for (l = 0; l < CONV_LEVELS; l++) { printf("Read conv block %d weights\n", l); for (i = 0; i < cshape[l][0]; i++) { for (j = 0; j < cshape[l][1]; j++) { for (k = 0; k < cshape[l][2]; k++) { for (m = 0; m < cshape[l][3]; m++) { fscanf(iin, "%f", &dval); wc[l][i][j][k][m] = dval; } } } } total_lvls_read += 1; } for (z = 0; z < CONV_LEVELS; z++) { // batchnorm weights and biases printf("Read batchnorm block %d weights\n", z); for (i = 0; i < cshape[z][0]; i++) { fscanf(iin, "%f", &dval); batchnorm_weights[z][i] = dval; } for (i = 0; i < cshape[z][0]; i++) { fscanf(iin, "%f", &dval); // printf("bias %i : %f \n", i, dval); batchnorm_biases[z][i] = dval; } for (i = 0; i < cshape[z][0]; i++) { fscanf(iin, "%f", &dval); // printf("bias %i : %f \n", i, dval); batchnorm_means[z][i] = dval; } for (i = 0; i < cshape[z][0]; i++) { fscanf(iin, "%f", &dval); // printf("bias %i : %f \n", i, dval); batchnorm_vars[z][i] = dval; } } if (total_lvls_read >= lvls && lvls != -1) return; // Reading dense weights int num_dense_layers = 1; for (z = 0; z < num_dense_layers; z++) { printf("Read dense block %d weights\n", z); for (i = 0; i < dshape[z][0]; i++) { for (j = 0; j < dshape[z][1]; j++) { fscanf(iin, "%f", &dval); // printf("weight: %i : %f \n", i, dval); wd[z][i][j] = dval; } } for (i = 0; i < dshape[z][1]; i++) { fscanf(iin, "%f", &dval); // printf("bias %i : %f \n", i, dval); bd[z][i] = dval; } } fclose(iin); /////////////**************** SPARSE ************///////////////////////////// #if SPARSE_CONVOLUTIONS // convert to sparse format for (l = 0; l < CONV_LEVELS; l++) for (i = 0; i < cshape[l][0]; i++) for (j = 0; j < cshape[l][1]; j++) { // printf("going for %d/%d, %d/%d, %d/%d\n", l, 13, i, cshape[l][0], j, // cshape[l][1]); csr_t *a = dense2csr2(cshape[l][2], cshape[l][3], wc[l][i][j]); // print_csr(a); wc_sparse[l][i][j] = a; // printf("done..%d/%d, %d/%d, %d/%d\n", l, 13, i, cshape[l][0], j, // cshape[l][1]); } // Free convolution weights #if FIRST_CONV_SPARSE == 0 l = 0; // allocate new memory for first conv and copy from wc float *****wc_first_conv = (float *****)malloc(1 * sizeof(float ****)); wc_first_conv[l] = (float ****)malloc(cshape[l][0] * sizeof(float ***)); int k1, k2; for (i = 0; i < cshape[l][0]; i++) { wc_first_conv[l][i] = (float ***)malloc(cshape[l][1] * sizeof(float **)); for (j = 0; j < cshape[l][1]; j++) { wc_first_conv[l][i][j] = (float **)malloc(cshape[l][2] * sizeof(float *)); for (k1 = 0; k1 < cshape[l][2]; k1++) { wc_first_conv[l][i][j][k1] = (float *)malloc(cshape[l][3] * sizeof(float)); for (k2 = 0; k2 < cshape[l][3]; k2++) wc_first_conv[l][i][j][k1][k2] = wc[l][i][j][k1][k2]; } } } #endif // FIRST_CONV_SPARSE == 0 // free up all dense conv layer representation for (l = 0; l < CONV_LEVELS; l++) { for (i = 0; i < cshape[l][0]; i++) { for (j = 0; j < cshape[l][1]; j++) { for (k = 0; k < cshape[l][2]; k++) { free(wc[l][i][j][k]); } free(wc[l][i][j]); } free(wc[l][i]); } free(wc[l]); } free(wc); #if FIRST_CONV_SPARSE == 0 // replace old wc pointer with the data for only first conv layer created // above wc = wc_first_conv; #endif // FIRST_CONV_SPARSE == 0 #endif // SPARSE_CONVOLUTIONS } /****************************************************************************************************************************/ void read_image(char *in_file) { int i, j, l; FILE *iin; float dval; iin = fopen(in_file, "r"); if (iin == NULL) { printf("Image file %s absent\n", in_file); exit(1); } /* Reading image */ for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { for (l = 0; l < 3; l++) { fscanf(iin, "%f", &dval); block1[l][i][j] = dval; } } } } /****************************************************************************************************************************/ void convolution_3_x_3(float **matrix, float **kernel, float **out, int size, int stride) { int i, j; float sum; float zeropad[size + 2][size + 2]; memset(zeropad, 0, ((size + 2) * (size + 2) * sizeof(float))); // jack for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { zeropad[i + 1][j + 1] = matrix[i][j]; } } for (i = 0; i < size; i = i + stride) { for (j = 0; j < size; j = j + stride) { sum = zeropad[i][j] * kernel[0][0] + zeropad[i][j + 1] * kernel[0][1] + zeropad[i][j + 2] * kernel[0][2] + zeropad[i + 1][j] * kernel[1][0] + zeropad[i + 1][j + 1] * kernel[1][1] + zeropad[i + 1][j + 2] * kernel[1][2] + zeropad[i + 2][j] * kernel[2][0] + zeropad[i + 2][j + 1] * kernel[2][1] + zeropad[i + 2][j + 2] * kernel[2][2]; out[i][j] += sum; } } } /****************************************************************************************************************************/ /****************************************************************************************************************************/ void pointwise_convolution(float ****point_kernel, float ***block2, float ***block1, int input_channels, int output_channels, int image_size) { struct timeval start, end; gettimeofday(&start, NULL); int i, j, k, l; float sum; for (i = 0; i < output_channels; i++) { for (j = 0; j < image_size; j++) { for (k = 0; k < image_size; k++) { sum = 0.; for (l = 0; l < input_channels; l++) { sum += block2[l][j][k] * point_kernel[i][l][0] [0]; // 0 because they are always 1x1 filters } block1[i][j][k] = sum; } } } gettimeofday(&end, NULL); pw_conv_time += get_seconds(start, end); } /****************************************************************************************************************************/ void batchnorm_and_relu(float ***in, float ***out, float *weights, float *bias, float *mean, float *var, int num_channels, int image_size) { int channel, i, j; // ((x - mean) * invstd) * w + b #pragma omp parallel for private(channel, i, j) schedule(dynamic, 1) \ num_threads(NUMBER_OF_THREADS) for (channel = 0; channel < num_channels; channel++) { float invstd = 1. / sqrt(var[channel] + 0.000001); for (i = 0; i < image_size; i++) { for (j = 0; j < image_size; j++) { out[channel][i][j] = (weights[channel] * invstd) * in[channel][i][j] + (bias[channel] - ((weights[channel] * mean[channel]) * invstd)); // out[channel][i][j] = ((in[channel][i][j] - mean[channel]) * invstd) * // weights[channel] + bias[channel]; if (out[channel][i][j] < 0.f) out[channel][i][j] = 0.f; } } } } /****************************************************************************************************************************/ void depthwise_convolution(float ***block1, float ***block2, float ****depth_kernel, float ****point_kernel, int level) { int i, j; int input_channels = cshape[level][0]; int output_channels = cshape[level + 1][0]; // printf("level %i: %i ==> %i\n", level, input_channels, output_channels); #pragma omp parallel for private(i) schedule(dynamic, 1) \ num_threads(NUMBER_OF_THREADS) for (i = 0; i < input_channels; i++) { #if SPARSE_CONVOLUTIONS convolution_3_x_3_sparse(block1[i], wc_sparse[level][i][0], block2[i], im_sizes[level], strides[level]); #else convolution_3_x_3(block1[i], depth_kernel[i][0], block2[i], im_sizes[level], strides[level]); #endif } batchnorm_and_relu(block2, block1, batchnorm_weights[level], batchnorm_biases[level], batchnorm_means[level], batchnorm_vars[level], input_channels, im_sizes[level + 1]); reset_mem_block(block2); level++; // now do linear combination of the elements in output and write them back // into the first memory block #if SPARSE_CONVOLUTIONS #pragma omp parallel for private(i, j) schedule(dynamic, 1) \ num_threads(NUMBER_OF_THREADS) for (i = 0; i < output_channels; i++) { for (j = 0; j < input_channels; j++) { pointwise_convolution_sparse(block2[j], wc_sparse[level][i][j], block1[j], im_sizes[level]); } } #else pointwise_convolution(point_kernel, block1, block2, input_channels, output_channels, im_sizes[level]); #endif batchnorm_and_relu(block2, block1, batchnorm_weights[level], batchnorm_biases[level], batchnorm_means[level], batchnorm_vars[level], output_channels, im_sizes[level + 1]); reset_mem_block(block2); } /****************************************************************************************************************************/ void add_bias_and_relu_flatten(float *out, float *bs, int size, int relu) { int i; for (i = 0; i < size; i++) { out[i] += bs[i]; // printf("%f\n", out[i]); if (relu == 1) { if (out[i] < 0) out[i] = 0.f; } } } /****************************************************************************************************************************/ void flatten(float ***in, float *out, int sh0, int sh1, int sh2) { int i, j, k, total = 0; for (i = 0; i < sh0; i++) { for (j = 0; j < sh1; j++) { for (k = 0; k < sh2; k++) { out[total] = in[i][j][k]; total += 1; } } } } /****************************************************************************************************************************/ void dense(float *in, float **weights, float *out, int sh_in, int sh_out) { struct timeval start, end; gettimeofday(&start, NULL); int i, j; for (i = 0; i < sh_out; i++) { float sum = 0.0; for (j = 0; j < sh_in; j++) { sum += in[j] * weights[j][i]; } out[i] = sum; } gettimeofday(&end, NULL); dense_time += get_seconds(start, end); } /****************************************************************************************************************************/ void write_out_block(int layer, float ***block) { int layer_name = layer; // * 2 - 1; char filename[16]; sprintf(filename, "outputs/output%d", layer_name); FILE *f = fopen(filename, "w"); if (f == NULL) { printf("Error opening file!\n"); exit(1); } for (int i = 0; i < 32; i++) { for (int j = 0; j < mem_block_shape[1]; j++) { for (int k = 0; k < mem_block_shape[2]; k++) { fprintf(f, "%f \n", block[i][j][k]); } } } fclose(f); } /****************************************************************************************************************************/ void write_out_layer(int layer) { int layer_name = layer; // * 2 - 1; char filename[7]; sprintf(filename, "layer%d", layer_name); FILE *f = fopen(filename, "w"); int depth = 1; if (f == NULL) { printf("Error opening file!\n"); exit(1); } for (int o = 0; o < cshape[layer][0]; o++) { for (int i = 0; i < cshape[layer][1]; i++) { for (int k_h = 0; k_h < cshape[layer][2]; k_h++) { for (int k_w = 0; k_w < cshape[layer][3]; k_w++) { fprintf(f, "%f ", wc[layer][o][i][k_h][k_w]); } } fprintf(f, "\n"); } } fclose(f); layer_name = layer + 1; char filename2[7]; sprintf(filename2, "layer%d", layer_name); // get batchnorms FILE *f2 = fopen(filename2, "w"); if (f2 == NULL) { printf("Error opening file!\n"); exit(1); } for (int i = 0; i < cshape[layer][0]; i++) { fprintf(f2, "%f \n", batchnorm_weights[layer][i]); } fprintf(f2, "\n\n\n"); for (int i = 0; i < cshape[layer][0]; i++) { fprintf(f2, "%f \n", batchnorm_biases[layer][i]); } fprintf(f2, "\n\n\n"); for (int i = 0; i < cshape[layer][0]; i++) { fprintf(f2, "%f \n", batchnorm_means[layer][i]); } fprintf(f2, "\n\n\n"); for (int i = 0; i < cshape[layer][0]; i++) { fprintf(f2, "%f \n", batchnorm_vars[layer][i]); } fclose(f); } /****************************************************************************************************************************/ void output_predictions(FILE *out, int only_convolution, int size, int cur_size) { int i; int c = 0; if (only_convolution == 1) { // for (i = 0; i < 512*7*7; i++) { for (i = 0; i < size * cur_size * cur_size; i++) { fprintf(out, "%g\n", mem_block1_dense[i]); } } else { double maximum = -1; // dshape[0][1] ==> 10 for (i = 0; i < dshape[0][1]; i++) { fprintf(out, "%g\n", mem_block2_dense[i]); if (mem_block1_dense[i] > maximum) { maximum = mem_block2_dense[i]; c = i + 1; } } fprintf(out, "\n"); printf("This image depicts class: %d\n", c); } } /****************************************************************************************************************************/ void get_mobilenet_predict() { int level = 0; int i, j; // normal convolution #pragma omp parallel for private(i, j) schedule(dynamic, 1) \ num_threads(NUMBER_OF_THREADS) for (i = 0; i < cshape[level][0]; i++) { for (j = 0; j < cshape[level][1]; j++) { #if FIRST_CONV_SPARSE convolution_3_x_3_sparse(block1[j], wc_sparse[level][i][j], block2[i], im_sizes[level], 1); #else convolution_3_x_3(block1[j], wc[level][i][j], block2[i], im_sizes[level], 1); #endif } } batchnorm_and_relu(block2, block1, batchnorm_weights[level], batchnorm_biases[level], batchnorm_means[level], batchnorm_vars[level], 32, 32); reset_mem_block(block2); // depthwise convolutions for (level = 1; level < (CONV_LEVELS - 1); level = level + 2) { depthwise_convolution(block1, block2, wc[level], wc[level + 1], (level)); } // flatten flatten(block1, mem_block1_dense, cshape[level][0], im_sizes[level], im_sizes[level]); // dense level = 0; dense(mem_block1_dense, wd[level], mem_block2_dense, dshape[level][0], dshape[level][1]); add_bias_and_relu_flatten(mem_block2_dense, bd[level], dshape[level][1], 0); reset_mem_block_dense(mem_block1_dense); return; } /****************************************************************************************************************************/ char *trimwhitespace(char *str) { char *end; // Trim leading space while (isspace((unsigned char)*str)) str++; if (*str == 0) // All spaces? return str; // Trim trailing space end = str + strlen(str) - 1; while (end > str && isspace((unsigned char)*end)) end--; // Write new null terminator *(end + 1) = 0; return str; } /****************************************************************************************************************************/ int main(int argc, char *argv[]) { FILE *file_list, *results; char buf[1024]; struct timeval tStart, tEnd; double deltaTime; char *weights_file; char *image_list_file; char *output_file; int lvls = -1; int only_convolution = 0; //----------------------------------------------------------------------- printf("Using %d threads\n", NUMBER_OF_THREADS); if (argc != 4 && argc != 5) { printf( "Usage: <program.exe> <weights file> <images list file> <output file> " "<only_convolution [optional]>\n"); return 0; } weights_file = argv[1]; // printf("%s\n", weights_file); image_list_file = argv[2]; output_file = argv[3]; if (argc == 5) { lvls = 20; only_convolution = 1; } //----------------------------------------------------------------------- init_memory(); file_list = fopen(image_list_file, "r"); if (file_list == NULL) { printf("Check file list location: %s\n", image_list_file); return 1; } results = fopen(output_file, "w"); if (results == NULL) { printf("Couldn't open file for writing: %s\n", output_file); return 1; } gettimeofday(&tStart, NULL); read_weights(weights_file, lvls); gettimeofday(&tEnd, NULL); deltaTime = get_seconds(tStart, tEnd); printf("Reading weights: %.3lf sec\n", deltaTime); while (!feof(file_list)) { pw_conv_time = 0.0; dense_time = 0.0; fgets(buf, 1024, file_list); if (strlen(buf) == 0) { break; } // printf("%d\n", strlen(buf)); read_image(trimwhitespace(buf)); gettimeofday(&tStart, NULL); get_mobilenet_predict(); gettimeofday(&tEnd, NULL); deltaTime = get_seconds(tStart, tEnd); printf("Infer image %s: %.3lf sec\n", buf, deltaTime); printf("pw_conv time: %.3lf sec\n", pw_conv_time); printf("dense time: %.3lf sec\n", dense_time); output_predictions(results, only_convolution, 1024, 1); } // free_memory(); fclose(file_list); return 0; }
GB_binop__remainder_fp64.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__remainder_fp64 // A.*B function (eWiseMult): GB_AemultB__remainder_fp64 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__remainder_fp64 // C+=b function (dense accum): GB_Cdense_accumb__remainder_fp64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__remainder_fp64 // C=scalar+B GB_bind1st__remainder_fp64 // C=scalar+B' GB_bind1st_tran__remainder_fp64 // C=A+scalar GB_bind2nd__remainder_fp64 // C=A'+scalar GB_bind2nd_tran__remainder_fp64 // C type: double // A type: double // B,b type: double // BinaryOp: cij = remainder (aij, bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ double bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double 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 = remainder (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_REMAINDER || GxB_NO_FP64 || GxB_NO_REMAINDER_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__remainder_fp64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__remainder_fp64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__remainder_fp64 ( 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 double double bwork = (*((double *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *GB_RESTRICT Cx = (double *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *GB_RESTRICT Cx = (double *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__remainder_fp64 ( 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__remainder_fp64 ( 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__remainder_fp64 ( 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 double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; double bij = Bx [p] ; Cx [p] = remainder (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__remainder_fp64 ( 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 ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double aij = Ax [p] ; Cx [p] = remainder (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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = remainder (x, aij) ; \ } GrB_Info GB_bind1st_tran__remainder_fp64 ( 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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = Ax [pA] ; \ Cx [pC] = remainder (aij, y) ; \ } GrB_Info GB_bind2nd_tran__remainder_fp64 ( 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 double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ark_heat1D_omp.c
/*--------------------------------------------------------------- * Programmer(s): Shelby Lockhart @ LLNL *--------------------------------------------------------------- * Based on the serial code ark_heat1D.c developed by * Daniel R. Reynolds @ SMU and parallelized with OpenMP *--------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2021, 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 test simulates a simple 1D heat equation, * u_t = k*u_xx + f * for t in [0, 10], x in [0, 1], with initial conditions * u(0,x) = 0 * Dirichlet boundary conditions, i.e. * u_t(t,0) = u_t(t,1) = 0, * and a point-source heating term, * f = 1 for x=0.5. * * The spatial derivatives are computed using second-order * centered differences, with the data distributed over N points * on a uniform spatial grid. * * This program solves the problem with either an ERK or DIRK * method. For the DIRK method, we use a Newton iteration with * the SUNPCG linear solver, and a user-supplied Jacobian-vector * product routine. * * 100 outputs are printed at equal intervals, and run statistics * are printed at the end. *---------------------------------------------------------------*/ /* Header files */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <arkode/arkode_arkstep.h> /* prototypes for ARKStep fcts., consts */ #include <nvector/nvector_openmp.h> /* OpenMP N_Vector types, fcts., macros */ #include <sunlinsol/sunlinsol_pcg.h> /* access to PCG SUNLinearSolver */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype, etc */ #ifdef _OPENMP #include <omp.h> /* OpenMP function defs. */ #endif #if defined(SUNDIALS_EXTENDED_PRECISION) #define GSYM "Lg" #define ESYM "Le" #define FSYM "Lf" #else #define GSYM "g" #define ESYM "e" #define FSYM "f" #endif /* user data structure */ typedef struct { sunindextype N; /* number of intervals */ int nthreads; /* number of OpenMP threads */ realtype dx; /* mesh spacing */ realtype k; /* diffusion coefficient */ } *UserData; /* User-supplied Functions Called by the Solver */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data); static int Jac(N_Vector v, N_Vector Jv, realtype t, N_Vector y, N_Vector fy, void *user_data, N_Vector tmp); /* Private function to check function return values */ static int check_flag(void *flagvalue, const char *funcname, int opt); /* Main Program */ int main(int argc, char *argv[]) { /* general problem parameters */ realtype T0 = RCONST(0.0); /* initial time */ realtype Tf = RCONST(1.0); /* final time */ int Nt = 10; /* total number of output times */ realtype rtol = 1.e-6; /* relative tolerance */ realtype atol = 1.e-10; /* absolute tolerance */ UserData udata = NULL; realtype *data; sunindextype N = 201; /* spatial mesh size */ realtype k = 0.5; /* heat conductivity */ sunindextype i; /* general problem variables */ int flag; /* reusable error-checking flag */ N_Vector y = NULL; /* empty vector for storing solution */ SUNLinearSolver LS = NULL; /* empty linear solver object */ void *arkode_mem = NULL; /* empty ARKStep memory structure */ FILE *FID, *UFID; realtype t, dTout, tout; int iout, num_threads; long int nst, nst_a, nfe, nfi, nsetups, nli, nJv, nlcf, nni, ncfn, netf; /* Create the SUNDIALS context object for this simulation */ SUNContext ctx; flag = SUNContext_Create(NULL, &ctx); if (check_flag(&flag, "SUNContext_Create", 1)) return 1; /* 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); /* allocate and fill udata structure */ udata = (UserData) malloc(sizeof(*udata)); udata->N = N; udata->k = k; udata->dx = RCONST(1.0)/(N-1); /* mesh spacing */ udata->nthreads = num_threads; /* Initial problem output */ printf("\n1D Heat PDE test problem:\n"); printf(" N = %li\n", (long int) udata->N); printf(" diffusion coefficient: k = %"GSYM"\n", udata->k); /* Initialize data structures */ y = N_VNew_OpenMP(N, num_threads, ctx); /* Create OpenMP vector for solution */ if (check_flag((void *) y, "N_VNew_OpenMP", 0)) return 1; N_VConst(0.0, y); /* Set initial conditions */ arkode_mem = ARKStepCreate(NULL, f, T0, y, ctx); /* Create the solver memory */ if (check_flag((void *) arkode_mem, "ARKStepCreate", 0)) return 1; /* Set routines */ flag = ARKStepSetUserData(arkode_mem, (void *) udata); /* Pass udata to user functions */ if (check_flag(&flag, "ARKStepSetUserData", 1)) return 1; flag = ARKStepSetMaxNumSteps(arkode_mem, 10000); /* Increase max num steps */ if (check_flag(&flag, "ARKStepSetMaxNumSteps", 1)) return 1; flag = ARKStepSetPredictorMethod(arkode_mem, 1); /* Specify maximum-order predictor */ if (check_flag(&flag, "ARKStepSetPredictorMethod", 1)) return 1; flag = ARKStepSStolerances(arkode_mem, rtol, atol); /* Specify tolerances */ if (check_flag(&flag, "ARKStepSStolerances", 1)) return 1; /* Initialize PCG solver -- no preconditioning, with up to N iterations */ LS = SUNLinSol_PCG(y, 0, (int) N, ctx); if (check_flag((void *)LS, "SUNLinSol_PCG", 0)) return 1; /* Linear solver interface -- set user-supplied J*v routine (no 'jtsetup' required) */ flag = ARKStepSetLinearSolver(arkode_mem, LS, NULL); /* Attach linear solver to ARKStep */ if (check_flag(&flag, "ARKStepSetLinearSolver", 1)) return 1; flag = ARKStepSetJacTimes(arkode_mem, NULL, Jac); /* Set the Jacobian routine */ if (check_flag(&flag, "ARKStepSetJacTimes", 1)) return 1; /* Specify linearly implicit RHS, with non-time-dependent Jacobian */ flag = ARKStepSetLinear(arkode_mem, 0); if (check_flag(&flag, "ARKStepSetLinear", 1)) return 1; /* output mesh to disk */ FID=fopen("heat_mesh.txt","w"); for (i=0; i<N; i++) fprintf(FID," %.16"ESYM"\n", udata->dx*i); fclose(FID); /* Open output stream for results, access data array */ UFID=fopen("heat1D.txt","w"); data = N_VGetArrayPointer(y); /* output initial condition to disk */ for (i=0; i<N; i++) fprintf(UFID," %.16"ESYM"", data[i]); fprintf(UFID,"\n"); /* Main time-stepping loop: calls ARKStep to perform the integration, then prints results. Stops when the final time has been reached */ t = T0; dTout = (Tf-T0)/Nt; tout = T0+dTout; printf(" t ||u||_rms\n"); printf(" -------------------------\n"); printf(" %10.6"FSYM" %10.6f\n", t, sqrt(N_VDotProd(y,y)/N)); for (iout=0; iout<Nt; iout++) { flag = ARKStepEvolve(arkode_mem, tout, y, &t, ARK_NORMAL); /* call integrator */ if (check_flag(&flag, "ARKStepEvolve", 1)) break; printf(" %10.6"FSYM" %10.6f\n", t, sqrt(N_VDotProd(y,y)/N)); /* print solution stats */ if (flag >= 0) { /* successful solve: update output time */ tout += dTout; tout = (tout > Tf) ? Tf : tout; } else { /* unsuccessful solve: break */ fprintf(stderr,"Solver failure, stopping integration\n"); break; } /* output results to disk */ for (i=0; i<N; i++) fprintf(UFID," %.16"ESYM"", data[i]); fprintf(UFID,"\n"); } printf(" -------------------------\n"); fclose(UFID); /* Print some final statistics */ flag = ARKStepGetNumSteps(arkode_mem, &nst); check_flag(&flag, "ARKStepGetNumSteps", 1); flag = ARKStepGetNumStepAttempts(arkode_mem, &nst_a); check_flag(&flag, "ARKStepGetNumStepAttempts", 1); flag = ARKStepGetNumRhsEvals(arkode_mem, &nfe, &nfi); check_flag(&flag, "ARKStepGetNumRhsEvals", 1); flag = ARKStepGetNumLinSolvSetups(arkode_mem, &nsetups); check_flag(&flag, "ARKStepGetNumLinSolvSetups", 1); flag = ARKStepGetNumErrTestFails(arkode_mem, &netf); check_flag(&flag, "ARKStepGetNumErrTestFails", 1); flag = ARKStepGetNumNonlinSolvIters(arkode_mem, &nni); check_flag(&flag, "ARKStepGetNumNonlinSolvIters", 1); flag = ARKStepGetNumNonlinSolvConvFails(arkode_mem, &ncfn); check_flag(&flag, "ARKStepGetNumNonlinSolvConvFails", 1); flag = ARKStepGetNumLinIters(arkode_mem, &nli); check_flag(&flag, "ARKStepGetNumLinIters", 1); flag = ARKStepGetNumJtimesEvals(arkode_mem, &nJv); check_flag(&flag, "ARKStepGetNumJtimesEvals", 1); flag = ARKStepGetNumLinConvFails(arkode_mem, &nlcf); check_flag(&flag, "ARKStepGetNumLinConvFails", 1); printf("\nFinal Solver Statistics:\n"); printf(" Internal solver steps = %li (attempted = %li)\n", nst, nst_a); printf(" Total RHS evals: Fe = %li, Fi = %li\n", nfe, nfi); printf(" Total linear solver setups = %li\n", nsetups); printf(" Total linear iterations = %li\n", nli); printf(" Total number of Jacobian-vector products = %li\n", nJv); printf(" Total number of linear solver convergence failures = %li\n", nlcf); printf(" Total number of Newton iterations = %li\n", nni); printf(" Total number of nonlinear solver convergence failures = %li\n", ncfn); printf(" Total number of error test failures = %li\n", netf); /* Clean up and return with successful completion */ N_VDestroy(y); /* Free vectors */ free(udata); /* Free user data */ ARKStepFree(&arkode_mem); /* Free integrator memory */ SUNLinSolFree(LS); /* Free linear solver */ SUNContext_Free(&ctx); /* Free context */ return 0; } /*-------------------------------- * Functions called by the solver *--------------------------------*/ /* f routine to compute the ODE RHS function f(t,y). */ static int f(realtype t, N_Vector y, N_Vector ydot, void *user_data) { UserData udata = (UserData) user_data; /* access problem data */ sunindextype N = udata->N; /* set variable shortcuts */ realtype k = udata->k; realtype dx = udata->dx; realtype *Y=NULL, *Ydot=NULL; realtype c1, c2; sunindextype i = 0; sunindextype isource; Y = N_VGetArrayPointer(y); /* access data arrays */ if (check_flag((void *) Y, "N_VGetArrayPointer", 0)) return 1; Ydot = N_VGetArrayPointer(ydot); if (check_flag((void *) Ydot, "N_VGetArrayPointer", 0)) return 1; N_VConst(0.0, ydot); /* Initialize ydot to zero */ /* iterate over domain, computing all equations */ c1 = k/dx/dx; c2 = -RCONST(2.0)*k/dx/dx; isource = N/2; Ydot[0] = 0.0; /* left boundary condition */ #pragma omp parallel for default(shared) private(i) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) Ydot[i] = c1*Y[i-1] + c2*Y[i] + c1*Y[i+1]; Ydot[N-1] = 0.0; /* right boundary condition */ Ydot[isource] += 0.01/dx; /* source term */ return 0; /* Return with success */ } /* Jacobian routine to compute J(t,y) = df/dy. */ static int Jac(N_Vector v, N_Vector Jv, realtype t, N_Vector y, N_Vector fy, void *user_data, N_Vector tmp) { UserData udata = (UserData) user_data; /* variable shortcuts */ sunindextype N = udata->N; realtype k = udata->k; realtype dx = udata->dx; realtype *V=NULL, *JV=NULL; realtype c1, c2; sunindextype i = 0; V = N_VGetArrayPointer(v); /* access data arrays */ if (check_flag((void *) V, "N_VGetArrayPointer", 0)) return 1; JV = N_VGetArrayPointer(Jv); if (check_flag((void *) JV, "N_VGetArrayPointer", 0)) return 1; N_VConst(0.0, Jv); /* initialize Jv product to zero */ /* iterate over domain, computing all Jacobian-vector products */ c1 = k/dx/dx; c2 = -RCONST(2.0)*k/dx/dx; JV[0] = 0.0; #pragma omp parallel for default(shared) private(i) schedule(static) num_threads(udata->nthreads) for (i=1; i<N-1; i++) JV[i] = c1*V[i-1] + c2*V[i] + c1*V[i+1]; JV[N-1] = 0.0; return 0; /* Return with success */ } /*------------------------------- * Private helper functions *-------------------------------*/ /* Check function return value... opt == 0 means SUNDIALS function allocates memory so check if returned NULL pointer opt == 1 means SUNDIALS function returns a flag so check if flag >= 0 opt == 2 means function allocates memory so check if returned NULL pointer */ static int check_flag(void *flagvalue, const char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return 1; } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", funcname, *errflag); return 1; }} /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return 1; } return 0; } /*---- end of file ----*/
RACBVH.h
#ifndef RACBVH_H #define RACBVH_H #include "common.h" #include <queue> #include "RangeDecoder_File.h" #include "RangeDecoder_Mem.h" #include "positionquantizer_new.h" #include "integercompressorRACBVH.h" #include "stopwatch.hpp" //#define DEBUG_CODEC // enable extra codec info to verify correctness #define USE_DYNAMIC_VECTOR //#define USE_LIST #define USE_MEM_MANAGER #define USE_MM //#define USE_DM #define NBITS 16 #define BIT_MASK 0xFFFF #define FLOOR 0 #define CEIL 1 #ifdef _USE_RACBVH #ifdef GETIDXOFFSET #undef GETIDXOFFSET #define GETIDXOFFSET(node) ((node)->indexOffset >> 2) #endif #endif #ifdef USE_DYNAMIC_VECTOR #include "dynamicvector.h" #endif #ifdef USE_MEM_MANAGER #include "mem_managerRACBVH.h" #endif #ifdef _USE_RACM #include "compressed_mesh.h" #endif template <class T> class RACBVH { public : RACBVH(const char * pFileName, int maxAllowedMem, int blockSize); // FORCEINLINE const T &operator[](unsigned int i); FORCEINLINE const T &operator[](unsigned int i); ~RACBVH(); #ifdef USE_MM int readInt(); unsigned int readUInt(); long readLong(); float readFloat(); #endif #ifdef USE_DM int readInt(long &pos); unsigned int readUInt(long &pos); long readLong(long &pos); float readFloat(long &pos); #endif int maxAllowedMem; int loadClusterTable(); bool loadCluster(unsigned int CN, T* posCluster, long diskClusterOffset, int threadNum); //BSPArrayTreeNodePtr getNode(unsigned int index, unsigned int depth = 0); void completeBB(BSPArrayTreeNodePtr parentNode, BSPArrayTreeNodePtr node, int leftOrRight, unsigned int CN); unsigned int decodeDeltaForChildIndexInOutCluster(unsigned int numBoundary, unsigned int *listBoundary, RangeModel **rmDeltaChildIndex, RangeDecoder *rd); unsigned int decodeDeltaForTriIndex(unsigned int numBoundary, unsigned int *listBoundary, RangeModel **rmDeltaTriIndex, RangeDecoder *rd); int getBiggestAxis(I32 *minQ, I32 *maxQ) { I32 diffQ[3] = {maxQ[0]-minQ[0], maxQ[1]-minQ[1], maxQ[2]-minQ[2]}; return (diffQ[0]> diffQ[1] && diffQ[0]> diffQ[2]) ? 0 : (diffQ[1] > diffQ[2] ? 1 : 2); } PositionQuantizerNew* pq; struct FrontNode; typedef struct FrontNode { FrontNode* buffer_next; int IsInDV; int index; int count; int isChildInThis; int axis; } FrontNode; struct FrontTri; typedef struct FrontTri { FrontTri* buffer_next; int IsInDV; unsigned int index; } FrontTri; struct BaseTri; typedef struct BaseTri { BaseTri* buffer_next; int IsInDV; unsigned int index; } BaseTri; ///////////////////////////// // Variables ///////////////////////////// #if defined(_USE_RACM) && defined(_USE_TRI_3_TYPE_ENCODING) CMeshAbstract * m_pMesh; #endif CMemManagerRACBVH<BSPArrayTreeNode> m_physicalMemory; unsigned int m_nodesPerCluster; unsigned int m_sizeBasePage; unsigned int m_sizeBasePagePower; unsigned int m_numNodes; unsigned int m_numClusters; unsigned int m_maxNumPCN; unsigned int m_nodesPerClusterPower; float m_bb_min_f[3]; float m_bb_max_f[3]; unsigned int m_numBoundary; unsigned int *m_listBoundary; I32 m_maxRange; #if !defined(USE_MM) && !defined(USE_DM) FILE *fp[NUM_THREADS]; #endif #ifdef USE_MM // Compressed data CMemoryMappedFile <unsigned char> m_CompressedFile[NUM_THREADS]; #endif #ifdef USE_DM unsigned char *m_CompressedFile; #endif }; #include "io.h" #include <math.h> #include "stopwatch.hpp" template <class T> RACBVH<T>::RACBVH(const char * pFileName, int maxAllowedMem, int blockSize) { m_listBoundary = NULL; pq = NULL; this->maxAllowedMem = maxAllowedMem; #if !defined(USE_MM) && !defined(USE_DM) int i; for(i=0;i<NUM_THREADS;i++) fp[i] = fopen(pFileName, "rb"); #endif #ifdef USE_MM FILE *fpTemp = fopen(pFileName, "rb"); I64 fileSize = _filelengthi64(fileno(fpTemp)); fclose(fpTemp); int i; for(i=0;i<NUM_THREADS;i++) m_CompressedFile[i].Init(pFileName, "r", 1024*1024*32/(64*1024), fileSize); #endif #ifdef USE_DM FILE *fpTemp = fopen(pFileName, "rb"); I64 fileSize = _filelengthi64(fileno(fpTemp)); m_CompressedFile = new unsigned char[fileSize]; fread(m_CompressedFile, sizeof(unsigned char), fileSize, fpTemp); fclose(fpTemp); #endif loadClusterTable(); } template <class T> RACBVH<T>::~RACBVH() { if (m_listBoundary) delete m_listBoundary; if (pq) delete pq; #if !defined(USE_MM) && !defined(USE_DM) int i; for(i=0;i<NUM_THREADS;i++) if(fp[i]) fclose(fp[i]); #endif #ifdef USE_DM int i; for(i=0;i<NUM_THREADS;i++) delete m_CompressedFile; #endif } /* FORCEINLINE const BSPArrayTreeNode& RACBVH<BSPArrayTreeNode>::operator[](unsigned int i) { return *getNode(i); } const BSPArrayTreeNode& RACBVH<BSPArrayTreeNode>::operator[](unsigned int index) { // printf("getNode(%d)\n", index); static unsigned int SHIFT_NPC_BSPN = m_nodesPerClusterPower + BSPTREENODESIZEPOWER; static unsigned int CN_SHIFT = SHIFT_NPC_BSPN - 3; unsigned int CN = index >> CN_SHIFT; int TPCN = clusterTable[CN].PCN; if(TPCN == -1) { static int pp = 0; // Page Fault long DCO = clusterTable[CN].DCO; int PCN = -1; if(emptyList.empty()) { #ifdef _VICTIM_POLICY_RANDOM PCN = rand()%m_maxNumPCN; #endif #ifdef _VICTIM_POLICY_SECOND_CHANCE unsigned int beforeVictim = currentVictim; ClusterTableEntry *curEntry = &clusterTable[currentVictim]; while(curEntry->chance > 0) { curEntry->chance--; if(curEntry->chance < 0) curEntry->chance = 0; currentVictim = (currentVictim+1)%m_maxNumPCN; if(currentVictim == beforeVictim) { printf("There is no victim!!!\n"); } curEntry = &clusterTable[currentVictim]; } PCN = currentVictim; currentVictim = (currentVictim+1)%m_maxNumPCN; #endif clusterTable[PMM[PCN]].PCN = -1; } else { PCN = emptyList.front(); emptyList.pop(); } clusterTable[CN].PCN = TPCN = PCN; PMM[PCN] = CN; // loadCluster(CN, PCN, DCO); } #ifdef _VICTIM_POLICY_SECOND_CHANCE clusterTable[CN].chance = 1; #endif long offset = (index << 3) & offsetMask; BSPArrayTreeNodePtr node = (BSPArrayTreeNodePtr)(m_physicalMemory + (TPCN << SHIFT_NPC_BSPN) + offset); if((node->children2 & 1) == 1) { // Bounding box isn't completed char* PosCluster = m_physicalMemory + (TPCN << SHIFT_NPC_BSPN); BSPArrayTreeNodePtr localRoot = node; // find local root unsigned int parentIndex; while(true) { memcpy(&parentIndex, &localRoot->min.e[0], sizeof(unsigned int)); if(parentIndex / m_nodesPerCluster != CN) break; offset = (parentIndex << 5) & offsetMask; localRoot = (BSPArrayTreeNodePtr)(PosCluster + offset); } BSPArrayTreeNodePtr parentNode = ((BSPArrayTreeNodePtr)&((*this)[parentIndex << 2])); int leftOrRight = GETLEFTCHILD(parentNode) == index; completeBB(parentNode, localRoot, leftOrRight, PosCluster, CN); } return *node; } */ const BSPArrayTreeNode& RACBVH<BSPArrayTreeNode>::operator[](unsigned int index) { BSPArrayTreeNodePtr node = &m_physicalMemory[index >> 2]; if((node->children2 & 1) == 1) { extern Stopwatch **TComplete; #ifdef _USE_OPENMP int threadNum = omp_get_thread_num(); #else int threadNum = 0; #endif TComplete[threadNum]->Start(); // Bounding box isn't completed BSPArrayTreeNodePtr parentNode = node; BSPArrayTreeNodePtr localRoot = node; // find local root and get parent node of the local root. unsigned int parentIndex; unsigned int CN = (index >> 2) >> m_nodesPerClusterPower; while(true) { memcpy(&parentIndex, &localRoot->min.e[0], sizeof(unsigned int)); // busy wait when another processor is completing if(((parentNode->children2) >> 1) & 1) { while(((parentNode->children2) >> 1) & 1) { #ifdef _USE_OPENMP #pragma omp critical cout << omp_get_thread_num() << " is wating for " << CN << " " << parentIndex / m_nodesPerCluster << endl; #endif } assert((node->children2 & 3) == 0); TComplete[threadNum]->Stop(); return *node; } localRoot = parentNode; parentNode = &m_physicalMemory[parentIndex]; // parent node is in another cluster or has completed BB if(parentIndex / m_nodesPerCluster != CN) break; } int leftOrRight = GETLEFTCHILD(parentNode) == index; completeBB(parentNode, localRoot, leftOrRight, CN); TComplete[threadNum]->Stop(); } return *node; } // link module between CMemManager and RACBVH template <class T> bool loadCluster(RACBVH<T> *pBVH, unsigned int CN, T* posCluster, long diskClusterOffset, int threadNum = 0) { extern Stopwatch **TCluster; TCluster[threadNum]->Start(); bool returnValue = pBVH->loadCluster(CN, posCluster, diskClusterOffset, threadNum); TCluster[threadNum]->Stop(); return returnValue; } template <class T> bool RACBVH<T>::loadCluster(unsigned int CN, T* posCluster, long diskClusterOffset, int threadNum) { #if !defined(USE_MM) && !defined(USE_DM) fseek(fp[threadNum], diskClusterOffset, SEEK_SET); //RangeDecoder *rd_geom = new RangeDecoderFile(fp); unsigned char m_CompressedFile[4096*sizeof(BSPArrayTreeNode)]; fread(m_CompressedFile, 4096*sizeof(BSPArrayTreeNode), 1, fp[threadNum]); RangeDecoder *rd_geom = new RangeDecoderFile(m_CompressedFile, 4096*sizeof(BSPArrayTreeNode)); #endif #ifdef USE_MM m_CompressedFile[threadNum].SetCurrentPointer(diskClusterOffset); RangeDecoder *rd_geom = new RangeDecoderMemFile(m_CompressedFile[threadNum]); #endif #ifdef USE_DM RangeDecoder *rd_geom = new RangeDecoderFile(m_CompressedFile+diskClusterOffset, 4096*sizeof(BSPArrayTreeNode)); #endif IntegerCompressorRACBVH* ic[2]; RangeModel **rmDeltaChildIndex = new RangeModel*[m_numBoundary]; #ifdef _USE_TRI_DELTA_ENCODING RangeModel **rmDeltaTriIndex = new RangeModel*[m_numBoundary]; #endif RangeModel *rmIsChildInThis; #if defined(_USE_RACM) && defined(_USE_TRI_3_TYPE_ENCODING) //RangeModel *rmTriIndexType; #endif ic[0] = new IntegerCompressorRACBVH(); ic[1] = new IntegerCompressorRACBVH(); m_maxRange = pq->m_aiQuantRange[0] > pq->m_aiQuantRange[1] ? pq->m_aiQuantRange[0] : pq->m_aiQuantRange[1]; m_maxRange = m_maxRange > pq->m_aiQuantRange[2] ? m_maxRange : pq->m_aiQuantRange[2]; ic[0]->SetRange(m_maxRange); ic[1]->SetRange(m_maxRange); ic[0]->SetPrecision(NBITS); ic[1]->SetPrecision(NBITS); ic[0]->SetupDecompressor(rd_geom); ic[1]->SetupDecompressor(rd_geom); unsigned int clusterSize = rd_geom->decodeInt(); for(int i=0;i<m_numBoundary;i++) { rmDeltaChildIndex[i] = new RangeModel(m_listBoundary[i]+1, 0, FALSE); #ifdef _USE_TRI_DELTA_ENCODING rmDeltaTriIndex[i] = new RangeModel(m_listBoundary[i]+1, 0, FALSE); #endif } #if defined(_USE_RACM) && defined(_USE_TRI_3_TYPE_ENCODING) //rmTriIndexType = new RangeModel(3, 0, FALSE); DynamicVector *dvTriIndexFront = new DynamicVector(); DynamicVector *dvTriIndexBase = new DynamicVector(); typedef stdext::hash_map<unsigned int, FrontTri*> FrontHashTableTri; typedef FrontHashTableTri::iterator FrontHashTableTriIterator; FrontHashTableTri *frontHashTableTri = new FrontHashTableTri; #else DynamicVector *dvTriIndexBase = new DynamicVector(); #endif rmIsChildInThis = new RangeModel(4, 0, FALSE); DynamicVector *dvNodeIndex = new DynamicVector(); int beforeTriID = 0; unsigned int numParentCluster = 0; unsigned int numLocalRoot = 0; numParentCluster = rd_geom->decode(m_numClusters); unsigned int *listParentCN = new unsigned int[numParentCluster]; for(int i=0;i<numParentCluster;i++) { listParentCN[i] = rd_geom->decode(m_numClusters); } numLocalRoot = rd_geom->decode(m_nodesPerCluster); unsigned int *listParentIndex = new unsigned int[numLocalRoot]; for(int i=0;i<numLocalRoot;i++) { // unsigned int parentCN = listParentCN[rd_geom->decode(rmParentClusterOffset)]; unsigned int parentCN = listParentCN[rd_geom->decode(numParentCluster)]; listParentIndex[i] = (parentCN << m_nodesPerClusterPower) + rd_geom->decode(m_nodesPerCluster); } delete listParentCN; unsigned int curLocalRoot = 0; unsigned int beforeOutClusterChildIndex = 0; int triIDCache[3]; for(int i=0;i<clusterSize;i++) { BSPArrayTreeNodePtr node = &posCluster[i];//(BSPArrayTreeNodePtr)(m_physicalMemory + ((PCN << SHIFT_NPC_BSPN) + (i << BSPTREENODESIZEPOWER))); unsigned int curNodeIdx = CN*m_nodesPerCluster+i; unsigned int parentIndex; int isChildInThis = 0; int parentAxis = 0; BOOL leftOrRight = 0; BSPArrayTreeNodePtr parentNode = NULL; int indexCode = rd_geom->decode(dvNodeIndex->size()+1); unsigned int hasInCompleteBB = 0; int biggestaxis = 0; if(indexCode == 0) { if(curNodeIdx == 0) { // global root node->min.e[0] = m_bb_min_f[0]; node->min.e[1] = m_bb_min_f[1]; node->min.e[2] = m_bb_min_f[2]; node->max.e[0] = m_bb_max_f[0]; node->max.e[1] = m_bb_max_f[1]; node->max.e[2] = m_bb_max_f[2]; // Vector3 diff = node->max - node->min; // node->children |= diff.indexOfMaxComponent(); } else { // local root parentIndex = listParentIndex[curLocalRoot++];//rd_geom->decodeInt(); memcpy(&node->min.e[0], &parentIndex, sizeof(int)); unsigned int code = 0; // change Last(0) to None ------------------------- code = (unsigned int)ic[0]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[0]->Decompress(0, 1); memcpy(&node->max.e[0], &code, sizeof(unsigned int)); code = (unsigned int)ic[1]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[1]->Decompress(0, 1); memcpy(&node->max.e[1], &code, sizeof(unsigned int)); code = (unsigned int)ic[1]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[1]->Decompress(0, 1); memcpy(&node->max.e[2], &code, sizeof(unsigned int)); hasInCompleteBB = 1; } } else { parentIndex = indexCode-1; FrontNode* frontNode = (FrontNode *)dvNodeIndex->getElementWithRelativeIndex(parentIndex); parentIndex = frontNode->index; isChildInThis = frontNode->isChildInThis; parentAxis = frontNode->axis; if(frontNode->count == 0) { frontNode->count = frontNode->count+1; leftOrRight = 1; } else { leftOrRight = (isChildInThis & 1) == 1 ? 0 : 1; dvNodeIndex->removeElement(frontNode); delete frontNode; } unsigned int pMod = parentIndex - ((parentIndex >> m_nodesPerClusterPower) << m_nodesPerClusterPower); parentNode = &posCluster[pMod];//(BSPArrayTreeNodePtr)(m_physicalMemory + ((PCN << SHIFT_NPC_BSPN) + (pMod << BSPTREENODESIZEPOWER))); if(leftOrRight) { parentNode->children = (curNodeIdx << 4); } else { parentNode->children2 = (curNodeIdx << 4) | (parentNode->children2 & 1); } if((parentNode->children2 & 1) == 1) { // parent node's BB isn't completed hasInCompleteBB = 1; memcpy(&node->min.e[0], &parentIndex, sizeof(int)); unsigned int code = 0; if(leftOrRight) { // this is a left child // change Last to none code = (unsigned int)ic[0]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[0]->Decompress(0, 1); memcpy(&node->max.e[0], &code, sizeof(unsigned int)); code = (unsigned int)ic[1]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[1]->Decompress(0, 1); memcpy(&node->max.e[1], &code, sizeof(unsigned int)); code = (unsigned int)ic[1]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[1]->Decompress(0, 1); memcpy(&node->max.e[2], &code, sizeof(unsigned int)); } else { // this is a right child code = (unsigned int)ic[0]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[0]->Decompress(0, 1); memcpy(&node->max.e[0], &code, sizeof(unsigned int)); code = (unsigned int)ic[1]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[1]->Decompress(0, 1); memcpy(&node->max.e[1], &code, sizeof(unsigned int)); code = (unsigned int)ic[1]->Decompress(0, 1); code = (code << NBITS) + (unsigned int)ic[1]->Decompress(0, 1); memcpy(&node->max.e[2], &code, sizeof(unsigned int)); } } else { // parent node's BB is completed. hasInCompleteBB = 0; I32 parentMinQ[3]; I32 parentMaxQ[3]; I32 predictedQ; pq->EnQuantize(parentNode->min.e, parentMinQ); pq->EnQuantize(parentNode->max.e, parentMaxQ); biggestaxis = getBiggestAxis(parentMinQ, parentMaxQ); int axis1; int axis2; switch(biggestaxis) { case 0 : axis1 = 1; axis2 = 2; break; case 1 : axis1 = 2; axis2 = 0; break; case 2 : axis1 = 0; axis2 = 1; break; } predictedQ = (parentMinQ[biggestaxis] + parentMaxQ[biggestaxis]) >> 1; I32 qMin[3]; I32 qMax[3]; if(leftOrRight) { // this is a left child /* unsigned int sym = 63; if((sym & 1) == 1) qMin[biggestaxis] = ic[0]->DecompressLast(parentMinQ[biggestaxis], 1); else qMin[biggestaxis] = parentMinQ[biggestaxis]; if((sym & 2) == 2) qMax[biggestaxis] = ic[0]->DecompressLast(predictedQ, 0); else qMax[biggestaxis] = parentMaxQ[biggestaxis]; if((sym & 4) == 4) qMin[axis1] = ic[1]->DecompressLast(parentMinQ[axis1], 1); else qMin[axis1] = parentMinQ[axis1]; if((sym & 8) == 8) qMax[axis1] = ic[1]->DecompressLast(parentMaxQ[axis1], 0); else qMax[axis1] = parentMaxQ[axis1]; if((sym & 16) == 16) qMin[axis2] = ic[2]->DecompressLast(parentMinQ[axis2], 1); else qMin[axis2] = parentMinQ[axis2]; if((sym & 32) == 32) qMax[axis2] = ic[2]->DecompressLast(parentMaxQ[axis2], 0); else qMax[axis2] = parentMaxQ[axis2]; */ qMin[biggestaxis] = ic[0]->Decompress(parentMinQ[biggestaxis], 1); qMax[biggestaxis] = ic[0]->Decompress(predictedQ, 0); qMin[axis1] = ic[1]->Decompress(parentMinQ[axis1], 1); qMax[axis1] = ic[1]->Decompress(parentMaxQ[axis1], 0); qMin[axis2] = ic[1]->Decompress(parentMinQ[axis2], 1); qMax[axis2] = ic[1]->Decompress(parentMaxQ[axis2], 0); parentNode->children |= biggestaxis; } else { // this is a right child /* unsigned int sym = 63; if((isChildInThis & 2) == 2) { // left child is in this cluster sym = 0; BSPArrayTreeNodePtr lChild = (BSPArrayTreeNodePtr)(m_physicalMemory + (PCN*m_nodesPerCluster*sizeof(BSPArrayTreeNode) + ((parentNode->children >> 4)%m_nodesPerCluster)*sizeof(BSPArrayTreeNode))); BSPArrayTreeNodePtr rChild = node; I32 sMinQ[3]; I32 sMaxQ[3]; pq->EnQuantize(lChild->min.e, sMinQ);//, FLOOR); pq->EnQuantize(lChild->max.e, sMaxQ);//, CEIL); if(sMinQ[biggestaxis] == parentMinQ[biggestaxis]) sym |= 1; if(sMaxQ[biggestaxis] == parentMaxQ[biggestaxis]) sym |= 2; if(sMinQ[axis1] == parentMinQ[axis1]) sym |= 4; if(sMaxQ[axis1] == parentMaxQ[axis1]) sym |= 8; if(sMinQ[axis2] == parentMinQ[axis2]) sym |= 16; if(sMaxQ[axis2] == parentMaxQ[axis2]) sym |= 32; } sym = 63; */ /* if((sym & 1) == 1) qMin[biggestaxis] = ic[0]->DecompressLast(predictedQ, 1); else qMin[biggestaxis] = parentMinQ[biggestaxis]; if((sym & 2) == 2) qMax[biggestaxis] = ic[0]->DecompressLast(parentMaxQ[biggestaxis], 0); else qMax[biggestaxis] = parentMaxQ[biggestaxis]; if((sym & 4) == 4) qMin[axis1] = ic[1]->DecompressLast(parentMinQ[axis1], 1); else qMin[axis1] = parentMinQ[axis1]; if((sym & 8) == 8) qMax[axis1] = ic[1]->DecompressLast(parentMaxQ[axis1], 0); else qMax[axis1] = parentMaxQ[axis1]; if((sym & 16) == 16) qMin[axis2] = ic[2]->DecompressLast(parentMinQ[axis2], 1); else qMin[axis2] = parentMinQ[axis2]; if((sym & 32) == 32) qMax[axis2] = ic[2]->DecompressLast(parentMaxQ[axis2], 0); else qMax[axis2] = parentMaxQ[axis2]; */ qMin[biggestaxis] = ic[0]->Decompress(predictedQ, 1); qMax[biggestaxis] = ic[0]->Decompress(parentMaxQ[biggestaxis], 0); qMin[axis1] = ic[1]->Decompress(parentMinQ[axis1], 1); qMax[axis1] = ic[1]->Decompress(parentMaxQ[axis1], 0); qMin[axis2] = ic[1]->Decompress(parentMinQ[axis2], 1); qMax[axis2] = ic[1]->Decompress(parentMaxQ[axis2], 0); } pq->DeQuantize(qMin, node->min.e); pq->DeQuantize(qMax, node->max.e); } } int nodeAxis = rd_geom->decode(2); if(nodeAxis) { node->indexCount = 7; unsigned int TriID = 0; #ifdef _USE_TRI_3_TYPE_ENCODING // Compress triangle index #if defined(_USE_RACM) && defined(_USE_TRI_3_TYPE_ENCODING) unsigned int NewTris [10]; bool encoded = false; unsigned int triCompType = 0; unsigned int Corner; unsigned int NextCorner; unsigned int PrevCorner; unsigned int Vertex; unsigned int NextVertex; unsigned int PrevVertex; int NewTriNum; unsigned int v1, v2; //int type = rd_geom->decode(rmTriIndexType)+1; int type = rd_geom->decode(3)+1; // type 1 : cache if(type == 1 && i != 0) { TriID = triIDCache[rd_geom->decode(3)]; } // type 2 : front if(type == 2 && i != 0) { int triIndex = rd_geom->decode(dvTriIndexFront->size()+1);//icTriIndexFront->DecompressNone();// rd_geom->decode(rmTriIndexFront); FrontTri *frontTri = (FrontTri*)dvTriIndexFront->getElementWithRelativeIndex(triIndex); TriID = frontTri->index; } // type 3 : base + offset if(type == 3) { unsigned int base; unsigned int offset; unsigned int baseIndex; // baseIndex = rd_geom->decode(rmTriIndexBase); baseIndex = rd_geom->decode(dvTriIndexBase->size()+1);//icTriIndexBase->DecompressNone(); BaseTri *baseTri; if(baseIndex == 0) { base = rd_geom->decode(m_numClusters); baseTri = new BaseTri; baseTri->buffer_next = 0; baseTri->IsInDV = 0; baseTri->index = base; dvTriIndexBase->addElement(baseTri); } else { baseTri = (BaseTri*)dvTriIndexBase->getElementWithRelativeIndex(baseIndex-1); base = baseTri->index; } offset = rd_geom->decode(m_sizeBasePage); TriID = (base << m_sizeBasePagePower) + offset; } /* // delete from front list FrontHashTableTriIterator it = frontHashTableTri->find(TriID); if(it != frontHashTableTri->end()) { //unsigned int a = it->second; FrontTri *frontTri = (FrontTri*)it->second; dvTriIndexFront->removeElement(frontTri); frontHashTableTri->erase(it); delete frontTri; } */ Corner = m_pMesh->GetCornerFromTriID (TriID); NextCorner = m_pMesh->GetNextCornerGivenSameTri (Corner); PrevCorner = m_pMesh->GetPrevCornerGivenSameTri (Corner); Vertex = m_pMesh->GetIncidentVertexFromCorner (Corner); NextVertex = m_pMesh->GetIncidentVertexFromCorner (NextCorner); PrevVertex = m_pMesh->GetIncidentVertexFromCorner (PrevCorner); NewTriNum = 0; // insert to front list for(int c=0;c<3;c++) { triIDCache[c] = -1; switch(c) { case 0 : v1 = Vertex; v2 = NextVertex; break; case 1 : v1 = NextVertex; v2 = PrevVertex; break; case 2 : v1 = PrevVertex; v2 = Vertex; break; } if ((NewTriNum = m_pMesh->GetTrianglesSharingTwoVertices (v1, v2, NewTris, TriID, true)) == 1) { triIDCache[c] = NewTris[0]; /* FrontHashTableTriIterator it = frontHashTableTri->find(NewTris[0]); if(it == frontHashTableTri->end()) { FrontTri *frontTri = new FrontTri; frontTri->buffer_next = 0; frontTri->IsInDV = 0; frontTri->index = NewTris[0]; dvTriIndexFront->addElement(frontTri); frontHashTableTri->insert(std::pair<unsigned int, FrontTri*>(NewTris[0], frontTri)); } */ } } beforeTriID = TriID; node->indexOffset = TriID << 2; #else unsigned int base; unsigned int offset; unsigned int baseIndex; baseIndex = rd_geom->decode(dvTriIndexBase->size()+1); BaseTri *baseTri; if(baseIndex == 0) { base = rd_geom->decode(m_numClusters); baseTri = new BaseTri; baseTri->buffer_next = 0; baseTri->IsInDV = 0; baseTri->index = base; dvTriIndexBase->addElement(baseTri); } else { baseTri = (BaseTri*)dvTriIndexBase->getElementWithRelativeIndex(baseIndex-1); base = baseTri->index; } offset = rd_geom->decode(m_sizeBasePage); node->indexOffset = ((base << m_sizeBasePagePower) + offset) << 2; //node->indexOffset = rd_geom->decodeInt() << 2; #endif #endif #ifdef _USE_TRI_DELTA_ENCODING int sign = rd_geom->decode(2); int delta = decodeDeltaForTriIndex(m_numBoundary, m_listBoundary, rmDeltaTriIndex, rd_geom); if(delta == INT_MAX) TriID = rd_geom->decode((m_numNodes>>1)+1); else TriID = (beforeTriID + (sign ? delta : -delta)); beforeTriID = TriID; node->indexOffset = TriID << 2; #endif } else { int isChildInThis = rd_geom->decode(rmIsChildInThis); unsigned int delta = 0; switch(isChildInThis) { case 0 : delta = decodeDeltaForChildIndexInOutCluster(m_numBoundary, m_listBoundary, rmDeltaChildIndex, rd_geom); if(delta == UINT_MAX) node->children = rd_geom->decode(m_numNodes) << 4; else node->children = (beforeOutClusterChildIndex + delta) << 4; beforeOutClusterChildIndex = node->children >> 4; delta = decodeDeltaForChildIndexInOutCluster(m_numBoundary, m_listBoundary, rmDeltaChildIndex, rd_geom); if(delta == UINT_MAX) node->children2 = rd_geom->decode(m_numNodes) << 4; else node->children2 = (beforeOutClusterChildIndex + delta) << 4; beforeOutClusterChildIndex = node->children2 >> 4; break; case 1 : delta = decodeDeltaForChildIndexInOutCluster(m_numBoundary, m_listBoundary, rmDeltaChildIndex, rd_geom); if(delta == UINT_MAX) node->children = rd_geom->decode(m_numNodes) << 4; else node->children = (beforeOutClusterChildIndex + delta) << 4; beforeOutClusterChildIndex = node->children >> 4; break; case 2 : //beforeOutClusterChildIndex = node->children >> 4; delta = decodeDeltaForChildIndexInOutCluster(m_numBoundary, m_listBoundary, rmDeltaChildIndex, rd_geom); if(delta == UINT_MAX) node->children2 = rd_geom->decode(m_numNodes) << 4; else node->children2 = (beforeOutClusterChildIndex + delta) << 4; beforeOutClusterChildIndex = node->children2 >> 4; break; } if(isChildInThis > 0) { FrontNode* frontNode = new FrontNode; frontNode->buffer_next = 0; frontNode->IsInDV = 0; frontNode->index = curNodeIdx; frontNode->count = isChildInThis == 3 ? 0 : 1; frontNode->isChildInThis = isChildInThis; frontNode->axis = biggestaxis; dvNodeIndex->addElement(frontNode); } } // if parent node's BB isn't complete, this node, neither. node->children2 &= ~1u; node->children2 |= hasInCompleteBB; } while(dvNodeIndex->size() > 0) { delete dvNodeIndex->getAndRemoveFirstElement(); } delete dvNodeIndex; #if defined(_USE_RACM) && defined(_USE_TRI_3_TYPE_ENCODING) delete frontHashTableTri; while(dvTriIndexFront->size() > 0) { delete dvTriIndexFront->getAndRemoveFirstElement(); } while(dvTriIndexBase->size() > 0) { delete dvTriIndexBase->getAndRemoveFirstElement(); } delete dvTriIndexFront; delete dvTriIndexBase; //delete rmTriIndexType; #else while(dvTriIndexBase->size() > 0) { delete dvTriIndexBase->getAndRemoveFirstElement(); } delete dvTriIndexBase; #endif delete listParentIndex; delete rmIsChildInThis; // delete rmParentClusterOffset; for(int j=0;j<m_numBoundary;j++) { delete rmDeltaChildIndex[j]; #ifdef _USE_TRI_DELTA_ENCODING delete rmDeltaTriIndex[j]; #endif } delete rmDeltaChildIndex; #ifdef _USE_TRI_DELTA_ENCODING delete rmDeltaTriIndex; #endif rd_geom->done(); delete rd_geom; ic[0]->FinishDecompressor(); ic[1]->FinishDecompressor(); delete ic[0]; delete ic[1]; return true; } #ifdef USE_MM template <class T> int RACBVH<T>::readInt() { unsigned char c1 = m_CompressedFile[0].GetNextElement(); unsigned char c2 = m_CompressedFile[0].GetNextElement(); unsigned char c3 = m_CompressedFile[0].GetNextElement(); unsigned char c4 = m_CompressedFile[0].GetNextElement(); return (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); } template <class T> unsigned int RACBVH<T>::readUInt() { unsigned char c1 = m_CompressedFile[0].GetNextElement(); unsigned char c2 = m_CompressedFile[0].GetNextElement(); unsigned char c3 = m_CompressedFile[0].GetNextElement(); unsigned char c4 = m_CompressedFile[0].GetNextElement(); return (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); } template <class T> long RACBVH<T>::readLong() { unsigned char c1 = m_CompressedFile[0].GetNextElement(); unsigned char c2 = m_CompressedFile[0].GetNextElement(); unsigned char c3 = m_CompressedFile[0].GetNextElement(); unsigned char c4 = m_CompressedFile[0].GetNextElement(); return (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); } template <class T> float RACBVH<T>::readFloat() { unsigned char c1 = m_CompressedFile[0].GetNextElement(); unsigned char c2 = m_CompressedFile[0].GetNextElement(); unsigned char c3 = m_CompressedFile[0].GetNextElement(); unsigned char c4 = m_CompressedFile[0].GetNextElement(); float returnValue = 0; unsigned int temp = (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); memcpy(&returnValue, &temp, 4); return returnValue; } #endif #ifdef USE_DM template <class T> int RACBVH<T>::readInt(long &pos) { unsigned char c1 = m_CompressedFile[pos++]; unsigned char c2 = m_CompressedFile[pos++]; unsigned char c3 = m_CompressedFile[pos++]; unsigned char c4 = m_CompressedFile[pos++]; return (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); } template <class T> unsigned int RACBVH<T>::readUInt(long &pos) { unsigned char c1 = m_CompressedFile[pos++]; unsigned char c2 = m_CompressedFile[pos++]; unsigned char c3 = m_CompressedFile[pos++]; unsigned char c4 = m_CompressedFile[pos++]; return (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); } template <class T> long RACBVH<T>::readLong(long &pos) { unsigned char c1 = m_CompressedFile[pos++]; unsigned char c2 = m_CompressedFile[pos++]; unsigned char c3 = m_CompressedFile[pos++]; unsigned char c4 = m_CompressedFile[pos++]; return (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); } template <class T> float RACBVH<T>::readFloat(long &pos) { unsigned char c1 = m_CompressedFile[pos++]; unsigned char c2 = m_CompressedFile[pos++]; unsigned char c3 = m_CompressedFile[pos++]; unsigned char c4 = m_CompressedFile[pos++]; float returnValue = 0; unsigned int temp = (c4 << 24) | (c3 << 16) | (c2 << 8) | (c1 << 0); memcpy(&returnValue, &temp, 4); return returnValue; } #endif template <class T> int RACBVH<T>::loadClusterTable() { #if !defined(USE_MM) && !defined(USE_DM) fread(&m_nodesPerCluster, sizeof(unsigned int), 1, fp[0]); fread(&m_sizeBasePage, sizeof(unsigned int), 1, fp[0]); fread(&m_sizeBasePagePower, sizeof(unsigned int), 1, fp[0]); fread(&m_numNodes, sizeof(unsigned int), 1, fp[0]); fread(&m_numClusters, sizeof(unsigned int), 1, fp[0]); fread(m_bb_min_f, sizeof(float), 3, fp[0]); fread(m_bb_max_f, sizeof(float), 3, fp[0]); fread(&m_numBoundary, sizeof(unsigned int), 1, fp[0]); m_listBoundary = new unsigned int[m_numBoundary]; fread(m_listBoundary, sizeof(unsigned int), m_numBoundary, fp[0]); pq = new PositionQuantizerNew(); pq->SetMinMax(m_bb_min_f, m_bb_max_f); pq->SetPrecision(NBITS); pq->SetupQuantizer(); #endif #ifdef USE_MM m_nodesPerCluster = readUInt(); m_sizeBasePage = readUInt(); m_sizeBasePagePower = readUInt(); m_numNodes = readUInt(); m_numClusters = readUInt(); m_bb_min_f[0] = readFloat(); m_bb_min_f[1] = readFloat(); m_bb_min_f[2] = readFloat(); m_bb_max_f[0] = readFloat(); m_bb_max_f[1] = readFloat(); m_bb_max_f[2] = readFloat(); m_numBoundary = readUInt(); m_listBoundary = new unsigned int[m_numBoundary]; for(int i=0;i<m_numBoundary;i++) { m_listBoundary[i] = readUInt(); } pq = new PositionQuantizerNew(); pq->SetMinMax(m_bb_min_f, m_bb_max_f); pq->SetPrecision(NBITS); pq->SetupQuantizer(); #endif #ifdef USE_DM long pos = 0; m_nodesPerCluster = readUInt(pos); m_sizeBasePage = readUInt(pos); m_sizeBasePagePower = readUInt(pos); m_numNodes = readUInt(pos); m_numClusters = readUInt(pos); m_bb_min_f[0] = readFloat(pos); m_bb_min_f[1] = readFloat(pos); m_bb_min_f[2] = readFloat(pos); m_bb_max_f[0] = readFloat(pos); m_bb_max_f[1] = readFloat(pos); m_bb_max_f[2] = readFloat(pos); m_numBoundary = readUInt(pos); m_listBoundary = new unsigned int[m_numBoundary]; for(int i=0;i<m_numBoundary;i++) { m_listBoundary[i] = readUInt(pos); } pq = new PositionQuantizerNew(); pq->SetMinMax(m_bb_min_f, m_bb_max_f); pq->SetPrecision(NBITS); pq->SetupQuantizer(); #endif m_nodesPerClusterPower = log((double)m_nodesPerCluster)/log(2.0); int offsetPower = log((double)(m_nodesPerCluster*sizeof(BSPArrayTreeNode)))/log(2.0); assert(pow(2.0, (int)m_nodesPerClusterPower) == m_nodesPerCluster); assert(pow(2.0, offsetPower) == m_nodesPerCluster*sizeof(BSPArrayTreeNode)); OptionManager *opt = OptionManager::getSingletonPtr(); m_maxNumPCN = min(m_numClusters, maxAllowedMem/(m_nodesPerCluster * sizeof(BSPArrayTreeNode))); #ifdef USE_DM #else #endif m_physicalMemory.Init("RACBVH", m_numNodes, maxAllowedMem/(m_nodesPerCluster * sizeof(BSPArrayTreeNode)), m_nodesPerCluster); m_physicalMemory.m_pRACBVH = this; #if !defined(USE_MM) && !defined(USE_DM) for(int i=0;i<m_numClusters;i++) { long offset; fread(&offset, sizeof(long), 1, fp[0]); m_physicalMemory.m_DiskClusterOffset[i] = offset; } #endif #ifdef USE_MM for(int i=0;i<m_numClusters;i++) { m_physicalMemory.m_DiskClusterOffset[i] = readLong(); } #endif #ifdef USE_DM for(int i=0;i<m_numClusters;i++) { m_physicalMemory.m_DiskClusterOffset[i] = readLong(pos); } #endif printf("Load cluster table complete.\n"); return 1; } template <class T> void RACBVH<T>::completeBB(BSPArrayTreeNodePtr parentNode, BSPArrayTreeNodePtr node, int leftOrRight, unsigned int CN) { node->children2 |= 3u; I32 parentMinQ[3]; I32 parentMaxQ[3]; I32 predictedQ; pq->EnQuantize(parentNode->min.e, parentMinQ); pq->EnQuantize(parentNode->max.e, parentMaxQ); int biggestaxis = getBiggestAxis(parentMinQ, parentMaxQ); int axis1; int axis2; switch(biggestaxis) { case 0 : axis1 = 1; axis2 = 2; break; case 1 : axis1 = 2; axis2 = 0; break; case 2 : axis1 = 0; axis2 = 1; break; } predictedQ = (parentMinQ[biggestaxis] + parentMaxQ[biggestaxis]) >> 1; I32 qMin[3]; I32 qMax[3]; I32 error[6]; unsigned int code; memcpy(&code, &node->max[0], sizeof(unsigned int)); error[0] = code >> NBITS; error[1] = code & BIT_MASK; memcpy(&code, &node->max[1], sizeof(unsigned int)); error[2] = code >> NBITS; error[3] = code & BIT_MASK; memcpy(&code, &node->max[2], sizeof(unsigned int)); error[4] = code >> NBITS; error[5] = code & BIT_MASK; if(leftOrRight) { // this is a left child /* unsigned int sym = 63; if((sym & 1) == 1) qMin[biggestaxis] = parentMinQ[biggestaxis] + error[0]; else qMin[biggestaxis] = parentMinQ[biggestaxis]; if((sym & 2) == 2) qMax[biggestaxis] = predictedQ - error[1]; else qMax[biggestaxis] = parentMaxQ[biggestaxis]; if((sym & 4) == 4) qMin[axis1] = parentMinQ[axis1] + error[2]; else qMin[axis1] = parentMinQ[axis1]; if((sym & 8) == 8) qMax[axis1] = parentMaxQ[axis1] - error[3]; else qMax[axis1] = parentMaxQ[axis1]; if((sym & 16) == 16) qMin[axis2] = parentMinQ[axis2] + error[4]; else qMin[axis2] = parentMinQ[axis2]; if((sym & 32) == 32) qMax[axis2] = parentMaxQ[axis2] - error[5]; else qMax[axis2] = parentMaxQ[axis2]; */ parentNode->children |= biggestaxis; qMin[biggestaxis] = parentMinQ[biggestaxis] + error[0]; qMax[biggestaxis] = predictedQ - error[1]; qMin[axis1] = parentMinQ[axis1] + error[2]; qMax[axis1] = parentMaxQ[axis1] - error[3]; qMin[axis2] = parentMinQ[axis2] + error[4]; qMax[axis2] = parentMaxQ[axis2] - error[5]; } else { // this is a right child /* unsigned int sym = 63; if(CN == (GETLEFTCHILD(node) >> 2) / m_nodesPerCluster) { // left child is in this cluster sym = 0; long offset = (GETLEFTCHILD(parentNode) << 3) & offsetMask; BSPArrayTreeNodePtr lChild = (BSPArrayTreeNodePtr)(PosCluster + offset); BSPArrayTreeNodePtr rChild = node; I32 sMinQ[3]; I32 sMaxQ[3]; pq->EnQuantize(lChild->min.e, sMinQ);//, FLOOR); pq->EnQuantize(lChild->max.e, sMaxQ);//, CEIL); if(sMinQ[biggestaxis] == parentMinQ[biggestaxis]) sym |= 1; if(sMaxQ[biggestaxis] == parentMaxQ[biggestaxis]) sym |= 2; if(sMinQ[axis1] == parentMinQ[axis1]) sym |= 4; if(sMaxQ[axis1] == parentMaxQ[axis1]) sym |= 8; if(sMinQ[axis2] == parentMinQ[axis2]) sym |= 16; if(sMaxQ[axis2] == parentMaxQ[axis2]) sym |= 32; } sym = 63; if((sym & 1) == 1) qMin[biggestaxis] = predictedQ + error[0]; else qMin[biggestaxis] = parentMinQ[biggestaxis]; if((sym & 2) == 2) qMax[biggestaxis] = parentMaxQ[biggestaxis] - error[1]; else qMax[biggestaxis] = parentMaxQ[biggestaxis]; if((sym & 4) == 4) qMin[axis1] = parentMinQ[axis1] + error[2]; else qMin[axis1] = parentMinQ[axis1]; if((sym & 8) == 8) qMax[axis1] = parentMaxQ[axis1] - error[3]; else qMax[axis1] = parentMaxQ[axis1]; if((sym & 16) == 16) qMin[axis2] = parentMinQ[axis2] + error[4]; else qMin[axis2] = parentMinQ[axis2]; if((sym & 32) == 32) qMax[axis2] = parentMaxQ[axis2] - error[5]; else qMax[axis2] = parentMaxQ[axis2]; */ qMin[biggestaxis] = predictedQ + error[0]; qMax[biggestaxis] = parentMaxQ[biggestaxis] - error[1]; qMin[axis1] = parentMinQ[axis1] + error[2]; qMax[axis1] = parentMaxQ[axis1] - error[3]; qMin[axis2] = parentMinQ[axis2] + error[4]; qMax[axis2] = parentMaxQ[axis2] - error[5]; } for(int i=0;i<3;i++) { if(qMin[i] >= m_maxRange) qMin[i] -= m_maxRange; if(qMin[i] < 0) qMin[i] += m_maxRange; if(qMax[i] >= m_maxRange) qMax[i] -= m_maxRange; if(qMax[i] < 0) qMax[i] += m_maxRange; } pq->DeQuantize(qMin, node->min.e); pq->DeQuantize(qMax, node->max.e); node->children2 &= ~1u; if(!ISLEAF(node)) { if(CN == (GETLEFTCHILD(node) >> 2) / m_nodesPerCluster) { BSPArrayTreeNodePtr left = &m_physicalMemory[node->children >> 4]; completeBB(node, left, 1, CN); } if(CN == (GETRIGHTCHILD(node) >> 2) / m_nodesPerCluster) { BSPArrayTreeNodePtr right = &m_physicalMemory[node->children2 >> 4]; completeBB(node, right, 0, CN); } } node->children2 &= ~3u; } template <class T> unsigned int RACBVH<T>::decodeDeltaForChildIndexInOutCluster(unsigned int numBoundary, unsigned int *listBoundary, RangeModel **rmDeltaChildIndex, RangeDecoder *rd) { for(unsigned int pass=0;pass<numBoundary;pass++) { unsigned int delta = rd->decode(rmDeltaChildIndex[pass]); if(delta < listBoundary[pass]) { return delta; } } return UINT_MAX; } template <class T> unsigned int RACBVH<T>::decodeDeltaForTriIndex(unsigned int numBoundary, unsigned int *listBoundary, RangeModel **rmDeltaTriIndex, RangeDecoder *rd) { for(unsigned int pass=0;pass<numBoundary;pass++) { unsigned int delta = rd->decode(rmDeltaTriIndex[pass]); if(delta < listBoundary[pass]) { return delta; } } return INT_MAX; } #endif
ast-dump-openmp-parallel-master-XFAIL.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -fopenmp-version=50 -ast-dump %s 2>&1 | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s // REQUIRES: broken-PR41022 // https://bugs.llvm.org/show_bug.cgi?id=41022 void test_zero() { #pragma omp parallel master ; } // CHECK: {{.*}}ast-dump-openmp-parallel-master-XFAIL.c:4:22: warning: extra tokens at the end of '#pragma omp parallel' are ignored void test_one() { #pragma omp parallel master { ; } } // CHECK: {{.*}}ast-dump-openmp-parallel-master-XFAIL.c:10:22: warning: extra tokens at the end of '#pragma omp parallel' are ignored // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-parallel-master-XFAIL.c:3:1, line:6:1> line:3:6 test_zero 'void ()' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:18, line:6:1> // CHECK-NEXT: | `-OMPParallelDirective {{.*}} <line:4:9, col:28> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:5:3> // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-NullStmt {{.*}} <col:3> openmp_structured_block // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | `-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-parallel-master-XFAIL.c:4:9) *const restrict' // CHECK-NEXT: `-FunctionDecl {{.*}} <line:9:1, line:12:1> line:9:6 test_one 'void ()' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:17, line:12:1> // CHECK-NEXT: `-OMPParallelDirective {{.*}} <line:10:9, col:28> // CHECK-NEXT: `-CapturedStmt {{.*}} <line:11:3, col:7> // CHECK-NEXT: `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: |-CompoundStmt {{.*}} <col:3, col:7> openmp_structured_block // CHECK-NEXT: | `-NullStmt {{.*}} <col:5> // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: `-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-parallel-master-XFAIL.c:10:9) *const restrict'
alignment.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ /* Original code from the Application Kernel Matrix by Cray */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/time.h> #include <libgen.h> #include "param.h" #include "alignment.h" #include "bots.h" int readseqs(int first_seq, char *filename); int ktup, window, signif; int prot_ktup, prot_window, prot_signif; int gap_pos1, gap_pos2, mat_avscore; int nseqs, max_aa; #define MAX_ALN_LENGTH 5000 int *seqlen_array, def_aa_xref[NUMRES+1]; int *bench_output, *seq_output; double gap_open, gap_extend; double prot_gap_open, prot_gap_extend; double pw_go_penalty, pw_ge_penalty; double prot_pw_go_penalty, prot_pw_ge_penalty; char **args, **names, **seq_array; int matrix[NUMRES][NUMRES]; #define MIN(a,b) ((a)<(b)?(a):(b)) #define tbgap(k) ((k) <= 0 ? 0 : tb + gh * (k)) #define tegap(k) ((k) <= 0 ? 0 : te + gh * (k)) /*********************************************************************** * : **********************************************************************/ void del(int k, int *print_ptr, int *last_print, int *displ) { if (*last_print<0) *last_print = displ[(*print_ptr)-1] -= k; else *last_print = displ[(*print_ptr)++] = -k; } /*********************************************************************** * : **********************************************************************/ void add(int v, int *print_ptr, int *last_print, int *displ) { if (*last_print < 0) { displ[(*print_ptr)-1] = v; displ[(*print_ptr)++] = *last_print; } else { *last_print = displ[(*print_ptr)++] = v; } } /*********************************************************************** * : **********************************************************************/ int calc_score(int iat, int jat, int v1, int v2, int seq1, int seq2) { int i, j, ipos, jpos; ipos = v1 + iat; jpos = v2 + jat; i = seq_array[seq1][ipos]; j = seq_array[seq2][jpos]; return (matrix[i][j]); } /*********************************************************************** * : **********************************************************************/ int get_matrix(int *matptr, int *xref, int scale) { int gg_score = 0; int gr_score = 0; int i, j, k, ti, tj, ix; int av1, av2, av3, min, max, maxres; for (i = 0; i <= max_aa; i++) for (j = 0; j <= max_aa; j++) matrix[i][j] = 0; ix = 0; maxres = 0; for (i = 0; i <= max_aa; i++) { ti = xref[i]; for (j = 0; j <= i; j++) { tj = xref[j]; if ((ti != -1) && (tj != -1)) { k = matptr[ix]; if (ti == tj) { matrix[ti][ti] = k * scale; maxres++; } else { matrix[ti][tj] = k * scale; matrix[tj][ti] = k * scale; } ix++; } } } maxres--; av1 = av2 = av3 = 0; for (i = 0; i <= max_aa; i++) { for (j = 0; j <= i; j++) { av1 += matrix[i][j]; if (i == j) av2 += matrix[i][j]; else av3 += matrix[i][j]; } } av1 /= (maxres*maxres)/2; av2 /= maxres; av3 /= ((double)(maxres*maxres-maxres))/2; mat_avscore = -av3; min = max = matrix[0][0]; for (i = 0; i <= max_aa; i++) for (j = 1; j <= i; j++) { if (matrix[i][j] < min) min = matrix[i][j]; if (matrix[i][j] > max) max = matrix[i][j]; } for (i = 0; i < gap_pos1; i++) { matrix[i][gap_pos1] = gr_score; matrix[gap_pos1][i] = gr_score; matrix[i][gap_pos2] = gr_score; matrix[gap_pos2][i] = gr_score; } matrix[gap_pos1][gap_pos1] = gg_score; matrix[gap_pos2][gap_pos2] = gg_score; matrix[gap_pos2][gap_pos1] = gg_score; matrix[gap_pos1][gap_pos2] = gg_score; maxres += 2; return(maxres); } /*********************************************************************** * : **********************************************************************/ void forward_pass(char *ia, char *ib, int n, int m, int *se1, int *se2, int *maxscore, int g, int gh) { int i, j, f, p, t, hh; int HH[MAX_ALN_LENGTH]; int DD[MAX_ALN_LENGTH]; *maxscore = 0; *se1 = *se2 = 0; for (i = 0; i <= m; i++) {HH[i] = 0; DD[i] = -g;} for (i = 1; i <= n; i++) { hh = p = 0; f = -g; for (j = 1; j <= m; j++) { f -= gh; t = hh - g - gh; if (f < t) f = t; DD[j] -= gh; t = HH[j] - g - gh; if (DD[j] < t) DD[j] = t; hh = p + matrix[(int)ia[i]][(int)ib[j]]; if (hh < f) hh = f; if (hh < DD[j]) hh = DD[j]; if (hh < 0) hh = 0; p = HH[j]; HH[j] = hh; if (hh > *maxscore) {*maxscore = hh; *se1 = i; *se2 = j;} } } } /*********************************************************************** * : **********************************************************************/ void reverse_pass(char *ia, char *ib, int se1, int se2, int *sb1, int *sb2, int maxscore, int g, int gh) { int i, j, f, p, t, hh, cost; int HH[MAX_ALN_LENGTH]; int DD[MAX_ALN_LENGTH]; cost = 0; *sb1 = *sb2 = 1; for (i = se2; i > 0; i--){ HH[i] = -1; DD[i] = -1;} for (i = se1; i > 0; i--) { hh = f = -1; if (i == se1) p = 0; else p = -1; for (j = se2; j > 0; j--) { f -= gh; t = hh - g - gh; if (f < t) f = t; DD[j] -= gh; t = HH[j] - g - gh; if (DD[j] < t) DD[j] = t; hh = p + matrix[(int)ia[i]][(int)ib[j]]; if (hh < f) hh = f; if (hh < DD[j]) hh = DD[j]; p = HH[j]; HH[j] = hh; if (hh > cost) { cost = hh; *sb1 = i; *sb2 = j; if (cost >= maxscore) break; } } if (cost >= maxscore) break; } } /*********************************************************************** * : **********************************************************************/ int diff (int A, int B, int M, int N, int tb, int te, int *print_ptr, int *last_print, int *displ, int seq1, int seq2, int g, int gh) { int i, j, f, e, s, t, hh; int midi, midj, midh, type; int HH[MAX_ALN_LENGTH]; int DD[MAX_ALN_LENGTH]; int RR[MAX_ALN_LENGTH]; int SS[MAX_ALN_LENGTH]; if (N <= 0) {if (M > 0) del(M, print_ptr, last_print, displ); return( - (int) tbgap(M)); } if (M <= 1) { if (M <= 0) {add(N, print_ptr, last_print, displ); return( - (int)tbgap(N));} midh = -(tb+gh) - tegap(N); hh = -(te+gh) - tbgap(N); if (hh > midh) midh = hh; midj = 0; for (j = 1; j <= N; j++) { hh = calc_score(1,j,A,B,seq1,seq2) - tegap(N-j) - tbgap(j-1); if (hh > midh) {midh = hh; midj = j;} } if (midj == 0) { del(1, print_ptr, last_print, displ); add(N, print_ptr, last_print, displ); } else { if (midj > 1) add(midj-1, print_ptr, last_print, displ); displ[(*print_ptr)++] = *last_print = 0; if (midj < N) add(N-midj, print_ptr, last_print, displ); } return midh; } midi = M / 2; HH[0] = 0.0; t = -tb; for (j = 1; j <= N; j++) { HH[j] = t = t - gh; DD[j] = t - g; } t = -tb; for (i = 1; i <= midi; i++) { s = HH[0]; HH[0] = hh = t = t - gh; f = t - g; for (j = 1; j <= N; j++) { if ((hh = hh - g - gh) > (f = f - gh)) f = hh; if ((hh = HH[j] - g - gh) > (e = DD[j]- gh)) e = hh; hh = s + calc_score(i,j,A,B,seq1,seq2); if (f > hh) hh = f; if (e > hh) hh = e; s = HH[j]; HH[j] = hh; DD[j] = e; } } DD[0] = HH[0]; RR[N] = 0; t = -te; for (j = N-1; j >= 0; j--) {RR[j] = t = t - gh; SS[j] = t - g;} t = -te; for (i = M - 1; i >= midi; i--) { s = RR[N]; RR[N] = hh = t = t-gh; f = t - g; for (j = N - 1; j >= 0; j--) { if ((hh = hh - g - gh) > (f = f - gh)) f = hh; if ((hh = RR[j] - g - gh) > (e = SS[j] - gh)) e = hh; hh = s + calc_score(i+1,j+1,A,B,seq1,seq2); if (f > hh) hh = f; if (e > hh) hh = e; s = RR[j]; RR[j] = hh; SS[j] = e; } } SS[N] = RR[N]; midh = HH[0] + RR[0]; midj = 0; type = 1; for (j = 0; j <= N; j++) { hh = HH[j] + RR[j]; if (hh >= midh) if (hh > midh || (HH[j] != DD[j] && RR[j] == SS[j])) {midh = hh; midj = j;} } for (j = N; j >= 0; j--) { hh = DD[j] + SS[j] + g; if (hh > midh) {midh = hh;midj = j;type = 2;} } if (type == 1) { diff(A, B, midi, midj, tb, g, print_ptr, last_print, displ, seq1, seq2, g, gh); diff(A+midi, B+midj, M-midi, N-midj, g, te, print_ptr, last_print, displ, seq1, seq2, g, gh); } else { diff(A, B, midi-1, midj, tb, 0.0, print_ptr, last_print, displ, seq1, seq2, g, gh); del(2, print_ptr, last_print, displ); diff(A+midi+1, B+midj, M-midi-1, N-midj, 0.0, te, print_ptr, last_print, displ, seq1, seq2, g, gh); } return midh; } /*********************************************************************** * : **********************************************************************/ double tracepath(int tsb1, int tsb2, int *print_ptr, int *last_print, int *displ, int seq1, int seq2) { int i, k; int i1 = tsb1; int i2 = tsb2; int pos = 0; int count = 0; for (i = 1; i <= *print_ptr - 1; ++i) { if (displ[i]==0) { char c1 = seq_array[seq1][i1]; char c2 = seq_array[seq2][i2]; if ((c1!=gap_pos1) && (c1 != gap_pos2) && (c1 == c2)) count++; ++i1; ++i2; ++pos; } else if ((k = displ[i]) > 0) { i2 += k; pos += k; } else { i1 -= k; pos -= k; } } return (100.0 * (double) count); } int pairalign(int istart, int iend, int jstart, int jend) { int i, n, m, si, sj; int len1, len2, maxres; double gg, mm_score; int *mat_xref, *matptr; matptr = gon250mt; mat_xref = def_aa_xref; maxres = get_matrix(matptr, mat_xref, 10); if (maxres == 0) return(-1); bots_message("Start aligning "); #pragma omp parallel { #pragma omp for schedule(dynamic) private(i,n,si,sj,len1,m) for (si = 0; si < nseqs; si++) { if ((n = seqlen_array[si+1]) != 0){ for (i = 1, len1 = 0; i <= n; i++) { char c = seq_array[si+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len1++; } for (sj = si + 1; sj < nseqs; sj++) { if ((m = seqlen_array[sj+1]) != 0) { #pragma omp task untied \ private(i,gg,len2,mm_score) firstprivate(m,n,si,sj,len1) \ shared(nseqs, bench_output,seqlen_array,seq_array,gap_pos1,gap_pos2,pw_ge_penalty,pw_go_penalty,mat_avscore) { int se1, se2, sb1, sb2, maxscore, seq1, seq2, g, gh; int displ[2*MAX_ALN_LENGTH+1]; int print_ptr, last_print; for (i = 1, len2 = 0; i <= m; i++) { char c = seq_array[sj+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len2++; } gh = 10 * pw_ge_penalty; gg = pw_go_penalty + log((double) MIN(n, m)); g = (mat_avscore <= 0) ? 20 * gg : 2 * mat_avscore * gg; seq1 = si + 1; seq2 = sj + 1; forward_pass(&seq_array[seq1][0], &seq_array[seq2][0], n, m, &se1, &se2, &maxscore, g, gh); reverse_pass(&seq_array[seq1][0], &seq_array[seq2][0], se1, se2, &sb1, &sb2, maxscore, g, gh); print_ptr = 1; last_print = 0; diff(sb1-1, sb2-1, se1-sb1+1, se2-sb2+1, 0, 0, &print_ptr, &last_print, displ, seq1, seq2, g, gh); mm_score = tracepath(sb1, sb2, &print_ptr, &last_print, displ, seq1, seq2); if (len1 == 0 || len2 == 0) mm_score = 0.0; else mm_score /= (double) MIN(len1,len2); bench_output[si*nseqs+sj] = mm_score; } } } } } } bots_message(" completed!\n"); return 0; } int pairalign_seq(int istart, int iend, int jstart, int jend) { int i, n, m, si, sj; int len1, len2, maxres; double gg, mm_score; int *mat_xref, *matptr; matptr = gon250mt; mat_xref = def_aa_xref; maxres = get_matrix(matptr, mat_xref, 10); if (maxres == 0) return(-1); for (si = 0; si < nseqs; si++) { if ((n = seqlen_array[si+1]) != 0){ for (i = 1, len1 = 0; i <= n; i++) { char c = seq_array[si+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len1++; } for (sj = si + 1; sj < nseqs; sj++) { if ((m = seqlen_array[sj+1]) != 0){ int se1, se2, sb1, sb2, maxscore, seq1, seq2, g, gh; int displ[2*MAX_ALN_LENGTH+1]; int print_ptr, last_print; for (i = 1, len2 = 0; i <= m; i++) { char c = seq_array[sj+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len2++; } gh = 10 * pw_ge_penalty; gg = pw_go_penalty + log((double) MIN(n, m)); g = (mat_avscore <= 0) ? 20 * gg : 2 * mat_avscore * gg; seq1 = si + 1; seq2 = sj + 1; forward_pass(&seq_array[seq1][0], &seq_array[seq2][0], n, m, &se1, &se2, &maxscore, g, gh); reverse_pass(&seq_array[seq1][0], &seq_array[seq2][0], se1, se2, &sb1, &sb2, maxscore, g, gh); print_ptr = 1; last_print = 0; diff(sb1-1, sb2-1, se1-sb1+1, se2-sb2+1, 0, 0, &print_ptr, &last_print, displ, seq1, seq2, g, gh); mm_score = tracepath(sb1, sb2, &print_ptr, &last_print, displ, seq1, seq2); if (len1 == 0 || len2 == 0) mm_score = 0.0; else mm_score /= (double) MIN(len1,len2); seq_output[si*nseqs+sj] = mm_score; } } } } return 0; } /*********************************************************************** * : **********************************************************************/ void init_matrix(void) { int i, j; char c1, c2; gap_pos1 = NUMRES - 2; gap_pos2 = NUMRES - 1; max_aa = strlen(amino_acid_codes) - 2; for (i = 0; i < NUMRES; i++) def_aa_xref[i] = -1; for (i = 0; (c1 = amino_acid_order[i]); i++) for (j = 0; (c2 = amino_acid_codes[j]); j++) if (c1 == c2) {def_aa_xref[i] = j; break;} } void pairalign_init (char *filename) { int i; if (!filename || !filename[0]) { bots_error(0, "Please specify an input file with the -f option\n"); } init_matrix(); nseqs = readseqs(1,filename); bots_message("Multiple Pairwise Alignment (%d sequences)\n",nseqs); for (i = 1; i <= nseqs; i++) bots_debug("Sequence %d: %s %6.d aa\n", i, names[i], seqlen_array[i]); ktup = 1; window = 5; signif = 5; gap_open = 10.0; gap_extend = 0.2; pw_go_penalty = 10.0; pw_ge_penalty = 0.1; } void align_init () { int i,j; bench_output = (int *) malloc(sizeof(int)*nseqs*nseqs); for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) bench_output[i*nseqs+j] = 0; } void align() { pairalign(0, nseqs,0, nseqs); } void align_seq_init () { int i,j; seq_output = (int *) malloc(sizeof(int)*nseqs*nseqs); bench_output = (int *) malloc(sizeof(int)*nseqs*nseqs); for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) seq_output[i*nseqs+j] = 0; } void align_seq() { pairalign_seq(0, nseqs,0, nseqs); } void align_end () { int i,j; for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) if (bench_output[i*nseqs+j] != 0) bots_debug("Benchmark sequences (%d:%d) Aligned. Score: %d\n", i+1 , j+1 , (int) bench_output[i*nseqs+j]); } int align_verify () { int i,j; int result = BOTS_RESULT_SUCCESSFUL; for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) if (bench_output[i*nseqs+j] != seq_output[i*nseqs+j]) { bots_message("Error: Optimized prot. (%3d:%3d)=%5d Sequential prot. (%3d:%3d)=%5d\n", i+1, j+1, (int) bench_output[i*nseqs+j], i+1, j+1, (int) seq_output[i*nseqs+j]); result = BOTS_RESULT_UNSUCCESSFUL; } return result; }
fibo_para_1.c
//fibo_para_1.c #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <stdint.h> #include <windows.h> double fibo_pd( int n , double a[]) { long double i,j; if ( a[n] == 0 ){ #pragma omp task shared( i ) firstprivate ( n ) i = fibo_pd(n - 1, a ); #pragma omp task shared( j ) firstprivate ( n ) j = fibo_pd(n - 2, a ); #pragma omp taskwait a[n] = i + j; } return a[n]; } int main(int argc, char** argv ) { unsigned n = atoi(argv[1]); double a[n]; for (size_t i = 0; i < n; i++) { a[i] = 0; } a[0] = 1; a[1] = 1; double res; LARGE_INTEGER frequency; LARGE_INTEGER start; LARGE_INTEGER end; double interval; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&start); #pragma omp parallel default ( none ) shared(res, a, n) num_threads( 4 ) { #pragma omp single res = fibo_pd( n - 1 , a ); } QueryPerformanceCounter(&end); interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart; printf("Tiempo: %f\n", interval); printf("%.0Lf\n",res); }
target_data_at_exit.c
// RUN: %libomptarget-compile-generic -fopenmp-version=51 // RUN: %libomptarget-run-generic 2>&1 \ // RUN: | %fcheck-generic #include <stdio.h> int main() { int i; #pragma omp target enter data map(alloc:i) // i isn't present at the end of the target data region, but the "present" // modifier is only checked at the beginning of a region. #pragma omp target data map(present, alloc: i) { #pragma omp target exit data map(delete:i) } // CHECK-NOT: Libomptarget // CHECK: success // CHECK-NOT: Libomptarget fprintf(stderr, "success\n"); return 0; }
GB_unop__tan_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__tan_fc64_fc64) // op(A') function: GB (_unop_tran__tan_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = ctan (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ctan (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = ctan (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TAN || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__tan_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = ctan (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = ctan (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__tan_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_bool_bool.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__(none)) // op(A') function: GB (_unop_tran__identity_bool_bool) // C type: bool // A type: bool // cast: bool cij = aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ bool z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ bool z = aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ #if 0 GrB_Info GB (_unop_apply__(none)) ( bool *Cx, // Cx and Ax may be aliased const bool *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { bool aij = Ax [p] ; bool 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 ; bool aij = Ax [p] ; bool z = aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_bool_bool) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
FullyDistVec.h
/****************************************************************/ /* Parallel Combinatorial BLAS Library (for Graph Computations) */ /* version 1.6 -------------------------------------------------*/ /* date: 6/15/2017 ---------------------------------------------*/ /* authors: Ariful Azad, Aydin Buluc --------------------------*/ /****************************************************************/ /* Copyright (c) 2010-2017, The Regents of the University of California 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 _FULLY_DIST_VEC_H_ #define _FULLY_DIST_VEC_H_ #include <iostream> #include <fstream> #include <vector> #include <utility> #include <iterator> #include <random> #include "CombBLAS.h" #include "CommGrid.h" #include "FullyDist.h" #include "Exception.h" namespace combblas { template <class IT, class NT> class FullyDistSpVec; template <class IT, class NT, class DER> class SpParMat; template <class IT> class DistEdgeList; template <class IU, class NU> class DenseVectorLocalIterator; // ABAB: As opposed to SpParMat, IT here is used to encode global size and global indices; // therefore it can not be 32-bits, in general. template <class IT, class NT> class FullyDistVec: public FullyDist<IT,NT, typename combblas::disable_if< combblas::is_boolean<NT>::value, NT >::type > { public: FullyDistVec ( ); FullyDistVec ( IT globallen, NT initval); FullyDistVec ( std::shared_ptr<CommGrid> grid); FullyDistVec ( std::shared_ptr<CommGrid> grid, IT globallen, NT initval); FullyDistVec ( const FullyDistSpVec<IT, NT> & rhs ); // Sparse -> Dense conversion constructor FullyDistVec ( const std::vector<NT> & fillarr, std::shared_ptr<CommGrid> grid ); // initialize a FullyDistVec with a vector of length n/p from each processor template <class ITRHS, class NTRHS> FullyDistVec ( const FullyDistVec<ITRHS, NTRHS>& rhs ); // type converter constructor class ScalarReadSaveHandler { public: NT getNoNum(IT index) { return static_cast<NT>(1); } template <typename c, typename t> NT read(std::basic_istream<c,t>& is, IT index) { NT v; is >> v; return v; } template <typename c, typename t> void save(std::basic_ostream<c,t>& os, const NT& v, IT index) { os << v; } }; template <class HANDLER> void ParallelWrite(const std::string & filename, bool onebased, HANDLER handler, bool includeindices = true) { FullyDistSpVec<IT,NT> tmpSpVec = *this; // delegate tmpSpVec.ParallelWrite(filename, onebased, handler, includeindices); } void ParallelWrite(const std::string & filename, bool onebased, bool includeindices = true) { ParallelWrite(filename, onebased, ScalarReadSaveHandler(), includeindices); }; template <typename _BinaryOperation> void ParallelRead (const std::string & filename, bool onebased, _BinaryOperation BinOp) { FullyDistSpVec<IT,NT> tmpSpVec = *this; // delegate tmpSpVec.ParallelRead(filename, onebased, BinOp); *this = tmpSpVec; // sparse -> dense conversion } template <class HANDLER> std::ifstream& ReadDistribute (std::ifstream& infile, int master, HANDLER handler); std::ifstream& ReadDistribute (std::ifstream& infile, int master) { return ReadDistribute(infile, master, ScalarReadSaveHandler()); } template <class HANDLER> void SaveGathered(std::ofstream& outfile, int master, HANDLER handler, bool printProcSplits = false); void SaveGathered(std::ofstream& outfile, int master) { SaveGathered(outfile, master, ScalarReadSaveHandler(), false); } template <class ITRHS, class NTRHS> FullyDistVec<IT,NT> & operator=(const FullyDistVec< ITRHS,NTRHS > & rhs); // assignment with type conversion FullyDistVec<IT,NT> & operator=(const FullyDistVec<IT,NT> & rhs); //!< Actual assignment operator FullyDistVec<IT,NT> & operator=(const FullyDistSpVec<IT,NT> & rhs); //!< FullyDistSpVec->FullyDistVec conversion operator FullyDistVec<IT,NT> & operator=(NT fixedval) // assign fixed value { #ifdef _OPENMP #pragma omp parallel for #endif for(IT i=0; i < arr.size(); ++i) arr[i] = fixedval; return *this; } FullyDistVec<IT,NT> operator() (const FullyDistVec<IT,IT> & ri) const; //<! subsref FullyDistVec<IT,NT> & operator+=(const FullyDistSpVec<IT,NT> & rhs); FullyDistVec<IT,NT> & operator+=(const FullyDistVec<IT,NT> & rhs); FullyDistVec<IT,NT> & operator-=(const FullyDistSpVec<IT,NT> & rhs); FullyDistVec<IT,NT> & operator-=(const FullyDistVec<IT,NT> & rhs); bool operator==(const FullyDistVec<IT,NT> & rhs) const; void SetElement (IT indx, NT numx); // element-wise assignment void SetLocalElement(IT index, NT value) { arr[index] = value; }; // no checks, local index NT GetElement (IT indx) const; // element-wise fetch NT operator[](IT indx) const // more c++ like API { return GetElement(indx); } void Set(const FullyDistSpVec< IT,NT > & rhs); template <class NT1, typename _BinaryOperationIdx, typename _BinaryOperationVal> void GSet (const FullyDistSpVec<IT,NT1> & spVec, _BinaryOperationIdx __binopIdx, _BinaryOperationVal __binopVal, MPI_Win win); template <class NT1, typename _BinaryOperationIdx> FullyDistSpVec<IT,NT> GGet (const FullyDistSpVec<IT,NT1> & spVec, _BinaryOperationIdx __binopIdx, NT nullValue); void iota(IT globalsize, NT first); void RandPerm(); // randomly permute the vector FullyDistVec<IT,IT> sort(); // sort and return the permutation using FullyDist<IT,NT,typename combblas::disable_if< combblas::is_boolean<NT>::value, NT >::type>::LengthUntil; using FullyDist<IT,NT,typename combblas::disable_if< combblas::is_boolean<NT>::value, NT >::type>::TotalLength; using FullyDist<IT,NT,typename combblas::disable_if< combblas::is_boolean<NT>::value, NT >::type>::Owner; using FullyDist<IT,NT,typename combblas::disable_if< combblas::is_boolean<NT>::value, NT >::type>::MyLocLength; IT LocArrSize() const { return arr.size(); } // = MyLocLength() once arr is resized //TODO: we should change this function and return the vector directly const NT * GetLocArr() const { return arr.data(); } // = MyLocLength() once arr is resized template <typename _Predicate> FullyDistSpVec<IT,NT> Find(_Predicate pred) const; //!< Return the elements for which pred is true FullyDistSpVec<IT,NT> Find(NT val) const; //!< Return the elements val is found template <typename _Predicate> FullyDistVec<IT,IT> FindInds(_Predicate pred) const; //!< Return the indices where pred is true template <typename _Predicate> IT Count(_Predicate pred) const; //!< Return the number of elements for which pred is true template <typename _UnaryOperation> void Apply(_UnaryOperation __unary_op) { std::transform(arr.begin(), arr.end(), arr.begin(), __unary_op); } template <typename _BinaryOperation> void ApplyInd(_BinaryOperation __binary_op) { IT offset = LengthUntil(); #ifdef _OPENMP #pragma omp parallel for #endif for(size_t i=0; i < arr.size(); ++i) arr[i] = __binary_op(arr[i], i + offset); } template <typename _UnaryOperation, typename IRRELEVANT_NT> void Apply(_UnaryOperation __unary_op, const FullyDistSpVec<IT,IRRELEVANT_NT>& mask); // extended callback versions template <typename _BinaryOperation, typename _BinaryPredicate, class NT2> void EWiseApply(const FullyDistVec<IT,NT2> & other, _BinaryOperation __binary_op, _BinaryPredicate _do_op, const bool useExtendedBinOp); template <typename _BinaryOperation, typename _BinaryPredicate, class NT2> void EWiseApply(const FullyDistSpVec<IT,NT2> & other, _BinaryOperation __binary_op, _BinaryPredicate _do_op, bool applyNulls, NT2 nullValue, const bool useExtendedBinOp); // plain fallback versions template <typename _BinaryOperation, typename _BinaryPredicate, class NT2> void EWiseApply(const FullyDistVec<IT,NT2> & other, _BinaryOperation __binary_op, _BinaryPredicate _do_op) { EWiseApply(other, EWiseExtToPlainAdapter<NT, NT, NT2, _BinaryOperation>(__binary_op), EWiseExtToPlainAdapter<bool, NT, NT2, _BinaryPredicate>(_do_op), true); } template <typename _BinaryOperation, typename _BinaryPredicate, class NT2> void EWiseApply(const FullyDistSpVec<IT,NT2> & other, _BinaryOperation __binary_op, _BinaryPredicate _do_op, bool applyNulls, NT2 nullValue) { EWiseApply(other, EWiseExtToPlainAdapter<NT, NT, NT2, _BinaryOperation>(__binary_op), EWiseExtToPlainAdapter<bool, NT, NT2, _BinaryPredicate>(_do_op), applyNulls, nullValue, true); } template <typename T1, typename T2> class retTrue { public: bool operator()(const T1& x, const T2& y) { return true; } }; template <typename _BinaryOperation, class NT2> void EWiseApply(const FullyDistVec<IT,NT2> & other, _BinaryOperation __binary_op) { this->EWiseApply(other, __binary_op, retTrue<NT, NT2>()); } template <typename _BinaryOperation, class NT2> void EWiseApply(const FullyDistSpVec<IT,NT2> & other, _BinaryOperation __binary_op, bool applyNulls, NT2 nullValue) { this->EWiseApply(other, __binary_op, retTrue<NT, NT2>(), applyNulls, nullValue); } void PrintToFile(std::string prefix) { std::ofstream output; commGrid->OpenDebugFile(prefix, output); std::copy(arr.begin(), arr.end(), std::ostream_iterator<NT> (output, " ")); output << std::endl; output.close(); } void PrintInfo(std::string vectorname) const; void DebugPrint(); std::shared_ptr<CommGrid> getcommgrid() const { return commGrid; } std::pair<IT, NT> MinElement() const; // returns <index, value> pair of global minimum template <typename _BinaryOperation> NT Reduce(_BinaryOperation __binary_op, NT identity) const; //! Reduce can be used to implement max_element, for instance template <typename OUT, typename _BinaryOperation, typename _UnaryOperation> OUT Reduce(_BinaryOperation __binary_op, OUT default_val, _UnaryOperation __unary_op) const; void SelectCandidates(double nver); template <typename _BinaryOperation, typename OUT = typename std::result_of<_BinaryOperation&(NT,NT)>::type> void EWiseOut(const FullyDistVec<IT,NT> & rhs, _BinaryOperation __binary_op, FullyDistVec<IT,OUT> & result); using FullyDist<IT,NT,typename combblas::disable_if< combblas::is_boolean<NT>::value, NT >::type>::glen; using FullyDist<IT,NT,typename combblas::disable_if< combblas::is_boolean<NT>::value, NT >::type>::commGrid; private: std::vector< NT > arr; template <typename _BinaryOperation> void EWise(const FullyDistVec<IT,NT> & rhs, _BinaryOperation __binary_op); template <class IU, class NU> friend class DenseParMat; template <class IU, class NU, class UDER> friend class SpParMat; template <class IU, class NU> friend class FullyDistVec; template <class IU, class NU> friend class FullyDistSpVec; template <class IU, class NU> friend class DenseVectorLocalIterator; template <typename SR, typename IU, typename NUM, typename NUV, typename UDER> friend FullyDistVec<IU,typename promote_trait<NUM,NUV>::T_promote> SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistVec<IU,NUV> & x ); template <typename IU, typename NU1, typename NU2> friend FullyDistSpVec<IU,typename promote_trait<NU1,NU2>::T_promote> EWiseMult (const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , bool exclude, NU2 zero); template <typename IU, typename NU1, typename NU2, typename _BinaryOperation> friend FullyDistSpVec<IU,typename promote_trait<NU1,NU2>::T_promote> EWiseApply (const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , _BinaryOperation _binary_op, typename promote_trait<NU1,NU2>::T_promote zero); template <typename RET, typename IU, typename NU1, typename NU2, typename _BinaryOperation, typename _BinaryPredicate> friend FullyDistSpVec<IU,RET> EWiseApply (const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , _BinaryOperation _binary_op, _BinaryPredicate _doOp, bool allowVNulls, NU1 Vzero, const bool useExtendedBinOp); template <typename RET, typename IU, typename NU1, typename NU2, typename _BinaryOperation, typename _BinaryPredicate> friend FullyDistSpVec<IU,RET> EWiseApply_threaded (const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , _BinaryOperation _binary_op, _BinaryPredicate _doOp, bool allowVNulls, NU1 Vzero, const bool useExtendedBinOp); template <typename IU> friend void RenameVertices(DistEdgeList<IU> & DEL); template <typename IU, typename NU> friend FullyDistVec<IU,NU> Concatenate ( std::vector< FullyDistVec<IU,NU> > & vecs); template <typename IU, typename NU> friend void Augment (FullyDistVec<int64_t, int64_t>& mateRow2Col, FullyDistVec<int64_t, int64_t>& mateCol2Row, FullyDistVec<int64_t, int64_t>& parentsRow, FullyDistVec<int64_t, int64_t>& leaves); template <class IU, class DER> friend SpParMat<IU, bool, DER> PermMat (const FullyDistVec<IU,IU> & ri, const IU ncol); friend void maximumMatching(SpParMat < int64_t, bool, SpDCCols<int64_t,bool> > & A, FullyDistVec<int64_t, int64_t>& mateRow2Col,FullyDistVec<int64_t, int64_t>& mateCol2Row); }; } #include "FullyDistVec.cpp" #endif
compiler_cgen.c
/* Generated by Nim Compiler v0.15.0 */ /* (c) 2016 Andreas Rumpf */ /* The generated code is subject to the original license. */ #define NIM_INTBITS 64 #include "nimbase.h" #include <string.h> typedef struct Tcgen530027 Tcgen530027; typedef struct TNimType TNimType; typedef struct TNimNode TNimNode; typedef struct Ropeobj179006 Ropeobj179006; typedef struct NimStringDesc NimStringDesc; typedef struct TGenericSeq TGenericSeq; typedef struct Cell47305 Cell47305; typedef struct Cellseq47321 Cellseq47321; typedef struct Gcheap49818 Gcheap49818; typedef struct Gcstack49816 Gcstack49816; typedef struct Memregion29486 Memregion29486; typedef struct Smallchunk29440 Smallchunk29440; typedef struct Llchunk29480 Llchunk29480; typedef struct Bigchunk29442 Bigchunk29442; typedef struct Intset29414 Intset29414; typedef struct Trunk29410 Trunk29410; typedef struct Avlnode29484 Avlnode29484; typedef struct Gcstat49814 Gcstat49814; typedef struct Cellset47317 Cellset47317; typedef struct Pagedesc47313 Pagedesc47313; typedef struct Ttypeseq293836 Ttypeseq293836; typedef struct Ttype293840 Ttype293840; typedef struct Intset269030 Intset269030; typedef struct Trunk269026 Trunk269026; typedef struct Trunkseq269028 Trunkseq269028; typedef struct Tpasscontext342002 Tpasscontext342002; typedef struct Tsym293834 Tsym293834; typedef struct Tidobj200004 Tidobj200004; typedef struct TNimObject TNimObject; typedef struct TY293929 TY293929; typedef struct Tstrtable293806 Tstrtable293806; typedef struct Tsymseq293804 Tsymseq293804; typedef struct Tident200010 Tident200010; typedef struct Tlineinfo192336 Tlineinfo192336; typedef struct Tnode293802 Tnode293802; typedef struct Tloc293816 Tloc293816; typedef struct Tlib293820 Tlib293820; typedef struct TY530153 TY530153; typedef struct TY204018 TY204018; typedef struct Tidtable293850 Tidtable293850; typedef struct Tidpairseq293848 Tidpairseq293848; typedef struct Tlinkedlist147013 Tlinkedlist147013; typedef struct Tlistentry147007 Tlistentry147007; typedef struct Tcproc530021 Tcproc530021; typedef struct Tnodetable293862 Tnodetable293862; typedef struct Tnodepairseq293860 Tnodepairseq293860; typedef struct Debuginfo204009 Debuginfo204009; typedef struct TY204021 TY204021; typedef struct TY204023 TY204023; typedef struct Tnodeseq293796 Tnodeseq293796; typedef struct TY192350 TY192350; typedef struct TY530095 TY530095; typedef struct Trodreader333021 Trodreader333021; typedef struct TY293960 TY293960; typedef struct TY204017 TY204017; typedef struct Enumdesc204007 Enumdesc204007; typedef struct Tinfocc274008 Tinfocc274008; typedef struct Tblock530019 Tblock530019; typedef struct Ttraversalclosure538019 Ttraversalclosure538019; typedef struct TY135002 TY135002; typedef struct Tbitset340004 Tbitset340004; typedef struct TY192612 TY192612; typedef struct Tfileinfo192334 Tfileinfo192334; typedef struct Tinfoos177035 Tinfoos177035; typedef struct Tinfocpu177476 Tinfocpu177476; typedef struct Tstrentry147009 Tstrentry147009; typedef struct TY128506 TY128506; typedef struct Basechunk29438 Basechunk29438; typedef struct Freecell29430 Freecell29430; typedef struct Tinstantiation293824 Tinstantiation293824; typedef struct Tidpair293846 Tidpair293846; typedef struct Tnodepair293858 Tnodepair293858; typedef struct Filenamemapping204005 Filenamemapping204005; typedef struct TY333033 TY333033; typedef struct Tindex333019 Tindex333019; typedef struct Tiitable300142 Tiitable300142; typedef struct Tiipairseq300140 Tiipairseq300140; typedef struct Table333054 Table333054; typedef struct Keyvaluepairseq333057 Keyvaluepairseq333057; typedef struct Memfile331202 Memfile331202; typedef struct TY293961 TY293961; typedef struct Tiipair300138 Tiipair300138; typedef struct Keyvaluepair333060 Keyvaluepair333060; typedef NU8 Tnimkind3403; typedef NU8 Tnimtypeflag3409Set; typedef N_NIMCALL_PTR(void, TY3489) (void* p0, NI op0); typedef N_NIMCALL_PTR(void*, TY3494) (void* p0); struct TNimType { NI size; Tnimkind3403 kind; Tnimtypeflag3409Set flags; TNimType* base; TNimNode* node; void* finalizer; TY3489 marker; TY3494 deepcopy; }; typedef NU8 Tnimnodekind3405; struct TNimNode { Tnimnodekind3405 kind; NI offset; TNimType* typ; NCSTRING name; NI len; TNimNode** sons; }; typedef N_NIMCALL_PTR(void, Globalmarkerproc55802) (void); struct TGenericSeq { NI len; NI reserved; }; struct NimStringDesc { TGenericSeq Sup; NIM_CHAR data[SEQ_DECL_SIZE]; }; struct Cell47305 { NI refcount; TNimType* typ; }; struct Cellseq47321 { NI len; NI cap; Cell47305** d; }; typedef Smallchunk29440* TY29501[512]; typedef Trunk29410* Trunkbuckets29412[256]; struct Intset29414 { Trunkbuckets29412 data; }; struct Memregion29486 { NI minlargeobj; NI maxlargeobj; TY29501 freesmallchunks; Llchunk29480* llmem; NI currmem; NI maxmem; NI freemem; NI lastsize; Bigchunk29442* freechunkslist; Intset29414 chunkstarts; Avlnode29484* root; Avlnode29484* deleted; Avlnode29484* last; Avlnode29484* freeavlnodes; NIM_BOOL locked; }; struct Gcstat49814 { NI stackscans; NI cyclecollections; NI maxthreshold; NI maxstacksize; NI maxstackcells; NI cycletablesize; NI64 maxpause; }; struct Cellset47317 { NI counter; NI max; Pagedesc47313* head; Pagedesc47313** data; }; struct Gcheap49818 { Gcstack49816* stack; void* stackbottom; NI cyclethreshold; Cellseq47321 zct; Cellseq47321 decstack; Cellseq47321 tempstack; NI recgclock; Memregion29486 region; Gcstat49814 stat; Cellset47317 marked; Cellseq47321 additionalroots; }; struct Intset269030 { NI counter; NI max; Trunk269026* head; Trunkseq269028* data; }; struct TNimObject { TNimType* m_type; }; struct Tidobj200004 { TNimObject Sup; NI id; }; typedef NU8 Tsymkind293435; struct Tstrtable293806 { NI counter; Tsymseq293804* data; }; typedef NU16 Tmagic293524; struct Tlineinfo192336 { NI16 line; NI16 col; NI32 fileindex; }; typedef NU32 Tsymflag293184Set; typedef NU32 Toption170009Set; typedef NU8 Tlockind293808; typedef NU8 Tstorageloc293812; typedef NU16 Tlocflag293810Set; struct Tloc293816 { Tlockind293808 k; Tstorageloc293812 s; Tlocflag293810Set flags; Ttype293840* t; Ropeobj179006* r; }; struct Tsym293834 { Tidobj200004 Sup; Tsymkind293435 kind; union{ struct {Ttypeseq293836* typeinstcache; } S1; struct {TY293929* procinstcache; Tsym293834* gcunsafetyreason; } S2; struct {TY293929* usedgenerics; Tstrtable293806 tab; } S3; struct {Tsym293834* guard; NI bitsize; } S4; } kindU; Tmagic293524 magic; Ttype293840* typ; Tident200010* name; Tlineinfo192336 info; Tsym293834* owner; Tsymflag293184Set flags; Tnode293802* ast; Toption170009Set options; NI position; NI offset; Tloc293816 loc; Tlib293820* annex; Tnode293802* constraint; }; struct TY204018 { NimStringDesc* Field0; NI Field1; }; struct Tpasscontext342002 { TNimObject Sup; NIM_BOOL fromcache; }; typedef Ropeobj179006* Tcfilesections530009[18]; typedef NU8 Codegenflag530025Set; struct Tidtable293850 { NI counter; Tidpairseq293848* data; }; struct Tlinkedlist147013 { Tlistentry147007* head; Tlistentry147007* tail; NI counter; }; struct Tnodetable293862 { NI counter; Tnodepairseq293860* data; }; typedef Ropeobj179006* TY530136[10]; struct Tcgen530027 { Tpasscontext342002 Sup; Tcfilesections530009 s; Codegenflag530025Set flags; Tsym293834* module; NimStringDesc* filename; NimStringDesc* cfilename; Ropeobj179006* tmpbase; Tidtable293850 typecache; Tidtable293850 forwtypecache; Intset269030 declaredthings; Intset269030 declaredprotos; Tlinkedlist147013 headerfiles; Intset269030 typeinfomarker; Tcproc530021* initproc; Tcproc530021* postinitproc; Tcproc530021* preinitproc; Ttypeseq293836* typestack; Tnodetable293862 datacache; Tsymseq293804* forwardedprocs; NI typenodes; NI nimtypes; Ropeobj179006* typenodesname; Ropeobj179006* nimtypesname; NI labels; TY530136 extensionloaders; Ropeobj179006* injectstmt; }; struct Debuginfo204009 { NI version; TY204021* files; TY204023* enums; NIM_BOOL conflicts; }; struct Tident200010 { Tidobj200004 Sup; NimStringDesc* s; Tident200010* next; NI h; }; struct Tcproc530021 { Tsym293834* prc; NIM_BOOL beforeretneeded; NIM_BOOL threadvaraccessed; Tlineinfo192336 lastlineinfo; Tnodeseq293796* nestedtrystmts; NI inexceptblock; TY192350* finallysafepoints; NI labels; TY530095* blocks; NI breakidx; Toption170009Set options; NI maxframelen; Tcgen530027* module; NI withinloop; NI splitdecls; NI gcframeid; Ropeobj179006* gcframetype; }; typedef NU8 Tsymflag293184; typedef NU8 Codegenflag530025; typedef NU8 Toption170009; typedef NU64 Tglobaloption170013Set; typedef NU8 Tglobaloption170013; typedef NU8 Tcommands170076; typedef NU16 Tnodeflag293427Set; typedef NU8 Tnodekind293020; struct Tnode293802 { Ttype293840* typ; Tlineinfo192336 info; Tnodeflag293427Set flags; Tnodekind293020 kind; union{ struct {NI64 intval; } S1; struct {NF floatval; } S2; struct {NimStringDesc* strval; } S3; struct {Tsym293834* sym; } S4; struct {Tident200010* ident; } S5; struct {Tnodeseq293796* sons; } S6; } kindU; NimStringDesc* comment; }; typedef Ropeobj179006* TY534289[1]; typedef NU8 Tlocflag293810; struct Tlistentry147007 { TNimObject Sup; Tlistentry147007* prev; Tlistentry147007* next; }; typedef NU8 Tlibkind293818; struct Tlib293820 { Tlistentry147007 Sup; Tlibkind293818 kind; NIM_BOOL generated; NIM_BOOL isoverriden; Ropeobj179006* name; Tnode293802* path; }; typedef NU8 Tcfilesection530005; typedef NU8 Ttypekind293244; typedef NU8 Tcallingconvention293002; typedef NU32 Ttypeflag293431Set; struct Ttype293840 { Tidobj200004 Sup; Ttypekind293244 kind; Tcallingconvention293002 callconv; Ttypeflag293431Set flags; Ttypeseq293836* sons; Tnode293802* n; Tsym293834* owner; Tsym293834* sym; Tsym293834* destructor; Tsym293834* deepcopy; Tsym293834* assignment; TY293960* methods; NI64 size; NI16 align; NI16 locklevel; Tloc293816 loc; }; typedef Ropeobj179006* TY533811[2]; typedef NU8 Tctypekind530007; typedef NU64 Ttypekind293244Set; typedef NU8 Ttypeflag293431; typedef NimStringDesc* TY534943[14]; typedef NU8 Tprefereddesc321011; typedef Ropeobj179006* TY179507[1]; struct Enumdesc204007 { NI size; NU32 owner; NI id; NimStringDesc* name; TY204017* values; }; typedef Ropeobj179006* TY536235[4]; typedef NimStringDesc* TY293016[10]; typedef Ropeobj179006* TY536238[3]; struct Ropeobj179006 { TNimObject Sup; Ropeobj179006* left; Ropeobj179006* right; NI length; NimStringDesc* data; }; typedef NU8 Tinfoccprop274004Set; struct Tinfocc274008 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; NimStringDesc* Field3; NimStringDesc* Field4; NimStringDesc* Field5; NimStringDesc* Field6; NimStringDesc* Field7; NimStringDesc* Field8; NimStringDesc* Field9; NimStringDesc* Field10; NimStringDesc* Field11; NimStringDesc* Field12; NimStringDesc* Field13; NimStringDesc* Field14; NimStringDesc* Field15; NimStringDesc* Field16; NimStringDesc* Field17; NimStringDesc* Field18; NimStringDesc* Field19; Tinfoccprop274004Set Field20; }; typedef Tinfocc274008 TY274427[13]; typedef NU8 Tsystemcc274002; typedef NU8 Tnodeflag293427; typedef NU8 Tcprocsection530011; typedef Ropeobj179006* Tcprocsections530013[3]; struct Tblock530019 { NI id; Ropeobj179006* label; Tcprocsections530013 sections; NIM_BOOL isloop; NI16 nestedtrystmts; NI16 nestedexceptstmts; NI16 framelen; }; typedef NU8 Tgcmode170080; typedef NU8 Ttypeinforeason538016; struct Ttraversalclosure538019 { Tcproc530021* p; NimStringDesc* visitorfrmt; }; typedef NU8 Ttypefieldresult321145; typedef NU8 Tinfoccprop274004; typedef Ropeobj179006* TY537847[6]; typedef Ropeobj179006* TY537401[7]; typedef Ropeobj179006* TY537475[5]; typedef NU16 Tmsgkind192002; typedef NU8 Tassignmentflag539302Set; typedef NU8 Tassignmentflag539302; typedef NimStringDesc* TY553655[19]; typedef NimStringDesc* TY552642[3]; typedef NimStringDesc* TY557765[4]; typedef NimStringDesc* TY552828[42]; typedef NimStringDesc* TY552281[7]; typedef NU8 Trenderflag312004Set; typedef NimStringDesc* TY558052[2]; typedef NU8 Tclosuretypekind536681; typedef NimStringDesc* TY557428[6]; typedef NU8 Tanalysisresult474003; typedef NU8 char136Set[32]; typedef NU8 Tdistinctcompare325427; typedef NU8 Ttypecmpflag325429Set; typedef NU16 Tspecialword276003; typedef NU8 Tsystemos177004; struct Tfileinfo192334 { NimStringDesc* fullpath; NimStringDesc* projpath; NimStringDesc* shortname; Ropeobj179006* quotedname; Ropeobj179006* quotedfullname; TY192350* lines; NimStringDesc* dirtyfile; }; typedef NU8 Tinfoosprop177031Set; struct Tinfoos177035 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; NimStringDesc* Field3; NimStringDesc* Field4; NimStringDesc* Field5; NimStringDesc* Field6; NimStringDesc* Field7; NimStringDesc* Field8; NimStringDesc* Field9; NimStringDesc* Field10; NimStringDesc* Field11; Tinfoosprop177031Set Field12; }; typedef Tinfoos177035 TY177082[24]; typedef NU8 Tendian177474; struct Tinfocpu177476 { NimStringDesc* Field0; NI Field1; Tendian177474 Field2; NI Field3; NI Field4; }; typedef Tinfocpu177476 TY177510[19]; typedef NU8 Tsystemcpu177452; struct Tstrentry147009 { Tlistentry147007 Sup; NimStringDesc* data; }; struct TY128506 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; }; struct Gcstack49816 { Gcstack49816* prev; Gcstack49816* next; void* starts; void* pos; NI maxstacksize; }; struct Basechunk29438 { NI prevsize; NI size; NIM_BOOL used; }; struct Smallchunk29440 { Basechunk29438 Sup; Smallchunk29440* next; Smallchunk29440* prev; Freecell29430* freelist; NI free; NI acc; NF data; }; struct Llchunk29480 { NI size; NI acc; Llchunk29480* next; }; struct Bigchunk29442 { Basechunk29438 Sup; Bigchunk29442* next; Bigchunk29442* prev; NI align; NF data; }; typedef NI TY29419[8]; struct Trunk29410 { Trunk29410* next; NI key; TY29419 bits; }; typedef Avlnode29484* TY29491[2]; struct Avlnode29484 { TY29491 link; NI key; NI upperbound; NI level; }; struct Pagedesc47313 { Pagedesc47313* next; NI key; TY29419 bits; }; struct Trunk269026 { Trunk269026* next; NI key; TY29419 bits; }; struct Tidpair293846 { Tidobj200004* key; TNimObject* val; }; struct Tnodepair293858 { NI h; Tnode293802* key; NI val; }; struct Filenamemapping204005 { NimStringDesc* package; NimStringDesc* file; NU32 mangled; }; typedef NU8 Treasonforrecompile333002; struct Tiitable300142 { NI counter; Tiipairseq300140* data; }; struct Tindex333019 { NI lastidxkey; NI lastidxval; Tiitable300142 tab; NimStringDesc* r; NI offset; }; struct Table333054 { Keyvaluepairseq333057* data; NI counter; }; struct Memfile331202 { void* mem; NI size; int handle; }; struct Trodreader333021 { TNimObject Sup; NI pos; NCSTRING s; Toption170009Set options; Treasonforrecompile333002 reason; TY333033* moddeps; TY333033* files; NI dataidx; NI convertersidx; NI initidx; NI interfidx; NI compilerprocsidx; NI methodsidx; NimStringDesc* filename; Tindex333019 index; Tindex333019 imports; NI readerindex; NI line; NI moduleid; Table333054 syms; Memfile331202 memfile; Tsymseq293804* methods; NimStringDesc* origfile; NIM_BOOL inviewmode; }; struct TY293961 { NI Field0; Tsym293834* Field1; }; struct Freecell29430 { Freecell29430* next; NI zerofield; }; struct Tinstantiation293824 { Tsym293834* sym; Ttypeseq293836* concretetypes; NI compilesid; }; struct Tiipair300138 { NI key; NI val; }; struct Keyvaluepair333060 { NI Field0; NI Field1; Tsym293834* Field2; }; struct Ttypeseq293836 { TGenericSeq Sup; Ttype293840* data[SEQ_DECL_SIZE]; }; struct TY530153 { TGenericSeq Sup; Tcgen530027* data[SEQ_DECL_SIZE]; }; struct Tsymseq293804 { TGenericSeq Sup; Tsym293834* data[SEQ_DECL_SIZE]; }; struct TY204017 { TGenericSeq Sup; TY204018 data[SEQ_DECL_SIZE]; }; struct TY135002 { TGenericSeq Sup; NimStringDesc* data[SEQ_DECL_SIZE]; }; struct Tbitset340004 { TGenericSeq Sup; NI8 data[SEQ_DECL_SIZE]; }; struct TY530095 { TGenericSeq Sup; Tblock530019 data[SEQ_DECL_SIZE]; }; struct TY192350 { TGenericSeq Sup; Ropeobj179006* data[SEQ_DECL_SIZE]; }; struct Tnodeseq293796 { TGenericSeq Sup; Tnode293802* data[SEQ_DECL_SIZE]; }; struct TY192612 { TGenericSeq Sup; Tfileinfo192334 data[SEQ_DECL_SIZE]; }; struct Trunkseq269028 { TGenericSeq Sup; Trunk269026* data[SEQ_DECL_SIZE]; }; struct TY293929 { TGenericSeq Sup; Tinstantiation293824* data[SEQ_DECL_SIZE]; }; struct Tidpairseq293848 { TGenericSeq Sup; Tidpair293846 data[SEQ_DECL_SIZE]; }; struct Tnodepairseq293860 { TGenericSeq Sup; Tnodepair293858 data[SEQ_DECL_SIZE]; }; struct TY204021 { TGenericSeq Sup; Filenamemapping204005 data[SEQ_DECL_SIZE]; }; struct TY204023 { TGenericSeq Sup; Enumdesc204007 data[SEQ_DECL_SIZE]; }; struct TY293960 { TGenericSeq Sup; TY293961 data[SEQ_DECL_SIZE]; }; struct TY333033 { TGenericSeq Sup; NI32 data[SEQ_DECL_SIZE]; }; struct Tiipairseq300140 { TGenericSeq Sup; Tiipair300138 data[SEQ_DECL_SIZE]; }; struct Keyvaluepairseq333057 { TGenericSeq Sup; Keyvaluepair333060 data[SEQ_DECL_SIZE]; }; N_NIMCALL(void, nimGCvisit)(void* d0, NI op0); N_NIMCALL(void, T839829468_2)(void); N_NIMCALL(void, nimRegisterGlobalMarker)(Globalmarkerproc55802 markerproc0); N_NIMCALL(void, T839829468_3)(void); N_NIMCALL(Ropeobj179006*, rope_179277_2381377266)(NimStringDesc* s0); static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0); static N_INLINE(Cell47305*, usrtocell_51440_1689653243)(void* usr0); static N_INLINE(void, rtladdzct_52601_1689653243)(Cell47305* c0); N_NOINLINE(void, addzct_51417_1689653243)(Cellseq47321* s0, Cell47305* c0); N_NIMCALL(void, T839829468_5)(void); N_NIMCALL(void, T839829468_6)(void); static N_INLINE(void, nimGCunrefNoCycle)(void* p0); N_NIMCALL(void*, newSeqRC1)(TNimType* typ0, NI len0); N_NIMCALL(void, T839829468_7)(void); N_NIMCALL(void, initintset_269885_2627731572)(Intset269030* Result); N_NOINLINE(void, chckNil)(void* p0); N_NIMCALL(void, genericReset)(void* dest0, TNimType* mt0); N_NIMCALL(void, T839829468_8)(void); N_NIMCALL(Tcgen530027*, newmodule_564044_839829468)(Tsym293834* module0); N_NIMCALL(Tcgen530027*, getcgenmodule_533226_839829468)(Tsym293834* s0); N_NIMCALL(void, internalerror_197113_155036129)(NimStringDesc* errmsg0); N_NIMCALL(NimStringDesc*, HEX24_197185_1689653243)(TY204018 x0); N_NIMCALL(Tcgen530027*, rawnewmodule_564038_839829468)(Tsym293834* module0); N_NIMCALL(Tcgen530027*, rawnewmodule_563663_839829468)(Tsym293834* module0, NimStringDesc* filename0); N_NIMCALL(void*, newObj)(TNimType* typ0, NI size0); static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0); static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0); N_NIMCALL(NimStringDesc*, HEX24_8401_1689653243)(NU64 x0); N_NIMCALL(NU32, hashowner_533977_839829468)(Tsym293834* s0); N_NIMCALL(NU32, register_204121_1926258066)(Debuginfo204009* self0, NimStringDesc* package0, NimStringDesc* file0); N_NIMCALL(NimStringDesc*, rawNewString)(NI space0); N_NIMCALL(void, initlinkedlist_147031_3771138726)(Tlinkedlist147013* list0); N_NIMCALL(NimStringDesc*, copyStringRC1)(NimStringDesc* src0); N_NIMCALL(void, initidtable_297019_850551059)(Tidtable293850* x0); N_NIMCALL(Tcproc530021*, newproc_530206_3723162438)(Tsym293834* prc0, Tcgen530027* module0); static N_INLINE(void, asgnRef)(void** dest0, void* src0); static N_INLINE(void, incref_53419_1689653243)(Cell47305* c0); static N_INLINE(void, decref_53001_1689653243)(Cell47305* c0); N_NIMCALL(Toption170009Set, initprocoptions_563635_839829468)(Tcgen530027* m0); N_NIMCALL(Tcproc530021*, newpreinitproc_563625_839829468)(Tcgen530027* m0); N_NIMCALL(Tcproc530021*, newpostinitproc_563630_839829468)(Tcgen530027* m0); N_NIMCALL(void, initnodetable_297085_850551059)(Tnodetable293862* x0); N_NIMCALL(Ropeobj179006*, gettempname_534598_839829468)(Tcgen530027* m0); N_NIMCALL(Ropeobj179006*, HEX26_179418_2381377266)(Ropeobj179006* a0, Ropeobj179006* b0); N_NIMCALL(Ropeobj179006*, rope_179401_2381377266)(NI64 i0); N_NIMCALL(NimStringDesc*, tofullpath_193261_155036129)(NI32 fileidx0); N_NIMCALL(TGenericSeq*, setLengthSeq)(TGenericSeq* seq0, NI elemsize0, NI newlen0); N_NIMCALL(NimStringDesc*, tofilename_193257_155036129)(NI32 fileidx0); N_NIMCALL(NimStringDesc*, noschangeFileExt)(NimStringDesc* filename0, NimStringDesc* ext0); N_NIMCALL(NimStringDesc*, completecfilepath_274854_2528170400)(NimStringDesc* cfile0, NIM_BOOL createsubdir0); N_NIMCALL(void, readmergeinfo_531613_2760143328)(NimStringDesc* cfilename0, Tcgen530027* m0); N_NIMCALL(NimStringDesc*, getcfile_564201_839829468)(Tcgen530027* m0); N_NIMCALL(NimStringDesc*, copyString)(NimStringDesc* src0); N_NIMCALL(NimStringDesc*, withpackagename_171073_2607990831)(NimStringDesc* path0); static N_INLINE(NIM_BOOL, skipcodegen_342085_2355241294)(Tnode293802* n0); N_NIMCALL(void, genstmts_540244_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(void, expr_540248_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, fillprocloc_540201_839829468)(Tsym293834* sym0); N_NIMCALL(void, fillloc_533282_839829468)(Tloc293816* a0, Tlockind293808 k0, Ttype293840* typ0, Ropeobj179006* r0, Tstorageloc293812 s0); N_NIMCALL(void, unsureAsgnRef)(void** dest0, void* src0); N_NIMCALL(Ropeobj179006*, manglename_534205_839829468)(Tsym293834* s0); N_NIMCALL(NIM_BOOL, iskeyword_533960_839829468)(Tident200010* w0); N_NIMCALL(NimStringDesc*, mangle_529847_2036603609)(NimStringDesc* name0); N_NIMCALL(void, add_179487_2381377266)(Ropeobj179006** a0, NimStringDesc* b0); N_NIMCALL(void, add_179482_2381377266)(Ropeobj179006** a0, Ropeobj179006* b0); N_NIMCALL(Ropeobj179006*, HEX25_179905_2381377266)(NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(void, genprocprototype_540254_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(void, useheader_533369_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(NIM_BOOL, includestr_147249_3771138726)(Tlinkedlist147013* list0, NimStringDesc* data0); N_NIMCALL(NimStringDesc*, getstr_298230_850551059)(Tnode293802* a0); N_NIMCALL(Tsym293834*, getmodule_300123_2984716966)(Tsym293834* s0); N_NIMCALL(NIM_BOOL, containsorincl_269862_2627731572)(Intset269030* s0, NI key0); N_NIMCALL(Ropeobj179006*, ropecg_533407_839829468)(Tcgen530027* m0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(NimStringDesc*, nimIntToStr)(NI x0); static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0); N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI start_79210_1689653243, NI last0); N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI first0, NI last0); N_NIMCALL(Ropeobj179006*, cgsym_533403_839829468)(Tcgen530027* m0, NimStringDesc* name0); N_NIMCALL(Tsym293834*, getcompilerproc_339748_3937434831)(NimStringDesc* name0); N_NIMCALL(void, genproc_533951_839829468)(Tcgen530027* m0, Tsym293834* prc0); N_NIMCALL(NIM_BOOL, isactivated_562431_839829468)(Tsym293834* prc0); N_NIMCALL(void, addforwardedproc_533203_839829468)(Tcgen530027* m0, Tsym293834* prc0); N_NIMCALL(TGenericSeq*, incrSeqV2)(TGenericSeq* seq0, NI elemsize0); N_NIMCALL(void, genprocnoforward_561906_839829468)(Tcgen530027* m0, Tsym293834* prc0); N_NIMCALL(void, genprocaux_561284_839829468)(Tcgen530027* m0, Tsym293834* prc0); N_NIMCALL(Ropeobj179006*, genprocheader_536867_839829468)(Tcgen530027* m0, Tsym293834* prc0); N_NIMCALL(void, genclinedir_533813_839829468)(Ropeobj179006** r0, Tlineinfo192336 info0); N_NIMCALL(void, genclinedir_533725_839829468)(Ropeobj179006** r0, NimStringDesc* filename0, NI line0); N_NIMCALL(void, addf_180205_2381377266)(Ropeobj179006** c0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(NimStringDesc*, makesinglelinecstring_529835_2036603609)(NimStringDesc* s0); N_NIMCALL(NI, safelinenm_533721_839829468)(Tlineinfo192336 info0); static N_INLINE(NI, tolinenumber_193415_155036129)(Tlineinfo192336 info0); N_NIMCALL(void, genprocparams_535115_839829468)(Tcgen530027* m0, Ttype293840* t0, Ropeobj179006** rettype0, Ropeobj179006** params0, Intset269030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0); N_NIMCALL(NIM_BOOL, isinvalidreturntype_534550_839829468)(Ttype293840* rettype0); N_NIMCALL(Tctypekind530007, maptype_534394_839829468)(Ttype293840* typ0); N_NIMCALL(Tctypekind530007, mapsettype_534389_839829468)(Ttype293840* typ0); N_NIMCALL(NI64, getsize_321135_3876443242)(Ttype293840* typ0); N_NIMCALL(Ttype293840*, lastson_296377_850551059)(Ttype293840* n0); N_NIMCALL(NI64, firstord_321001_3876443242)(Ttype293840* t0); N_NIMCALL(Ttype293840*, skiptypes_297099_850551059)(Ttype293840* t0, Ttypekind293244Set kinds0); N_NIMCALL(NIM_BOOL, isimportedcpptype_534478_839829468)(Ttype293840* t0); N_NIMCALL(NIM_BOOL, needscomplexassignment_534511_839829468)(Ttype293840* typ0); N_NIMCALL(NIM_BOOL, containsgarbagecollectedref_321117_3876443242)(Ttype293840* typ0); static N_INLINE(NIM_BOOL, isobjlackingtypefield_534515_839829468)(Ttype293840* typ0); N_NIMCALL(NIM_BOOL, ispureobject_321138_3876443242)(Ttype293840* typ0); N_NIMCALL(Ropeobj179006*, gettypedescaux_534505_839829468)(Tcgen530027* m0, Ttype293840* typ0, Intset269030* check0); N_NIMCALL(Ttype293840*, getuniquetype_529640_2036603609)(Ttype293840* key0); N_NIMCALL(Ropeobj179006*, gettypepre_534972_839829468)(Tcgen530027* m0, Ttype293840* typ0); N_NIMCALL(Ropeobj179006*, getsimpletypedesc_534936_839829468)(Tcgen530027* m0, Ttype293840* typ0); N_NIMCALL(Ropeobj179006*, typenameorliteral_534898_839829468)(Ttype293840* t0, NimStringDesc* literal0); N_NIMCALL(Ropeobj179006*, gettypename_534313_839829468)(Ttype293840* typ0); N_NIMCALL(Ropeobj179006*, typename_534292_839829468)(Ttype293840* typ0); N_NIMCALL(NimStringDesc*, reprEnum)(NI e0, TNimType* typ0); N_NIMCALL(Ropeobj179006*, cachegettype_534593_839829468)(Tidtable293850 tab0, Ttype293840* key0); N_NIMCALL(TNimObject*, idtableget_300086_2984716966)(Tidtable293850 t0, Tidobj200004* key0); N_NIMCALL(NimStringDesc*, typetostring_321017_3876443242)(Ttype293840* typ0, Tprefereddesc321011 prefer0); N_NIMCALL(Ttype293840*, elemtype_321394_3876443242)(Ttype293840* t0); N_NIMCALL(Ropeobj179006*, HEX26_179447_2381377266)(Ropeobj179006* a0, NimStringDesc* b0); N_NIMCALL(Ropeobj179006*, gettypeforward_535039_839829468)(Tcgen530027* m0, Ttype293840* typ0); N_NIMCALL(NIM_BOOL, isimportedtype_534451_839829468)(Ttype293840* t0); N_NIMCALL(NimStringDesc*, getforwardstructformat_535015_839829468)(Tcgen530027* m0); N_NIMCALL(Ropeobj179006*, structorunion_535001_839829468)(Ttype293840* t0); N_NIMCALL(void, idtableput_300094_2984716966)(Tidtable293850* t0, Tidobj200004* key0, TNimObject* val0); N_NIMCALL(void, pushtype_534958_839829468)(Tcgen530027* m0, Ttype293840* typ0); N_NIMCALL(Ropeobj179006*, gettypedescweak_535079_839829468)(Tcgen530027* m0, Ttype293840* t0, Intset269030* check0); N_NIMCALL(void, internalerror_197100_155036129)(Tlineinfo192336 info0, NimStringDesc* errmsg0); N_NIMCALL(NIM_BOOL, hasenum_204230_1926258066)(Debuginfo204009* self0, NimStringDesc* ename0, NI id0, NU32 owner0); N_NIMCALL(void*, newSeq)(TNimType* typ0, NI len0); static N_INLINE(NI, len_294081_850551059)(Tnode293802* n0); N_NIMCALL(void, registerenum_204419_1926258066)(Debuginfo204009* self0, Enumdesc204007* ed0); N_NIMCALL(void, genericSeqAssign)(void* dest0, void* src_86404_1689653243, TNimType* mt0); N_NIMCALL(void, appcg_533632_839829468)(Tcgen530027* m0, Ropeobj179006** c0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(NI64, lengthord_321007_3876443242)(Ttype293840* t0); N_NIMCALL(NIM_BOOL, scancppgenericslot_535827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0); N_NIMCALL(Ttype293840*, resolvestarsincpptype_535891_839829468)(Ttype293840* typ0, NI idx0, NI stars0); N_NIMCALL(NI, len_296339_850551059)(Ttype293840* n0); N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI start0); N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI first0); N_NIMCALL(Ropeobj179006*, getrecorddesc_535643_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0, Intset269030* check0); N_NIMCALL(Ropeobj179006*, getrecordfields_535636_839829468)(Tcgen530027* m0, Ttype293840* typ0, Intset269030* check0); N_NIMCALL(Ropeobj179006*, genrecordfieldsaux_535421_839829468)(Tcgen530027* m0, Tnode293802* n0, Ropeobj179006* accessexpr0, Ttype293840* rectype0, Intset269030* check0); N_NIMCALL(NI, sonslen_296351_850551059)(Tnode293802* n0); N_NIMCALL(Tnode293802*, lastson_296364_850551059)(Tnode293802* n0); N_NIMCALL(Ropeobj179006*, HEX26_179452_2381377266)(NimStringDesc* a0, Ropeobj179006* b0); N_NIMCALL(Ropeobj179006*, manglerecfieldname_535361_839829468)(Tsym293834* field0, Ttype293840* rectype0); N_NIMCALL(NimStringDesc*, manglefield_533973_839829468)(Tident200010* name0); N_NIMCALL(NIM_CHAR, nsuToUpperAsciiChar)(NIM_CHAR c0); N_NIMCALL(Ropeobj179006*, gettupledesc_535777_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0, Intset269030* check0); N_NIMCALL(NI, sonslen_296327_850551059)(Ttype293840* n0); N_NIMCALL(void, excl_269841_2627731572)(Intset269030* s0, NI key0); static N_INLINE(NIM_BOOL, iscompiletimeonly_329706_3876443242)(Ttype293840* t0); N_NIMCALL(Tstorageloc293812, paramstorageloc_535098_839829468)(Tsym293834* param0); N_NIMCALL(NIM_BOOL, ccgintroducedptr_534611_839829468)(Tsym293834* s0); N_NIMCALL(Tctypekind530007, mapreturntype_534447_839829468)(Ttype293840* typ0); N_NIMCALL(Tnode293802*, easyresultasgn_561191_839829468)(Tnode293802* n0); static N_INLINE(Tnode293802*, HEX5BHEX5D_294238_850551059)(Tnode293802* n0, NI i0); N_NIMCALL(Tnode293802*, getbody_336226_1724185294)(Tsym293834* s0); N_NIMCALL(Ropeobj179006*, localvardecl_539532_839829468)(Tcproc530021* p0, Tsym293834* s0); N_NIMCALL(Ropeobj179006*, gettypedesc_536673_839829468)(Tcgen530027* m0, Ttype293840* typ0); N_NIMCALL(void, initlocexprsingleuse_540289_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* result0); N_NIMCALL(void, initloc_533273_839829468)(Tloc293816* result0, Tlockind293808 k0, Ttype293840* typ0, Tstorageloc293812 s0); N_NIMCALL(void, linefmt_533714_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); static N_INLINE(Ropeobj179006**, s_530179_3723162438)(Tcproc530021* p0, Tcprocsection530011 s0); N_NIMCALL(Ropeobj179006*, indentline_533656_839829468)(Tcproc530021* p0, Ropeobj179006* r0); N_NIMCALL(void, prepend_179893_2381377266)(Ropeobj179006** a0, Ropeobj179006* b0); N_NIMCALL(Ropeobj179006*, rdloc_539188_839829468)(Tloc293816* a0); N_NIMCALL(void, assignlocalvar_539614_839829468)(Tcproc530021* p0, Tsym293834* s0); N_NIMCALL(void, line_533690_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, Ropeobj179006* r0); N_NIMCALL(void, localdebuginfo_539449_839829468)(Tcproc530021* p0, Tsym293834* s0); N_NIMCALL(void, linef_533700_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(Ropeobj179006*, makecstring_192638_155036129)(NimStringDesc* s0); N_NIMCALL(NimStringDesc*, nsuNormalize)(NimStringDesc* s0); N_NIMCALL(Ropeobj179006*, gentypeinfo_536941_839829468)(Tcgen530027* m0, Ttype293840* t_536944_839829468); N_NIMCALL(Tcgen530027*, bmod_530201_3723162438)(Tsym293834* module0); N_NIMCALL(void, gentypeinfoauxbase_536960_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttype293840* origtype0, Ropeobj179006* name0, Ropeobj179006* base0); N_NIMCALL(NIM_BOOL, canformacycle_321123_3876443242)(Ttype293840* typ0); N_NIMCALL(void, gentupleinfo_537551_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0); N_NIMCALL(Ropeobj179006*, getnimnode_536945_839829468)(Tcgen530027* m0); N_NIMCALL(Ttype293840*, fakeclosuretype_538010_839829468)(Tsym293834* owner0); N_NIMCALL(Ttype293840*, newtype_296107_850551059)(Ttypekind293244 kind0, Tsym293834* owner0); N_NIMCALL(void, rawaddson_297394_850551059)(Ttype293840* father0, Ttype293840* son0); N_NIMCALL(void, gentypeinfoaux_537027_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttype293840* origtype0, Ropeobj179006* name0); N_NIMCALL(Ropeobj179006*, gentraverseproc_538632_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttypeinforeason538016 reason0); N_NIMCALL(void, gentraverseprocseq_538399_839829468)(Ttraversalclosure538019* c0, Ropeobj179006* accessor0, Ttype293840* typ0); N_NIMCALL(void, gettemp_538032_839829468)(Tcproc530021* p0, Ttype293840* t0, Tloc293816* result0, NIM_BOOL needsinit0); N_NIMCALL(void, constructloc_539388_839829468)(Tcproc530021* p0, Tloc293816* loc0, NIM_BOOL istemp0); static N_INLINE(NIM_BOOL, iscomplexvaluetype_539317_839829468)(Ttype293840* t0); N_NIMCALL(void, usestringh_533345_839829468)(Tcgen530027* m0); N_NIMCALL(Ropeobj179006*, addrloc_539204_839829468)(Tloc293816* a0); N_NIMCALL(void, genobjectinit_539242_839829468)(Tcproc530021* p0, Tcprocsection530011 section0, Ttype293840* t0, Tloc293816* a0, NIM_BOOL takeaddr0); N_NIMCALL(Ttypefieldresult321145, analyseobjectwithtypefield_321149_3876443242)(Ttype293840* t0); N_NIMCALL(Ttype293840*, getsystype_339150_3937434831)(Ttypekind293244 kind0); N_NIMCALL(void, gentraverseproc_538022_839829468)(Ttraversalclosure538019* c0, Ropeobj179006* accessor0, Ttype293840* typ_538027_839829468); static N_INLINE(Ropeobj179006*, parentobj_538257_839829468)(Ropeobj179006* accessor0, Tcgen530027* m0); N_NIMCALL(void, gentraverseproc_538039_839829468)(Ttraversalclosure538019* c0, Ropeobj179006* accessor0, Tnode293802* n0); N_NIMCALL(void, gencaserange_538028_839829468)(Tcproc530021* p0, Tnode293802* branch0); N_NIMCALL(Ropeobj179006*, genliteral_540273_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(Ropeobj179006*, genliteral_550476_839829468)(Tcproc530021* p0, Tnode293802* n0, Ttype293840* ty0); N_NIMCALL(Ropeobj179006*, intliteral_540270_839829468)(NI64 i0); N_NIMCALL(Ropeobj179006*, int64literal_550430_839829468)(NI64 i0); N_NIMCALL(Ropeobj179006*, uint64literal_550442_839829468)(NU64 i0); N_NIMCALL(NI, nodetabletestorset_343682_1142335848)(Tnodetable293862* t0, Tnode293802* key0, NI val0); N_NIMCALL(Ropeobj179006*, getstrlit_550468_839829468)(Tcgen530027* m0, NimStringDesc* s0); N_NIMCALL(NimStringDesc*, tostrmaxprecision_299007_3471544153)(NF f0); N_NIMCALL(Tnode293802*, copynode_297528_850551059)(Tnode293802* src0); N_NIMCALL(void, linecg_533707_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(void, genarrayinfo_538005_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0); N_NIMCALL(void, gensetinfo_537867_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0); N_NIMCALL(void, genenuminfo_537599_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0); N_NIMCALL(void, genobjectinfo_537508_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttype293840* origtype0, Ropeobj179006* name0); N_NIMCALL(void, genobjectfields_537104_839829468)(Tcgen530027* m0, Ttype293840* typ0, Tnode293802* n0, Ropeobj179006* expr0); N_NIMCALL(Ropeobj179006*, discriminatortablename_537057_839829468)(Tcgen530027* m0, Ttype293840* objtype_537060_839829468, Tsym293834* d0); N_NIMCALL(Tsym293834*, lookupinrecord_300119_2984716966)(Tnode293802* n0, Tident200010* field0); N_NIMCALL(NI64, getordvalue_321129_3876443242)(Tnode293802* n0); N_NIMCALL(void, gendeepcopyproc_539066_839829468)(Tcgen530027* m0, Tsym293834* s0, Ropeobj179006* result0); N_NIMCALL(void, initlocalvar_539398_839829468)(Tcproc530021* p0, Tsym293834* v0, NIM_BOOL immediateasgn0); N_NIMCALL(void, fillresult_534865_839829468)(Tsym293834* param0); N_NIMCALL(void, assignparam_539994_839829468)(Tcproc530021* p0, Tsym293834* s0); N_NIMCALL(void, closuresetup_561158_839829468)(Tcproc530021* p0, Tsym293834* prc0); N_NIMCALL(Ropeobj179006*, initgcframe_539435_839829468)(Tcproc530021* p0); N_NIMCALL(Ropeobj179006*, initframe_561140_839829468)(Tcproc530021* p0, Ropeobj179006* procname0, Ropeobj179006* filename0); N_NIMCALL(Ropeobj179006*, quotedfilename_197818_155036129)(Tlineinfo192336 i0); N_NIMCALL(void, appcg_533648_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(Ropeobj179006*, deinitgcframe_539441_839829468)(Tcproc530021* p0); N_NIMCALL(Ropeobj179006*, deinitframe_561150_839829468)(Tcproc530021* p0); N_NIMCALL(Tcgen530027*, findpendingmodule_533241_839829468)(Tcgen530027* m0, Tsym293834* s0); N_NIMCALL(void, symindynamiclib_560929_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(NIM_BOOL, isgetprocaddr_560443_839829468)(Tlib293820* lib0); N_NIMCALL(void, loaddynamiclib_560481_839829468)(Tcgen530027* m0, Tlib293820* lib0); N_NIMCALL(void, libcandidates_171605_2607990831)(NimStringDesc* s0, TY135002** dest0); N_NIMCALL(void, rawmessage_195612_155036129)(Tmsgkind192002 msg0, NimStringDesc* arg0); N_NIMCALL(void, initlocexpr_540283_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* result0); N_NIMCALL(Ropeobj179006*, mangledynlibproc_539816_839829468)(Tsym293834* sym0); N_NIMCALL(NimStringDesc*, HEX24_179856_2381377266)(Ropeobj179006* r0); N_NIMCALL(void, symindynamiclibpartial_561071_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(void, genvarprototype_540236_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(void, genvarprototypeaux_545254_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(void, declarethreadvar_539676_839829468)(Tcgen530027* m0, Tsym293834* s0, NIM_BOOL isextern0); static N_INLINE(NIM_BOOL, emulatedthreadvars_533949_839829468)(void); static N_INLINE(NIM_BOOL, crossescppboundary_561754_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(void, putlocintodest_540258_839829468)(Tcproc530021* p0, Tloc293816* d0, Tloc293816* s0); N_NIMCALL(void, genassignment_540264_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0); N_NIMCALL(void, genrefassign_539311_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0); static N_INLINE(NIM_BOOL, usesnativegc_170177_2607990831)(void); N_NIMCALL(void, optasgnloc_550789_839829468)(Tloc293816* a0, Ttype293840* t0, Ropeobj179006* field0, Tloc293816* Result); N_NIMCALL(void, genoptasgntuple_551001_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0); N_NIMCALL(void, gengenericasgn_551167_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0); N_NIMCALL(NI, asgncomplexity_550751_839829468)(Tnode293802* n0); N_NIMCALL(void, genoptasgnobject_551084_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0, Tnode293802* t0); N_NIMCALL(void, genericAssign)(void* dest0, void* src0, TNimType* mt0); N_NIMCALL(void, localerror_197085_155036129)(Tlineinfo192336 info0, NimStringDesc* arg0); N_NIMCALL(NIM_BOOL, issimpleconst_533311_839829468)(Ttype293840* typ0); N_NIMCALL(void, putintodest_551468_839829468)(Tcproc530021* p0, Tloc293816* d0, Ttype293840* t0, Ropeobj179006* r0, Tstorageloc293812 s0); N_NIMCALL(void, gencomplexconst_559249_839829468)(Tcproc530021* p0, Tsym293834* sym0, Tloc293816* d0); N_NIMCALL(void, requestconstimpl_540240_839829468)(Tcproc530021* p0, Tsym293834* sym0); N_NIMCALL(Ropeobj179006*, genconstexpr_555849_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, tobitset_341001_452470228)(Tnode293802* s0, Tbitset340004** b0); N_NIMCALL(Ropeobj179006*, genrawsetdata_550629_839829468)(Tbitset340004* cs0, NI size0); N_NIMCALL(NimStringDesc*, nsuToHex)(NI64 x0, NI len0); N_NIMCALL(NI64, bitsettoword_550578_839829468)(Tbitset340004* s0, NI size0); N_NIMCALL(Ropeobj179006*, genconstseq_560371_839829468)(Tcproc530021* p0, Tnode293802* n0, Ttype293840* t0); N_NIMCALL(void, appcg_533640_839829468)(Tcgen530027* m0, Tcfilesection530005 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(Ropeobj179006*, genconstsimplelist_560299_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(Ropeobj179006*, gennamedconstexpr_560284_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, accessthreadlocalvar_533945_839829468)(Tcproc530021* p0, Tsym293834* s0); static N_INLINE(Ropeobj179006**, procsec_530194_3723162438)(Tcproc530021* p0, Tcprocsection530011 s0); static N_INLINE(NIM_BOOL, isemptytype_298441_850551059)(Ttype293840* t0); N_NIMCALL(void, putdataintodest_551436_839829468)(Tcproc530021* p0, Tloc293816* d0, Ttype293840* t0, Ropeobj179006* r0); N_NIMCALL(void, genlinedir_533823_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(Ropeobj179006*, sourceline_193065_155036129)(Tlineinfo192336 i0); N_NIMCALL(NIM_BOOL, freshlineinfo_533818_839829468)(Tcproc530021* p0, Tlineinfo192336 info0); N_NIMCALL(void, genmagicexpr_558033_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0); N_NIMCALL(void, genandor_555311_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0); N_NIMCALL(Ropeobj179006*, getlabel_540217_839829468)(Tcproc530021* p0); N_NIMCALL(void, fixlabel_540230_839829468)(Tcproc530021* p0, Ropeobj179006* labl0); N_NIMCALL(void, unaryarith_553646_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0); N_NIMCALL(void, unaryarithoverflow_552633_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0); N_NIMCALL(void, binaryfloatarith_557729_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0); N_NIMCALL(void, binaryarith_552819_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0); N_NIMCALL(void, geneqproc_553214_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, binaryarithoverflow_552262_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0); N_NIMCALL(Ropeobj179006*, binaryarithoverflowraw_552235_839829468)(Tcproc530021* p0, Ttype293840* t0, Tloc293816* a0, Tloc293816* b0, NimStringDesc* frmt0); N_NIMCALL(Ropeobj179006*, rdcharloc_539227_839829468)(Tloc293816* a0); N_NIMCALL(NI64, lastord_321004_3876443242)(Ttype293840* t0); N_NIMCALL(void, genrepr_556339_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(Ropeobj179006*, lenfield_540305_839829468)(Tcproc530021* p0); N_NIMCALL(void, gcusage_555439_839829468)(Tnode293802* n0); N_NIMCALL(void, message_197095_155036129)(Tlineinfo192336 info0, Tmsgkind192002 msg0, NimStringDesc* arg0); N_NIMCALL(NimStringDesc*, rendertree_312044_382274130)(Tnode293802* n0, Trenderflag312004Set renderflags0); N_NIMCALL(void, gengettypeinfo_556383_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genswap_556638_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, unaryexpr_552209_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, binarystmt_551501_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genstrconcat_555452_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genstrappend_555554_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genseqelemappend_555683_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genstrequals_557667_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, binaryexpr_551549_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genisnil_553620_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, gendollar_556391_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genof_556331_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, genof_556201_839829468)(Tcproc530021* p0, Tnode293802* x0, Ttype293840* typ0, Tloc293816* d0); N_NIMCALL(void, globalerror_197071_155036129)(Tlineinfo192336 info0, Tmsgkind192002 msg0, NimStringDesc* arg0); N_NIMCALL(Ropeobj179006*, genofhelper_556140_839829468)(Tcproc530021* p0, Ttype293840* dest0, Ropeobj179006* a0); N_NIMCALL(void, gennew_555782_839829468)(Tcproc530021* p0, Tnode293802* e0); N_NIMCALL(void, rawgennew_555741_839829468)(Tcproc530021* p0, Tloc293816* a0, Ropeobj179006* sizeexpr_555745_839829468); N_NIMCALL(void, gennewfinalize_556111_839829468)(Tcproc530021* p0, Tnode293802* e0); N_NIMCALL(void, gennewseq_555824_839829468)(Tcproc530021* p0, Tnode293802* e0); N_NIMCALL(void, gennewseqaux_555795_839829468)(Tcproc530021* p0, Tloc293816* dest0, Ropeobj179006* length0); N_NIMCALL(void, gennewseqofcap_555836_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, gensomecast_557481_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(Ropeobj179006*, getclosuretype_536685_839829468)(Tcgen530027* m0, Ttype293840* t0, Tclosuretypekind536681 kind0); N_NIMCALL(void, genord_557475_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, unaryexprchar_552222_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genarraylen_556415_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0); N_NIMCALL(void, unarystmt_551527_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, gensetlengthstr_556632_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, gensetlengthseq_556500_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, gensetop_557419_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0); N_NIMCALL(void, binarystmtinexcl_556858_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(Ropeobj179006*, rdsetelemloc_556662_839829468)(Tloc293816* a0, Ttype293840* settype0); N_NIMCALL(void, binaryexprchar_551809_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, geninop_557009_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(NIM_BOOL, fewcmps_556803_839829468)(Tnode293802* s0); N_NIMCALL(void, geninexpraux_554496_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* a0, Tloc293816* b0, Tloc293816* d0); N_NIMCALL(void, binaryexprin_556837_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* a0, Tloc293816* b0, Tloc293816* d0, NimStringDesc* frmt0); N_NIMCALL(void, gencall_544632_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genclosurecall_541452_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0); N_NIMCALL(Ropeobj179006*, genarg_540787_839829468)(Tcproc530021* p0, Tnode293802* n_540790_839829468, Tsym293834* param0, Tnode293802* call0); static N_INLINE(Ropeobj179006*, genargstringtocstring_540776_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(Ropeobj179006*, openarrayloc_540665_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(Tnode293802*, skipconv_329882_3876443242)(Tnode293802* n0); N_NIMCALL(Tmagic293524, getmagic_319502_2616423590)(Tnode293802* op0); N_NIMCALL(Ropeobj179006*, genargnoparam_540938_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(Ropeobj179006*, getrawproctype_541459_839829468)(Tcproc530021* p0, Ttype293840* t0); N_NIMCALL(NIM_BOOL, leftappearsonrightside_540329_839829468)(Tnode293802* le0, Tnode293802* ri0); N_NIMCALL(Tanalysisresult474003, ispartof_474340_788060399)(Tnode293802* a0, Tnode293802* b0); static N_INLINE(NIM_BOOL, hasnoinit_540383_839829468)(Tnode293802* call0); N_NIMCALL(void, resetloc_539350_839829468)(Tcproc530021* p0, Tloc293816* loc0); N_NIMCALL(Ropeobj179006*, addcomma_541464_839829468)(Ropeobj179006* r0); N_NIMCALL(void, geninfixcall_542929_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0); N_NIMCALL(NIM_BOOL, contains_110056_4286263276)(NimStringDesc* s0, char136Set chars0); N_NIMCALL(Ropeobj179006*, genpatterncall_542699_839829468)(Tcproc530021* p0, Tnode293802* ri_542702_839829468, NimStringDesc* pat0, Ttype293840* typ_542704_839829468); N_NIMCALL(Ropeobj179006*, genotherarg_540277_839829468)(Tcproc530021* p0, Tnode293802* ri0, NI i0, Ttype293840* typ0); N_NIMCALL(Ropeobj179006*, genthisarg_542475_839829468)(Tcproc530021* p0, Tnode293802* ri_542478_839829468, NI i0, Ttype293840* typ0); N_NIMCALL(Tnode293802*, skipaddrderef_542433_839829468)(Tnode293802* node0); N_NIMCALL(void, fixupcall_540410_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0, Ropeobj179006* callee0, Ropeobj179006* params0); N_NIMCALL(void, gennamedparamcall_543616_839829468)(Tcproc530021* p0, Tnode293802* ri0, Tloc293816* d0); N_NIMCALL(NIM_BOOL, contains_110046_4286263276)(NimStringDesc* s0, NIM_CHAR c0); N_NIMCALL(void, genprefixcall_540960_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0); static N_INLINE(void, poststmtactions_533942_839829468)(Tcproc530021* p0); N_NIMCALL(void, genreset_555731_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, genecho_555369_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(NimStringDesc*, nsuRepeatStr)(NimStringDesc* s0, NI n0); N_NIMCALL(void, genarrtoseq_556046_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0); N_NIMCALL(void, genseqconstr_556004_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0); N_NIMCALL(void, localerror_197080_155036129)(Tlineinfo192336 info0, Tmsgkind192002 msg0, NimStringDesc* arg0); N_NIMCALL(Tnode293802*, wrapprocforspawn_436501_2218250499)(Tsym293834* owner0, Tnode293802* spawnexpr0, Ttype293840* rettype0, Tnode293802* barrier0, Tnode293802* dest0); N_NIMCALL(Tnode293802*, liftparallel_479822_1773027539)(Tsym293834* owner0, Tnode293802* n0); N_NIMCALL(void, gendeepcopy_551374_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0); N_NIMCALL(NIM_BOOL, isdeepconstexpr_319566_2616423590)(Tnode293802* n0); N_NIMCALL(Ropeobj179006*, gensetnode_550664_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, gensetconstr_558496_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(NimStringDesc*, nimInt64ToStr)(NI64 x0); N_NIMCALL(void, exprcomplexconst_559684_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, genarrayconstr_559207_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(NIM_BOOL, handleconstexpr_555853_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, gentupleconstr_558618_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, genobjconstr_555903_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(Tsym293834*, lookupfieldagain_554154_839829468)(Tcproc530021* p0, Ttype293840* ty_554157_839829468, Tsym293834* field0, Ropeobj179006** r0); N_NIMCALL(void, genfieldcheck_554504_839829468)(Tcproc530021* p0, Tnode293802* e0, Ropeobj179006* obj0, Tsym293834* field0, Ttype293840* origty0); N_NIMCALL(Tnode293802*, newstrnode_294677_850551059)(Tnodekind293020 kind0, NimStringDesc* strval0); N_NIMCALL(void, gencast_557538_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genconv_557633_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(NIM_BOOL, comparetypes_327214_3876443242)(Ttype293840* x0, Ttype293840* y0, Tdistinctcompare325427 cmp0, Ttypecmpflag325429Set flags0); N_NIMCALL(void, genaddr_554051_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); static N_INLINE(NIM_BOOL, iscppref_553807_839829468)(Tcproc530021* p0, Ttype293840* typ0); N_NIMCALL(void, genbracketexpr_555277_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, genarrayelem_555093_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0); N_NIMCALL(NIM_BOOL, isconstexpr_319510_2616423590)(Tnode293802* n0); N_NIMCALL(void, genopenarrayelem_555169_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0); N_NIMCALL(void, genseqelem_555205_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0); N_NIMCALL(void, gencstringelem_555144_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0); N_NIMCALL(void, gentupleelem_554124_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genderef_544921_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NIM_BOOL enforcederef0); N_NIMCALL(void, genrecordfield_554448_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(Ttype293840*, genrecordfieldaux_554096_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tloc293816* a0); N_NIMCALL(void, gencheckedrecordfield_555046_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0); N_NIMCALL(void, genblock_547083_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(NI, startblock_544978_839829468)(Tcproc530021* p0, NimStringDesc* start0, Ropeobj179006** args0, NI args0Len0); N_NIMCALL(void, endblock_545060_839829468)(Tcproc530021* p0); N_NIMCALL(void, endblock_545035_839829468)(Tcproc530021* p0, Ropeobj179006* blockend0); N_NIMCALL(Ropeobj179006*, blockbody_545025_839829468)(Tblock530019* b0); N_NIMCALL(void, genstmtlistexpr_559402_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, genif_545982_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, downconv_559581_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(NI, inheritancediff_327252_3876443242)(Ttype293840* a0, Ttype293840* b0); N_NIMCALL(void, upconv_559431_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, genrangechck_557591_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0, NimStringDesc* magic0); N_NIMCALL(void, convstrtocstr_557643_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, convcstrtostr_557655_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, genclosure_558836_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); static N_INLINE(NIM_BOOL, isconstclosure_558810_839829468)(Tnode293802* n0); static N_INLINE(NIM_BOOL, isroutine_298324_850551059)(Tsym293834* s0); N_NIMCALL(void, genwhilestmt_546985_839829468)(Tcproc530021* p0, Tnode293802* t0); static N_INLINE(Ropeobj179006*, assignlabel_545020_839829468)(Tblock530019* b0); N_NIMCALL(NIM_BOOL, stmtscontainpragma_529083_2036603609)(Tnode293802* n0, Tspecialword276003 w0); N_NIMCALL(void, gencomputedgoto_546744_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, genvarstmt_545854_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, gensinglevar_545276_839829468)(Tcproc530021* p0, Tnode293802* a0); N_NIMCALL(void, gengotovar_545258_839829468)(Tcproc530021* p0, Tnode293802* value0); N_NIMCALL(void, assignglobalvar_539819_839829468)(Tcproc530021* p0, Tsym293834* s0); N_NIMCALL(void, varindynamiclib_539812_839829468)(Tcgen530027* m0, Tsym293834* sym0); N_NIMCALL(void, registergcroot_544762_839829468)(Tcproc530021* p0, Tsym293834* v0); N_NIMCALL(Ropeobj179006*, gentraverseprocforglobal_539032_839829468)(Tcgen530027* m0, Tsym293834* s0); static N_INLINE(NIM_BOOL, isassignedimmediately_544781_839829468)(Tnode293802* n0); N_NIMCALL(NIM_BOOL, containshiddenpointer_321120_3876443242)(Ttype293840* typ0); static N_INLINE(void, loadinto_544928_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* a0); N_NIMCALL(void, genasgncall_544695_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0); N_NIMCALL(void, genclosurevar_545832_839829468)(Tcproc530021* p0, Tnode293802* a0); N_NIMCALL(void, genvartuple_544794_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(Tnode293802*, lowertupleunpacking_434037_2218250499)(Tnode293802* n0, Tsym293834* owner0); N_NIMCALL(void, genconststmt_545909_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(NIM_BOOL, containscompiletimeonly_329721_3876443242)(Ttype293840* t0); static N_INLINE(NIM_BOOL, emitlazily_533248_839829468)(Tsym293834* s0); N_NIMCALL(void, gencase_548827_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0); N_NIMCALL(void, genstringcase_548417_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0); N_NIMCALL(NI, nextpoweroftwo_101629_1009420244)(NI x0); N_NIMCALL(void, gencasestringbranch_548100_839829468)(Tcproc530021* p0, Tnode293802* b0, Tloc293816* e0, Ropeobj179006* labl0, Ropeobj179006** branches0, NI branches0Len0); N_NIMCALL(NI64, hashstring_529100_2036603609)(NimStringDesc* s0); N_NIMCALL(Ropeobj179006*, gencasesecondpass_547965_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0, NI labid0, NI until0); N_NIMCALL(void, exprblock_545103_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(void, gencasegeneric_548087_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0); N_NIMCALL(Ropeobj179006*, genifforcaseuntil_548021_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc293816* a0); N_NIMCALL(void, gencasegenericbranch_547910_839829468)(Tcproc530021* p0, Tnode293802* b0, Tloc293816* e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj179006* labl0); N_NIMCALL(void, gengotoforcase_546673_839829468)(Tcproc530021* p0, Tnode293802* casestmt0); N_NIMCALL(void, genordinalcase_548725_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0); N_NIMCALL(NI, ifswitchsplitpoint_548616_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(NIM_BOOL, branchhastoobigrange_548576_839829468)(Tnode293802* b0); N_NIMCALL(void, genreturnstmt_546617_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(void, blockleaveactions_546442_839829468)(Tcproc530021* p0, NI howmanytrys0, NI howmanyexcepts0); static N_INLINE(Tnode293802*, pop_319246_1689653243)(Tnodeseq293796** s0); N_NIMCALL(void, genbreakstmt_547444_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(void, genasgn_550239_839829468)(Tcproc530021* p0, Tnode293802* e0, NIM_BOOL fastasgn0); N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_550080_839829468)(Tcproc530021* p0, Tnode293802* asgn0); N_NIMCALL(void, asgnfielddiscriminant_550209_839829468)(Tcproc530021* p0, Tnode293802* e0); N_NIMCALL(void, gendiscriminantcheck_550144_839829468)(Tcproc530021* p0, Tloc293816* a0, Tloc293816* tmp0, Ttype293840* objtype0, Tsym293834* field0); N_NIMCALL(Ropeobj179006*, discriminatortabledecl_537094_839829468)(Tcgen530027* m0, Ttype293840* objtype0, Tsym293834* d0); N_NIMCALL(void, genasmstmt_549659_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(Ropeobj179006*, genasmoremitstmt_549529_839829468)(Tcproc530021* p0, Tnode293802* t0, NIM_BOOL isasmstmt0); N_NIMCALL(NimStringDesc*, resizeString)(NimStringDesc* dest0, NI addlen0); N_NIMCALL(void, gentrycpp_548866_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0); static N_INLINE(void, gensimpleblock_545095_839829468)(Tcproc530021* p0, Tnode293802* stmts0); N_NIMCALL(void, gentry_549114_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0); N_NIMCALL(NIM_BOOL, isdefined_201011_1967573533)(NimStringDesc* symbol0); N_NIMCALL(void, line_533695_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* r0); static N_INLINE(Ropeobj179006*, pop_179530_1689653243)(TY192350** s0); N_NIMCALL(void, genraisestmt_547828_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(NimStringDesc*, getraisefrmt_547824_839829468)(Tcproc530021* p0); N_NIMCALL(void, gentypesection_539184_839829468)(Tcgen530027* m0, Tnode293802* n0); N_NIMCALL(void, genpragma_550039_839829468)(Tcproc530021* p_550041_839829468, Tnode293802* n0); N_NIMCALL(Tspecialword276003, whichpragma_319911_2616423590)(Tnode293802* n0); N_NIMCALL(void, genemit_549839_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(Tcfilesection530005, determinesection_549819_839829468)(Tnode293802* n0); N_NIMCALL(NIM_BOOL, nsuStartsWith)(NimStringDesc* s0, NimStringDesc* prefix0); N_NIMCALL(void, genbreakpoint_549862_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(void, genwatchpoint_550016_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(Tsym293834*, skipgenericowner_298280_850551059)(Tsym293834* s0); N_NIMCALL(void, genparforstmt_547208_839829468)(Tcproc530021* p0, Tnode293802* t0); N_NIMCALL(void, genstate_545117_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, gengotostate_545144_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, genbreakstate_545229_839829468)(Tcproc530021* p0, Tnode293802* n0); N_NIMCALL(void, registermoduletomain_563243_839829468)(Tsym293834* m0); N_NIMCALL(Ropeobj179006*, getinitname_563235_839829468)(Tsym293834* m0); N_NIMCALL(Ropeobj179006*, getsomeinitname_562904_839829468)(Tsym293834* m0, NimStringDesc* suffix0); N_NIMCALL(Ropeobj179006*, getdatinitname_563239_839829468)(Tsym293834* m0); N_NIMCALL(Tnode293802*, generatemethoddispatchers_433151_3853300031)(void); N_NIMCALL(void, genmainproc_562729_839829468)(Tcgen530027* m0); N_NIMCALL(Ropeobj179006*, genfilenames_562688_839829468)(Tcgen530027* m0); N_NIMCALL(void, finishmodule_564420_839829468)(Tcgen530027* m0); N_NIMCALL(void, updatecachedmodule_564813_839829468)(Tcgen530027* m0); N_NIMCALL(NIM_BOOL, mergerequired_531832_2760143328)(Tcgen530027* m0); N_NIMCALL(void, mergefiles_532241_2760143328)(NimStringDesc* cfilename0, Tcgen530027* m0); N_NIMCALL(void, geninitcode_563286_839829468)(Tcgen530027* m0); N_NIMCALL(Ropeobj179006*, gensectionstart_531081_2760143328)(Tcprocsection530011 ps0); N_NIMCALL(Ropeobj179006*, gensectionend_531116_2760143328)(Tcprocsection530011 ps0); N_NIMCALL(Ropeobj179006*, gensectionstart_531015_2760143328)(Tcfilesection530005 fs0); N_NIMCALL(Ropeobj179006*, gensectionend_531050_2760143328)(Tcfilesection530005 fs0); N_NIMCALL(void, finishtypedescriptions_536842_839829468)(Tcgen530027* m0); N_NIMCALL(Ropeobj179006*, genmodule_563491_839829468)(Tcgen530027* m0, NimStringDesc* cfile0); N_NIMCALL(Ropeobj179006*, getfileheader_562683_839829468)(NimStringDesc* cfile0); N_NIMCALL(Ropeobj179006*, getcopyright_562665_839829468)(NimStringDesc* cfile0); N_NIMCALL(NimStringDesc*, getcompilecfilecmd_275284_2528170400)(NimStringDesc* cfilename0, NIM_BOOL isexternal0); static N_INLINE(void, addinttypes_562659_839829468)(Ropeobj179006** result0); N_NIMCALL(Ropeobj179006*, genmergeinfo_531203_2760143328)(Tcgen530027* m0); N_NIMCALL(void, generatethreadlocalstorage_539717_839829468)(Tcgen530027* m0); N_NIMCALL(void, generateheaders_561104_839829468)(Tcgen530027* m0); N_NIMCALL(NimStringDesc*, nsuReplaceChar)(NimStringDesc* s0, NIM_CHAR sub0, NIM_CHAR by0); N_NIMCALL(void, writerope_179836_2381377266)(Ropeobj179006* head0, NimStringDesc* filename0, NIM_BOOL usewarning0); N_NIMCALL(void, addfiletocompile_274863_2528170400)(NimStringDesc* filename0); N_NIMCALL(void, addfiletolink_274872_2528170400)(NimStringDesc* filename0); N_NIMCALL(void, writemodule_564637_839829468)(Tcgen530027* m0, NIM_BOOL pending0); N_NIMCALL(void, generatethreadvarssize_539771_839829468)(Tcgen530027* m0); N_NIMCALL(NIM_BOOL, shouldrecompile_564621_839829468)(Ropeobj179006* code0, NimStringDesc* cfile0); N_NIMCALL(NimStringDesc*, toobjfile_274859_2528170400)(NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, writeropeifnotequal_180511_2381377266)(Ropeobj179006* r0, NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, nosexistsFile)(NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, nosfileNewer)(NimStringDesc* a0, NimStringDesc* b0); N_NIMCALL(void, writemapping_275789_2528170400)(Ropeobj179006* gsymbolmapping0); N_NIMCALL(void, writeheader_564149_839829468)(Tcgen530027* m0); N_NIMCALL(void, nossplitFile)(NimStringDesc* path0, TY128506* Result); N_NIMCALL(void, resetmodule_563763_839829468)(Tcgen530027* m0); N_NIMCALL(void, nullify_563833_839829468)(Ropeobj179006** arr0); N_NIMCALL(void, nullify_563858_839829468)(Ropeobj179006** arr0); STRING_LITERAL(T839829468_4, "\011", 1); STRING_LITERAL(T839829468_10, "compiler/cgen.nim", 17); NIM_CONST TY204018 T839829468_9 = {((NimStringDesc*) &T839829468_10), ((NI) 1158)} ; STRING_LITERAL(T839829468_11, "T", 1); STRING_LITERAL(T839829468_12, "_", 1); STRING_LITERAL(T839829468_13, "added pending module twice: ", 28); STRING_LITERAL(T839829468_14, ".h", 2); STRING_LITERAL(T839829468_15, ".cpp", 4); STRING_LITERAL(T839829468_16, ".m", 2); STRING_LITERAL(T839829468_17, ".c", 2); STRING_LITERAL(T839829468_18, "0", 1); STRING_LITERAL(T839829468_19, "$", 1); STRING_LITERAL(T839829468_20, "ropes: invalid format string $", 30); STRING_LITERAL(T839829468_21, "$N#line $2 $1$N", 15); STRING_LITERAL(T839829468_22, "N_LIB_IMPORT ", 13); STRING_LITERAL(T839829468_23, "N_LIB_EXPORT ", 13); STRING_LITERAL(T839829468_24, "static ", 7); STRING_LITERAL(T839829468_25, "mapType", 7); STRING_LITERAL(T839829468_26, "void", 4); STRING_LITERAL(T839829468_27, "getTypeDescAux: t == nil", 24); STRING_LITERAL(T839829468_28, "TY", 2); STRING_LITERAL(T839829468_29, "getTypeName: ", 13); STRING_LITERAL(T839829468_30, "void*", 5); STRING_LITERAL(T839829468_31, "NimStringDesc", 13); STRING_LITERAL(T839829468_32, "NimStringDesc*", 14); STRING_LITERAL(T839829468_33, "NCSTRING", 8); STRING_LITERAL(T839829468_34, "NIM_BOOL", 8); STRING_LITERAL(T839829468_35, "NIM_CHAR", 8); STRING_LITERAL(T839829468_36, "NI", 2); STRING_LITERAL(T839829468_37, "NI8", 3); STRING_LITERAL(T839829468_38, "NI16", 4); STRING_LITERAL(T839829468_39, "NI32", 4); STRING_LITERAL(T839829468_40, "NI64", 4); STRING_LITERAL(T839829468_41, "NF", 2); STRING_LITERAL(T839829468_42, "NF32", 4); STRING_LITERAL(T839829468_43, "NF64", 4); STRING_LITERAL(T839829468_44, "NF128", 5); STRING_LITERAL(T839829468_45, "NU", 2); STRING_LITERAL(T839829468_46, "NU8", 3); STRING_LITERAL(T839829468_47, "NU16", 4); STRING_LITERAL(T839829468_48, "NU32", 4); STRING_LITERAL(T839829468_49, "NU64", 4); NIM_CONST TY534943 Numericaltypetostr_534941_839829468 = {((NimStringDesc*) &T839829468_36), ((NimStringDesc*) &T839829468_37), ((NimStringDesc*) &T839829468_38), ((NimStringDesc*) &T839829468_39), ((NimStringDesc*) &T839829468_40), ((NimStringDesc*) &T839829468_41), ((NimStringDesc*) &T839829468_42), ((NimStringDesc*) &T839829468_43), ((NimStringDesc*) &T839829468_44), ((NimStringDesc*) &T839829468_45), ((NimStringDesc*) &T839829468_46), ((NimStringDesc*) &T839829468_47), ((NimStringDesc*) &T839829468_48), ((NimStringDesc*) &T839829468_49)} ; STRING_LITERAL(T839829468_50, "tyStatic for getSimpleTypeDesc", 30); STRING_LITERAL(T839829468_51, "cannot generate C type for: ", 28); STRING_LITERAL(T839829468_52, "&", 1); STRING_LITERAL(T839829468_53, "*", 1); STRING_LITERAL(T839829468_54, "$1 $2;$n", 8); STRING_LITERAL(T839829468_55, "typedef $1 $2 $2;$n", 19); STRING_LITERAL(T839829468_56, "union", 5); STRING_LITERAL(T839829468_57, "struct", 6); STRING_LITERAL(T839829468_58, "getTypeForward(", 15); STRING_LITERAL(T839829468_59, "typedef NI32 $1;$n", 18); STRING_LITERAL(T839829468_60, "typedef NU8 $1;$n", 17); STRING_LITERAL(T839829468_61, "typedef NU16 $1;$n", 18); STRING_LITERAL(T839829468_62, "typedef NI64 $1;$n", 18); STRING_LITERAL(T839829468_63, "getTypeDescAux: enum", 20); STRING_LITERAL(T839829468_64, "typedef $1_PTR($2, $3) $4;$n", 28); STRING_LITERAL(T839829468_65, "N_NIMCALL", 9); STRING_LITERAL(T839829468_66, "N_STDCALL", 9); STRING_LITERAL(T839829468_67, "N_CDECL", 7); STRING_LITERAL(T839829468_68, "N_SAFECALL", 10); STRING_LITERAL(T839829468_69, "N_SYSCALL", 9); STRING_LITERAL(T839829468_70, "N_INLINE", 8); STRING_LITERAL(T839829468_71, "N_NOINLINE", 10); STRING_LITERAL(T839829468_72, "N_FASTCALL", 10); STRING_LITERAL(T839829468_73, "N_CLOSURE", 9); STRING_LITERAL(T839829468_74, "N_NOCONV", 8); NIM_CONST TY293016 Callingconvtostr_534587_839829468 = {((NimStringDesc*) &T839829468_65), ((NimStringDesc*) &T839829468_66), ((NimStringDesc*) &T839829468_67), ((NimStringDesc*) &T839829468_68), ((NimStringDesc*) &T839829468_69), ((NimStringDesc*) &T839829468_70), ((NimStringDesc*) &T839829468_71), ((NimStringDesc*) &T839829468_72), ((NimStringDesc*) &T839829468_73), ((NimStringDesc*) &T839829468_74)} ; STRING_LITERAL(T839829468_75, "typedef struct {$nN_NIMCALL_PTR($2, ClPrc) $3;$nvoid* ClEnv;$n}" " $1;$n", 69); STRING_LITERAL(T839829468_76, "struct $2 : #TGenericSeq {$n", 28); STRING_LITERAL(T839829468_77, "struct $2 {$n #TGenericSeq Sup;$n", 34); STRING_LITERAL(T839829468_78, " $1 data[SEQ_DECL_SIZE];$n};$n", 31); STRING_LITERAL(T839829468_79, "TGenericSeq", 11); STRING_LITERAL(T839829468_80, "typedef $1 $2[$3];$n", 20); STRING_LITERAL(T839829468_81, "invalid apostrophe type parameter index", 39); STRING_LITERAL(T839829468_82, "<", 1); STRING_LITERAL(T839829468_83, " COMMA ", 7); STRING_LITERAL(T839829468_84, "> ", 2); extern NIM_CONST TY274427 Cc_274413_2528170400; STRING_LITERAL(T839829468_85, " {$n", 4); STRING_LITERAL(T839829468_86, " {$n#TNimType* m_type;$n", 24); STRING_LITERAL(T839829468_87, " : public $1 {$n", 16); STRING_LITERAL(T839829468_88, " {$n $1 Sup;$n", 15); STRING_LITERAL(T839829468_89, "genRecordFieldsAux", 18); STRING_LITERAL(T839829468_90, "$1.$2", 5); STRING_LITERAL(T839829468_91, "S", 1); STRING_LITERAL(T839829468_92, "struct {", 8); STRING_LITERAL(T839829468_93, "} $1;$n", 7); STRING_LITERAL(T839829468_94, "genRecordFieldsAux(record case branch)", 38); STRING_LITERAL(T839829468_95, "union{$n$1} $2;$n", 17); STRING_LITERAL(T839829468_96, "mangleRecFieldName", 18); STRING_LITERAL(T839829468_97, "$1 $2[SEQ_DECL_SIZE];$n", 23); STRING_LITERAL(T839829468_98, "$1 $2:$3;$n", 11); STRING_LITERAL(T839829468_99, "genRecordFieldsAux()", 20); STRING_LITERAL(T839829468_100, "char dummy;$n", 13); STRING_LITERAL(T839829468_101, "};", 2); STRING_LITERAL(T839829468_102, "$1 $2 {$n", 9); STRING_LITERAL(T839829468_103, "$1 Field$2;$n", 13); STRING_LITERAL(T839829468_104, "char dummy;", 11); STRING_LITERAL(T839829468_105, "Set", 3); STRING_LITERAL(T839829468_106, "typedef NU$2 $1;$n", 18); STRING_LITERAL(T839829468_107, "typedef NU8 $1[$2];$n", 21); STRING_LITERAL(T839829468_108, "getTypeDescAux(", 15); STRING_LITERAL(T839829468_109, "genProcParams", 13); STRING_LITERAL(T839829468_110, ", ", 2); STRING_LITERAL(T839829468_111, " ", 1); STRING_LITERAL(T839829468_112, ", NI $1Len$2", 12); STRING_LITERAL(T839829468_113, " Result", 7); STRING_LITERAL(T839829468_114, "void* ClEnv", 11); STRING_LITERAL(T839829468_115, "...", 3); STRING_LITERAL(T839829468_116, "void)", 5); STRING_LITERAL(T839829468_117, ")", 1); STRING_LITERAL(T839829468_118, "(", 1); STRING_LITERAL(T839829468_119, "$1($2, $3)$4", 12); STRING_LITERAL(T839829468_120, "proc has no result symbol", 25); STRING_LITERAL(T839829468_121, " register", 9); STRING_LITERAL(T839829468_122, " volatile", 9); STRING_LITERAL(T839829468_123, "$1 = $2;$n", 10); STRING_LITERAL(T839829468_124, "(*$1)", 5); STRING_LITERAL(T839829468_125, ";", 1); STRING_LITERAL(T839829468_126, "FR.s[$1].address = (void*)$3; FR.s[$1].typ = $4; FR.s[$1].name " "= $2;$n", 70); STRING_LITERAL(T839829468_127, "NTI$1", 5); STRING_LITERAL(T839829468_128, "(&", 2); STRING_LITERAL(T839829468_129, "TNimType", 8); STRING_LITERAL(T839829468_130, "TNimNode", 8); STRING_LITERAL(T839829468_131, "extern TNimType $1; /* $2 */$n", 30); STRING_LITERAL(T839829468_132, "0", 1); STRING_LITERAL(T839829468_133, "void*", 5); STRING_LITERAL(T839829468_134, "$1.size = sizeof($2);$n$1.kind = $3;$n$1.base = $4;$n", 53); STRING_LITERAL(T839829468_135, "$1.flags = $2;$n", 16); STRING_LITERAL(T839829468_136, "TNimType $1; /* $2 */$n", 23); STRING_LITERAL(T839829468_137, "genTypeInfo(", 12); STRING_LITERAL(T839829468_138, "$1[$2]", 6); STRING_LITERAL(T839829468_139, "static TNimNode* $1[$2];$n", 26); STRING_LITERAL(T839829468_140, "$1[$2] = &$3;$n", 15); STRING_LITERAL(T839829468_141, "$1.kind = 1;$n$1.offset = offsetof($2, Field$3);$n$1.typ = $4;$" "n$1.name = \"Field$3\";$n", 86); STRING_LITERAL(T839829468_142, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n", 45); STRING_LITERAL(T839829468_143, "$1.len = $2; $1.kind = 2;$n", 27); STRING_LITERAL(T839829468_144, "$1.node = &$2;$n", 16); STRING_LITERAL(T839829468_145, "#nimGCvisit((void*)$1, op);$n", 29); STRING_LITERAL(T839829468_146, "N_NIMCALL(void, $1)(void* p, NI op)", 35); STRING_LITERAL(T839829468_147, "$1 a;$n", 7); STRING_LITERAL(T839829468_148, "a = ($1)p;$n", 12); STRING_LITERAL(T839829468_149, "LOC", 3); STRING_LITERAL(T839829468_150, "$1 = ($2)0;$n", 13); STRING_LITERAL(T839829468_151, "<string.h>", 10); STRING_LITERAL(T839829468_152, "memset((void*)$1, 0, sizeof($2));$n", 35); STRING_LITERAL(T839829468_153, ".Sup", 4); STRING_LITERAL(T839829468_154, "$1.m_type = $2;$n", 17); STRING_LITERAL(T839829468_155, "#objectInit($1, $2);$n", 22); STRING_LITERAL(T839829468_156, "for ($1 = 0; $1 < $2->$3; $1++) {$n", 35); STRING_LITERAL(T839829468_157, "len", 3); STRING_LITERAL(T839829468_158, "Sup.len", 7); STRING_LITERAL(T839829468_159, "for ($1 = 0; $1 < $2; $1++) {$n", 31); STRING_LITERAL(T839829468_160, "}$n", 3); STRING_LITERAL(T839829468_161, "$1.Sup", 6); STRING_LITERAL(T839829468_162, "genTraverseProc", 15); STRING_LITERAL(T839829468_163, "switch ($1.$2) {$n", 18); STRING_LITERAL(T839829468_164, "case $1 ... $2:$n", 17); STRING_LITERAL(T839829468_165, "genLiteral: ty is nil", 21); STRING_LITERAL(T839829468_166, "(-2147483647 -1)", 16); STRING_LITERAL(T839829468_167, "IL64($1)", 8); STRING_LITERAL(T839829468_168, "(IL64(-9223372036854775807) - IL64(1))", 38); STRING_LITERAL(T839829468_169, "NIM_TRUE", 8); STRING_LITERAL(T839829468_170, "NIM_FALSE", 9); STRING_LITERAL(T839829468_171, "ULL", 3); STRING_LITERAL(T839829468_172, "(($1) $2)", 9); STRING_LITERAL(T839829468_173, "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n", 45); STRING_LITERAL(T839829468_174, "NIM_NIL", 7); STRING_LITERAL(T839829468_175, "((#NimStringDesc*) NIM_NIL)", 27); STRING_LITERAL(T839829468_176, "((#NimStringDesc*) &$1)", 23); STRING_LITERAL(T839829468_177, "STRING_LITERAL($1, $2, $3);$n", 29); STRING_LITERAL(T839829468_178, "((#NimStringDesc*) &$1$2)", 25); STRING_LITERAL(T839829468_179, "genLiteral(", 11); STRING_LITERAL(T839829468_180, "case $1:$n", 10); STRING_LITERAL(T839829468_181, "default:$n", 10); STRING_LITERAL(T839829468_182, "break;$n", 8); STRING_LITERAL(T839829468_183, "} $n", 4); STRING_LITERAL(T839829468_184, "genTraverseProc()", 17); STRING_LITERAL(T839829468_185, "$1.Field$2", 10); STRING_LITERAL(T839829468_186, "$1.ClEnv", 8); STRING_LITERAL(T839829468_187, "$1->data[$2]", 12); STRING_LITERAL(T839829468_188, "a", 1); STRING_LITERAL(T839829468_189, "(*a)", 4); STRING_LITERAL(T839829468_190, "$1 {$n$2$3$4}$n", 15); STRING_LITERAL(T839829468_191, "$1;$n", 5); STRING_LITERAL(T839829468_192, "$1.marker = $2;$n", 17); STRING_LITERAL(T839829468_193, "$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n", 43); STRING_LITERAL(T839829468_194, "$1.offset = $2;$n", 17); STRING_LITERAL(T839829468_195, "NI $1;$n", 8); STRING_LITERAL(T839829468_196, "static char* NIM_CONST $1[$2] = {$n$3};$n", 41); STRING_LITERAL(T839829468_197, "for ($1 = 0; $1 < $2; $1++) {$n$3[$1+$4].kind = 1;$n$3[$1+$4].o" "ffset = $1;$n$3[$1+$4].name = $5[$1];$n$6[$1] = &$3[$1+$4];$n}$n", 127); STRING_LITERAL(T839829468_198, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n", 61); STRING_LITERAL(T839829468_199, "$1.flags = 1<<2;$n", 18); STRING_LITERAL(T839829468_200, "anonymous obj with discriminator", 32); STRING_LITERAL(T839829468_201, "NimDT_$1_$2", 11); STRING_LITERAL(T839829468_202, "$1.kind = 3;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n" "ame = $5;$n$1.sons = &$6[0];$n$1.len = $7;$n", 107); STRING_LITERAL(T839829468_203, "TNimNode* $1[$2];$n", 19); STRING_LITERAL(T839829468_204, "genObjectFields; nkOfBranch broken", 34); STRING_LITERAL(T839829468_205, "genObjectFields(nkRecCase)", 26); STRING_LITERAL(T839829468_206, "$1.kind = 1;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n" "ame = $5;$n", 74); STRING_LITERAL(T839829468_207, "genObjectFields", 15); STRING_LITERAL(T839829468_208, "$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n", 49); STRING_LITERAL(T839829468_209, "\011return $1;$n", 13); STRING_LITERAL(T839829468_210, "Result", 6); STRING_LITERAL(T839829468_211, "closure generation failed", 25); STRING_LITERAL(T839829468_212, "$1 = ($2) ClEnv;$n", 18); STRING_LITERAL(T839829468_213, "__declspec(noreturn) ", 21); STRING_LITERAL(T839829468_214, "__declspec(naked) ", 18); STRING_LITERAL(T839829468_215, "$N$1 {$n$2$3$4}$N$N", 19); STRING_LITERAL(T839829468_216, "$N$1 {$N", 8); STRING_LITERAL(T839829468_217, "struct {$1} GCFRAME;$n", 22); STRING_LITERAL(T839829468_218, "nimFrame", 8); STRING_LITERAL(T839829468_219, "VarSlot", 7); STRING_LITERAL(T839829468_220, "\011nimfrs($1, $2, $3, $4)$N", 25); STRING_LITERAL(T839829468_221, "\011nimfr($1, $2)$N", 16); STRING_LITERAL(T839829468_222, "\011#nimProfile();$n", 17); STRING_LITERAL(T839829468_223, "{", 1); STRING_LITERAL(T839829468_224, "\011}BeforeRet: ;$n", 16); STRING_LITERAL(T839829468_225, "if (((NU)&GCFRAME) < 4096) #nimGCFrame(&GCFRAME);$n", 51); STRING_LITERAL(T839829468_226, "\011#popFrame();$n", 15); STRING_LITERAL(T839829468_227, "}$N", 3); STRING_LITERAL(T839829468_228, "static void* $1;$n", 18); STRING_LITERAL(T839829468_229, "||", 2); STRING_LITERAL(T839829468_230, "($1 = #nimLoadLibrary((#NimStringDesc*) &$2))$n", 47); STRING_LITERAL(T839829468_231, "if (!($1)) #nimLoadLibraryError((#NimStringDesc*) &$2);$n", 57); STRING_LITERAL(T839829468_232, "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n", 60); STRING_LITERAL(T839829468_233, "loadDynamicLib", 14); STRING_LITERAL(T839829468_234, "Dl_$1", 5); STRING_LITERAL(T839829468_235, "\011$1 = ($2) ($3$4));$n", 21); NIM_CONST TY204018 T839829468_236 = {((NimStringDesc*) &T839829468_10), ((NI) 535)} ; STRING_LITERAL(T839829468_237, "wrong index: ", 13); STRING_LITERAL(T839829468_238, "\011$1 = ($2) #nimGetProcAddr($3, $4);$n", 37); STRING_LITERAL(T839829468_239, "$2 $1;$n", 8); STRING_LITERAL(T839829468_240, "extern ", 7); STRING_LITERAL(T839829468_241, "NIM_THREADVAR ", 14); STRING_LITERAL(T839829468_242, " $1;$n", 6); STRING_LITERAL(T839829468_243, "cgsym: ", 7); STRING_LITERAL(T839829468_244, ": ", 2); STRING_LITERAL(T839829468_245, "extern $1 $2;$n", 15); STRING_LITERAL(T839829468_246, "extern \"C\" ", 11); STRING_LITERAL(T839829468_247, " __attribute__((naked))", 23); STRING_LITERAL(T839829468_248, " __attribute__((noreturn))", 26); STRING_LITERAL(T839829468_249, "#asgnRef((void**) $1, $2);$n", 28); STRING_LITERAL(T839829468_250, "#asgnRefNoCycle((void**) $1, $2);$n", 35); STRING_LITERAL(T839829468_251, "#unsureAsgnRef((void**) $1, $2);$n", 34); STRING_LITERAL(T839829468_252, "#genericSeqAssign($1, $2, $3);$n", 32); STRING_LITERAL(T839829468_253, "$1 = #copyString($2);$n", 23); STRING_LITERAL(T839829468_254, "$3 = $1; $1 = #copyStringRC1($2);$n", 35); STRING_LITERAL(T839829468_255, "if ($1) #nimGCunrefNoCycle($1);$n", 33); STRING_LITERAL(T839829468_256, "#unsureAsgnRef((void**) $1, #copyString($2));$n", 47); STRING_LITERAL(T839829468_257, ".", 1); STRING_LITERAL(T839829468_258, "ClEnv", 5); STRING_LITERAL(T839829468_259, "$1.ClPrc = $2.ClPrc;$n", 22); STRING_LITERAL(T839829468_260, "Field$1", 7); STRING_LITERAL(T839829468_261, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n", 53); STRING_LITERAL(T839829468_262, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n", 50); STRING_LITERAL(T839829468_263, "#genericAssign((void*)$1, (void*)$2, $3);$n", 43); STRING_LITERAL(T839829468_265, "compiler/ccgexprs.nim", 21); NIM_CONST TY204018 T839829468_264 = {((NimStringDesc*) &T839829468_265), ((NI) 320)} ; STRING_LITERAL(T839829468_266, "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 60); STRING_LITERAL(T839829468_267, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len0);$n", 63); STRING_LITERAL(T839829468_268, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n", 45); STRING_LITERAL(T839829468_269, "genAssignment: ", 15); STRING_LITERAL(T839829468_270, "request to generate code for .compileTime proc: ", 48); STRING_LITERAL(T839829468_271, "expr: proc not init ", 20); STRING_LITERAL(T839829468_272, "NIM_CONST $1 $2 = $3;$n", 23); STRING_LITERAL(T839829468_273, "{$n", 3); STRING_LITERAL(T839829468_274, "0x$1,$n", 7); STRING_LITERAL(T839829468_275, "0x$1, ", 6); STRING_LITERAL(T839829468_276, "0x$1}$n", 7); STRING_LITERAL(T839829468_277, "{{$1, $1}", 9); STRING_LITERAL(T839829468_278, ", {", 3); STRING_LITERAL(T839829468_279, ",$n", 3); STRING_LITERAL(T839829468_280, "}", 1); STRING_LITERAL(T839829468_281, "NIM_CONST struct {$n #TGenericSeq Sup;$n $1 data[$2];$n} $3 =" " $4;$n", 69); STRING_LITERAL(T839829468_282, "(($1)&$2)", 9); STRING_LITERAL(T839829468_283, "$1,$n", 5); STRING_LITERAL(T839829468_284, "extern NIM_CONST $1 $2;$n", 25); STRING_LITERAL(T839829468_285, "expr: var not init ", 19); STRING_LITERAL(T839829468_286, "\011NimThreadVars* NimTV;$n", 24); STRING_LITERAL(T839829468_287, "\011NimTV = (NimThreadVars*) #GetThreadLocalVars();$n", 50); STRING_LITERAL(T839829468_288, "NimTV->", 7); STRING_LITERAL(T839829468_289, "expr: temp not init ", 20); STRING_LITERAL(T839829468_290, "expr: param not init ", 21); STRING_LITERAL(T839829468_291, "expr(", 5); STRING_LITERAL(T839829468_292, "); unknown symbol", 17); STRING_LITERAL(T839829468_293, "//", 2); STRING_LITERAL(T839829468_294, "#endb($1, $2);$n", 16); STRING_LITERAL(T839829468_295, "nimln($1, $2);$n", 16); STRING_LITERAL(T839829468_296, "LA", 2); STRING_LITERAL(T839829468_297, "if ($1) goto $2;$n", 18); STRING_LITERAL(T839829468_298, "if (!($1)) goto $2;$n", 21); STRING_LITERAL(T839829468_299, "$1: ;$n", 7); STRING_LITERAL(T839829468_300, "!($1)", 5); STRING_LITERAL(T839829468_301, "$1", 2); STRING_LITERAL(T839829468_302, "($3)((NU$2) ~($1))", 18); STRING_LITERAL(T839829468_303, "-($1)", 5); STRING_LITERAL(T839829468_304, "($1 > 0? ($1) : -($1))", 22); STRING_LITERAL(T839829468_305, "(($3)(NU)(NU8)($1))", 19); STRING_LITERAL(T839829468_306, "(($3)(NU64)(NU8)($1))", 21); STRING_LITERAL(T839829468_307, "(($3)(NU)(NU16)($1))", 20); STRING_LITERAL(T839829468_308, "(($3)(NU64)(NU16)($1))", 22); STRING_LITERAL(T839829468_309, "(($3)(NU64)(NU32)($1))", 22); STRING_LITERAL(T839829468_310, "(($3)(NU64)(NU)($1))", 20); STRING_LITERAL(T839829468_311, "(($3)(NU8)(NU)($1))", 19); STRING_LITERAL(T839829468_312, "(($3)(NU16)(NU)($1))", 20); STRING_LITERAL(T839829468_313, "(($3)(NU32)(NU64)($1))", 22); STRING_LITERAL(T839829468_314, "((double) ($1))", 15); STRING_LITERAL(T839829468_315, "float64ToInt32($1)", 18); STRING_LITERAL(T839829468_316, "float64ToInt64($1)", 18); NIM_CONST TY553655 unarithtab_553653_839829468 = {((NimStringDesc*) &T839829468_300), ((NimStringDesc*) &T839829468_301), ((NimStringDesc*) &T839829468_302), ((NimStringDesc*) &T839829468_301), ((NimStringDesc*) &T839829468_303), ((NimStringDesc*) &T839829468_304), ((NimStringDesc*) &T839829468_305), ((NimStringDesc*) &T839829468_306), ((NimStringDesc*) &T839829468_307), ((NimStringDesc*) &T839829468_308), ((NimStringDesc*) &T839829468_309), ((NimStringDesc*) &T839829468_310), ((NimStringDesc*) &T839829468_311), ((NimStringDesc*) &T839829468_312), ((NimStringDesc*) &T839829468_313), ((NimStringDesc*) &T839829468_314), ((NimStringDesc*) &T839829468_314), ((NimStringDesc*) &T839829468_315), ((NimStringDesc*) &T839829468_316)} ; STRING_LITERAL(T839829468_317, "if ($1 == $2) #raiseOverflow();$n", 33); STRING_LITERAL(T839829468_318, "((NI$2)-($1))", 13); NIM_CONST TY552642 opr_552640_839829468 = {((NimStringDesc*) &T839829468_318), ((NimStringDesc*) &T839829468_303), ((NimStringDesc*) &T839829468_304)} ; STRING_LITERAL(T839829468_319, "(($4)($2) $1 ($4)($3))", 22); STRING_LITERAL(T839829468_320, "+", 1); STRING_LITERAL(T839829468_321, "-", 1); STRING_LITERAL(T839829468_322, "/", 1); NIM_CONST TY557765 opr_557763_839829468 = {((NimStringDesc*) &T839829468_320), ((NimStringDesc*) &T839829468_321), ((NimStringDesc*) &T839829468_53), ((NimStringDesc*) &T839829468_322)} ; STRING_LITERAL(T839829468_323, "#nanCheck($1);$n", 16); STRING_LITERAL(T839829468_324, "#infCheck($1);$n", 16); STRING_LITERAL(T839829468_325, "(($4)($1) + ($4)($2))", 21); STRING_LITERAL(T839829468_326, "(($4)($1) - ($4)($2))", 21); STRING_LITERAL(T839829468_327, "(($4)($1) * ($4)($2))", 21); STRING_LITERAL(T839829468_328, "(($4)($1) / ($4)($2))", 21); STRING_LITERAL(T839829468_329, "($4)((NU$3)($1) >> (NU$3)($2))", 30); STRING_LITERAL(T839829468_330, "($4)((NU$3)($1) << (NU$3)($2))", 30); STRING_LITERAL(T839829468_331, "($4)($1 & $2)", 13); STRING_LITERAL(T839829468_332, "($4)($1 | $2)", 13); STRING_LITERAL(T839829468_333, "($4)($1 ^ $2)", 13); STRING_LITERAL(T839829468_334, "(($1 <= $2) ? $1 : $2)", 22); STRING_LITERAL(T839829468_335, "(($1 >= $2) ? $1 : $2)", 22); STRING_LITERAL(T839829468_336, "($4)((NU$3)($1) + (NU$3)($2))", 29); STRING_LITERAL(T839829468_337, "($4)((NU$3)($1) - (NU$3)($2))", 29); STRING_LITERAL(T839829468_338, "($4)((NU$3)($1) * (NU$3)($2))", 29); STRING_LITERAL(T839829468_339, "($4)((NU$3)($1) / (NU$3)($2))", 29); STRING_LITERAL(T839829468_340, "($4)((NU$3)($1) % (NU$3)($2))", 29); STRING_LITERAL(T839829468_341, "($1 == $2)", 10); STRING_LITERAL(T839829468_342, "($1 <= $2)", 10); STRING_LITERAL(T839829468_343, "($1 < $2)", 9); STRING_LITERAL(T839829468_344, "((NU$3)($1) <= (NU$3)($2))", 26); STRING_LITERAL(T839829468_345, "((NU$3)($1) < (NU$3)($2))", 25); STRING_LITERAL(T839829468_346, "((NU64)($1) <= (NU64)($2))", 26); STRING_LITERAL(T839829468_347, "((NU64)($1) < (NU64)($2))", 25); STRING_LITERAL(T839829468_348, "((NU8)($1) == (NU8)($2))", 24); STRING_LITERAL(T839829468_349, "((NU8)($1) <= (NU8)($2))", 24); STRING_LITERAL(T839829468_350, "((NU8)($1) < (NU8)($2))", 23); STRING_LITERAL(T839829468_351, "($1 != $2)", 10); NIM_CONST TY552828 binarithtab_552826_839829468 = {((NimStringDesc*) &T839829468_325), ((NimStringDesc*) &T839829468_326), ((NimStringDesc*) &T839829468_327), ((NimStringDesc*) &T839829468_328), ((NimStringDesc*) &T839829468_329), ((NimStringDesc*) &T839829468_330), ((NimStringDesc*) &T839829468_331), ((NimStringDesc*) &T839829468_332), ((NimStringDesc*) &T839829468_333), ((NimStringDesc*) &T839829468_334), ((NimStringDesc*) &T839829468_335), ((NimStringDesc*) &T839829468_334), ((NimStringDesc*) &T839829468_335), ((NimStringDesc*) &T839829468_336), ((NimStringDesc*) &T839829468_337), ((NimStringDesc*) &T839829468_338), ((NimStringDesc*) &T839829468_339), ((NimStringDesc*) &T839829468_340), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_344), ((NimStringDesc*) &T839829468_345), ((NimStringDesc*) &T839829468_346), ((NimStringDesc*) &T839829468_347), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_348), ((NimStringDesc*) &T839829468_349), ((NimStringDesc*) &T839829468_350), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_351)} ; STRING_LITERAL(T839829468_352, "($1.ClPrc == $2.ClPrc && $1.ClEnv == $2.ClEnv)", 46); STRING_LITERAL(T839829468_353, "($#)($# + $#)", 13); STRING_LITERAL(T839829468_354, "($#)($# - $#)", 13); STRING_LITERAL(T839829468_355, "($#)($# * $#)", 13); STRING_LITERAL(T839829468_356, "($#)($# / $#)", 13); STRING_LITERAL(T839829468_357, "($#)($# % $#)", 13); NIM_CONST TY552281 opr_552279_839829468 = {((NimStringDesc*) &T839829468_353), ((NimStringDesc*) &T839829468_354), ((NimStringDesc*) &T839829468_355), ((NimStringDesc*) &T839829468_356), ((NimStringDesc*) &T839829468_357), ((NimStringDesc*) &T839829468_353), ((NimStringDesc*) &T839829468_354)} ; STRING_LITERAL(T839829468_358, "((NU8)($1))", 11); STRING_LITERAL(T839829468_359, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n", 43); STRING_LITERAL(T839829468_360, "$# = #addInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_361, "$# = #subInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_362, "$# = #mulInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_363, "$# = #divInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_364, "$# = #modInt64($#, $#);$n", 25); NIM_CONST TY552281 prc64_552274_839829468 = {((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361), ((NimStringDesc*) &T839829468_362), ((NimStringDesc*) &T839829468_363), ((NimStringDesc*) &T839829468_364), ((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361)} ; STRING_LITERAL(T839829468_365, "$# = #addInt($#, $#);$n", 23); STRING_LITERAL(T839829468_366, "$# = #subInt($#, $#);$n", 23); STRING_LITERAL(T839829468_367, "$# = #mulInt($#, $#);$n", 23); STRING_LITERAL(T839829468_368, "$# = #divInt($#, $#);$n", 23); STRING_LITERAL(T839829468_369, "$# = #modInt($#, $#);$n", 23); NIM_CONST TY552281 prc_552269_839829468 = {((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366), ((NimStringDesc*) &T839829468_367), ((NimStringDesc*) &T839829468_368), ((NimStringDesc*) &T839829468_369), ((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366)} ; STRING_LITERAL(T839829468_370, "($#)($#)", 8); STRING_LITERAL(T839829468_371, "#reprInt((NI64)$1)", 18); STRING_LITERAL(T839829468_372, "#reprFloat($1)", 14); STRING_LITERAL(T839829468_373, "#reprBool($1)", 13); STRING_LITERAL(T839829468_374, "#reprChar($1)", 13); STRING_LITERAL(T839829468_375, "#reprEnum((NI)$1, $2)", 21); STRING_LITERAL(T839829468_376, "#reprStr($1)", 12); STRING_LITERAL(T839829468_377, "#reprSet($1, $2)", 16); STRING_LITERAL(T839829468_378, "$1, $1Len0", 10); STRING_LITERAL(T839829468_379, "$1->data, $1->$2", 16); STRING_LITERAL(T839829468_380, "$1, $2", 6); STRING_LITERAL(T839829468_381, "genRepr()", 9); STRING_LITERAL(T839829468_382, "#reprOpenArray($1, $2)", 22); STRING_LITERAL(T839829468_383, "#reprAny($1, $2)", 16); STRING_LITERAL(T839829468_384, "\'repr\' doesn\'t support \'void\' type", 34); STRING_LITERAL(T839829468_385, "($1 - 1)", 8); STRING_LITERAL(T839829468_386, "#subInt($1, 1)", 14); STRING_LITERAL(T839829468_387, "binaryStmt", 10); STRING_LITERAL(T839829468_388, "$1 += $2;$n", 11); STRING_LITERAL(T839829468_389, "$1 -= $2;$n", 11); NIM_CONST TY558052 opr_558050_839829468 = {((NimStringDesc*) &T839829468_388), ((NimStringDesc*) &T839829468_389)} ; NIM_CONST TY558052 fun64_558055_839829468 = {((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361)} ; NIM_CONST TY558052 fun_558060_839829468 = {((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366)} ; STRING_LITERAL(T839829468_390, "#appendChar($1, $2);$n", 22); STRING_LITERAL(T839829468_391, "$1->$2 + ", 9); STRING_LITERAL(T839829468_392, "#appendString($1, $2);$n", 24); STRING_LITERAL(T839829468_393, "$1 = #rawNewString($2$3);$n", 27); STRING_LITERAL(T839829468_394, "$1 = #addChar($1, $2);$n", 24); STRING_LITERAL(T839829468_395, "$1 = #resizeString($1, $2$3);$n", 31); STRING_LITERAL(T839829468_396, "$1 = ($2) #incrSeqV2(&($1)->Sup, sizeof($3));$n", 47); STRING_LITERAL(T839829468_397, "$1 = ($2) #incrSeqV2($1, sizeof($3));$n", 39); STRING_LITERAL(T839829468_398, "$1->data[$1->$2]", 16); STRING_LITERAL(T839829468_399, "++$1->$2;$n", 11); STRING_LITERAL(T839829468_400, "(($1) && ($1)->$2 == 0)", 23); STRING_LITERAL(T839829468_401, "#eqStrings($1, $2)", 18); STRING_LITERAL(T839829468_402, "(#cmpStrings($1, $2) <= 0)", 26); STRING_LITERAL(T839829468_403, "(#cmpStrings($1, $2) < 0)", 25); STRING_LITERAL(T839829468_404, "$1.ClPrc == 0", 13); STRING_LITERAL(T839829468_405, "$1 == 0", 7); STRING_LITERAL(T839829468_406, "#nimIntToStr($1)", 16); STRING_LITERAL(T839829468_407, "#nimInt64ToStr($1)", 18); STRING_LITERAL(T839829468_408, "#nimBoolToStr($1)", 17); STRING_LITERAL(T839829468_409, "#nimCharToStr($1)", 17); STRING_LITERAL(T839829468_410, "#nimFloatToStr($1)", 18); STRING_LITERAL(T839829468_411, "#cstrToNimstr($1)", 17); STRING_LITERAL(T839829468_412, "no \'of\' operator available for pure objects", 43); STRING_LITERAL(T839829468_413, "(($1) && ($2))", 14); STRING_LITERAL(T839829468_414, "$1.m_type == $2", 15); STRING_LITERAL(T839829468_415, "Nim_OfCheck_CACHE", 17); STRING_LITERAL(T839829468_416, "static TNimType* $#[2];$n", 25); STRING_LITERAL(T839829468_417, "#isObjWithCache($#.m_type, $#, $#)", 34); STRING_LITERAL(T839829468_418, "($1)", 4); STRING_LITERAL(T839829468_419, "sizeof($1)", 10); STRING_LITERAL(T839829468_420, "if ($1) #nimGCunref($1);$n", 26); STRING_LITERAL(T839829468_421, "($1) #newObjRC1($2, $3)", 23); STRING_LITERAL(T839829468_422, "($1) #newObj($2, $3)", 20); STRING_LITERAL(T839829468_423, "$1->finalizer = (void*)$2;$n", 28); STRING_LITERAL(T839829468_424, "($1) #newObj($2, sizeof($3))", 28); STRING_LITERAL(T839829468_425, "($1) #newSeqRC1($2, $3)", 23); STRING_LITERAL(T839829468_426, "($1) #newSeq($2, $3)", 20); STRING_LITERAL(T839829468_427, "($1)#nimNewSeqOfCap($2, $3)", 27); STRING_LITERAL(T839829468_428, "((NI)sizeof($1))", 16); STRING_LITERAL(T839829468_429, "(*($1*) ($2))", 13); STRING_LITERAL(T839829468_430, "(($1) ($2))", 11); STRING_LITERAL(T839829468_431, "($1Len0-1)", 10); STRING_LITERAL(T839829468_432, "$1Len0", 6); STRING_LITERAL(T839829468_433, "($1 ? (strlen($1)-1) : -1)", 26); STRING_LITERAL(T839829468_434, "($1 ? strlen($1) : 0)", 21); STRING_LITERAL(T839829468_435, "($1 ? ($1->Sup.len-1) : -1)", 27); STRING_LITERAL(T839829468_436, "($1 ? $1->Sup.len : 0)", 22); STRING_LITERAL(T839829468_437, "($1 ? ($1->len-1) : -1)", 23); STRING_LITERAL(T839829468_438, "($1 ? $1->len : 0)", 18); STRING_LITERAL(T839829468_439, "genArrayLen()", 13); STRING_LITERAL(T839829468_440, "($1->Sup.len)", 13); STRING_LITERAL(T839829468_441, "$1->len", 7); STRING_LITERAL(T839829468_442, "unaryStmt", 9); STRING_LITERAL(T839829468_443, "#nimGCref($1);$n", 16); STRING_LITERAL(T839829468_444, "#nimGCunref($1);$n", 18); STRING_LITERAL(T839829468_445, "$1 = #setLengthStr($1, $2);$n", 29); STRING_LITERAL(T839829468_446, "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n", 54); STRING_LITERAL(T839829468_447, "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n", 46); STRING_LITERAL(T839829468_448, "($1- $2)", 8); STRING_LITERAL(T839829468_449, "$1 |= ((", 8); STRING_LITERAL(T839829468_450, ")1)<<(($2)%(sizeof(", 19); STRING_LITERAL(T839829468_451, ")*8));$n", 8); STRING_LITERAL(T839829468_452, "$1 &= ~(((", 10); STRING_LITERAL(T839829468_453, ")1) << (($2) % (sizeof(", 23); STRING_LITERAL(T839829468_454, ")*8)));$n", 9); STRING_LITERAL(T839829468_455, "#countBits32($1)", 16); STRING_LITERAL(T839829468_456, "#countBits64($1)", 16); STRING_LITERAL(T839829468_457, "(($1 & ~ $2 ==0)&&($1 != $2))", 29); STRING_LITERAL(T839829468_458, "(($1 & ~ $2)==0)", 16); STRING_LITERAL(T839829468_459, "($1 & $2)", 9); STRING_LITERAL(T839829468_460, "($1 | $2)", 9); STRING_LITERAL(T839829468_461, "($1 & ~ $2)", 11); STRING_LITERAL(T839829468_462, "($1 ^ $2)", 9); STRING_LITERAL(T839829468_463, "fewCmps", 7); STRING_LITERAL(T839829468_464, "$1 >= $2 && $1 <= $3", 20); STRING_LITERAL(T839829468_465, "$1 == $2", 8); STRING_LITERAL(T839829468_466, " || ", 4); STRING_LITERAL(T839829468_467, "(($1 &(1U<<((NU)($2)&7U)))!=0)", 30); STRING_LITERAL(T839829468_468, "(($1 &(1U<<((NU)($2)&15U)))!=0)", 31); STRING_LITERAL(T839829468_469, "(($1 &(1U<<((NU)($2)&31U)))!=0)", 31); STRING_LITERAL(T839829468_470, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)", 36); STRING_LITERAL(T839829468_471, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)", 43); STRING_LITERAL(T839829468_472, "genSetOp()", 10); STRING_LITERAL(T839829468_473, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n", 34); STRING_LITERAL(T839829468_474, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n", 36); STRING_LITERAL(T839829468_475, "#cardSet($1, ", 13); STRING_LITERAL(T839829468_476, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == " "0);$n if (!$3) break;}$n", 88); STRING_LITERAL(T839829468_477, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == " "0);$n if (!$3) break;}$nif ($3) $3 = (memcmp($4, $5, $2) != 0);" "$n", 129); STRING_LITERAL(T839829468_478, "|", 1); STRING_LITERAL(T839829468_479, "& ~", 3); STRING_LITERAL(T839829468_480, "^", 1); NIM_CONST TY557428 lookupopr_557426_839829468 = {((NimStringDesc*) &T839829468_476), ((NimStringDesc*) &T839829468_477), ((NimStringDesc*) &T839829468_52), ((NimStringDesc*) &T839829468_478), ((NimStringDesc*) &T839829468_479), ((NimStringDesc*) &T839829468_480)} ; STRING_LITERAL(T839829468_481, "(memcmp($1, $2, ", 16); STRING_LITERAL(T839829468_482, ")==0)", 5); STRING_LITERAL(T839829468_483, "for ($1 = 0; $1 < $2; $1++) $n $3[$1] = $4[$1] $6 $5[$1];$n", 60); STRING_LITERAL(T839829468_484, "genSetOp", 8); STRING_LITERAL(T839829468_485, "$1->data", 8); STRING_LITERAL(T839829468_486, "($1)+($2), ($3)-($2)+1", 22); STRING_LITERAL(T839829468_487, "(*$1)->data+($2), ($3)-($2)+1", 29); STRING_LITERAL(T839829468_488, "$1->data+($2), ($3)-($2)+1", 26); STRING_LITERAL(T839829468_489, "openArrayLoc: ", 14); STRING_LITERAL(T839829468_490, "", 0); STRING_LITERAL(T839829468_491, "(*$1)->data, (*$1)->$2", 22); STRING_LITERAL(T839829468_492, "$1.ClPrc($3$1.ClEnv)", 20); STRING_LITERAL(T839829468_493, "$1.ClEnv? $1.ClPrc($3$1.ClEnv):(($4)($1.ClPrc))($2)", 51); STRING_LITERAL(T839829468_494, "$1 = 0;$n", 9); STRING_LITERAL(T839829468_495, "#chckNil((void*)$1);$n", 22); STRING_LITERAL(T839829468_496, "#genericReset((void*)$1, $2);$n", 31); STRING_LITERAL(T839829468_497, ";$n", 3); STRING_LITERAL(T839829468_499, "compiler/ccgcalls.nim", 21); NIM_CONST TY204018 T839829468_498 = {((NimStringDesc*) &T839829468_499), ((NI) 423)} ; static NIM_CONST char136Set T839829468_500 = { 0x00, 0x00, 0x00, 0x00, 0x88, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} ; STRING_LITERAL(T839829468_501, "wrong argument count", 20); STRING_LITERAL(T839829468_502, "call expression expected for C++ pattern", 40); NIM_CONST TY204018 T839829468_503 = {((NimStringDesc*) &T839829468_499), ((NI) 328)} ; STRING_LITERAL(T839829468_504, "->", 2); STRING_LITERAL(T839829468_505, ");$n", 4); STRING_LITERAL(T839829468_506, "[", 1); NIM_CONST TY204018 T839829468_507 = {((NimStringDesc*) &T839829468_499), ((NI) 472)} ; STRING_LITERAL(T839829468_508, "varargs for objective C method?", 31); STRING_LITERAL(T839829468_509, "Result: ", 8); STRING_LITERAL(T839829468_510, "];$n", 4); STRING_LITERAL(T839829468_511, "]", 1); NIM_CONST TY204018 T839829468_512 = {((NimStringDesc*) &T839829468_265), ((NI) 925)} ; STRING_LITERAL(T839829468_513, "<stdio.h>", 9); STRING_LITERAL(T839829468_514, ", \"nil\"", 7); STRING_LITERAL(T839829468_515, ", $1? ($1)->data:\"nil\"", 22); STRING_LITERAL(T839829468_516, "printf($1$2);$n", 15); STRING_LITERAL(T839829468_517, "%s", 2); STRING_LITERAL(T839829468_518, "fflush(stdout);$n", 17); STRING_LITERAL(T839829468_519, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n", 45); STRING_LITERAL(T839829468_520, "#genericSeqDeepCopy($1, $2, $3);$n", 34); STRING_LITERAL(T839829468_521, "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 62); STRING_LITERAL(T839829468_522, "genDeepCopy: ", 13); STRING_LITERAL(T839829468_523, "genMagicExpr: ", 14); STRING_LITERAL(T839829468_524, "static NIM_CONST $1 $2 = $3;$n", 30); STRING_LITERAL(T839829468_525, "memset($1, 0, sizeof($1));$n", 28); STRING_LITERAL(T839829468_526, "for ($1 = $3; $1 <= $4; $1++) $n$2[(NU)($1)>>3] |=(1U<<((NU)($1" ")&7U));$n", 72); STRING_LITERAL(T839829468_527, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n", 40); STRING_LITERAL(T839829468_528, "for ($1 = $3; $1 <= $4; $1++) $n$2 |=((", 39); STRING_LITERAL(T839829468_529, ")(1)<<(($1)%(sizeof(", 20); STRING_LITERAL(T839829468_530, "$1 |=((", 7); STRING_LITERAL(T839829468_531, ")(1)<<(($2)%(sizeof(", 20); STRING_LITERAL(T839829468_532, "genCheckedRecordField", 21); STRING_LITERAL(T839829468_533, "genObjConstr", 12); STRING_LITERAL(T839829468_534, "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n", 52); STRING_LITERAL(T839829468_535, "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n", 55); STRING_LITERAL(T839829468_536, "LOC$1.source", 12); STRING_LITERAL(T839829468_537, "union { $1 source; $2 dest; } LOC$3;$n", 38); STRING_LITERAL(T839829468_538, "LOC$#.dest", 10); STRING_LITERAL(T839829468_539, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n", 46); STRING_LITERAL(T839829468_540, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n", 45); STRING_LITERAL(T839829468_541, "$1[($2)- $3]", 12); STRING_LITERAL(T839829468_542, "if ((NU)($1) >= (NU)($2Len0)) #raiseIndexError();$n", 51); STRING_LITERAL(T839829468_543, "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n", 50); STRING_LITERAL(T839829468_544, "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n", 51); STRING_LITERAL(T839829468_545, "genTupleElem", 12); STRING_LITERAL(T839829468_546, ".Field$1", 8); STRING_LITERAL(T839829468_547, "expr(nkBracketExpr, ", 20); STRING_LITERAL(T839829468_548, "genDeref ", 9); STRING_LITERAL(T839829468_549, "genRecordFieldAux", 17); STRING_LITERAL(T839829468_550, "genRecordField 3", 16); STRING_LITERAL(T839829468_551, ".$1", 3); STRING_LITERAL(T839829468_552, "} $1: ;$n", 9); STRING_LITERAL(T839829468_553, "FR.len-=$1;$n", 13); STRING_LITERAL(T839829468_554, "FR.len+=$1;$n", 13); STRING_LITERAL(T839829468_555, "if (!$1) goto $2;$n", 19); STRING_LITERAL(T839829468_556, "goto $1;$n", 10); STRING_LITERAL(T839829468_557, "genIf()", 7); STRING_LITERAL(T839829468_558, "->Sup", 5); STRING_LITERAL(T839829468_559, "$1 = &$2;$n", 11); STRING_LITERAL(T839829468_560, "if ($1) #chckObj($2.m_type, $3);$n", 34); STRING_LITERAL(T839829468_561, "#chckObj($1.m_type, $2);$n", 26); STRING_LITERAL(T839829468_562, "(($1)#$5($2, $3, $4))", 21); STRING_LITERAL(T839829468_563, "chckRangeF", 10); STRING_LITERAL(T839829468_564, "chckRange64", 11); STRING_LITERAL(T839829468_565, "chckRange", 9); STRING_LITERAL(T839829468_566, "CNSTCLOSURE", 11); STRING_LITERAL(T839829468_567, "closure to closure created", 26); STRING_LITERAL(T839829468_568, "$1.ClPrc = $2; $1.ClEnv = $3;$n", 31); STRING_LITERAL(T839829468_569, "while (1) {$n", 13); STRING_LITERAL(T839829468_570, "case statement must be exhaustive for computed goto", 51); STRING_LITERAL(T839829468_571, "case statement has too many cases for computed goto", 51); STRING_LITERAL(T839829468_572, "case statement has to start at 0 for computed goto", 50); STRING_LITERAL(T839829468_573, "no case statement found for computed goto", 41); STRING_LITERAL(T839829468_574, "TMP$1", 5); STRING_LITERAL(T839829468_575, "static void* $#[$#] = {", 23); STRING_LITERAL(T839829468_576, "&&TMP$#, ", 9); STRING_LITERAL(T839829468_577, "&&TMP$#};$n", 11); STRING_LITERAL(T839829468_578, "goto *$#[$#];$n", 15); STRING_LITERAL(T839829468_579, "range notation not available for computed goto", 46); STRING_LITERAL(T839829468_580, "TMP$#:$n", 8); STRING_LITERAL(T839829468_581, "#nimProfile();$n", 16); STRING_LITERAL(T839829468_582, "\'goto\' target must be a literal value", 37); STRING_LITERAL(T839829468_583, "goto NIMSTATE_$#;$n", 19); STRING_LITERAL(T839829468_584, "$1 = ($2*) #nimGetProcAddr($3, $4);$n", 37); STRING_LITERAL(T839829468_585, "$2* $1;$n", 9); STRING_LITERAL(T839829468_586, "#dbgRegisterGlobal($1, &$2, $3);$n", 34); STRING_LITERAL(T839829468_587, "#nimGCvisit((void*)$1, 0);$n", 28); STRING_LITERAL(T839829468_588, "N_NIMCALL(void, $1)(void)", 25); STRING_LITERAL(T839829468_589, "#nimRegisterGlobalMarker($1);$n", 31); STRING_LITERAL(T839829468_590, "$#($#);$n", 9); STRING_LITERAL(T839829468_591, "$# = $#;$n", 10); STRING_LITERAL(T839829468_592, "genVarTuple", 11); STRING_LITERAL(T839829468_593, "genConstStmt", 12); STRING_LITERAL(T839829468_594, "for statement not eliminated", 28); STRING_LITERAL(T839829468_595, "if (#eqStrings($1, $2)) goto $3;$n", 34); STRING_LITERAL(T839829468_596, "switch (#hashString($1) & $2) {$n", 33); STRING_LITERAL(T839829468_597, "case $1: $n$2break;$n", 21); STRING_LITERAL(T839829468_598, "goto LA$1;$n", 12); STRING_LITERAL(T839829468_599, "LA$1: ;$n", 9); STRING_LITERAL(T839829468_600, "if ($1 >= $2 && $1 <= $3) goto $4;$n", 36); STRING_LITERAL(T839829468_601, "if ($1 == $2) goto $3;$n", 24); STRING_LITERAL(T839829468_602, "NIMSTATE_$#:$n", 14); STRING_LITERAL(T839829468_603, "switch ($1) {$n", 15); STRING_LITERAL(T839829468_604, "default: __assume(0);$n", 23); STRING_LITERAL(T839829468_605, "#popSafePoint();$n", 18); STRING_LITERAL(T839829468_606, "#popCurrentException();$n", 25); STRING_LITERAL(T839829468_607, "if ($1.status != 0) #popCurrentException();$n", 45); STRING_LITERAL(T839829468_608, "goto BeforeRet;$n", 17); STRING_LITERAL(T839829468_609, "no loop to break", 16); STRING_LITERAL(T839829468_610, "extern $1", 9); STRING_LITERAL(T839829468_611, "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n", 62); STRING_LITERAL(T839829468_612, "genAsmOrEmitStmt()", 18); STRING_LITERAL(T839829468_613, "\"", 1); STRING_LITERAL(T839829468_614, "\\n\"\012", 4); STRING_LITERAL(T839829468_615, "Exception", 9); STRING_LITERAL(T839829468_616, "E_Base", 6); STRING_LITERAL(T839829468_617, "try {$n", 7); STRING_LITERAL(T839829468_618, "} catch (NimException& $1) {$n", 30); STRING_LITERAL(T839829468_619, "#setFrame((TFrame*)&FR);$n", 26); STRING_LITERAL(T839829468_620, "else ", 5); STRING_LITERAL(T839829468_621, "#isObj($1.exp->m_type, $2)", 26); STRING_LITERAL(T839829468_622, "if ($1) ", 8); STRING_LITERAL(T839829468_623, "throw;$n", 8); STRING_LITERAL(T839829468_624, "<setjmp.h>", 10); STRING_LITERAL(T839829468_625, "#TSafePoint $1;$n", 17); STRING_LITERAL(T839829468_626, "#pushSafePoint(&$1);$n", 22); STRING_LITERAL(T839829468_627, "nimStdSetjmp", 12); STRING_LITERAL(T839829468_628, "$1.status = setjmp($1.context);$n", 33); STRING_LITERAL(T839829468_629, "nimSigSetjmp", 12); STRING_LITERAL(T839829468_630, "$1.status = sigsetjmp($1.context, 0);$n", 39); STRING_LITERAL(T839829468_631, "nimRawSetjmp", 12); STRING_LITERAL(T839829468_632, "$1.status = _setjmp($1.context);$n", 34); STRING_LITERAL(T839829468_633, "if ($1.status == 0) {$n", 23); STRING_LITERAL(T839829468_634, "else {$n", 8); STRING_LITERAL(T839829468_635, "else", 4); STRING_LITERAL(T839829468_636, "$1.status = 0;$n", 16); STRING_LITERAL(T839829468_637, "#isObj(#getCurrentException()->Sup.m_type, $1)", 46); STRING_LITERAL(T839829468_638, "#isObj(#getCurrentException()->m_type, $1)", 42); STRING_LITERAL(T839829468_639, "if ($1) {$n", 11); STRING_LITERAL(T839829468_640, "if ($1.status != 0) #reraiseException();$n", 42); STRING_LITERAL(T839829468_641, "#raiseException((#Exception*)$1, $2);$n", 39); STRING_LITERAL(T839829468_642, "#reraiseException();$n", 22); STRING_LITERAL(T839829468_643, "/*TYPESECTION*/", 15); STRING_LITERAL(T839829468_644, "/*VARSECTION*/", 14); STRING_LITERAL(T839829468_645, "/*INCLUDESECTION*/", 18); STRING_LITERAL(T839829468_646, "bp", 2); STRING_LITERAL(T839829468_647, "#dbgRegisterBreakpoint($1, (NCSTRING)$2, (NCSTRING)$3);$n", 57); STRING_LITERAL(T839829468_648, "#dbgRegisterWatchpoint($1, (NCSTRING)$2, $3);$n", 47); STRING_LITERAL(T839829468_649, "#pragma omp parallel for $4$nfor ($1 = $2; $1 <= $3; ++$1)", 58); STRING_LITERAL(T839829468_651, "compiler/ccgstmts.nim", 21); NIM_CONST TY204018 T839829468_650 = {((NimStringDesc*) &T839829468_651), ((NI) 145)} ; STRING_LITERAL(T839829468_652, "STATE$1: ;$n", 12); STRING_LITERAL(T839829468_653, "case -1: goto BeforeRet;$n", 26); STRING_LITERAL(T839829468_654, "case $1: goto STATE$1;$n", 24); STRING_LITERAL(T839829468_655, "if (((NI*) $1)[0] < 0) break;$n", 31); STRING_LITERAL(T839829468_656, "if ((((NI*) $1.ClEnv)[0]) < 0) break;$n", 39); STRING_LITERAL(T839829468_657, "); unknown node kind", 20); NIM_CONST TY204018 T839829468_658 = {((NimStringDesc*) &T839829468_651), ((NI) 1122)} ; STRING_LITERAL(T839829468_659, "Init000", 7); STRING_LITERAL(T839829468_660, "DatInit000", 10); STRING_LITERAL(T839829468_661, "NIM_EXTERNC N_NOINLINE(void, $1)(void);$N", 41); STRING_LITERAL(T839829468_662, "\011$1();$N", 8); STRING_LITERAL(T839829468_663, "N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDECL(void, NimMa" "in)(void) {$N\011void (*volatile inner)();$N\011PreMain();$N\011inner = N" "imMainInner;$N$2\011(*inner)();$N}$N$N", 162); STRING_LITERAL(T839829468_664, "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N " " HINSTANCE hPrevInstance, $N LP" "STR lpCmdLine, int nCmdShow) {$N\011NimMain();$N\011return nim_program" "_result;$N}$N$N", 206); STRING_LITERAL(T839829468_665, "N_LIB_EXPORT N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDEC" "L(void, NimMain)(void) {$N\011void (*volatile inner)();$N\011PreMain()" ";$N\011inner = NimMainInner;$N$2\011(*inner)();$N}$N$N", 175); STRING_LITERAL(T839829468_666, "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N " " LPVOID lpvReserved) {$N\011if(fwdreason == DLL_PROC" "ESS_ATTACH) {$N\011NimMain();$N}$N\011return 1;$N}$N$N", 175); STRING_LITERAL(T839829468_667, "<windows.h>", 11); STRING_LITERAL(T839829468_668, "void NIM_POSIX_INIT NimMainInit(void) {$N\011NimMain();$N}$N$N", 59); STRING_LITERAL(T839829468_669, "int cmdCount;$Nchar** cmdLine;$Nchar** gEnv;$NN_CDECL(void, Nim" "MainInner)(void) {$N$1}$N$NN_CDECL(void, NimMain)(void) {$N\011void" " (*volatile inner)();$N\011PreMain();$N\011inner = NimMainInner;$N$2\011(" "*inner)();$N}$N$N", 208); STRING_LITERAL(T839829468_670, "int main(void) {$N\011NimMain();$N\011return 0;$N}$N$N", 48); STRING_LITERAL(T839829468_671, "int main(int argc, char** args, char** env) {$N\011cmdLine = args;" "$N\011cmdCount = argc;$N\011gEnv = env;$N\011NimMain();$N\011return nim_prog" "ram_result;$N}$N$N", 145); STRING_LITERAL(T839829468_672, "dbgRegisterBreakpoint", 21); STRING_LITERAL(T839829468_673, "dbgRegisterFilename", 19); STRING_LITERAL(T839829468_674, "dbgRegisterFilename($1);$N", 26); STRING_LITERAL(T839829468_675, "\011#initStackBottomWith((void *)&inner);$N", 40); STRING_LITERAL(T839829468_676, "void PreMainInner() {$N\011systemInit000();$N$1$2$3}$N$Nvoid PreMa" "in() {$N\011void (*volatile inner)();$N\011systemDatInit000();$N\011inner" " = PreMainInner;$N$4$5\011(*inner)();$N}$N$N", 168); STRING_LITERAL(T839829468_677, "\011#initThreadVarsEmulation();$N", 30); STRING_LITERAL(T839829468_678, "still forwarded: ", 17); STRING_LITERAL(T839829468_679, "NIM_EXTERNC N_NOINLINE(void, $1)(void) {$N", 42); STRING_LITERAL(T839829468_680, "static #TNimNode $1[$2];$n", 26); STRING_LITERAL(T839829468_681, "static #TNimType $1[$2];$n", 26); STRING_LITERAL(T839829468_682, "\011TFrame FR; FR.len = 0;$N", 25); STRING_LITERAL(T839829468_683, "}$N$N", 5); STRING_LITERAL(T839829468_684, "N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N", 46); STRING_LITERAL(T839829468_685, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump" "f */$N/* The generated code is subject to the original license. " "*/$N", 131); STRING_LITERAL(T839829468_686, "0.15.0", 6); STRING_LITERAL(T839829468_687, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump" "f */$N/* The generated code is subject to the original license. " "*/$N/* Compiled for: $2, $3, $4 */$N/* Command for C compiler:$n" " $5 */$N", 201); extern NIM_CONST TY177082 Os_177068_4151366050; extern NIM_CONST TY177510 Cpu_177496_4151366050; STRING_LITERAL(T839829468_688, "#define NIM_INTBITS $1", 22); STRING_LITERAL(T839829468_689, "typedef struct {$1} NimThreadVars;$n", 36); STRING_LITERAL(T839829468_690, "#include \"nimbase.h\"", 20); STRING_LITERAL(T839829468_691, "#include \"$1\"$N", 15); STRING_LITERAL(T839829468_692, "#include $1$N", 13); STRING_LITERAL(T839829468_693, "extern \"C\"", 10); STRING_LITERAL(T839829468_694, "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n", 61); STRING_LITERAL(T839829468_695, "__$1__", 6); STRING_LITERAL(T839829468_696, "#ifndef $1$n#define $1$n", 24); STRING_LITERAL(T839829468_697, "N_CDECL(void, NimMain)(void);$n", 31); STRING_LITERAL(T839829468_698, "#endif /* $1 */$n", 17); Tcgen530027* generatedheader_533201_839829468; extern TNimType NTI530015; /* BModule */ Ropeobj179006* indent_533655_839829468; extern TNimType NTI179004; /* Rope */ extern Gcheap49818 gch_49858_1689653243; Ropeobj179006* nimtv_539656_839829468; Ttypeseq293836* nimtvdeps_539674_839829468; extern TNimType NTI293836; /* TTypeSeq */ Intset269030 nimtvdeclared_539675_839829468; extern TNimType NTI269030; /* IntSet */ NI breakpointid_549860_839829468; Ropeobj179006* gbreakpoints_549861_839829468; extern TY530153* gmodules_530170_3723162438; extern TNimType NTI530027; /* TCGen */ extern Debuginfo204009 gdebuginfo_204470_1926258066; extern Toption170009Set goptions_170128_2607990831; extern TNimType NTI293804; /* TSymSeq */ extern Tglobaloption170013Set gglobaloptions_170130_2607990831; extern NimStringDesc* headerfile_170138_2607990831; extern NimStringDesc* gprojectfull_170211_2607990831; extern Tcommands170076 gcmd_170132_2607990831; extern NI gerrorcounter_193069_155036129; extern Ropeobj179006* rnl_179903_2381377266; extern NI gforwardedprocscounter_530171_3723162438; extern TNimType NTI293244; /* TTypeKind */ extern TNimType NTI204017; /* seq[(string, int)] */ extern Tsystemcc274002 ccompiler_274431_2528170400; extern NimStringDesc* tnl_177644_4151366050; extern NI floatsize_177642_4151366050; extern Tgcmode170080 gselectedgc_170133_2607990831; extern TNimType NTI293020; /* TNodeKind */ extern TNimType NTI135002; /* seq[string] */ extern TNimType NTI293435; /* TSymKind */ extern TNimType NTI293816; /* TLoc */ extern NI intsize_177641_4151366050; extern TNimType NTI293524; /* TMagic */ extern TNimType NTI192350; /* seq[Rope] */ extern TNimType NTI293796; /* TNodeSeq */ extern Ropeobj179006* mainmodprocs_530148_3723162438; extern Ropeobj179006* maindatinit_530151_3723162438; extern Ropeobj179006* mainmodinit_530149_3723162438; extern Ropeobj179006* othermodsinit_530150_3723162438; extern Tsystemos177004 targetos_177629_4151366050; extern TY192612* fileinfos_192629_155036129; extern Tsystemcpu177452 targetcpu_177627_4151366050; extern Ropeobj179006* gmapping_530152_3723162438; N_NIMCALL(void, T839829468_2)(void) { nimGCvisit((void*)generatedheader_533201_839829468, 0); } N_NIMCALL(void, T839829468_3)(void) { nimGCvisit((void*)indent_533655_839829468, 0); } static N_INLINE(Cell47305*, usrtocell_51440_1689653243)(void* usr0) { Cell47305* result0; result0 = (Cell47305*)0; result0 = ((Cell47305*) ((NI)((NU64)(((NI) (usr0))) - (NU64)(((NI)sizeof(Cell47305)))))); return result0; } static N_INLINE(void, rtladdzct_52601_1689653243)(Cell47305* c0) { addzct_51417_1689653243((&gch_49858_1689653243.zct), c0); } static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0) { { Cell47305* c0; if (!!((src0 == NIM_NIL))) goto LA3; c0 = usrtocell_51440_1689653243(src0); (*c0).refcount += ((NI) 8); } LA3: ; { Cell47305* c0; if (!!(((*dest0) == NIM_NIL))) goto LA7; c0 = usrtocell_51440_1689653243((*dest0)); { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA11; rtladdzct_52601_1689653243(c0); } LA11: ; } LA7: ; (*dest0) = src0; } N_NIMCALL(void, T839829468_5)(void) { nimGCvisit((void*)nimtv_539656_839829468, 0); } N_NIMCALL(void, T839829468_6)(void) { nimGCvisit((void*)nimtvdeps_539674_839829468, 0); } static N_INLINE(void, nimGCunrefNoCycle)(void* p0) { Cell47305* c0; c0 = usrtocell_51440_1689653243(p0); { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA3; rtladdzct_52601_1689653243(c0); } LA3: ; } N_NIMCALL(void, T839829468_7)(void) { nimGCvisit((void*)nimtvdeclared_539675_839829468.head, 0); nimGCvisit((void*)nimtvdeclared_539675_839829468.data, 0); } N_NIMCALL(void, T839829468_8)(void) { nimGCvisit((void*)gbreakpoints_549861_839829468, 0); } N_NIMCALL(Tcgen530027*, getcgenmodule_533226_839829468)(Tsym293834* s0) { Tcgen530027* result0; result0 = (Tcgen530027*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (((NI) 0) <= (*s0).position); if (!(LOC3)) goto LA4; LOC3 = ((*s0).position < (gmodules_530170_3723162438 ? gmodules_530170_3723162438->Sup.len : 0)); LA4: ; if (!LOC3) goto LA5; result0 = gmodules_530170_3723162438->data[(*s0).position]; } goto LA1; LA5: ; { result0 = NIM_NIL; } LA1: ; return result0; } static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0) { void* LOC1; LOC1 = (void*)0; LOC1 = memcpy(dest0, source0, ((size_t) (size0))); } static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0) { copymem_7485_1689653243(((void*) ((&(*dest0).data[((*dest0).Sup.len)- 0]))), ((void*) ((*src0).data)), ((NI) ((NI)((*src0).Sup.len + ((NI) 1))))); (*dest0).Sup.len += (*src0).Sup.len; } N_NIMCALL(NU32, hashowner_533977_839829468)(Tsym293834* s0) { NU32 result0; Tsym293834* m0; Tsym293834* p0; result0 = (NU32)0; m0 = s0; { while (1) { if (!!(((*m0).kind == ((Tsymkind293435) 6)))) goto LA2; m0 = (*m0).owner; } LA2: ; } p0 = (*m0).owner; result0 = register_204121_1926258066((&gdebuginfo_204470_1926258066), (*(*p0).name).s, (*(*m0).name).s); return result0; } static N_INLINE(void, incref_53419_1689653243)(Cell47305* c0) { (*c0).refcount = (NI)((NU64)((*c0).refcount) + (NU64)(((NI) 8))); } static N_INLINE(void, decref_53001_1689653243)(Cell47305* c0) { { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA3; rtladdzct_52601_1689653243(c0); } LA3: ; } static N_INLINE(void, asgnRef)(void** dest0, void* src0) { { Cell47305* LOC5; if (!!((src0 == NIM_NIL))) goto LA3; LOC5 = (Cell47305*)0; LOC5 = usrtocell_51440_1689653243(src0); incref_53419_1689653243(LOC5); } LA3: ; { Cell47305* LOC10; if (!!(((*dest0) == NIM_NIL))) goto LA8; LOC10 = (Cell47305*)0; LOC10 = usrtocell_51440_1689653243((*dest0)); decref_53001_1689653243(LOC10); } LA8: ; (*dest0) = src0; } N_NIMCALL(Toption170009Set, initprocoptions_563635_839829468)(Tcgen530027* m0) { Toption170009Set result0; memset((void*)(&result0), 0, sizeof(result0)); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 13))&31U)))!=0)) goto LA3; result0 = (goptions_170128_2607990831 & ~ 32768); } goto LA1; LA3: ; { result0 = goptions_170128_2607990831; } LA1: ; return result0; } N_NIMCALL(Tcproc530021*, newpreinitproc_563625_839829468)(Tcgen530027* m0) { Tcproc530021* result0; result0 = (Tcproc530021*)0; result0 = newproc_530206_3723162438(NIM_NIL, m0); (*result0).labels = ((NI) 100000); return result0; } N_NIMCALL(Tcproc530021*, newpostinitproc_563630_839829468)(Tcgen530027* m0) { Tcproc530021* result0; result0 = (Tcproc530021*)0; result0 = newproc_530206_3723162438(NIM_NIL, m0); (*result0).labels = ((NI) 200000); return result0; } N_NIMCALL(Ropeobj179006*, gettempname_534598_839829468)(Tcgen530027* m0) { Ropeobj179006* result0; Ropeobj179006* LOC1; result0 = (Ropeobj179006*)0; LOC1 = (Ropeobj179006*)0; LOC1 = rope_179401_2381377266(((NI64) ((*m0).labels))); result0 = HEX26_179418_2381377266((*m0).tmpbase, LOC1); (*m0).labels += ((NI) 1); return result0; } N_NIMCALL(Tcgen530027*, rawnewmodule_563663_839829468)(Tsym293834* module0, NimStringDesc* filename0) { Tcgen530027* result0; NimStringDesc* LOC1; NU32 LOC2; NimStringDesc* LOC3; NimStringDesc* LOC4; NimStringDesc* LOC5; result0 = (Tcgen530027*)0; result0 = (Tcgen530027*) newObj((&NTI530015), sizeof(Tcgen530027)); (*result0).Sup.Sup.m_type = (&NTI530027); LOC1 = (NimStringDesc*)0; LOC2 = (NU32)0; LOC2 = hashowner_533977_839829468(module0); LOC3 = (NimStringDesc*)0; LOC3 = HEX24_8401_1689653243(((NU64) (LOC2))); LOC1 = rawNewString(LOC3->Sup.len + 2); appendString(LOC1, ((NimStringDesc*) &T839829468_11)); appendString(LOC1, LOC3); appendString(LOC1, ((NimStringDesc*) &T839829468_12)); asgnRefNoCycle((void**) (&(*result0).tmpbase), rope_179277_2381377266(LOC1)); initlinkedlist_147031_3771138726((&(*result0).headerfiles)); initintset_269885_2627731572((&(*result0).declaredthings)); initintset_269885_2627731572((&(*result0).declaredprotos)); LOC4 = (NimStringDesc*)0; LOC4 = (*result0).cfilename; (*result0).cfilename = copyStringRC1(filename0); if (LOC4) nimGCunrefNoCycle(LOC4); LOC5 = (NimStringDesc*)0; LOC5 = (*result0).filename; (*result0).filename = copyStringRC1(filename0); if (LOC5) nimGCunrefNoCycle(LOC5); initidtable_297019_850551059((&(*result0).typecache)); initidtable_297019_850551059((&(*result0).forwtypecache)); asgnRefNoCycle((void**) (&(*result0).module), module0); initintset_269885_2627731572((&(*result0).typeinfomarker)); asgnRef((void**) (&(*result0).initproc), newproc_530206_3723162438(NIM_NIL, result0)); (*(*result0).initproc).options = initprocoptions_563635_839829468(result0); asgnRef((void**) (&(*result0).preinitproc), newpreinitproc_563625_839829468(result0)); asgnRef((void**) (&(*result0).postinitproc), newpostinitproc_563630_839829468(result0)); initnodetable_297085_850551059((&(*result0).datacache)); if ((*result0).typestack) nimGCunrefNoCycle((*result0).typestack); (*result0).typestack = (Ttypeseq293836*) newSeqRC1((&NTI293836), 0); if ((*result0).forwardedprocs) nimGCunrefNoCycle((*result0).forwardedprocs); (*result0).forwardedprocs = (Tsymseq293804*) newSeqRC1((&NTI293804), 0); asgnRefNoCycle((void**) (&(*result0).typenodesname), gettempname_534598_839829468(result0)); asgnRefNoCycle((void**) (&(*result0).nimtypesname), gettempname_534598_839829468(result0)); { if (!(((*module0).flags &(1U<<((NU)(((Tsymflag293184) 13))&31U)))!=0)) goto LA8; (*result0).flags |= ((NU8)1)<<((((Codegenflag530025) 0))%(sizeof(NU8)*8)); (*(*result0).preinitproc).options &= ~(((NU32)1) << ((((Toption170009) 15)) % (sizeof(NU32)*8))); (*(*result0).postinitproc).options &= ~(((NU32)1) << ((((Toption170009) 15)) % (sizeof(NU32)*8))); } LA8: ; return result0; } N_NIMCALL(Tcgen530027*, rawnewmodule_564038_839829468)(Tsym293834* module0) { Tcgen530027* result0; NimStringDesc* LOC1; result0 = (Tcgen530027*)0; LOC1 = (NimStringDesc*)0; LOC1 = tofullpath_193261_155036129(((NI32) ((*module0).position))); result0 = rawnewmodule_563663_839829468(module0, LOC1); return result0; } N_NIMCALL(Tcgen530027*, newmodule_564044_839829468)(Tsym293834* module0) { Tcgen530027* result0; result0 = (Tcgen530027*)0; { Tcgen530027* LOC3; NimStringDesc* LOC6; LOC3 = (Tcgen530027*)0; LOC3 = getcgenmodule_533226_839829468(module0); if (!!((LOC3 == NIM_NIL))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_197185_1689653243(T839829468_9); internalerror_197113_155036129(LOC6); } LA4: ; result0 = rawnewmodule_564038_839829468(module0); { if (!((gmodules_530170_3723162438 ? gmodules_530170_3723162438->Sup.len : 0) <= (*module0).position)) goto LA9; gmodules_530170_3723162438 = (TY530153*) setLengthSeq(&(gmodules_530170_3723162438)->Sup, sizeof(Tcgen530027*), ((NI) ((NI)((*module0).position + ((NI) 1))))); } LA9: ; asgnRef((void**) (&gmodules_530170_3723162438->data[(*module0).position]), result0); { if (!((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 2))&63U)))!=0)) goto LA13; { NimStringDesc* LOC19; NimStringDesc* LOC20; if (!(((*module0).flags &(1U<<((NU)(((Tsymflag293184) 25))&31U)))!=0)) goto LA17; LOC19 = (NimStringDesc*)0; LOC20 = (NimStringDesc*)0; LOC20 = tofilename_193257_155036129(((NI32) ((*module0).position))); LOC19 = rawNewString(LOC20->Sup.len + 28); appendString(LOC19, ((NimStringDesc*) &T839829468_13)); appendString(LOC19, LOC20); internalerror_197113_155036129(LOC19); } LA17: ; } LA13: ; return result0; } N_NIMCALL(Tpasscontext342002*, myopen_564112_839829468)(Tsym293834* module0) { Tpasscontext342002* result0; Tcgen530027* LOC1; result0 = (Tpasscontext342002*)0; LOC1 = (Tcgen530027*)0; LOC1 = newmodule_564044_839829468(module0); result0 = &LOC1->Sup; { NIM_BOOL LOC4; NimStringDesc* f0; NimStringDesc* LOC13; NimStringDesc* LOC14; LOC4 = (NIM_BOOL)0; LOC4 = ((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 27))&63U)))!=0); if (!(LOC4)) goto LA5; LOC4 = (generatedheader_533201_839829468 == NIM_NIL); LA5: ; if (!LOC4) goto LA6; { if (!(((NI) 0) < (headerfile_170138_2607990831 ? headerfile_170138_2607990831->Sup.len : 0))) goto LA10; f0 = headerfile_170138_2607990831; } goto LA8; LA10: ; { f0 = gprojectfull_170211_2607990831; } LA8: ; LOC13 = (NimStringDesc*)0; LOC13 = completecfilepath_274854_2528170400(f0, NIM_TRUE); LOC14 = (NimStringDesc*)0; LOC14 = noschangeFileExt(LOC13, ((NimStringDesc*) &T839829468_14)); asgnRef((void**) (&generatedheader_533201_839829468), rawnewmodule_563663_839829468(module0, LOC14)); (*generatedheader_533201_839829468).flags |= ((NU8)1)<<((((Codegenflag530025) 3))%(sizeof(NU8)*8)); } LA6: ; return result0; } N_NIMCALL(NimStringDesc*, getcfile_564201_839829468)(Tcgen530027* m0) { NimStringDesc* result0; NimStringDesc* ext0; NimStringDesc* LOC13; NimStringDesc* LOC14; result0 = (NimStringDesc*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; ext0 = copyString(((NimStringDesc*) &T839829468_15)); } goto LA1; LA5: ; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = (gcmd_170132_2607990831 == ((Tcommands170076) 3)); if (LOC8) goto LA9; LOC8 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 28))&31U)))!=0); LA9: ; if (!LOC8) goto LA10; ext0 = copyString(((NimStringDesc*) &T839829468_16)); } goto LA1; LA10: ; { ext0 = copyString(((NimStringDesc*) &T839829468_17)); } LA1: ; LOC13 = (NimStringDesc*)0; LOC13 = withpackagename_171073_2607990831((*m0).cfilename); LOC14 = (NimStringDesc*)0; LOC14 = completecfilepath_274854_2528170400(LOC13, NIM_TRUE); result0 = noschangeFileExt(LOC14, ext0); return result0; } N_NIMCALL(Tpasscontext342002*, myopencached_564246_839829468)(Tsym293834* module0, Trodreader333021* rd0) { Tpasscontext342002* result0; Tcgen530027* m0; NimStringDesc* LOC1; result0 = (Tpasscontext342002*)0; m0 = newmodule_564044_839829468(module0); LOC1 = (NimStringDesc*)0; LOC1 = getcfile_564201_839829468(m0); readmergeinfo_531613_2760143328(LOC1, m0); result0 = &m0->Sup; return result0; } static N_INLINE(NIM_BOOL, skipcodegen_342085_2355241294)(Tnode293802* n0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = (((NI) 0) < gerrorcounter_193069_155036129); return result0; } N_NIMCALL(void, fillloc_533282_839829468)(Tloc293816* a0, Tlockind293808 k0, Ttype293840* typ0, Ropeobj179006* r0, Tstorageloc293812 s0) { { if (!((*a0).k == ((Tlockind293808) 0))) goto LA3; (*a0).k = k0; unsureAsgnRef((void**) (&(*a0).t), typ0); (*a0).s = s0; { if (!((*a0).r == NIM_NIL)) goto LA7; unsureAsgnRef((void**) (&(*a0).r), r0); } LA7: ; } LA3: ; } N_NIMCALL(NIM_BOOL, iskeyword_533960_839829468)(Tident200010* w0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; switch ((*w0).Sup.id) { case ((NI) 200) ... ((NI) 262): case ((NI) 4) ... ((NI) 70): case ((NI) 138): { result0 = NIM_TRUE; goto BeforeRet; } break; default: { result0 = NIM_FALSE; goto BeforeRet; } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj179006*, manglename_534205_839829468)(Tsym293834* s0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = (*s0).loc.r; { NIM_BOOL keeporigname0; NIM_BOOL LOC5; NIM_BOOL LOC6; NIM_BOOL LOC9; NimStringDesc* LOC10; if (!(result0 == NIM_NIL)) goto LA3; LOC5 = (NIM_BOOL)0; LOC6 = (NIM_BOOL)0; LOC6 = ((2824 &(1U<<((NU)((*s0).kind)&31U)))!=0); if (!(LOC6)) goto LA7; LOC6 = ((IL64(2149580812) & (*s0).flags) == 0); LA7: ; LOC5 = LOC6; if (!(LOC5)) goto LA8; LOC9 = (NIM_BOOL)0; LOC9 = iskeyword_533960_839829468((*s0).name); LOC5 = !(LOC9); LA8: ; keeporigname0 = LOC5; LOC10 = (NimStringDesc*)0; LOC10 = mangle_529847_2036603609((*(*s0).name).s); result0 = rope_179277_2381377266(LOC10); { if (!keeporigname0) goto LA13; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_18)); } goto LA11; LA13: ; { TY534289 LOC16; Ropeobj179006* LOC17; Ropeobj179006* LOC18; TY534289 LOC19; Ropeobj179006* LOC20; NU32 LOC21; Ropeobj179006* LOC22; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (Ropeobj179006*)0; LOC17 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_12), LOC16, 0); add_179482_2381377266(&result0, LOC17); LOC18 = (Ropeobj179006*)0; LOC18 = rope_179401_2381377266(((NI64) ((*s0).Sup.id))); add_179482_2381377266(&result0, LOC18); memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (Ropeobj179006*)0; LOC20 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_12), LOC19, 0); add_179482_2381377266(&result0, LOC20); LOC21 = (NU32)0; LOC21 = hashowner_533977_839829468(s0); LOC22 = (Ropeobj179006*)0; LOC22 = rope_179401_2381377266(((NI64) (LOC21))); add_179482_2381377266(&result0, LOC22); } LA11: ; asgnRefNoCycle((void**) (&(*s0).loc.r), result0); } LA3: ; return result0; } N_NIMCALL(void, fillprocloc_540201_839829468)(Tsym293834* sym0) { { Ropeobj179006* LOC5; if (!((*sym0).loc.k == ((Tlockind293808) 0))) goto LA3; LOC5 = (Ropeobj179006*)0; LOC5 = manglename_534205_839829468(sym0); fillloc_533282_839829468((&(*sym0).loc), ((Tlockind293808) 7), (*sym0).typ, LOC5, ((Tstorageloc293812) 2)); } LA3: ; } N_NIMCALL(void, useheader_533369_839829468)(Tcgen530027* m0, Tsym293834* sym0) { { NimStringDesc* LOC5; NIM_BOOL LOC6; if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag293810) 6))&15U)))!=0)) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = getstr_298230_850551059((*(*sym0).annex).path); LOC6 = (NIM_BOOL)0; LOC6 = includestr_147249_3771138726((&(*m0).headerfiles), LOC5); } LA3: ; } static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0) { (*dest0).data[((*dest0).Sup.len)- 0] = c0; (*dest0).data[((NI)((*dest0).Sup.len + ((NI) 1)))- 0] = 0; (*dest0).Sup.len += ((NI) 1); } N_NIMCALL(NIM_BOOL, isactivated_562431_839829468)(Tsym293834* prc0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = !(((*prc0).typ == NIM_NIL)); return result0; } N_NIMCALL(void, addforwardedproc_533203_839829468)(Tcgen530027* m0, Tsym293834* prc0) { (*m0).forwardedprocs = (Tsymseq293804*) incrSeqV2(&((*m0).forwardedprocs)->Sup, sizeof(Tsym293834*)); asgnRefNoCycle((void**) (&(*m0).forwardedprocs->data[(*m0).forwardedprocs->Sup.len]), prc0); ++(*m0).forwardedprocs->Sup.len; gforwardedprocscounter_530171_3723162438 += ((NI) 1); } N_NIMCALL(void, genclinedir_533725_839829468)(Ropeobj179006** r0, NimStringDesc* filename0, NI line0) { { TY533811 LOC5; NimStringDesc* LOC6; if (!((goptions_170128_2607990831 &(1U<<((NU)(((Toption170009) 10))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (NimStringDesc*)0; LOC6 = makesinglelinecstring_529835_2036603609(filename0); LOC5[0] = rope_179277_2381377266(LOC6); LOC5[1] = rope_179401_2381377266(((NI64) (line0))); addf_180205_2381377266(r0, ((NimStringDesc*) &T839829468_21), LOC5, 2); } LA3: ; } static N_INLINE(NI, tolinenumber_193415_155036129)(Tlineinfo192336 info0) { NI result0; result0 = (NI)0; result0 = ((NI) (info0.line)); return result0; } N_NIMCALL(NI, safelinenm_533721_839829468)(Tlineinfo192336 info0) { NI result0; result0 = (NI)0; result0 = tolinenumber_193415_155036129(info0); { if (!(result0 < ((NI) 0))) goto LA3; result0 = ((NI) 0); } LA3: ; return result0; } N_NIMCALL(void, genclinedir_533813_839829468)(Ropeobj179006** r0, Tlineinfo192336 info0) { NimStringDesc* LOC1; NI LOC2; LOC1 = (NimStringDesc*)0; LOC1 = tofullpath_193261_155036129(info0.fileindex); LOC2 = (NI)0; LOC2 = safelinenm_533721_839829468(info0); genclinedir_533725_839829468(r0, LOC1, LOC2); } N_NIMCALL(Tctypekind530007, mapsettype_534389_839829468)(Ttype293840* typ0) { Tctypekind530007 result0; NI64 LOC1; result0 = (Tctypekind530007)0; LOC1 = (NI64)0; LOC1 = getsize_321135_3876443242(typ0); switch (((NI) (LOC1))) { case ((NI) 1): { result0 = ((Tctypekind530007) 4); } break; case ((NI) 2): { result0 = ((Tctypekind530007) 5); } break; case ((NI) 4): { result0 = ((Tctypekind530007) 6); } break; case ((NI) 8): { result0 = ((Tctypekind530007) 7); } break; default: { result0 = ((Tctypekind530007) 17); } break; } return result0; } N_NIMCALL(Tctypekind530007, maptype_534394_839829468)(Ttype293840* typ0) { Tctypekind530007 result0; result0 = (Tctypekind530007)0; switch ((*typ0).kind) { case ((Ttypekind293244) 0): case ((Ttypekind293244) 7): { result0 = ((Tctypekind530007) 0); } break; case ((Ttypekind293244) 1): { result0 = ((Tctypekind530007) 2); } break; case ((Ttypekind293244) 2): { result0 = ((Tctypekind530007) 1); } break; case ((Ttypekind293244) 19): { result0 = mapsettype_534389_839829468(typ0); } break; case ((Ttypekind293244) 27): case ((Ttypekind293244) 4): case ((Ttypekind293244) 16): case ((Ttypekind293244) 48): { result0 = ((Tctypekind530007) 17); } break; case ((Ttypekind293244) 17): case ((Ttypekind293244) 18): { result0 = ((Tctypekind530007) 19); } break; case ((Ttypekind293244) 10): case ((Ttypekind293244) 11): case ((Ttypekind293244) 12): case ((Ttypekind293244) 13): case ((Ttypekind293244) 15): case ((Ttypekind293244) 46): case ((Ttypekind293244) 47): case ((Ttypekind293244) 49): case ((Ttypekind293244) 8): { Ttype293840* LOC8; LOC8 = (Ttype293840*)0; LOC8 = lastson_296377_850551059(typ0); result0 = maptype_534394_839829468(LOC8); } break; case ((Ttypekind293244) 14): { { NI64 LOC12; LOC12 = (NI64)0; LOC12 = firstord_321001_3876443242(typ0); if (!(LOC12 < IL64(0))) goto LA13; result0 = ((Tctypekind530007) 6); } goto LA10; LA13: ; { NI64 LOC16; LOC16 = (NI64)0; LOC16 = getsize_321135_3876443242(typ0); switch (((NI) (LOC16))) { case ((NI) 1): { result0 = ((Tctypekind530007) 13); } break; case ((NI) 2): { result0 = ((Tctypekind530007) 14); } break; case ((NI) 4): { result0 = ((Tctypekind530007) 6); } break; case ((NI) 8): { result0 = ((Tctypekind530007) 7); } break; default: { internalerror_197113_155036129(((NimStringDesc*) &T839829468_25)); } break; } } LA10: ; } break; case ((Ttypekind293244) 20): { result0 = maptype_534394_839829468((*typ0).sons->data[((NI) 0)]); } break; case ((Ttypekind293244) 21): case ((Ttypekind293244) 23): case ((Ttypekind293244) 22): { Ttype293840* base0; Ttype293840* LOC24; LOC24 = (Ttype293840*)0; LOC24 = lastson_296377_850551059(typ0); base0 = skiptypes_297099_850551059(LOC24, IL64(211106232576256)); switch ((*base0).kind) { case ((Ttypekind293244) 27): case ((Ttypekind293244) 4): case ((Ttypekind293244) 16): case ((Ttypekind293244) 48): { result0 = ((Tctypekind530007) 18); } break; default: { result0 = ((Tctypekind530007) 20); } break; } } break; case ((Ttypekind293244) 26): { result0 = ((Tctypekind530007) 20); } break; case ((Ttypekind293244) 24): { result0 = ((Tctypekind530007) 22); } break; case ((Ttypekind293244) 25): { { if (!!(((*typ0).callconv == ((Tcallingconvention293002) 8)))) goto LA32; result0 = ((Tctypekind530007) 23); } goto LA30; LA32: ; { result0 = ((Tctypekind530007) 19); } LA30: ; } break; case ((Ttypekind293244) 28): { result0 = ((Tctypekind530007) 21); } break; case ((Ttypekind293244) 29): { result0 = ((Tctypekind530007) 24); } break; case ((Ttypekind293244) 31) ... ((Ttypekind293244) 44): { result0 = ((Tctypekind530007) ((NI)(((NI) ((NI)(((NI) ((*typ0).kind)) - ((NI) 31)))) + ((NI) 3)))); } break; case ((Ttypekind293244) 59): { { Ttype293840* LOC43; if (!!(((*typ0).n == NIM_NIL))) goto LA41; LOC43 = (Ttype293840*)0; LOC43 = lastson_296377_850551059(typ0); result0 = maptype_534394_839829468(LOC43); } goto LA39; LA41: ; { internalerror_197113_155036129(((NimStringDesc*) &T839829468_25)); } LA39: ; } break; default: { internalerror_197113_155036129(((NimStringDesc*) &T839829468_25)); } break; } return result0; } N_NIMCALL(NIM_BOOL, isimportedcpptype_534478_839829468)(Ttype293840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = !(((*t0).sym == NIM_NIL)); if (!(LOC1)) goto LA2; LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NIM_BOOL, needscomplexassignment_534511_839829468)(Ttype293840* typ0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = containsgarbagecollectedref_321117_3876443242(typ0); return result0; } static N_INLINE(NIM_BOOL, isobjlackingtypefield_534515_839829468)(Ttype293840* typ0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC3; NIM_BOOL LOC4; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((*typ0).kind == ((Ttypekind293244) 17)); if (!(LOC1)) goto LA2; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 2))&31U)))!=0); if (!(LOC4)) goto LA5; LOC4 = ((*typ0).sons->data[((NI) 0)] == NIM_NIL); LA5: ; LOC3 = LOC4; if (LOC3) goto LA6; LOC3 = ispureobject_321138_3876443242(typ0); LA6: ; LOC1 = LOC3; LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NIM_BOOL, isinvalidreturntype_534550_839829468)(Ttype293840* rettype0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!(rettype0 == NIM_NIL)) goto LA3; result0 = NIM_TRUE; } goto LA1; LA3: ; { Tctypekind530007 LOC6; LOC6 = (Tctypekind530007)0; LOC6 = maptype_534394_839829468(rettype0); switch (LOC6) { case ((Tctypekind530007) 17): { Ttype293840* LOC8; LOC8 = (Ttype293840*)0; LOC8 = skiptypes_297099_850551059(rettype0, IL64(211106232576256)); result0 = !(((14680064 &((NU64)1<<((NU)((*LOC8).kind)&63U)))!=0)); } break; case ((Tctypekind530007) 19): { Ttype293840* t0; NIM_BOOL LOC16; NIM_BOOL LOC18; NIM_BOOL LOC20; t0 = skiptypes_297099_850551059(rettype0, IL64(211106232576256)); { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = isimportedcpptype_534478_839829468(rettype0); if (LOC12) goto LA13; LOC12 = isimportedcpptype_534478_839829468(t0); LA13: ; if (!LOC12) goto LA14; result0 = NIM_FALSE; goto BeforeRet; } LA14: ; LOC16 = (NIM_BOOL)0; LOC16 = needscomplexassignment_534511_839829468(t0); if (LOC16) goto LA17; LOC18 = (NIM_BOOL)0; LOC18 = ((*t0).kind == ((Ttypekind293244) 17)); if (!(LOC18)) goto LA19; LOC20 = (NIM_BOOL)0; LOC20 = isobjlackingtypefield_534515_839829468(t0); LOC18 = !(LOC20); LA19: ; LOC16 = LOC18; LA17: ; result0 = LOC16; } break; default: { result0 = NIM_FALSE; } break; } } LA1: ; }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj179006*, typename_534292_839829468)(Ttype293840* typ0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NimStringDesc* LOC5; if (!!(((*typ0).sym == NIM_NIL))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = mangle_529847_2036603609((*(*(*typ0).sym).name).s); result0 = rope_179277_2381377266(LOC5); } goto LA1; LA3: ; { TY534289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_28), LOC7, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, gettypename_534313_839829468)(Ttype293840* typ0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*typ0).sym == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = !(((96 & (*(*typ0).sym).flags) == 0)); LA4: ; if (!LOC3) goto LA5; result0 = (*(*typ0).sym).loc.r; } goto LA1; LA5: ; { { Ropeobj179006* LOC12; Ropeobj179006* LOC13; if (!((*typ0).loc.r == NIM_NIL)) goto LA10; LOC12 = (Ropeobj179006*)0; LOC12 = typename_534292_839829468(typ0); LOC13 = (Ropeobj179006*)0; LOC13 = rope_179401_2381377266(((NI64) ((*typ0).Sup.id))); asgnRefNoCycle((void**) (&(*typ0).loc.r), HEX26_179418_2381377266(LOC12, LOC13)); } LA10: ; result0 = (*typ0).loc.r; } LA1: ; { NimStringDesc* LOC18; if (!(result0 == NIM_NIL)) goto LA16; LOC18 = (NimStringDesc*)0; LOC18 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI293244))->Sup.len + 13); appendString(LOC18, ((NimStringDesc*) &T839829468_29)); appendString(LOC18, reprEnum((NI)(*typ0).kind, (&NTI293244))); internalerror_197113_155036129(LOC18); } LA16: ; return result0; } N_NIMCALL(Ropeobj179006*, typenameorliteral_534898_839829468)(Ttype293840* t0, NimStringDesc* literal0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = !(((*t0).sym == NIM_NIL)); if (!(LOC4)) goto LA5; LOC4 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag293184) 5))&31U)))!=0); LA5: ; LOC3 = LOC4; if (!(LOC3)) goto LA6; LOC3 = ((*(*t0).sym).magic == ((Tmagic293524) 0)); LA6: ; if (!LOC3) goto LA7; result0 = gettypename_534313_839829468(t0); } goto LA1; LA7: ; { result0 = rope_179277_2381377266(literal0); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, getsimpletypedesc_534936_839829468)(Tcgen530027* m0, Ttype293840* typ0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; switch ((*typ0).kind) { case ((Ttypekind293244) 26): { result0 = typenameorliteral_534898_839829468(typ0, ((NimStringDesc*) &T839829468_30)); } break; case ((Ttypekind293244) 28): { Ropeobj179006* LOC3; LOC3 = (Ropeobj179006*)0; LOC3 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_31)); result0 = typenameorliteral_534898_839829468(typ0, ((NimStringDesc*) &T839829468_32)); } break; case ((Ttypekind293244) 29): { result0 = typenameorliteral_534898_839829468(typ0, ((NimStringDesc*) &T839829468_33)); } break; case ((Ttypekind293244) 1): { result0 = typenameorliteral_534898_839829468(typ0, ((NimStringDesc*) &T839829468_34)); } break; case ((Ttypekind293244) 2): { result0 = typenameorliteral_534898_839829468(typ0, ((NimStringDesc*) &T839829468_35)); } break; case ((Ttypekind293244) 5): { result0 = typenameorliteral_534898_839829468(typ0, ((NimStringDesc*) &T839829468_18)); } break; case ((Ttypekind293244) 31) ... ((Ttypekind293244) 44): { result0 = typenameorliteral_534898_839829468(typ0, Numericaltypetostr_534941_839829468[((*typ0).kind)- 31]); } break; case ((Ttypekind293244) 13): case ((Ttypekind293244) 20): case ((Ttypekind293244) 15): { result0 = getsimpletypedesc_534936_839829468(m0, (*typ0).sons->data[((NI) 0)]); } break; case ((Ttypekind293244) 59): { { Ttype293840* LOC15; if (!!(((*typ0).n == NIM_NIL))) goto LA13; LOC15 = (Ttype293840*)0; LOC15 = lastson_296377_850551059(typ0); result0 = getsimpletypedesc_534936_839829468(m0, LOC15); } goto LA11; LA13: ; { internalerror_197113_155036129(((NimStringDesc*) &T839829468_50)); } LA11: ; } break; case ((Ttypekind293244) 11): { Ttype293840* LOC18; LOC18 = (Ttype293840*)0; LOC18 = lastson_296377_850551059(typ0); result0 = getsimpletypedesc_534936_839829468(m0, LOC18); } break; default: { result0 = NIM_NIL; } break; } return result0; } N_NIMCALL(Ropeobj179006*, cachegettype_534593_839829468)(Tidtable293850 tab0, Ttype293840* key0) { Ropeobj179006* result0; Tidobj200004* LOC1; TNimObject* LOC2; result0 = (Ropeobj179006*)0; LOC1 = (Tidobj200004*)0; LOC1 = &key0->Sup; LOC2 = (TNimObject*)0; LOC2 = idtableget_300086_2984716966(tab0, LOC1); result0 = ((Ropeobj179006*) (LOC2)); return result0; } N_NIMCALL(Ropeobj179006*, gettypepre_534972_839829468)(Tcgen530027* m0, Ttype293840* typ0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { if (!(typ0 == NIM_NIL)) goto LA3; result0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_26)); } goto LA1; LA3: ; { result0 = getsimpletypedesc_534936_839829468(m0, typ0); { if (!(result0 == NIM_NIL)) goto LA8; result0 = cachegettype_534593_839829468((*m0).typecache, typ0); } LA8: ; } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, isimportedtype_534451_839829468)(Ttype293840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = !(((*t0).sym == NIM_NIL)); if (!(LOC1)) goto LA2; LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag293184) 5))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NimStringDesc*, getforwardstructformat_535015_839829468)(Tcgen530027* m0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; result0 = copyString(((NimStringDesc*) &T839829468_54)); } goto LA1; LA5: ; { result0 = copyString(((NimStringDesc*) &T839829468_55)); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, structorunion_535001_839829468)(Ttype293840* t0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag293431) 1))&31U)))!=0)) goto LA3; result0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_56)); } goto LA1; LA3: ; { result0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_57)); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, gettypeforward_535039_839829468)(Tcgen530027* m0, Ttype293840* typ0) { Ropeobj179006* result0; { result0 = (Ropeobj179006*)0; result0 = cachegettype_534593_839829468((*m0).forwtypecache, typ0); { if (!!((result0 == NIM_NIL))) goto LA3; goto BeforeRet; } LA3: ; result0 = gettypepre_534972_839829468(m0, typ0); { if (!!((result0 == NIM_NIL))) goto LA7; goto BeforeRet; } LA7: ; switch ((*typ0).kind) { case ((Ttypekind293244) 24): case ((Ttypekind293244) 18): case ((Ttypekind293244) 17): { Tidobj200004* LOC17; TNimObject* LOC18; result0 = gettypename_534313_839829468(typ0); { NIM_BOOL LOC12; NimStringDesc* LOC15; TY533811 LOC16; LOC12 = (NIM_BOOL)0; LOC12 = isimportedtype_534451_839829468(typ0); if (!!(LOC12)) goto LA13; LOC15 = (NimStringDesc*)0; LOC15 = getforwardstructformat_535015_839829468(m0); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = structorunion_535001_839829468(typ0); LOC16[1] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 2))- 0], LOC15, LOC16, 2); } LA13: ; LOC17 = (Tidobj200004*)0; LOC17 = &typ0->Sup; LOC18 = (TNimObject*)0; LOC18 = &result0->Sup; idtableput_300094_2984716966((&(*m0).forwtypecache), LOC17, LOC18); } break; default: { NimStringDesc* LOC20; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI293244))->Sup.len + 16); appendString(LOC20, ((NimStringDesc*) &T839829468_58)); appendString(LOC20, reprEnum((NI)(*typ0).kind, (&NTI293244))); appendChar(LOC20, 41); internalerror_197113_155036129(LOC20); } break; } }BeforeRet: ; return result0; } N_NIMCALL(void, pushtype_534958_839829468)(Tcgen530027* m0, Ttype293840* typ0) { (*m0).typestack = (Ttypeseq293836*) incrSeqV2(&((*m0).typestack)->Sup, sizeof(Ttype293840*)); asgnRefNoCycle((void**) (&(*m0).typestack->data[(*m0).typestack->Sup.len]), typ0); ++(*m0).typestack->Sup.len; } N_NIMCALL(Ropeobj179006*, gettypedescweak_535079_839829468)(Tcgen530027* m0, Ttype293840* t0, Intset269030* check0) { Ropeobj179006* result0; Ttype293840* etb0; result0 = (Ropeobj179006*)0; etb0 = skiptypes_297099_850551059(t0, IL64(211106232576256)); switch ((*etb0).kind) { case ((Ttypekind293244) 17): case ((Ttypekind293244) 18): { { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = isimportedcpptype_534478_839829468(etb0); if (!(LOC4)) goto LA5; LOC4 = ((*t0).kind == ((Ttypekind293244) 11)); LA5: ; if (!LOC4) goto LA6; result0 = gettypedescaux_534505_839829468(m0, t0, check0); } goto LA2; LA6: ; { Ttype293840* x0; x0 = getuniquetype_529640_2036603609(etb0); result0 = gettypeforward_535039_839829468(m0, x0); pushtype_534958_839829468(m0, x0); } LA2: ; } break; case ((Ttypekind293244) 24): { Ttype293840* x0; Ropeobj179006* LOC10; x0 = getuniquetype_529640_2036603609(etb0); LOC10 = (Ropeobj179006*)0; LOC10 = gettypeforward_535039_839829468(m0, x0); result0 = HEX26_179447_2381377266(LOC10, ((NimStringDesc*) &T839829468_53)); pushtype_534958_839829468(m0, x0); } break; default: { result0 = gettypedescaux_534505_839829468(m0, t0, check0); } break; } return result0; } static N_INLINE(NI, len_294081_850551059)(Tnode293802* n0) { NI result0; result0 = (NI)0; { if (!(*n0).kindU.S6.sons == 0) goto LA3; result0 = ((NI) 0); } goto LA1; LA3: ; { result0 = ((*n0).kindU.S6.sons ? (*n0).kindU.S6.sons->Sup.len : 0); } LA1: ; return result0; } N_NIMCALL(void, appcg_533632_839829468)(Tcgen530027* m0, Ropeobj179006** c0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0) { Ropeobj179006* LOC1; LOC1 = (Ropeobj179006*)0; LOC1 = ropecg_533407_839829468(m0, frmt0, args0, args0Len0); add_179482_2381377266(c0, LOC1); } N_NIMCALL(NIM_BOOL, scancppgenericslot_535827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0) { NIM_BOOL result0; NI begin0; { result0 = (NIM_BOOL)0; (*cursor0) += ((NI) 1); begin0 = (*cursor0); { while (1) { if (!((NU8)(pat0->data[(*cursor0)]) == (NU8)(42))) goto LA2; (*cursor0) += ((NI) 1); } LA2: ; } { if (!(((NU8)(pat0->data[(*cursor0)])) >= ((NU8)(48)) && ((NU8)(pat0->data[(*cursor0)])) <= ((NU8)(57)))) goto LA5; (*outidx0) = ((NI) ((NI)(((NI) (((NU8)(pat0->data[(*cursor0)])))) - ((NI) 48)))); (*outstars0) = (NI)((*cursor0) - begin0); (*cursor0) += ((NI) 1); result0 = NIM_TRUE; goto BeforeRet; } goto LA3; LA5: ; { result0 = NIM_FALSE; goto BeforeRet; } LA3: ; }BeforeRet: ; return result0; } N_NIMCALL(Ttype293840*, resolvestarsincpptype_535891_839829468)(Ttype293840* typ0, NI idx0, NI stars0) { Ttype293840* result0; result0 = (Ttype293840*)0; { NI LOC3; LOC3 = (NI)0; LOC3 = len_296339_850551059(typ0); if (!(LOC3 <= idx0)) goto LA4; internalerror_197113_155036129(((NimStringDesc*) &T839829468_81)); } LA4: ; result0 = (*typ0).sons->data[idx0]; { NI i_535906_839829468; NI res_535931_839829468; i_535906_839829468 = (NI)0; res_535931_839829468 = ((NI) 1); { while (1) { if (!(res_535931_839829468 <= stars0)) goto LA8; i_535906_839829468 = res_535931_839829468; { NIM_BOOL LOC11; NI LOC13; LOC11 = (NIM_BOOL)0; LOC11 = !((result0 == NIM_NIL)); if (!(LOC11)) goto LA12; LOC13 = (NI)0; LOC13 = len_296339_850551059(result0); LOC11 = (((NI) 0) < LOC13); LA12: ; if (!LOC11) goto LA14; { if (!((*result0).kind == ((Ttypekind293244) 11))) goto LA18; result0 = (*result0).sons->data[((NI) 1)]; } goto LA16; LA18: ; { result0 = elemtype_321394_3876443242(result0); } LA16: ; } LA14: ; res_535931_839829468 += ((NI) 1); } LA8: ; } } return result0; } N_NIMCALL(NimStringDesc*, manglefield_533973_839829468)(Tident200010* name0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; result0 = mangle_529847_2036603609((*name0).s); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = iskeyword_533960_839829468(name0); if (!LOC3) goto LA4; result0->data[((NI) 0)] = nsuToUpperAsciiChar(result0->data[((NI) 0)]); } LA4: ; return result0; } N_NIMCALL(Ropeobj179006*, manglerecfieldname_535361_839829468)(Tsym293834* field0, Ttype293840* rectype0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*rectype0).sym == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = !(((96 & (*(*rectype0).sym).flags) == 0)); LA4: ; if (!LOC3) goto LA5; result0 = (*field0).loc.r; } goto LA1; LA5: ; { NimStringDesc* LOC8; LOC8 = (NimStringDesc*)0; LOC8 = manglefield_533973_839829468((*field0).name); result0 = rope_179277_2381377266(LOC8); } LA1: ; { if (!(result0 == NIM_NIL)) goto LA11; internalerror_197100_155036129((*field0).info, ((NimStringDesc*) &T839829468_96)); } LA11: ; return result0; } N_NIMCALL(Ropeobj179006*, genrecordfieldsaux_535421_839829468)(Tcgen530027* m0, Tnode293802* n0, Ropeobj179006* accessexpr0, Ttype293840* rectype0, Intset269030* check0) { Ropeobj179006* result0; Ropeobj179006* ae0; Ropeobj179006* uname0; Ropeobj179006* sname0; Ropeobj179006* a0; Tnode293802* k0; Tsym293834* field0; { result0 = (Ropeobj179006*)0; ae0 = (Ropeobj179006*)0; uname0 = (Ropeobj179006*)0; sname0 = (Ropeobj179006*)0; a0 = (Ropeobj179006*)0; k0 = (Tnode293802*)0; field0 = (Tsym293834*)0; result0 = NIM_NIL; switch ((*n0).kind) { case ((Tnodekind293020) 138): { { NI i_535447_839829468; NI HEX3Atmp_535620_839829468; NI LOC3; NI res_535623_839829468; i_535447_839829468 = (NI)0; HEX3Atmp_535620_839829468 = (NI)0; LOC3 = (NI)0; LOC3 = sonslen_296351_850551059(n0); HEX3Atmp_535620_839829468 = (NI)(LOC3 - ((NI) 1)); res_535623_839829468 = ((NI) 0); { while (1) { Ropeobj179006* LOC6; if (!(res_535623_839829468 <= HEX3Atmp_535620_839829468)) goto LA5; i_535447_839829468 = res_535623_839829468; LOC6 = (Ropeobj179006*)0; LOC6 = genrecordfieldsaux_535421_839829468(m0, (*n0).kindU.S6.sons->data[i_535447_839829468], accessexpr0, rectype0, check0); add_179482_2381377266(&result0, LOC6); res_535623_839829468 += ((NI) 1); } LA5: ; } } } break; case ((Tnodekind293020) 139): { Ropeobj179006* LOC12; NimStringDesc* LOC13; NimStringDesc* LOC14; Ropeobj179006* unionbody0; { if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)))) goto LA10; internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_89)); } LA10: ; LOC12 = (Ropeobj179006*)0; LOC12 = genrecordfieldsaux_535421_839829468(m0, (*n0).kindU.S6.sons->data[((NI) 0)], accessexpr0, rectype0, check0); add_179482_2381377266(&result0, LOC12); LOC13 = (NimStringDesc*)0; LOC14 = (NimStringDesc*)0; LOC14 = mangle_529847_2036603609((*(*(*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s); LOC13 = rawNewString(LOC14->Sup.len + 1); appendString(LOC13, LOC14); appendChar(LOC13, 85); uname0 = rope_179277_2381377266(LOC13); { TY533811 LOC19; if (!!((accessexpr0 == NIM_NIL))) goto LA17; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = accessexpr0; LOC19[1] = uname0; ae0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_90), LOC19, 2); } goto LA15; LA17: ; { ae0 = uname0; } LA15: ; unionbody0 = NIM_NIL; { NI i_535491_839829468; NI HEX3Atmp_535629_839829468; NI LOC22; NI res_535632_839829468; i_535491_839829468 = (NI)0; HEX3Atmp_535629_839829468 = (NI)0; LOC22 = (NI)0; LOC22 = sonslen_296351_850551059(n0); HEX3Atmp_535629_839829468 = (NI)(LOC22 - ((NI) 1)); res_535632_839829468 = ((NI) 1); { while (1) { if (!(res_535632_839829468 <= HEX3Atmp_535629_839829468)) goto LA24; i_535491_839829468 = res_535632_839829468; switch ((*(*n0).kindU.S6.sons->data[i_535491_839829468]).kind) { case ((Tnodekind293020) 85): case ((Tnodekind293020) 88): { k0 = lastson_296364_850551059((*n0).kindU.S6.sons->data[i_535491_839829468]); { Ropeobj179006* LOC30; TY533811 LOC31; Ropeobj179006* LOC32; if (!!(((*k0).kind == ((Tnodekind293020) 3)))) goto LA28; LOC30 = (Ropeobj179006*)0; LOC30 = rope_179401_2381377266(((NI64) (i_535491_839829468))); sname0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_91), LOC30); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = ae0; LOC31[1] = sname0; LOC32 = (Ropeobj179006*)0; LOC32 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_90), LOC31, 2); a0 = genrecordfieldsaux_535421_839829468(m0, k0, LOC32, rectype0, check0); { TY179507 LOC37; if (!!((a0 == NIM_NIL))) goto LA35; add_179487_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_92)); add_179482_2381377266(&unionbody0, a0); memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = sname0; addf_180205_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_93), LOC37, 1); } LA35: ; } goto LA26; LA28: ; { Ropeobj179006* LOC39; LOC39 = (Ropeobj179006*)0; LOC39 = genrecordfieldsaux_535421_839829468(m0, k0, ae0, rectype0, check0); add_179482_2381377266(&unionbody0, LOC39); } LA26: ; } break; default: { internalerror_197113_155036129(((NimStringDesc*) &T839829468_94)); } break; } res_535632_839829468 += ((NI) 1); } LA24: ; } } { TY533811 LOC45; if (!!((unionbody0 == NIM_NIL))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = unionbody0; LOC45[1] = uname0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_95), LOC45, 2); } LA43: ; } break; case ((Tnodekind293020) 3): { field0 = (*n0).kindU.S4.sym; { if (!((*(*field0).typ).kind == ((Ttypekind293244) 62))) goto LA49; goto BeforeRet; } LA49: ; sname0 = manglerecfieldname_535361_839829468(field0, rectype0); { TY533811 LOC55; if (!!((accessexpr0 == NIM_NIL))) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = accessexpr0; LOC55[1] = sname0; ae0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_90), LOC55, 2); } goto LA51; LA53: ; { ae0 = sname0; } LA51: ; fillloc_533282_839829468((&(*field0).loc), ((Tlockind293808) 5), (*field0).typ, ae0, ((Tstorageloc293812) 0)); { NIM_BOOL LOC59; Ttype293840* fieldtype0; LOC59 = (NIM_BOOL)0; LOC59 = isimportedcpptype_534478_839829468(rectype0); if (!!(LOC59)) goto LA60; fieldtype0 = skiptypes_297099_850551059((*field0).loc.t, IL64(211106232576256)); { NIM_BOOL LOC64; TY533811 LOC68; Ttype293840* LOC69; LOC64 = (NIM_BOOL)0; LOC64 = ((*fieldtype0).kind == ((Ttypekind293244) 16)); if (!(LOC64)) goto LA65; LOC64 = (((*fieldtype0).flags &(1U<<((NU)(((Ttypeflag293431) 0))&31U)))!=0); LA65: ; if (!LOC64) goto LA66; memset((void*)LOC68, 0, sizeof(LOC68)); LOC69 = (Ttype293840*)0; LOC69 = elemtype_321394_3876443242(fieldtype0); LOC68[0] = gettypedescaux_534505_839829468(m0, LOC69, check0); LOC68[1] = sname0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_97), LOC68, 2); } goto LA62; LA66: ; { TY533811 LOC73; if (!((*fieldtype0).kind == ((Ttypekind293244) 24))) goto LA71; memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = gettypedescweak_535079_839829468(m0, (*field0).loc.t, check0); LOC73[1] = sname0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC73, 2); } goto LA62; LA71: ; { TY536238 LOC77; NimStringDesc* LOC78; if (!!(((*field0).kindU.S4.bitsize == ((NI) 0)))) goto LA75; memset((void*)LOC77, 0, sizeof(LOC77)); LOC77[0] = gettypedescaux_534505_839829468(m0, (*field0).loc.t, check0); LOC77[1] = sname0; LOC78 = (NimStringDesc*)0; LOC78 = nimIntToStr((*field0).kindU.S4.bitsize); LOC77[2] = rope_179277_2381377266(LOC78); addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_98), LOC77, 3); } goto LA62; LA75: ; { TY533811 LOC80; memset((void*)LOC80, 0, sizeof(LOC80)); LOC80[0] = gettypedescaux_534505_839829468(m0, (*field0).loc.t, check0); LOC80[1] = sname0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC80, 2); } LA62: ; } LA60: ; } break; default: { internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_99)); } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj179006*, getrecordfields_535636_839829468)(Tcgen530027* m0, Ttype293840* typ0, Intset269030* check0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = genrecordfieldsaux_535421_839829468(m0, (*typ0).n, NIM_NIL, typ0, check0); return result0; } N_NIMCALL(Ropeobj179006*, getrecorddesc_535643_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0, Intset269030* check0) { Ropeobj179006* result0; NIM_BOOL hasfield0; Ropeobj179006* attribute0; TY536238 LOC6; Ropeobj179006* desc0; NimStringDesc* LOC46; result0 = (Ropeobj179006*)0; hasfield0 = NIM_FALSE; { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 21))&31U)))!=0)) goto LA3; attribute0 = rope_179277_2381377266(Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field19); } goto LA1; LA3: ; { attribute0 = NIM_NIL; } LA1: ; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = structorunion_535001_839829468(typ0); LOC6[1] = name0; LOC6[2] = attribute0; result0 = ropecg_533407_839829468(m0, Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field18, LOC6, 3); { if (!((*typ0).kind == ((Ttypekind293244) 17))) goto LA9; { if (!((*typ0).sons->data[((NI) 0)] == NIM_NIL)) goto LA13; { NIM_BOOL LOC17; NIM_BOOL LOC18; TY534289 LOC23; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = !(((*typ0).sym == NIM_NIL)); if (!(LOC18)) goto LA19; LOC18 = (((*(*typ0).sym).flags &(1U<<((NU)(((Tsymflag293184) 9))&31U)))!=0); LA19: ; LOC17 = LOC18; if (LOC17) goto LA20; LOC17 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 2))&31U)))!=0); LA20: ; if (!LOC17) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); appcg_533632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_85), LOC23, 0); } goto LA15; LA21: ; { TY533811 LOC25; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = name0; LOC25[1] = attribute0; appcg_533632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_86), LOC25, 2); hasfield0 = NIM_TRUE; } LA15: ; } goto LA11; LA13: ; { NIM_BOOL LOC27; TY179507 LOC31; Ttype293840* LOC32; LOC27 = (NIM_BOOL)0; LOC27 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC27) goto LA28; LOC27 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA28: ; if (!LOC27) goto LA29; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ttype293840*)0; LOC32 = skiptypes_297099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360)); LOC31[0] = gettypedescaux_534505_839829468(m0, LOC32, check0); appcg_533632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_87), LOC31, 1); hasfield0 = NIM_TRUE; } goto LA11; LA29: ; { TY179507 LOC34; Ttype293840* LOC35; memset((void*)LOC34, 0, sizeof(LOC34)); LOC35 = (Ttype293840*)0; LOC35 = skiptypes_297099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360)); LOC34[0] = gettypedescaux_534505_839829468(m0, LOC35, check0); appcg_533632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_88), LOC34, 1); hasfield0 = NIM_TRUE; } LA11: ; } goto LA7; LA9: ; { TY179507 LOC37; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = name0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_85), LOC37, 1); } LA7: ; desc0 = getrecordfields_535636_839829468(m0, typ0, check0); { NIM_BOOL LOC40; TY534289 LOC44; LOC40 = (NIM_BOOL)0; LOC40 = (desc0 == NIM_NIL); if (!(LOC40)) goto LA41; LOC40 = !(hasfield0); LA41: ; if (!LOC40) goto LA42; memset((void*)LOC44, 0, sizeof(LOC44)); addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_100), LOC44, 0); } goto LA38; LA42: ; { add_179482_2381377266(&result0, desc0); } LA38: ; LOC46 = (NimStringDesc*)0; LOC46 = rawNewString(tnl_177644_4151366050->Sup.len + 2); appendString(LOC46, ((NimStringDesc*) &T839829468_101)); appendString(LOC46, tnl_177644_4151366050); add_179487_2381377266(&result0, LOC46); return result0; } N_NIMCALL(Ropeobj179006*, gettupledesc_535777_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0, Intset269030* check0) { Ropeobj179006* result0; TY533811 LOC1; Ropeobj179006* desc0; NimStringDesc* LOC13; result0 = (Ropeobj179006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = structorunion_535001_839829468(typ0); LOC1[1] = name0; result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_102), LOC1, 2); desc0 = NIM_NIL; { NI i_535799_839829468; NI HEX3Atmp_535820_839829468; NI LOC3; NI res_535823_839829468; i_535799_839829468 = (NI)0; HEX3Atmp_535820_839829468 = (NI)0; LOC3 = (NI)0; LOC3 = sonslen_296327_850551059(typ0); HEX3Atmp_535820_839829468 = (NI)(LOC3 - ((NI) 1)); res_535823_839829468 = ((NI) 0); { while (1) { TY533811 LOC6; if (!(res_535823_839829468 <= HEX3Atmp_535820_839829468)) goto LA5; i_535799_839829468 = res_535823_839829468; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = gettypedescaux_534505_839829468(m0, (*typ0).sons->data[i_535799_839829468], check0); LOC6[1] = rope_179401_2381377266(((NI64) (i_535799_839829468))); addf_180205_2381377266(&desc0, ((NimStringDesc*) &T839829468_103), LOC6, 2); res_535823_839829468 += ((NI) 1); } LA5: ; } } { NimStringDesc* LOC11; if (!(desc0 == NIM_NIL)) goto LA9; LOC11 = (NimStringDesc*)0; LOC11 = rawNewString(tnl_177644_4151366050->Sup.len + 11); appendString(LOC11, ((NimStringDesc*) &T839829468_104)); appendString(LOC11, tnl_177644_4151366050); add_179487_2381377266(&result0, LOC11); } goto LA7; LA9: ; { add_179482_2381377266(&result0, desc0); } LA7: ; LOC13 = (NimStringDesc*)0; LOC13 = rawNewString(tnl_177644_4151366050->Sup.len + 2); appendString(LOC13, ((NimStringDesc*) &T839829468_101)); appendString(LOC13, tnl_177644_4151366050); add_179487_2381377266(&result0, LOC13); return result0; } N_NIMCALL(Ropeobj179006*, gettypedescaux_534505_839829468)(Tcgen530027* m0, Ttype293840* typ0, Intset269030* check0) { Ropeobj179006* result0; Ttype293840* t_535942_839829468; { result0 = (Ropeobj179006*)0; t_535942_839829468 = getuniquetype_529640_2036603609(typ0); { if (!(t_535942_839829468 == NIM_NIL)) goto LA3; internalerror_197113_155036129(((NimStringDesc*) &T839829468_27)); } LA3: ; { if (!!(((*t_535942_839829468).sym == NIM_NIL))) goto LA7; useheader_533369_839829468(m0, (*t_535942_839829468).sym); } LA7: ; result0 = gettypepre_534972_839829468(m0, t_535942_839829468); { if (!!((result0 == NIM_NIL))) goto LA11; goto BeforeRet; } LA11: ; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = containsorincl_269862_2627731572(check0, (*t_535942_839829468).Sup.id); if (!LOC15) goto LA16; { NIM_BOOL LOC20; NimStringDesc* LOC24; NimStringDesc* LOC25; LOC20 = (NIM_BOOL)0; LOC20 = isimportedcpptype_534478_839829468(typ0); if (LOC20) goto LA21; LOC20 = isimportedcpptype_534478_839829468(t_535942_839829468); LA21: ; if (!!(LOC20)) goto LA22; LOC24 = (NimStringDesc*)0; LOC25 = (NimStringDesc*)0; LOC25 = typetostring_321017_3876443242(typ0, ((Tprefereddesc321011) 0)); LOC24 = rawNewString(LOC25->Sup.len + 28); appendString(LOC24, ((NimStringDesc*) &T839829468_51)); appendString(LOC24, LOC25); internalerror_197113_155036129(LOC24); } LA22: ; } LA16: ; switch ((*t_535942_839829468).kind) { case ((Ttypekind293244) 22): case ((Ttypekind293244) 21): case ((Ttypekind293244) 23): { NimStringDesc* star0; Ttype293840* et0; Ttype293840* LOC38; Ttype293840* etb0; { NIM_BOOL LOC29; NIM_BOOL LOC30; NIM_BOOL LOC33; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((*t_535942_839829468).kind == ((Ttypekind293244) 23)); if (!(LOC30)) goto LA31; LOC30 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 18))&31U)))!=0)); LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA32; LOC33 = (NIM_BOOL)0; LOC33 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC33) goto LA34; LOC33 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA34: ; LOC29 = LOC33; LA32: ; if (!LOC29) goto LA35; star0 = copyString(((NimStringDesc*) &T839829468_52)); } goto LA27; LA35: ; { star0 = copyString(((NimStringDesc*) &T839829468_53)); } LA27: ; LOC38 = (Ttype293840*)0; LOC38 = skiptypes_297099_850551059(typ0, IL64(211106232576256)); et0 = lastson_296377_850551059(LOC38); etb0 = skiptypes_297099_850551059(et0, IL64(211106232576256)); { if (!((IL64(281475110993936) &((NU64)1<<((NU)((*etb0).kind)&63U)))!=0)) goto LA41; et0 = elemtype_321394_3876443242(etb0); etb0 = skiptypes_297099_850551059(et0, IL64(211106232576256)); star0->data[((NI) 0)] = 42; } LA41: ; switch ((*etb0).kind) { case ((Ttypekind293244) 17): case ((Ttypekind293244) 18): { { NIM_BOOL LOC46; Ropeobj179006* LOC50; LOC46 = (NIM_BOOL)0; LOC46 = isimportedcpptype_534478_839829468(etb0); if (!(LOC46)) goto LA47; LOC46 = ((*et0).kind == ((Ttypekind293244) 11)); LA47: ; if (!LOC46) goto LA48; LOC50 = (Ropeobj179006*)0; LOC50 = gettypedescaux_534505_839829468(m0, et0, check0); result0 = HEX26_179447_2381377266(LOC50, star0); } goto LA44; LA48: ; { Ttype293840* x0; Ropeobj179006* name0; Tidobj200004* LOC52; TNimObject* LOC53; x0 = getuniquetype_529640_2036603609(etb0); name0 = gettypeforward_535039_839829468(m0, x0); result0 = HEX26_179447_2381377266(name0, star0); LOC52 = (Tidobj200004*)0; LOC52 = &t_535942_839829468->Sup; LOC53 = (TNimObject*)0; LOC53 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC52, LOC53); pushtype_534958_839829468(m0, x0); } LA44: ; } break; case ((Ttypekind293244) 24): { Ttype293840* x0; Ropeobj179006* name0; Ropeobj179006* LOC55; Tidobj200004* LOC56; TNimObject* LOC57; x0 = getuniquetype_529640_2036603609(etb0); name0 = gettypeforward_535039_839829468(m0, x0); LOC55 = (Ropeobj179006*)0; LOC55 = HEX26_179447_2381377266(name0, ((NimStringDesc*) &T839829468_53)); result0 = HEX26_179447_2381377266(LOC55, star0); LOC56 = (Tidobj200004*)0; LOC56 = &t_535942_839829468->Sup; LOC57 = (TNimObject*)0; LOC57 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC56, LOC57); pushtype_534958_839829468(m0, x0); } break; default: { Ropeobj179006* LOC59; Tidobj200004* LOC60; TNimObject* LOC61; LOC59 = (Ropeobj179006*)0; LOC59 = gettypedescaux_534505_839829468(m0, et0, check0); result0 = HEX26_179447_2381377266(LOC59, star0); LOC60 = (Tidobj200004*)0; LOC60 = &t_535942_839829468->Sup; LOC61 = (TNimObject*)0; LOC61 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC60, LOC61); } break; } } break; case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { Ropeobj179006* LOC63; Tidobj200004* LOC64; TNimObject* LOC65; LOC63 = (Ropeobj179006*)0; LOC63 = gettypedescweak_535079_839829468(m0, (*t_535942_839829468).sons->data[((NI) 0)], check0); result0 = HEX26_179447_2381377266(LOC63, ((NimStringDesc*) &T839829468_53)); LOC64 = (Tidobj200004*)0; LOC64 = &t_535942_839829468->Sup; LOC65 = (TNimObject*)0; LOC65 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC64, LOC65); } break; case ((Ttypekind293244) 20): case ((Ttypekind293244) 14): { Ttype293840* t0; { if (!((*t_535942_839829468).kind == ((Ttypekind293244) 20))) goto LA69; t0 = lastson_296377_850551059(t_535942_839829468); } goto LA67; LA69: ; { t0 = t_535942_839829468; } LA67: ; result0 = cachegettype_534593_839829468((*m0).typecache, t0); { if (!(result0 == NIM_NIL)) goto LA74; result0 = gettypename_534313_839829468(t0); { NIM_BOOL LOC78; NIM_BOOL LOC80; Tidobj200004* LOC84; TNimObject* LOC85; NI size0; NU32 owner0; LOC78 = (NIM_BOOL)0; LOC78 = isimportedcpptype_534478_839829468(t0); if (LOC78) goto LA79; LOC80 = (NIM_BOOL)0; LOC80 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag293184) 5))&31U)))!=0); if (!(LOC80)) goto LA81; LOC80 = ((*(*t0).sym).magic == ((Tmagic293524) 0)); LA81: ; LOC78 = LOC80; LA79: ; if (!!(LOC78)) goto LA82; LOC84 = (Tidobj200004*)0; LOC84 = &t0->Sup; LOC85 = (TNimObject*)0; LOC85 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC84, LOC85); size0 = (NI)0; { NI64 LOC88; TY179507 LOC91; LOC88 = (NI64)0; LOC88 = firstord_321001_3876443242(t0); if (!(LOC88 < IL64(0))) goto LA89; memset((void*)LOC91, 0, sizeof(LOC91)); LOC91[0] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC91, 1); size0 = ((NI) 4); } goto LA86; LA89: ; { NI64 LOC93; LOC93 = (NI64)0; LOC93 = getsize_321135_3876443242(t0); size0 = ((NI) (LOC93)); switch (size0) { case ((NI) 1): { TY179507 LOC95; memset((void*)LOC95, 0, sizeof(LOC95)); LOC95[0] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_60), LOC95, 1); } break; case ((NI) 2): { TY179507 LOC97; memset((void*)LOC97, 0, sizeof(LOC97)); LOC97[0] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_61), LOC97, 1); } break; case ((NI) 4): { TY179507 LOC99; memset((void*)LOC99, 0, sizeof(LOC99)); LOC99[0] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC99, 1); } break; case ((NI) 8): { TY179507 LOC101; memset((void*)LOC101, 0, sizeof(LOC101)); LOC101[0] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_62), LOC101, 1); } break; default: { internalerror_197100_155036129((*(*t0).sym).info, ((NimStringDesc*) &T839829468_63)); } break; } } LA86: ; owner0 = hashowner_533977_839829468((*t0).sym); { NIM_BOOL LOC105; TY204017* vals0; Enumdesc204007 LOC114; LOC105 = (NIM_BOOL)0; LOC105 = hasenum_204230_1926258066((&gdebuginfo_204470_1926258066), (*(*(*t0).sym).name).s, ((NI) ((*(*t0).sym).info.line)), owner0); if (!!(LOC105)) goto LA106; vals0 = (TY204017*) newSeq((&NTI204017), 0); { NI i_536144_839829468; NI HEX3Atmp_536649_839829468; NI LOC109; NI res_536652_839829468; i_536144_839829468 = (NI)0; HEX3Atmp_536649_839829468 = (NI)0; LOC109 = (NI)0; LOC109 = len_294081_850551059((*t0).n); HEX3Atmp_536649_839829468 = (NI)(LOC109 - ((NI) 1)); res_536652_839829468 = ((NI) 0); { while (1) { Tsym293834* field0; TY204018 LOC112; NimStringDesc* LOC113; if (!(res_536652_839829468 <= HEX3Atmp_536649_839829468)) goto LA111; i_536144_839829468 = res_536652_839829468; field0 = (*(*(*t0).n).kindU.S6.sons->data[i_536144_839829468]).kindU.S4.sym; memset((void*)(&LOC112), 0, sizeof(LOC112)); LOC112.Field0 = copyString((*(*field0).name).s); LOC112.Field1 = (*field0).position; vals0 = (TY204017*) incrSeqV2(&(vals0)->Sup, sizeof(TY204018)); LOC113 = (NimStringDesc*)0; LOC113 = vals0->data[vals0->Sup.len].Field0; vals0->data[vals0->Sup.len].Field0 = copyStringRC1(LOC112.Field0); if (LOC113) nimGCunrefNoCycle(LOC113); vals0->data[vals0->Sup.len].Field1 = LOC112.Field1; ++vals0->Sup.len; res_536652_839829468 += ((NI) 1); } LA111: ; } } memset((void*)(&LOC114), 0, sizeof(LOC114)); memset((void*)(&LOC114), 0, sizeof(LOC114)); LOC114.size = size0; LOC114.owner = owner0; LOC114.id = (*(*t0).sym).Sup.id; LOC114.name = copyString((*(*(*t0).sym).name).s); genericSeqAssign((&LOC114.values), vals0, (&NTI204017)); registerenum_204419_1926258066((&gdebuginfo_204470_1926258066), (&LOC114)); } LA106: ; } LA82: ; } LA74: ; } break; case ((Ttypekind293244) 25): { Tidobj200004* LOC116; TNimObject* LOC117; Ropeobj179006* rettype0; Ropeobj179006* desc0; result0 = gettypename_534313_839829468(t_535942_839829468); LOC116 = (Tidobj200004*)0; LOC116 = &t_535942_839829468->Sup; LOC117 = (TNimObject*)0; LOC117 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC116, LOC117); rettype0 = (Ropeobj179006*)0; desc0 = (Ropeobj179006*)0; genprocparams_535115_839829468(m0, t_535942_839829468, &rettype0, &desc0, check0, NIM_TRUE, NIM_TRUE); { NIM_BOOL LOC120; LOC120 = (NIM_BOOL)0; LOC120 = isimportedtype_534451_839829468(t_535942_839829468); if (!!(LOC120)) goto LA121; { TY536235 LOC127; if (!!(((*t_535942_839829468).callconv == ((Tcallingconvention293002) 8)))) goto LA125; memset((void*)LOC127, 0, sizeof(LOC127)); LOC127[0] = rope_179277_2381377266(Callingconvtostr_534587_839829468[((*t_535942_839829468).callconv)- 0]); LOC127[1] = rettype0; LOC127[2] = result0; LOC127[3] = desc0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC127, 4); } goto LA123; LA125: ; { TY536238 LOC129; memset((void*)LOC129, 0, sizeof(LOC129)); LOC129[0] = result0; LOC129[1] = rettype0; LOC129[2] = desc0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC129, 3); } LA123: ; } LA121: ; } break; case ((Ttypekind293244) 24): { Tidobj200004* LOC144; Ropeobj179006* LOC145; TNimObject* LOC146; result0 = cachegettype_534593_839829468((*m0).forwtypecache, t_535942_839829468); { Tidobj200004* LOC142; TNimObject* LOC143; if (!(result0 == NIM_NIL)) goto LA133; result0 = gettypename_534313_839829468(t_535942_839829468); { NIM_BOOL LOC137; NimStringDesc* LOC140; TY533811 LOC141; LOC137 = (NIM_BOOL)0; LOC137 = isimportedtype_534451_839829468(t_535942_839829468); if (!!(LOC137)) goto LA138; LOC140 = (NimStringDesc*)0; LOC140 = getforwardstructformat_535015_839829468(m0); memset((void*)LOC141, 0, sizeof(LOC141)); LOC141[0] = structorunion_535001_839829468(t_535942_839829468); LOC141[1] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 2))- 0], LOC140, LOC141, 2); } LA138: ; LOC142 = (Tidobj200004*)0; LOC142 = &t_535942_839829468->Sup; LOC143 = (TNimObject*)0; LOC143 = &result0->Sup; idtableput_300094_2984716966((&(*m0).forwtypecache), LOC142, LOC143); } LA133: ; LOC144 = (Tidobj200004*)0; LOC144 = &t_535942_839829468->Sup; LOC145 = (Ropeobj179006*)0; LOC145 = HEX26_179447_2381377266(result0, ((NimStringDesc*) &T839829468_53)); LOC146 = (TNimObject*)0; LOC146 = &LOC145->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC144, LOC146); { NIM_BOOL LOC149; LOC149 = (NIM_BOOL)0; LOC149 = isimportedtype_534451_839829468(t_535942_839829468); if (!!(LOC149)) goto LA150; { Ttype293840* LOC154; NimStringDesc* LOC157; NimStringDesc* LOC158; TY533811 LOC166; LOC154 = (Ttype293840*)0; LOC154 = skiptypes_297099_850551059((*t_535942_839829468).sons->data[((NI) 0)], IL64(211106232576256)); if (!!(((*LOC154).kind == ((Ttypekind293244) 3)))) goto LA155; LOC157 = (NimStringDesc*)0; LOC158 = (NimStringDesc*)0; { NIM_BOOL LOC161; LOC161 = (NIM_BOOL)0; LOC161 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC161) goto LA162; LOC161 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA162: ; if (!LOC161) goto LA163; LOC158 = copyString(((NimStringDesc*) &T839829468_76)); } goto LA159; LA163: ; { LOC158 = copyString(((NimStringDesc*) &T839829468_77)); } LA159: ; LOC157 = rawNewString(LOC158->Sup.len + 31); appendString(LOC157, LOC158); appendString(LOC157, ((NimStringDesc*) &T839829468_78)); memset((void*)LOC166, 0, sizeof(LOC166)); LOC166[0] = gettypedescaux_534505_839829468(m0, (*t_535942_839829468).sons->data[((NI) 0)], check0); LOC166[1] = result0; appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 4))- 0], LOC157, LOC166, 2); } goto LA152; LA155: ; { result0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_79)); } LA152: ; } LA150: ; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_53)); } break; case ((Ttypekind293244) 4): case ((Ttypekind293244) 16): { NI64 n0; Tidobj200004* LOC173; TNimObject* LOC174; n0 = lengthord_321007_3876443242(t_535942_839829468); { if (!(n0 <= IL64(0))) goto LA171; n0 = IL64(1); } LA171: ; result0 = gettypename_534313_839829468(t_535942_839829468); LOC173 = (Tidobj200004*)0; LOC173 = &t_535942_839829468->Sup; LOC174 = (TNimObject*)0; LOC174 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC173, LOC174); { NIM_BOOL LOC177; Ropeobj179006* foo0; TY536238 LOC180; LOC177 = (NIM_BOOL)0; LOC177 = isimportedtype_534451_839829468(t_535942_839829468); if (!!(LOC177)) goto LA178; foo0 = gettypedescaux_534505_839829468(m0, (*t_535942_839829468).sons->data[((NI) 1)], check0); memset((void*)LOC180, 0, sizeof(LOC180)); LOC180[0] = foo0; LOC180[1] = result0; LOC180[2] = rope_179401_2381377266(n0); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_80), LOC180, 3); } LA178: ; } break; case ((Ttypekind293244) 17): case ((Ttypekind293244) 18): { { NIM_BOOL LOC184; Ropeobj179006* cppname0; NI i0; NI chunkstart0; Ropeobj179006* LOC226; LOC184 = (NIM_BOOL)0; LOC184 = isimportedcpptype_534478_839829468(t_535942_839829468); if (!(LOC184)) goto LA185; LOC184 = ((*typ0).kind == ((Ttypekind293244) 11)); LA185: ; if (!LOC184) goto LA186; cppname0 = gettypename_534313_839829468(t_535942_839829468); i0 = ((NI) 0); chunkstart0 = ((NI) 0); { while (1) { if (!(i0 < ((*cppname0).data ? (*cppname0).data->Sup.len : 0))) goto LA189; { NI chunkend0; NI idx0; NI stars0; if (!((NU8)((*cppname0).data->data[i0]) == (NU8)(39))) goto LA192; chunkend0 = (i0 - 1); idx0 = (NI)0; stars0 = (NI)0; { NIM_BOOL LOC196; NimStringDesc* LOC199; Ttype293840* typeinslot0; LOC196 = (NIM_BOOL)0; LOC196 = scancppgenericslot_535827_839829468((*cppname0).data, (&i0), (&idx0), (&stars0)); if (!LOC196) goto LA197; LOC199 = (NimStringDesc*)0; LOC199 = copyStrLast((*cppname0).data, chunkstart0, chunkend0); add_179487_2381377266(&result0, LOC199); chunkstart0 = i0; typeinslot0 = resolvestarsincpptype_535891_839829468(typ0, (NI)(idx0 + ((NI) 1)), stars0); { NIM_BOOL LOC202; TY534289 LOC206; Ropeobj179006* LOC207; LOC202 = (NIM_BOOL)0; LOC202 = (typeinslot0 == NIM_NIL); if (LOC202) goto LA203; LOC202 = ((*typeinslot0).kind == ((Ttypekind293244) 62)); LA203: ; if (!LOC202) goto LA204; memset((void*)LOC206, 0, sizeof(LOC206)); LOC207 = (Ropeobj179006*)0; LOC207 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_26), LOC206, 0); add_179482_2381377266(&result0, LOC207); } goto LA200; LA204: ; { Ropeobj179006* LOC209; LOC209 = (Ropeobj179006*)0; LOC209 = gettypedescaux_534505_839829468(m0, typeinslot0, check0); add_179482_2381377266(&result0, LOC209); } LA200: ; } LA197: ; } goto LA190; LA192: ; { i0 += ((NI) 1); } LA190: ; } LA189: ; } { NimStringDesc* LOC215; if (!!((chunkstart0 == ((NI) 0)))) goto LA213; LOC215 = (NimStringDesc*)0; LOC215 = copyStr((*cppname0).data, chunkstart0); add_179487_2381377266(&result0, LOC215); } goto LA211; LA213: ; { result0 = HEX26_179447_2381377266(cppname0, ((NimStringDesc*) &T839829468_82)); { NI i_536516_839829468; NI HEX3Atmp_536665_839829468; NI LOC218; NI res_536668_839829468; i_536516_839829468 = (NI)0; HEX3Atmp_536665_839829468 = (NI)0; LOC218 = (NI)0; LOC218 = len_296339_850551059(typ0); HEX3Atmp_536665_839829468 = (NI)(LOC218 - ((NI) 2)); res_536668_839829468 = ((NI) 1); { while (1) { Ropeobj179006* LOC225; if (!(res_536668_839829468 <= HEX3Atmp_536665_839829468)) goto LA220; i_536516_839829468 = res_536668_839829468; { if (!(((NI) 1) < i_536516_839829468)) goto LA223; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_83)); } LA223: ; LOC225 = (Ropeobj179006*)0; LOC225 = gettypedescaux_534505_839829468(m0, (*typ0).sons->data[i_536516_839829468], check0); add_179482_2381377266(&result0, LOC225); res_536668_839829468 += ((NI) 1); } LA220: ; } } add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_84)); } LA211: ; LOC226 = (Ropeobj179006*)0; LOC226 = getrecorddesc_535643_839829468(m0, t_535942_839829468, result0, check0); } goto LA182; LA186: ; { Tidobj200004* LOC241; TNimObject* LOC242; Ropeobj179006* recdesc0; result0 = cachegettype_534593_839829468((*m0).forwtypecache, t_535942_839829468); { Tidobj200004* LOC239; TNimObject* LOC240; if (!(result0 == NIM_NIL)) goto LA230; result0 = gettypename_534313_839829468(t_535942_839829468); { NIM_BOOL LOC234; NimStringDesc* LOC237; TY533811 LOC238; LOC234 = (NIM_BOOL)0; LOC234 = isimportedtype_534451_839829468(t_535942_839829468); if (!!(LOC234)) goto LA235; LOC237 = (NimStringDesc*)0; LOC237 = getforwardstructformat_535015_839829468(m0); memset((void*)LOC238, 0, sizeof(LOC238)); LOC238[0] = structorunion_535001_839829468(t_535942_839829468); LOC238[1] = result0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 2))- 0], LOC237, LOC238, 2); } LA235: ; LOC239 = (Tidobj200004*)0; LOC239 = &t_535942_839829468->Sup; LOC240 = (TNimObject*)0; LOC240 = &result0->Sup; idtableput_300094_2984716966((&(*m0).forwtypecache), LOC239, LOC240); } LA230: ; LOC241 = (Tidobj200004*)0; LOC241 = &t_535942_839829468->Sup; LOC242 = (TNimObject*)0; LOC242 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC241, LOC242); { if (!!(((*t_535942_839829468).kind == ((Ttypekind293244) 18)))) goto LA245; recdesc0 = getrecorddesc_535643_839829468(m0, t_535942_839829468, result0, check0); } goto LA243; LA245: ; { recdesc0 = gettupledesc_535777_839829468(m0, t_535942_839829468, result0, check0); } LA243: ; { NIM_BOOL LOC250; LOC250 = (NIM_BOOL)0; LOC250 = isimportedtype_534451_839829468(t_535942_839829468); if (!!(LOC250)) goto LA251; add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], recdesc0); } LA251: ; } LA182: ; } break; case ((Ttypekind293244) 19): { Ttype293840* LOC254; Ropeobj179006* LOC255; Tidobj200004* LOC256; TNimObject* LOC257; LOC254 = (Ttype293840*)0; LOC254 = lastson_296377_850551059(t_535942_839829468); LOC255 = (Ropeobj179006*)0; LOC255 = gettypename_534313_839829468(LOC254); result0 = HEX26_179447_2381377266(LOC255, ((NimStringDesc*) &T839829468_105)); LOC256 = (Tidobj200004*)0; LOC256 = &t_535942_839829468->Sup; LOC257 = (TNimObject*)0; LOC257 = &result0->Sup; idtableput_300094_2984716966((&(*m0).typecache), LOC256, LOC257); { NIM_BOOL LOC260; NI s0; NI64 LOC263; LOC260 = (NIM_BOOL)0; LOC260 = isimportedtype_534451_839829468(t_535942_839829468); if (!!(LOC260)) goto LA261; LOC263 = (NI64)0; LOC263 = getsize_321135_3876443242(t_535942_839829468); s0 = ((NI) (LOC263)); switch (s0) { case ((NI) 1): case ((NI) 2): case ((NI) 4): case ((NI) 8): { TY533811 LOC265; memset((void*)LOC265, 0, sizeof(LOC265)); LOC265[0] = result0; LOC265[1] = rope_179401_2381377266(((NI64) ((NI)(s0 * ((NI) 8))))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_106), LOC265, 2); } break; default: { TY533811 LOC267; NI64 LOC268; memset((void*)LOC267, 0, sizeof(LOC267)); LOC267[0] = result0; LOC268 = (NI64)0; LOC268 = getsize_321135_3876443242(t_535942_839829468); LOC267[1] = rope_179401_2381377266(LOC268); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_107), LOC267, 2); } break; } } LA261: ; } break; case ((Ttypekind293244) 11): case ((Ttypekind293244) 13): case ((Ttypekind293244) 15): case ((Ttypekind293244) 46): case ((Ttypekind293244) 47): case ((Ttypekind293244) 49): case ((Ttypekind293244) 8): { Ttype293840* LOC270; LOC270 = (Ttype293840*)0; LOC270 = lastson_296377_850551059(t_535942_839829468); result0 = gettypedescaux_534505_839829468(m0, LOC270, check0); } break; default: { NimStringDesc* LOC272; LOC272 = (NimStringDesc*)0; LOC272 = rawNewString(reprEnum((NI)(*t_535942_839829468).kind, (&NTI293244))->Sup.len + 16); appendString(LOC272, ((NimStringDesc*) &T839829468_108)); appendString(LOC272, reprEnum((NI)(*t_535942_839829468).kind, (&NTI293244))); appendChar(LOC272, 41); internalerror_197113_155036129(LOC272); result0 = NIM_NIL; } break; } excl_269841_2627731572(check0, (*t_535942_839829468).Sup.id); }BeforeRet: ; return result0; } static N_INLINE(NIM_BOOL, iscompiletimeonly_329706_3876443242)(Ttype293840* t0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((IL64(576460752303423744) &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); return result0; } N_NIMCALL(Tstorageloc293812, paramstorageloc_535098_839829468)(Tsym293834* param0) { Tstorageloc293812 result0; result0 = (Tstorageloc293812)0; { Ttype293840* LOC3; LOC3 = (Ttype293840*)0; LOC3 = skiptypes_297099_850551059((*param0).typ, 8388864); if (!!(((IL64(281475110993936) &((NU64)1<<((NU)((*LOC3).kind)&63U)))!=0))) goto LA4; result0 = ((Tstorageloc293812) 2); } goto LA1; LA4: ; { result0 = ((Tstorageloc293812) 0); } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, ccgintroducedptr_534611_839829468)(Tsym293834* s0) { NIM_BOOL result0; Ttype293840* pt0; { result0 = (NIM_BOOL)0; pt0 = skiptypes_297099_850551059((*s0).typ, IL64(211106232576256)); { if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag293431) 13))&31U)))!=0)) goto LA3; result0 = NIM_TRUE; goto BeforeRet; } goto LA1; LA3: ; { if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag293431) 12))&31U)))!=0)) goto LA6; result0 = NIM_FALSE; goto BeforeRet; } goto LA1; LA6: ; LA1: ; switch ((*pt0).kind) { case ((Ttypekind293244) 17): { { NIM_BOOL LOC11; NI64 LOC13; LOC11 = (NIM_BOOL)0; LOC11 = (((*s0).options &(1U<<((NU)(((Toption170009) 18))&31U)))!=0); if (LOC11) goto LA12; LOC13 = (NI64)0; LOC13 = getsize_321135_3876443242(pt0); LOC11 = (((NI64) ((NI)(floatsize_177642_4151366050 * ((NI) 2)))) < LOC13); LA12: ; if (!LOC11) goto LA14; result0 = NIM_TRUE; } goto LA9; LA14: ; { NIM_BOOL LOC17; LOC17 = (NIM_BOOL)0; LOC17 = (((*pt0).flags &(1U<<((NU)(((Ttypeflag293431) 2))&31U)))!=0); if (!(LOC17)) goto LA18; LOC17 = ((*pt0).sons->data[((NI) 0)] == NIM_NIL); LA18: ; if (!LOC17) goto LA19; result0 = NIM_FALSE; } goto LA9; LA19: ; { result0 = NIM_TRUE; } LA9: ; } break; case ((Ttypekind293244) 18): { NIM_BOOL LOC23; NI64 LOC24; LOC23 = (NIM_BOOL)0; LOC24 = (NI64)0; LOC24 = getsize_321135_3876443242(pt0); LOC23 = (((NI64) ((NI)(floatsize_177642_4151366050 * ((NI) 2)))) < LOC24); if (LOC23) goto LA25; LOC23 = (((*s0).options &(1U<<((NU)(((Toption170009) 18))&31U)))!=0); LA25: ; result0 = LOC23; } break; default: { result0 = NIM_FALSE; } break; } }BeforeRet: ; return result0; } N_NIMCALL(Tctypekind530007, mapreturntype_534447_839829468)(Ttype293840* typ0) { Tctypekind530007 result0; result0 = (Tctypekind530007)0; result0 = maptype_534394_839829468(typ0); return result0; } N_NIMCALL(void, genprocparams_535115_839829468)(Tcgen530027* m0, Ttype293840* t0, Ropeobj179006** rettype0, Ropeobj179006** params0, Intset269030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0) { unsureAsgnRef((void**) (&(*params0)), NIM_NIL); { NIM_BOOL LOC3; TY534289 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).sons->data[((NI) 0)] == NIM_NIL); if (LOC3) goto LA4; LOC3 = isinvalidreturntype_534550_839829468((*t0).sons->data[((NI) 0)]); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); unsureAsgnRef((void**) (&(*rettype0)), HEX25_179905_2381377266(((NimStringDesc*) &T839829468_26), LOC7, 0)); } goto LA1; LA5: ; { unsureAsgnRef((void**) (&(*rettype0)), gettypedescaux_534505_839829468(m0, (*t0).sons->data[((NI) 0)], check0)); } LA1: ; { NI i_535152_839829468; NI HEX3Atmp_535353_839829468; NI LOC10; NI res_535356_839829468; i_535152_839829468 = (NI)0; HEX3Atmp_535353_839829468 = (NI)0; LOC10 = (NI)0; LOC10 = sonslen_296351_850551059((*t0).n); HEX3Atmp_535353_839829468 = (NI)(LOC10 - ((NI) 1)); res_535356_839829468 = ((NI) 1); { while (1) { if (!(res_535356_839829468 <= HEX3Atmp_535353_839829468)) goto LA12; i_535152_839829468 = res_535356_839829468; { Tsym293834* param0; Ropeobj179006* LOC29; Tstorageloc293812 LOC30; TY534289 LOC45; Ropeobj179006* LOC46; Ttype293840* arr0; NI j0; { if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_535152_839829468]).kind == ((Tnodekind293020) 3)))) goto LA16; internalerror_197100_155036129((*(*t0).n).info, ((NimStringDesc*) &T839829468_109)); } LA16: ; param0 = (*(*(*t0).n).kindU.S6.sons->data[i_535152_839829468]).kindU.S4.sym; { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = iscompiletimeonly_329706_3876443242((*param0).typ); if (!LOC20) goto LA21; goto LA13; } LA21: ; { TY534289 LOC27; Ropeobj179006* LOC28; if (!!(((*params0) == NIM_NIL))) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Ropeobj179006*)0; LOC28 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC27, 0); add_179482_2381377266(params0, LOC28); } LA25: ; LOC29 = (Ropeobj179006*)0; LOC29 = manglename_534205_839829468(param0); LOC30 = (Tstorageloc293812)0; LOC30 = paramstorageloc_535098_839829468(param0); fillloc_533282_839829468((&(*param0).loc), ((Tlockind293808) 4), (*param0).typ, LOC29, LOC30); { NIM_BOOL LOC33; Ropeobj179006* LOC36; TY534289 LOC37; Ropeobj179006* LOC38; LOC33 = (NIM_BOOL)0; LOC33 = ccgintroducedptr_534611_839829468(param0); if (!LOC33) goto LA34; LOC36 = (Ropeobj179006*)0; LOC36 = gettypedescweak_535079_839829468(m0, (*param0).typ, check0); add_179482_2381377266(params0, LOC36); memset((void*)LOC37, 0, sizeof(LOC37)); LOC38 = (Ropeobj179006*)0; LOC38 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_53), LOC37, 0); add_179482_2381377266(params0, LOC38); (*param0).loc.flags |= ((NU16)1)<<((((Tlocflag293810) 0))%(sizeof(NU16)*8)); (*param0).loc.s = ((Tstorageloc293812) 0); } goto LA31; LA34: ; { Ropeobj179006* LOC42; if (!weakdep0) goto LA40; LOC42 = (Ropeobj179006*)0; LOC42 = gettypedescweak_535079_839829468(m0, (*param0).typ, check0); add_179482_2381377266(params0, LOC42); } goto LA31; LA40: ; { Ropeobj179006* LOC44; LOC44 = (Ropeobj179006*)0; LOC44 = gettypedescaux_534505_839829468(m0, (*param0).typ, check0); add_179482_2381377266(params0, LOC44); } LA31: ; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (Ropeobj179006*)0; LOC46 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_111), LOC45, 0); add_179482_2381377266(params0, LOC46); add_179482_2381377266(params0, (*param0).loc.r); arr0 = (*param0).typ; { if (!((*arr0).kind == ((Ttypekind293244) 23))) goto LA49; arr0 = (*arr0).sons->data[((NI) 0)]; } LA49: ; j0 = ((NI) 0); { while (1) { TY533811 LOC57; if (!((IL64(281475110928384) &((NU64)1<<((NU)((*arr0).kind)&63U)))!=0)) goto LA52; { if (!((*(*param0).typ).kind == ((Ttypekind293244) 23))) goto LA55; (*param0).loc.s = ((Tstorageloc293812) 0); } LA55: ; memset((void*)LOC57, 0, sizeof(LOC57)); LOC57[0] = (*param0).loc.r; LOC57[1] = rope_179401_2381377266(((NI64) (j0))); addf_180205_2381377266(params0, ((NimStringDesc*) &T839829468_112), LOC57, 2); j0 += ((NI) 1); arr0 = (*arr0).sons->data[((NI) 0)]; } LA52: ; } } LA13: ; res_535356_839829468 += ((NI) 1); } LA12: ; } } { NIM_BOOL LOC60; Ttype293840* arr0; TY534289 LOC76; LOC60 = (NIM_BOOL)0; LOC60 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); if (!(LOC60)) goto LA61; LOC60 = isinvalidreturntype_534550_839829468((*t0).sons->data[((NI) 0)]); LA61: ; if (!LOC60) goto LA62; arr0 = (*t0).sons->data[((NI) 0)]; { if (!!(((*params0) == NIM_NIL))) goto LA66; add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA66: ; { Tctypekind530007 LOC70; Ropeobj179006* LOC73; LOC70 = (Tctypekind530007)0; LOC70 = mapreturntype_534447_839829468((*t0).sons->data[((NI) 0)]); if (!!((LOC70 == ((Tctypekind530007) 17)))) goto LA71; LOC73 = (Ropeobj179006*)0; LOC73 = gettypedescweak_535079_839829468(m0, arr0, check0); add_179482_2381377266(params0, LOC73); add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_53)); } goto LA68; LA71: ; { Ropeobj179006* LOC75; LOC75 = (Ropeobj179006*)0; LOC75 = gettypedescaux_534505_839829468(m0, arr0, check0); add_179482_2381377266(params0, LOC75); } LA68: ; memset((void*)LOC76, 0, sizeof(LOC76)); addf_180205_2381377266(params0, ((NimStringDesc*) &T839829468_113), LOC76, 0); } LA62: ; { NIM_BOOL LOC79; LOC79 = (NIM_BOOL)0; LOC79 = ((*t0).callconv == ((Tcallingconvention293002) 8)); if (!(LOC79)) goto LA80; LOC79 = declareenvironment0; LA80: ; if (!LOC79) goto LA81; { if (!!(((*params0) == NIM_NIL))) goto LA85; add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA85: ; add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_114)); } LA81: ; { if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag293431) 0))&31U)))!=0)) goto LA89; { if (!!(((*params0) == NIM_NIL))) goto LA93; add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA93: ; add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_115)); } LA89: ; { if (!((*params0) == NIM_NIL)) goto LA97; add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_116)); } goto LA95; LA97: ; { add_179487_2381377266(params0, ((NimStringDesc*) &T839829468_117)); } LA95: ; unsureAsgnRef((void**) (&(*params0)), HEX26_179452_2381377266(((NimStringDesc*) &T839829468_118), (*params0))); } N_NIMCALL(Ropeobj179006*, genprocheader_536867_839829468)(Tcgen530027* m0, Tsym293834* prc0) { Ropeobj179006* result0; Ropeobj179006* rettype0; Ropeobj179006* params0; Intset269030 check0; Ropeobj179006* LOC13; result0 = (Ropeobj179006*)0; rettype0 = (Ropeobj179006*)0; params0 = (Ropeobj179006*)0; genclinedir_533813_839829468(&result0, (*prc0).info); { if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag293810) 5))&15U)))!=0)) goto LA3; { if (!(((*m0).flags &(1U<<((NU)(((Codegenflag530025) 3))&7U)))!=0)) goto LA7; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_22)); } goto LA5; LA7: ; { add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_23)); } LA5: ; } goto LA1; LA3: ; { if (!((*(*prc0).typ).callconv == ((Tcallingconvention293002) 5))) goto LA11; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_24)); } goto LA1; LA11: ; LA1: ; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_269885_2627731572((&check0)); LOC13 = (Ropeobj179006*)0; LOC13 = manglename_534205_839829468(prc0); fillloc_533282_839829468((&(*prc0).loc), ((Tlockind293808) 7), (*prc0).typ, LOC13, ((Tstorageloc293812) 0)); genprocparams_535115_839829468(m0, (*prc0).typ, &rettype0, &params0, (&check0), NIM_TRUE, NIM_FALSE); { TY536235 LOC18; if (!(*prc0).constraint == 0) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rope_179277_2381377266(Callingconvtostr_534587_839829468[((*(*prc0).typ).callconv)- 0]); LOC18[1] = rettype0; LOC18[2] = (*prc0).loc.r; LOC18[3] = params0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_119), LOC18, 4); } goto LA14; LA16: ; { TY536238 LOC20; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rettype0; LOC20[1] = (*prc0).loc.r; LOC20[2] = params0; result0 = HEX25_179905_2381377266((*(*prc0).constraint).kindU.S3.strval, LOC20, 3); } LA14: ; return result0; } static N_INLINE(Tnode293802*, HEX5BHEX5D_294238_850551059)(Tnode293802* n0, NI i0) { Tnode293802* result0; result0 = (Tnode293802*)0; result0 = (*n0).kindU.S6.sons->data[i0]; return result0; } N_NIMCALL(Tnode293802*, easyresultasgn_561191_839829468)(Tnode293802* n0) { Tnode293802* result0; { result0 = (Tnode293802*)0; switch ((*n0).kind) { case ((Tnodekind293020) 115): case ((Tnodekind293020) 126): { NI i0; i0 = ((NI) 0); { while (1) { NIM_BOOL LOC4; NI LOC5; Tnode293802* LOC7; LOC4 = (NIM_BOOL)0; LOC5 = (NI)0; LOC5 = len_294081_850551059(n0); LOC4 = (i0 < LOC5); if (!(LOC4)) goto LA6; LOC7 = (Tnode293802*)0; LOC7 = HEX5BHEX5D_294238_850551059(n0, i0); LOC4 = ((*LOC7).kind == ((Tnodekind293020) 1) || (*LOC7).kind >= ((Tnodekind293020) 79) && (*LOC7).kind <= ((Tnodekind293020) 81) || (*LOC7).kind == ((Tnodekind293020) 84) || (*LOC7).kind == ((Tnodekind293020) 98) || (*LOC7).kind == ((Tnodekind293020) 101) || (*LOC7).kind == ((Tnodekind293020) 125)); LA6: ; if (!LOC4) goto LA3; i0 += ((NI) 1); } LA3: ; } { NI LOC10; Tnode293802* LOC13; LOC10 = (NI)0; LOC10 = len_294081_850551059(n0); if (!(i0 < LOC10)) goto LA11; LOC13 = (Tnode293802*)0; LOC13 = HEX5BHEX5D_294238_850551059(n0, i0); result0 = easyresultasgn_561191_839829468(LOC13); } LA11: ; } break; case ((Tnodekind293020) 73): case ((Tnodekind293020) 74): { { NIM_BOOL LOC17; Tnode293802* LOC18; Tnode293802* LOC20; LOC17 = (NIM_BOOL)0; LOC18 = (Tnode293802*)0; LOC18 = HEX5BHEX5D_294238_850551059(n0, ((NI) 0)); LOC17 = ((*LOC18).kind == ((Tnodekind293020) 3)); if (!(LOC17)) goto LA19; LOC20 = (Tnode293802*)0; LOC20 = HEX5BHEX5D_294238_850551059(n0, ((NI) 0)); LOC17 = (((Tsymkind293435) 11) == (*(*LOC20).kindU.S4.sym).kind); LA19: ; if (!LOC17) goto LA21; (*n0).flags |= ((NU16)1)<<((((Tnodeflag293427) 14))%(sizeof(NU16)*8)); result0 = HEX5BHEX5D_294238_850551059(n0, ((NI) 1)); goto BeforeRet; } LA21: ; } break; case ((Tnodekind293020) 109): { { NI LOC26; Tnode293802* LOC29; LOC26 = (NI)0; LOC26 = len_294081_850551059(n0); if (!(((NI) 0) < LOC26)) goto LA27; LOC29 = (Tnode293802*)0; LOC29 = HEX5BHEX5D_294238_850551059(n0, ((NI) 0)); result0 = easyresultasgn_561191_839829468(LOC29); { if (!!((result0 == NIM_NIL))) goto LA32; (*n0).flags |= ((NU16)1)<<((((Tnodeflag293427) 14))%(sizeof(NU16)*8)); } LA32: ; } LA27: ; } break; default: { } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj179006*, gettypedesc_536673_839829468)(Tcgen530027* m0, Ttype293840* typ0) { Ropeobj179006* result0; Intset269030 check0; result0 = (Ropeobj179006*)0; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_269885_2627731572((&check0)); result0 = gettypedescaux_534505_839829468(m0, typ0, (&check0)); return result0; } N_NIMCALL(Ropeobj179006*, localvardecl_539532_839829468)(Tcproc530021* p0, Tsym293834* s0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { Ropeobj179006* LOC5; if (!((*s0).loc.k == ((Tlockind293808) 0))) goto LA3; LOC5 = (Ropeobj179006*)0; LOC5 = manglename_534205_839829468(s0); fillloc_533282_839829468((&(*s0).loc), ((Tlockind293808) 2), (*s0).typ, LOC5, ((Tstorageloc293812) 2)); { if (!((*s0).kind == ((Tsymkind293435) 9))) goto LA8; (*s0).loc.flags |= ((NU16)1)<<((((Tlocflag293810) 2))%(sizeof(NU16)*8)); } LA8: ; } LA3: ; result0 = gettypedesc_536673_839829468((*p0).module, (*s0).loc.t); { if (!(*s0).constraint == 0) goto LA12; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag293184) 8))&31U)))!=0)) goto LA16; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_121)); } LA16: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag293184) 7))&31U)))!=0)) goto LA20; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_122)); } LA20: ; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_111)); add_179482_2381377266(&result0, (*s0).loc.r); } goto LA10; LA12: ; { TY533811 LOC23; memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = result0; LOC23[1] = (*s0).loc.r; result0 = HEX25_179905_2381377266((*(*s0).constraint).kindU.S3.strval, LOC23, 2); } LA10: ; return result0; } N_NIMCALL(void, initloc_533273_839829468)(Tloc293816* result0, Tlockind293808 k0, Ttype293840* typ0, Tstorageloc293812 s0) { (*result0).k = k0; (*result0).s = s0; unsureAsgnRef((void**) (&(*result0).t), typ0); unsureAsgnRef((void**) (&(*result0).r), NIM_NIL); (*result0).flags = 0; } N_NIMCALL(void, initlocexprsingleuse_540289_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* result0) { initloc_533273_839829468(result0, ((Tlockind293808) 0), (*e0).typ, ((Tstorageloc293812) 0)); (*result0).flags |= ((NU16)1)<<((((Tlocflag293810) 8))%(sizeof(NU16)*8)); expr_540248_839829468(p0, e0, result0); } static N_INLINE(Ropeobj179006**, s_530179_3723162438)(Tcproc530021* p0, Tcprocsection530011 s0) { Ropeobj179006** result0; result0 = (Ropeobj179006**)0; result0 = &(*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].sections[(s0)- 0]; return result0; } N_NIMCALL(Ropeobj179006*, indentline_533656_839829468)(Tcproc530021* p0, Ropeobj179006* r0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = r0; { NI i_533680_839829468; NI HEX3Atmp_533683_839829468; NI res_533686_839829468; i_533680_839829468 = (NI)0; HEX3Atmp_533683_839829468 = (NI)0; HEX3Atmp_533683_839829468 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); res_533686_839829468 = ((NI) 0); { while (1) { if (!(res_533686_839829468 <= HEX3Atmp_533683_839829468)) goto LA3; i_533680_839829468 = res_533686_839829468; prepend_179893_2381377266(&result0, indent_533655_839829468); res_533686_839829468 += ((NI) 1); } LA3: ; } } return result0; } N_NIMCALL(void, linefmt_533714_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0) { Ropeobj179006** LOC1; Ropeobj179006* LOC2; Ropeobj179006* LOC3; LOC1 = (Ropeobj179006**)0; LOC1 = s_530179_3723162438(p0, s0); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, frmt0, args0, args0Len0); LOC3 = (Ropeobj179006*)0; LOC3 = indentline_533656_839829468(p0, LOC2); add_179482_2381377266(LOC1, LOC3); } N_NIMCALL(Ropeobj179006*, rdloc_539188_839829468)(Tloc293816* a0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = (*a0).r; { TY179507 LOC5; if (!(((*a0).flags &(1U<<((NU)(((Tlocflag293810) 0))&15U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = result0; result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_124), LOC5, 1); } LA3: ; return result0; } N_NIMCALL(void, line_533690_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, Ropeobj179006* r0) { Ropeobj179006** LOC1; Ropeobj179006* LOC2; LOC1 = (Ropeobj179006**)0; LOC1 = s_530179_3723162438(p0, s0); LOC2 = (Ropeobj179006*)0; LOC2 = indentline_533656_839829468(p0, r0); add_179482_2381377266(LOC1, LOC2); } N_NIMCALL(void, linef_533700_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0) { Ropeobj179006** LOC1; Ropeobj179006* LOC2; Ropeobj179006* LOC3; LOC1 = (Ropeobj179006**)0; LOC1 = s_530179_3723162438(p0, s0); LOC2 = (Ropeobj179006*)0; LOC2 = HEX25_179905_2381377266(frmt0, args0, args0Len0); LOC3 = (Ropeobj179006*)0; LOC3 = indentline_533656_839829468(p0, LOC2); add_179482_2381377266(LOC1, LOC3); } N_NIMCALL(void, gentypeinfoauxbase_536960_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttype293840* origtype0, Ropeobj179006* name0, Ropeobj179006* base0) { NI nimtypekind0; Ropeobj179006* size0; TY536235 LOC17; NI flags0; Ropeobj179006* LOC33; TY533811 LOC34; NimStringDesc* LOC35; nimtypekind0 = (NI)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isobjlackingtypefield_534515_839829468(typ0); if (!LOC3) goto LA4; nimtypekind0 = ((NI) 18); } goto LA1; LA4: ; { nimtypekind0 = ((NI) ((*typ0).kind)); } LA1: ; size0 = (Ropeobj179006*)0; { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 0))&31U)))!=0)) goto LA9; size0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_133)); } goto LA7; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC12) goto LA13; LOC12 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; size0 = gettypedesc_536673_839829468(m0, origtype0); } goto LA7; LA14: ; { size0 = gettypedesc_536673_839829468(m0, typ0); } LA7: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = name0; LOC17[1] = size0; LOC17[2] = rope_179401_2381377266(((NI64) (nimtypekind0))); LOC17[3] = base0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_134), LOC17, 4); flags0 = ((NI) 0); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = containsgarbagecollectedref_321117_3876443242(typ0); if (!!(LOC20)) goto LA21; flags0 = (NI)(flags0 | ((NI) 1)); } LA21: ; { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = canformacycle_321123_3876443242(typ0); if (!!(LOC25)) goto LA26; flags0 = (NI)(flags0 | ((NI) 2)); } LA26: ; { TY533811 LOC32; if (!!((flags0 == ((NI) 0)))) goto LA30; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = name0; LOC32[1] = rope_179401_2381377266(((NI64) (flags0))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_135), LOC32, 2); } LA30: ; LOC33 = (Ropeobj179006*)0; LOC33 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_129)); memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = name0; LOC35 = (NimStringDesc*)0; LOC35 = typetostring_321017_3876443242(typ0, ((Tprefereddesc321011) 0)); LOC34[1] = rope_179277_2381377266(LOC35); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_136), LOC34, 2); } N_NIMCALL(Ropeobj179006*, getnimnode_536945_839829468)(Tcgen530027* m0) { Ropeobj179006* result0; TY533811 LOC1; result0 = (Ropeobj179006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = (*m0).typenodesname; LOC1[1] = rope_179401_2381377266(((NI64) ((*m0).typenodes))); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_138), LOC1, 2); (*m0).typenodes += ((NI) 1); return result0; } N_NIMCALL(void, gentupleinfo_537551_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0) { Ropeobj179006* LOC1; Ropeobj179006* expr0; NI length0; TY533811 LOC15; LOC1 = (Ropeobj179006*)0; LOC1 = rope_179277_2381377266(((NimStringDesc*) &T839829468_18)); gentypeinfoauxbase_536960_839829468(m0, typ0, typ0, name0, LOC1); expr0 = getnimnode_536945_839829468(m0); length0 = sonslen_296327_850551059(typ0); { Ropeobj179006* tmp0; TY533811 LOC6; TY536238 LOC12; if (!(((NI) 0) < length0)) goto LA4; tmp0 = gettempname_534598_839829468(m0); memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = tmp0; LOC6[1] = rope_179401_2381377266(((NI64) (length0))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC6, 2); { NI i_537573_839829468; NI HEX3Atmp_537592_839829468; NI res_537595_839829468; i_537573_839829468 = (NI)0; HEX3Atmp_537592_839829468 = (NI)0; HEX3Atmp_537592_839829468 = (NI)(length0 - ((NI) 1)); res_537595_839829468 = ((NI) 0); { while (1) { Ttype293840* a0; Ropeobj179006* tmp20; TY536238 LOC10; TY536235 LOC11; if (!(res_537595_839829468 <= HEX3Atmp_537592_839829468)) goto LA9; i_537573_839829468 = res_537595_839829468; a0 = (*typ0).sons->data[i_537573_839829468]; tmp20 = getnimnode_536945_839829468(m0); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = tmp0; LOC10[1] = rope_179401_2381377266(((NI64) (i_537573_839829468))); LOC10[2] = tmp20; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC10, 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = tmp20; LOC11[1] = gettypedesc_536673_839829468(m0, typ0); LOC11[2] = rope_179401_2381377266(((NI64) (i_537573_839829468))); LOC11[3] = gentypeinfo_536941_839829468(m0, a0); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_141), LOC11, 4); res_537595_839829468 += ((NI) 1); } LA9: ; } } memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = expr0; LOC12[1] = rope_179401_2381377266(((NI64) (length0))); LOC12[2] = tmp0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC12, 3); } goto LA2; LA4: ; { TY533811 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = expr0; LOC14[1] = rope_179401_2381377266(((NI64) (length0))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC14, 2); } LA2: ; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = name0; LOC15[1] = expr0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC15, 2); } N_NIMCALL(Ttype293840*, fakeclosuretype_538010_839829468)(Tsym293834* owner0) { Ttype293840* result0; Ttype293840* LOC1; Ttype293840* r0; Ttype293840* LOC2; result0 = (Ttype293840*)0; result0 = newtype_296107_850551059(((Ttypekind293244) 18), owner0); LOC1 = (Ttype293840*)0; LOC1 = newtype_296107_850551059(((Ttypekind293244) 26), owner0); rawaddson_297394_850551059(result0, LOC1); r0 = newtype_296107_850551059(((Ttypekind293244) 22), owner0); LOC2 = (Ttype293840*)0; LOC2 = newtype_296107_850551059(((Ttypekind293244) 18), owner0); rawaddson_297394_850551059(r0, LOC2); rawaddson_297394_850551059(result0, r0); return result0; } N_NIMCALL(void, gentypeinfoaux_537027_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttype293840* origtype0, Ropeobj179006* name0) { Ropeobj179006* base0; base0 = (Ropeobj179006*)0; { NIM_BOOL LOC3; NI LOC4; Ttype293840* x0; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = sonslen_296327_850551059(typ0); LOC3 = (((NI) 0) < LOC4); if (!(LOC3)) goto LA5; LOC3 = !(((*typ0).sons->data[((NI) 0)] == NIM_NIL)); LA5: ; if (!LOC3) goto LA6; x0 = (*typ0).sons->data[((NI) 0)]; { if (!((*typ0).kind == ((Ttypekind293244) 17))) goto LA10; x0 = skiptypes_297099_850551059(x0, IL64(211106247215360)); } LA10: ; base0 = gentypeinfo_536941_839829468(m0, x0); } goto LA1; LA6: ; { base0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_18)); } LA1: ; gentypeinfoauxbase_536960_839829468(m0, typ0, origtype0, name0, base0); } static N_INLINE(NIM_BOOL, iscomplexvaluetype_539317_839829468)(Ttype293840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC3; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((983056 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); if (LOC1) goto LA2; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind293244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention293002) 8)); LA4: ; LOC1 = LOC3; LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, usestringh_533345_839829468)(Tcgen530027* m0) { { NIM_BOOL LOC5; if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag530025) 4))&7U)))!=0))) goto LA3; (*m0).flags |= ((NU8)1)<<((((Codegenflag530025) 4))%(sizeof(NU8)*8)); LOC5 = (NIM_BOOL)0; LOC5 = includestr_147249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_151)); } LA3: ; } N_NIMCALL(Ropeobj179006*, addrloc_539204_839829468)(Tloc293816* a0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = (*a0).r; { NIM_BOOL LOC3; Tctypekind530007 LOC5; Ropeobj179006* LOC8; LOC3 = (NIM_BOOL)0; LOC3 = !((((*a0).flags &(1U<<((NU)(((Tlocflag293810) 0))&15U)))!=0)); if (!(LOC3)) goto LA4; LOC5 = (Tctypekind530007)0; LOC5 = maptype_534394_839829468((*a0).t); LOC3 = !((LOC5 == ((Tctypekind530007) 17))); LA4: ; if (!LOC3) goto LA6; LOC8 = (Ropeobj179006*)0; LOC8 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_128), result0); result0 = HEX26_179447_2381377266(LOC8, ((NimStringDesc*) &T839829468_117)); } LA6: ; return result0; } N_NIMCALL(void, genobjectinit_539242_839829468)(Tcproc530021* p0, Tcprocsection530011 section0, Ttype293840* t0, Tloc293816* a0, NIM_BOOL takeaddr0) { Ttypefieldresult321145 LOC1; LOC1 = (Ttypefieldresult321145)0; LOC1 = analyseobjectwithtypefield_321149_3876443242(t0); switch (LOC1) { case ((Ttypefieldresult321145) 0): { } break; case ((Ttypefieldresult321145) 1): { Ropeobj179006* r0; Ttype293840* s0; TY533811 LOC19; r0 = rdloc_539188_839829468(a0); { TY179507 LOC8; if (!!(takeaddr0)) goto LA6; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = r0; r0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_124), LOC8, 1); } LA6: ; s0 = skiptypes_297099_850551059(t0, IL64(211106232576256)); { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC11) goto LA12; LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA12: ; if (!!(LOC11)) goto LA13; { while (1) { NIM_BOOL LOC17; LOC17 = (NIM_BOOL)0; LOC17 = ((*s0).kind == ((Ttypekind293244) 17)); if (!(LOC17)) goto LA18; LOC17 = !(((*s0).sons->data[((NI) 0)] == NIM_NIL)); LA18: ; if (!LOC17) goto LA16; add_179487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); s0 = skiptypes_297099_850551059((*s0).sons->data[((NI) 0)], IL64(211106247215360)); } LA16: ; } } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = r0; LOC19[1] = gentypeinfo_536941_839829468((*p0).module, t0); linefmt_533714_839829468(p0, section0, ((NimStringDesc*) &T839829468_154), LOC19, 2); } break; case ((Ttypefieldresult321145) 2): { Ropeobj179006* r0; TY533811 LOC26; { if (!takeaddr0) goto LA23; r0 = addrloc_539204_839829468(a0); } goto LA21; LA23: ; { r0 = rdloc_539188_839829468(a0); } LA21: ; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = r0; LOC26[1] = gentypeinfo_536941_839829468((*p0).module, t0); linefmt_533714_839829468(p0, section0, ((NimStringDesc*) &T839829468_155), LOC26, 2); } break; } } N_NIMCALL(void, constructloc_539388_839829468)(Tcproc530021* p0, Tloc293816* loc0, NIM_BOOL istemp0) { Ttype293840* typ0; typ0 = skiptypes_297099_850551059((*loc0).t, IL64(211106233624832)); { NIM_BOOL LOC3; TY533811 LOC6; LOC3 = (NIM_BOOL)0; LOC3 = iscomplexvaluetype_539317_839829468(typ0); if (!!(LOC3)) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rdloc_539188_839829468(loc0); LOC6[1] = gettypedesc_536673_839829468((*p0).module, typ0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_150), LOC6, 2); } goto LA1; LA4: ; { { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = !(istemp0); if (LOC10) goto LA11; LOC10 = containsgarbagecollectedref_321117_3876443242((*loc0).t); LA11: ; if (!LOC10) goto LA12; { NIM_BOOL LOC16; TY533811 LOC19; LOC16 = (NIM_BOOL)0; LOC16 = isimportedcpptype_534478_839829468(typ0); if (!!(LOC16)) goto LA17; usestringh_533345_839829468((*p0).module); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_539204_839829468(loc0); LOC19[1] = rdloc_539188_839829468(loc0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_152), LOC19, 2); } LA17: ; } LA12: ; genobjectinit_539242_839829468(p0, ((Tcprocsection530011) 2), (*loc0).t, loc0, NIM_TRUE); } LA1: ; } N_NIMCALL(void, gettemp_538032_839829468)(Tcproc530021* p0, Ttype293840* t0, Tloc293816* result0, NIM_BOOL needsinit0) { Ropeobj179006* LOC1; TY533811 LOC2; (*p0).labels += ((NI) 1); LOC1 = (Ropeobj179006*)0; LOC1 = rope_179401_2381377266(((NI64) ((*p0).labels))); unsureAsgnRef((void**) (&(*result0).r), HEX26_179452_2381377266(((NimStringDesc*) &T839829468_149), LOC1)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC2[1] = (*result0).r; linefmt_533714_839829468(p0, ((Tcprocsection530011) 0), ((NimStringDesc*) &T839829468_54), LOC2, 2); (*result0).k = ((Tlockind293808) 1); unsureAsgnRef((void**) (&(*result0).t), t0); (*result0).s = ((Tstorageloc293812) 2); (*result0).flags = 0; constructloc_539388_839829468(p0, (&(*result0)), !(needsinit0)); } static N_INLINE(Ropeobj179006*, parentobj_538257_839829468)(Ropeobj179006* accessor0, Tcgen530027* m0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NIM_BOOL LOC3; TY179507 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = accessor0; result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_161), LOC7, 1); } goto LA1; LA5: ; { result0 = accessor0; } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, intliteral_540270_839829468)(NI64 i0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (IL64(-2147483648) < i0); if (!(LOC3)) goto LA4; LOC3 = (i0 <= IL64(2147483647)); LA4: ; if (!LOC3) goto LA5; result0 = rope_179401_2381377266(i0); } goto LA1; LA5: ; { TY534289 LOC10; if (!(i0 == IL64(-2147483648))) goto LA8; memset((void*)LOC10, 0, sizeof(LOC10)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_166), LOC10, 0); } goto LA1; LA8: ; { TY179507 LOC14; if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_179401_2381377266(i0); result0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC14, 1); } goto LA1; LA12: ; { TY534289 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_168), LOC16, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, int64literal_550430_839829468)(NI64 i0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { TY179507 LOC5; if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_179401_2381377266(i0); result0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC5, 1); } goto LA1; LA3: ; { TY534289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_168), LOC7, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, uint64literal_550442_839829468)(NU64 i0) { Ropeobj179006* result0; NimStringDesc* LOC1; NimStringDesc* LOC2; result0 = (Ropeobj179006*)0; LOC1 = (NimStringDesc*)0; LOC2 = (NimStringDesc*)0; LOC2 = HEX24_8401_1689653243(i0); LOC1 = rawNewString(LOC2->Sup.len + 3); appendString(LOC1, LOC2); appendString(LOC1, ((NimStringDesc*) &T839829468_171)); result0 = rope_179277_2381377266(LOC1); return result0; } N_NIMCALL(Ropeobj179006*, getstrlit_550468_839829468)(Tcgen530027* m0, NimStringDesc* s0) { Ropeobj179006* result0; Ropeobj179006* LOC1; TY536238 LOC2; result0 = (Ropeobj179006*)0; LOC1 = (Ropeobj179006*)0; LOC1 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_79)); result0 = gettempname_534598_839829468(m0); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = result0; LOC2[1] = makecstring_192638_155036129(s0); LOC2[2] = rope_179401_2381377266(((NI64) ((s0 ? s0->Sup.len : 0)))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_177), LOC2, 3); return result0; } N_NIMCALL(Ropeobj179006*, genliteral_550476_839829468)(Tcproc530021* p0, Tnode293802* n0, Ttype293840* ty0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { if (!(ty0 == NIM_NIL)) goto LA3; internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_165)); } LA3: ; switch ((*n0).kind) { case ((Tnodekind293020) 5) ... ((Tnodekind293020) 15): { Ttype293840* LOC6; LOC6 = (Ttype293840*)0; LOC6 = skiptypes_297099_850551059(ty0, IL64(211106242013440)); switch ((*LOC6).kind) { case ((Ttypekind293244) 2): case ((Ttypekind293244) 5): { result0 = intliteral_540270_839829468((*n0).kindU.S1.intval); } break; case ((Ttypekind293244) 1): { { TY534289 LOC13; if (!!(((*n0).kindU.S1.intval == IL64(0)))) goto LA11; memset((void*)LOC13, 0, sizeof(LOC13)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_169), LOC13, 0); } goto LA9; LA11: ; { TY534289 LOC15; memset((void*)LOC15, 0, sizeof(LOC15)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_170), LOC15, 0); } LA9: ; } break; case ((Ttypekind293244) 35): { result0 = int64literal_550430_839829468((*n0).kindU.S1.intval); } break; case ((Ttypekind293244) 44): { result0 = uint64literal_550442_839829468(((NU64) ((*n0).kindU.S1.intval))); } break; default: { TY533811 LOC19; Ttype293840* LOC20; memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (Ttype293840*)0; LOC20 = skiptypes_297099_850551059(ty0, IL64(211106242013440)); LOC19[0] = gettypedesc_536673_839829468((*p0).module, LOC20); LOC19[1] = intliteral_540270_839829468((*n0).kindU.S1.intval); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_172), LOC19, 2); } break; } } break; case ((Tnodekind293020) 23): { Ttype293840* t0; t0 = skiptypes_297099_850551059(ty0, IL64(211106242013440)); { NIM_BOOL LOC24; NI id0; Ropeobj179006* LOC28; LOC24 = (NIM_BOOL)0; LOC24 = ((*t0).kind == ((Ttypekind293244) 25)); if (!(LOC24)) goto LA25; LOC24 = ((*t0).callconv == ((Tcallingconvention293002) 8)); LA25: ; if (!LOC24) goto LA26; id0 = nodetabletestorset_343682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC28 = (Ropeobj179006*)0; LOC28 = rope_179401_2381377266(((NI64) (id0))); result0 = HEX26_179418_2381377266((*(*p0).module).tmpbase, LOC28); { TY533811 LOC33; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA31; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC33[1] = result0; addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_173), LOC33, 2); } LA31: ; } goto LA22; LA26: ; { result0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_174)); } LA22: ; } break; case ((Tnodekind293020) 20) ... ((Tnodekind293020) 22): { { TY534289 LOC40; if (!(*n0).kindU.S3.strval == 0) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); result0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_175), LOC40, 0); } goto LA36; LA38: ; { Ttype293840* LOC42; NI id0; LOC42 = (Ttype293840*)0; LOC42 = skiptypes_297099_850551059(ty0, IL64(211106242013440)); if (!((*LOC42).kind == ((Ttypekind293244) 28))) goto LA43; id0 = nodetabletestorset_343682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); { TY179507 LOC49; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA47; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = getstrlit_550468_839829468((*p0).module, (*n0).kindU.S3.strval); result0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_176), LOC49, 1); } goto LA45; LA47: ; { TY533811 LOC51; memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = (*(*p0).module).tmpbase; LOC51[1] = rope_179401_2381377266(((NI64) (id0))); result0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_178), LOC51, 2); } LA45: ; } goto LA36; LA43: ; { result0 = makecstring_192638_155036129((*n0).kindU.S3.strval); } LA36: ; } break; case ((Tnodekind293020) 16) ... ((Tnodekind293020) 18): { NimStringDesc* LOC54; LOC54 = (NimStringDesc*)0; LOC54 = tostrmaxprecision_299007_3471544153((*n0).kindU.S2.floatval); result0 = rope_179277_2381377266(LOC54); } break; default: { NimStringDesc* LOC56; LOC56 = (NimStringDesc*)0; LOC56 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI293020))->Sup.len + 12); appendString(LOC56, ((NimStringDesc*) &T839829468_179)); appendString(LOC56, reprEnum((NI)(*n0).kind, (&NTI293020))); appendChar(LOC56, 41); internalerror_197100_155036129((*n0).info, LOC56); result0 = NIM_NIL; } break; } return result0; } N_NIMCALL(Ropeobj179006*, genliteral_540273_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = genliteral_550476_839829468(p0, n0, (*n0).typ); return result0; } N_NIMCALL(void, gencaserange_538028_839829468)(Tcproc530021* p0, Tnode293802* branch0) { NI length0; length0 = len_294081_850551059(branch0); { NI j_548677_839829468; NI HEX3Atmp_548718_839829468; NI res_548721_839829468; j_548677_839829468 = (NI)0; HEX3Atmp_548718_839829468 = (NI)0; HEX3Atmp_548718_839829468 = (NI)(length0 - ((NI) 2)); res_548721_839829468 = ((NI) 0); { while (1) { if (!(res_548721_839829468 <= HEX3Atmp_548718_839829468)) goto LA3; j_548677_839829468 = res_548721_839829468; { Tnode293802* LOC6; LOC6 = (Tnode293802*)0; LOC6 = HEX5BHEX5D_294238_850551059(branch0, j_548677_839829468); if (!((*LOC6).kind == ((Tnodekind293020) 44))) goto LA7; { TY533811 LOC13; Tnode293802* LOC14; Tnode293802* LOC15; Tnode293802* LOC16; Tnode293802* LOC17; if (!((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 0))&7U)))!=0)) goto LA11; memset((void*)LOC13, 0, sizeof(LOC13)); LOC14 = (Tnode293802*)0; LOC14 = HEX5BHEX5D_294238_850551059(branch0, j_548677_839829468); LOC15 = (Tnode293802*)0; LOC15 = HEX5BHEX5D_294238_850551059(LOC14, ((NI) 0)); LOC13[0] = genliteral_540273_839829468(p0, LOC15); LOC16 = (Tnode293802*)0; LOC16 = HEX5BHEX5D_294238_850551059(branch0, j_548677_839829468); LOC17 = (Tnode293802*)0; LOC17 = HEX5BHEX5D_294238_850551059(LOC16, ((NI) 1)); LOC13[1] = genliteral_540273_839829468(p0, LOC17); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_164), LOC13, 2); } goto LA9; LA11: ; { Tnode293802* v0; Tnode293802* LOC19; Tnode293802* LOC20; LOC19 = (Tnode293802*)0; LOC19 = HEX5BHEX5D_294238_850551059(branch0, j_548677_839829468); LOC20 = (Tnode293802*)0; LOC20 = HEX5BHEX5D_294238_850551059(LOC19, ((NI) 0)); v0 = copynode_297528_850551059(LOC20); { while (1) { Tnode293802* LOC23; Tnode293802* LOC24; TY179507 LOC25; LOC23 = (Tnode293802*)0; LOC23 = HEX5BHEX5D_294238_850551059(branch0, j_548677_839829468); LOC24 = (Tnode293802*)0; LOC24 = HEX5BHEX5D_294238_850551059(LOC23, ((NI) 1)); if (!((*v0).kindU.S1.intval <= (*LOC24).kindU.S1.intval)) goto LA22; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = genliteral_540273_839829468(p0, v0); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_180), LOC25, 1); (*v0).kindU.S1.intval += ((NI) 1); } LA22: ; } } LA9: ; } goto LA4; LA7: ; { TY179507 LOC27; Tnode293802* LOC28; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Tnode293802*)0; LOC28 = HEX5BHEX5D_294238_850551059(branch0, j_548677_839829468); LOC27[0] = genliteral_540273_839829468(p0, LOC28); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_180), LOC27, 1); } LA4: ; res_548721_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, gentraverseproc_538039_839829468)(Ttraversalclosure538019* c0, Ropeobj179006* accessor0, Tnode293802* n0) { { { if (!(n0 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; switch ((*n0).kind) { case ((Tnodekind293020) 138): { { NI i_538068_839829468; NI HEX3Atmp_538239_839829468; NI LOC7; NI res_538242_839829468; i_538068_839829468 = (NI)0; HEX3Atmp_538239_839829468 = (NI)0; LOC7 = (NI)0; LOC7 = sonslen_296351_850551059(n0); HEX3Atmp_538239_839829468 = (NI)(LOC7 - ((NI) 1)); res_538242_839829468 = ((NI) 0); { while (1) { if (!(res_538242_839829468 <= HEX3Atmp_538239_839829468)) goto LA9; i_538068_839829468 = res_538242_839829468; gentraverseproc_538039_839829468(c0, accessor0, (*n0).kindU.S6.sons->data[i_538068_839829468]); res_538242_839829468 += ((NI) 1); } LA9: ; } } } break; case ((Tnodekind293020) 139): { Tcproc530021* p0; Tsym293834* disc0; TY533811 LOC15; TY534289 LOC28; { if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)))) goto LA13; internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_162)); } LA13: ; p0 = (*c0).p; disc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = accessor0; LOC15[1] = (*disc0).loc.r; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_163), LOC15, 2); { NI i_538098_839829468; NI HEX3Atmp_538249_839829468; NI LOC17; NI res_538252_839829468; i_538098_839829468 = (NI)0; HEX3Atmp_538249_839829468 = (NI)0; LOC17 = (NI)0; LOC17 = sonslen_296351_850551059(n0); HEX3Atmp_538249_839829468 = (NI)(LOC17 - ((NI) 1)); res_538252_839829468 = ((NI) 1); { while (1) { Tnode293802* branch0; Tnode293802* LOC26; TY534289 LOC27; if (!(res_538252_839829468 <= HEX3Atmp_538249_839829468)) goto LA19; i_538098_839829468 = res_538252_839829468; branch0 = (*n0).kindU.S6.sons->data[i_538098_839829468]; { if (!((*branch0).kind == ((Tnodekind293020) 85))) goto LA22; gencaserange_538028_839829468((*c0).p, branch0); } goto LA20; LA22: ; { TY534289 LOC25; memset((void*)LOC25, 0, sizeof(LOC25)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_181), LOC25, 0); } LA20: ; LOC26 = (Tnode293802*)0; LOC26 = lastson_296364_850551059(branch0); gentraverseproc_538039_839829468(c0, accessor0, LOC26); memset((void*)LOC27, 0, sizeof(LOC27)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_182), LOC27, 0); res_538252_839829468 += ((NI) 1); } LA19: ; } } memset((void*)LOC28, 0, sizeof(LOC28)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_183), LOC28, 0); } break; case ((Tnodekind293020) 3): { Tsym293834* field0; TY533811 LOC34; Ropeobj179006* LOC35; field0 = (*n0).kindU.S4.sym; { if (!((*field0).loc.t == NIM_NIL)) goto LA32; internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184)); } LA32: ; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = accessor0; LOC34[1] = (*field0).loc.r; LOC35 = (Ropeobj179006*)0; LOC35 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_90), LOC34, 2); gentraverseproc_538022_839829468(c0, LOC35, (*field0).loc.t); } break; default: { internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184)); } break; } }BeforeRet: ; } N_NIMCALL(void, linecg_533707_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0) { Ropeobj179006** LOC1; Ropeobj179006* LOC2; Ropeobj179006* LOC3; LOC1 = (Ropeobj179006**)0; LOC1 = s_530179_3723162438(p0, s0); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, frmt0, args0, args0Len0); LOC3 = (Ropeobj179006*)0; LOC3 = indentline_533656_839829468(p0, LOC2); add_179482_2381377266(LOC1, LOC3); } N_NIMCALL(void, gentraverseproc_538022_839829468)(Ttraversalclosure538019* c0, Ropeobj179006* accessor0, Ttype293840* typ_538027_839829468) { Ttype293840* typ_538302_839829468; Tcproc530021* p0; { { if (!(typ_538027_839829468 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; typ_538302_839829468 = getuniquetype_529640_2036603609(typ_538027_839829468); p0 = (*c0).p; switch ((*typ_538302_839829468).kind) { case ((Ttypekind293244) 11): case ((Ttypekind293244) 10): case ((Ttypekind293244) 8): { Ttype293840* LOC6; LOC6 = (Ttype293840*)0; LOC6 = lastson_296377_850551059(typ_538302_839829468); gentraverseproc_538022_839829468(c0, accessor0, LOC6); } break; case ((Ttypekind293244) 4): case ((Ttypekind293244) 16): { NI64 arraysize0; Tloc293816 i0; Ttype293840* LOC8; TY533811 LOC9; TY533811 LOC10; Ropeobj179006* LOC11; TY534289 LOC12; arraysize0 = lengthord_321007_3876443242((*typ_538302_839829468).sons->data[((NI) 0)]); memset((void*)(&i0), 0, sizeof(i0)); LOC8 = (Ttype293840*)0; LOC8 = getsystype_339150_3937434831(((Ttypekind293244) 31)); gettemp_538032_839829468(p0, LOC8, (&i0), NIM_FALSE); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = i0.r; LOC9[1] = rope_179401_2381377266(arraysize0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_159), LOC9, 2); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = accessor0; LOC10[1] = i0.r; LOC11 = (Ropeobj179006*)0; LOC11 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC10, 2); gentraverseproc_538022_839829468(c0, LOC11, (*typ_538302_839829468).sons->data[((NI) 1)]); memset((void*)LOC12, 0, sizeof(LOC12)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_160), LOC12, 0); } break; case ((Ttypekind293244) 17): { { NI i_538325_839829468; NI HEX3Atmp_538384_839829468; NI LOC15; NI res_538387_839829468; i_538325_839829468 = (NI)0; HEX3Atmp_538384_839829468 = (NI)0; LOC15 = (NI)0; LOC15 = sonslen_296327_850551059(typ_538302_839829468); HEX3Atmp_538384_839829468 = (NI)(LOC15 - ((NI) 1)); res_538387_839829468 = ((NI) 0); { while (1) { Ttype293840* x0; Ropeobj179006* LOC22; if (!(res_538387_839829468 <= HEX3Atmp_538384_839829468)) goto LA17; i_538325_839829468 = res_538387_839829468; x0 = (*typ_538302_839829468).sons->data[i_538325_839829468]; { if (!!((x0 == NIM_NIL))) goto LA20; x0 = skiptypes_297099_850551059(x0, IL64(211106247215360)); } LA20: ; LOC22 = (Ropeobj179006*)0; LOC22 = parentobj_538257_839829468(accessor0, (*(*c0).p).module); gentraverseproc_538022_839829468(c0, LOC22, x0); res_538387_839829468 += ((NI) 1); } LA17: ; } } { if (!!(((*typ_538302_839829468).n == NIM_NIL))) goto LA25; gentraverseproc_538039_839829468(c0, accessor0, (*typ_538302_839829468).n); } LA25: ; } break; case ((Ttypekind293244) 18): { Ttype293840* typ0; typ0 = getuniquetype_529640_2036603609(typ_538302_839829468); { NI i_538363_839829468; NI HEX3Atmp_538392_839829468; NI LOC29; NI res_538395_839829468; i_538363_839829468 = (NI)0; HEX3Atmp_538392_839829468 = (NI)0; LOC29 = (NI)0; LOC29 = sonslen_296327_850551059(typ0); HEX3Atmp_538392_839829468 = (NI)(LOC29 - ((NI) 1)); res_538395_839829468 = ((NI) 0); { while (1) { TY533811 LOC32; Ropeobj179006* LOC33; if (!(res_538395_839829468 <= HEX3Atmp_538392_839829468)) goto LA31; i_538363_839829468 = res_538395_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = accessor0; LOC32[1] = rope_179401_2381377266(((NI64) (i_538363_839829468))); LOC33 = (Ropeobj179006*)0; LOC33 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_185), LOC32, 2); gentraverseproc_538022_839829468(c0, LOC33, (*typ0).sons->data[i_538363_839829468]); res_538395_839829468 += ((NI) 1); } LA31: ; } } } break; case ((Ttypekind293244) 22): case ((Ttypekind293244) 28): case ((Ttypekind293244) 24): { TY179507 LOC35; memset((void*)LOC35, 0, sizeof(LOC35)); LOC35[0] = accessor0; linecg_533707_839829468(p0, ((Tcprocsection530011) 2), (*c0).visitorfrmt, LOC35, 1); } break; case ((Ttypekind293244) 25): { { TY179507 LOC41; TY179507 LOC42; if (!((*typ_538302_839829468).callconv == ((Tcallingconvention293002) 8))) goto LA39; memset((void*)LOC41, 0, sizeof(LOC41)); memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = accessor0; LOC41[0] = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_186), LOC42, 1); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), (*c0).visitorfrmt, LOC41, 1); } LA39: ; } break; default: { } break; } }BeforeRet: ; } N_NIMCALL(void, gentraverseprocseq_538399_839829468)(Ttraversalclosure538019* c0, Ropeobj179006* accessor0, Ttype293840* typ0) { Tcproc530021* p0; Tloc293816 i0; Ttype293840* LOC1; TY536238 LOC2; NimStringDesc* LOC3; TY533811 LOC11; Ropeobj179006* LOC12; TY534289 LOC13; p0 = (*c0).p; memset((void*)(&i0), 0, sizeof(i0)); LOC1 = (Ttype293840*)0; LOC1 = getsystype_339150_3937434831(((Ttypekind293244) 31)); gettemp_538032_839829468(p0, LOC1, (&i0), NIM_FALSE); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = i0.r; LOC2[1] = accessor0; LOC3 = (NimStringDesc*)0; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC6) goto LA7; LOC6 = (((*(*(*(*c0).p).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA7: ; if (!LOC6) goto LA8; LOC3 = copyString(((NimStringDesc*) &T839829468_157)); } goto LA4; LA8: ; { LOC3 = copyString(((NimStringDesc*) &T839829468_158)); } LA4: ; LOC2[2] = rope_179277_2381377266(LOC3); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_156), LOC2, 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = accessor0; LOC11[1] = i0.r; LOC12 = (Ropeobj179006*)0; LOC12 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_187), LOC11, 2); gentraverseproc_538022_839829468(c0, LOC12, (*typ0).sons->data[((NI) 0)]); memset((void*)LOC13, 0, sizeof(LOC13)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_160), LOC13, 0); } N_NIMCALL(Ropeobj179006*, gentraverseproc_538632_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttypeinforeason538016 reason0) { Ropeobj179006* result0; Ttraversalclosure538019 c0; Tcproc530021* p0; Ropeobj179006* header0; TY179507 LOC3; Ropeobj179006* t0; TY179507 LOC4; TY179507 LOC5; Ropeobj179006* generatedproc0; TY536235 LOC20; Ropeobj179006** LOC21; Ropeobj179006** LOC22; Ropeobj179006** LOC23; TY179507 LOC24; result0 = (Ropeobj179006*)0; memset((void*)(&c0), 0, sizeof(c0)); p0 = newproc_530206_3723162438(NIM_NIL, m0); result0 = gettempname_534598_839829468(m0); switch (reason0) { case ((Ttypeinforeason538016) 0): { c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_145)); } break; default: { } break; } memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = result0; header0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_146), LOC3, 1); t0 = gettypedesc_536673_839829468(m0, typ0); memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = t0; linef_533700_839829468(p0, ((Tcprocsection530011) 0), ((NimStringDesc*) &T839829468_147), LOC4, 1); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = t0; linef_533700_839829468(p0, ((Tcprocsection530011) 1), ((NimStringDesc*) &T839829468_148), LOC5, 1); c0.p = p0; { Ropeobj179006* LOC10; if (!((*typ0).kind == ((Ttypekind293244) 24))) goto LA8; LOC10 = (Ropeobj179006*)0; LOC10 = rope_179277_2381377266(((NimStringDesc*) &T839829468_188)); gentraverseprocseq_538399_839829468((&c0), LOC10, typ0); } goto LA6; LA8: ; { { Ttype293840* LOC14; Ropeobj179006* LOC17; LOC14 = (Ttype293840*)0; LOC14 = skiptypes_297099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106232576256)); if (!((65552 &((NU64)1<<((NU)((*LOC14).kind)&63U)))!=0)) goto LA15; LOC17 = (Ropeobj179006*)0; LOC17 = rope_179277_2381377266(((NimStringDesc*) &T839829468_188)); gentraverseproc_538022_839829468((&c0), LOC17, (*typ0).sons->data[((NI) 0)]); } goto LA12; LA15: ; { Ropeobj179006* LOC19; LOC19 = (Ropeobj179006*)0; LOC19 = rope_179277_2381377266(((NimStringDesc*) &T839829468_189)); gentraverseproc_538022_839829468((&c0), LOC19, (*typ0).sons->data[((NI) 0)]); } LA12: ; } LA6: ; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = header0; LOC21 = (Ropeobj179006**)0; LOC21 = s_530179_3723162438(p0, ((Tcprocsection530011) 0)); LOC20[1] = (*LOC21); LOC22 = (Ropeobj179006**)0; LOC22 = s_530179_3723162438(p0, ((Tcprocsection530011) 1)); LOC20[2] = (*LOC22); LOC23 = (Ropeobj179006**)0; LOC23 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); LOC20[3] = (*LOC23); generatedproc0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_190), LOC20, 4); memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = header0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC24, 1); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 10))- 0], generatedproc0); return result0; } N_NIMCALL(void, genarrayinfo_538005_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0) { Ropeobj179006* LOC1; LOC1 = (Ropeobj179006*)0; LOC1 = gentypeinfo_536941_839829468(m0, (*typ0).sons->data[((NI) 1)]); gentypeinfoauxbase_536960_839829468(m0, typ0, typ0, name0, LOC1); } N_NIMCALL(void, gensetinfo_537867_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0) { Ropeobj179006* tmp0; TY536238 LOC1; NI64 LOC2; gentypeinfoaux_537027_839829468(m0, typ0, typ0, name0); tmp0 = getnimnode_536945_839829468(m0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = tmp0; LOC2 = (NI64)0; LOC2 = firstord_321001_3876443242(typ0); LOC1[1] = rope_179401_2381377266(LOC2); LOC1[2] = name0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_193), LOC1, 3); } N_NIMCALL(void, genenuminfo_537599_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ropeobj179006* name0) { Ropeobj179006* nodeptrs0; NI length0; TY533811 LOC1; Ropeobj179006* enumnames0; Ropeobj179006* specialcases0; NI firstnimnode0; NIM_BOOL hasholes0; Ropeobj179006* enumarray0; Ropeobj179006* counter0; TY179507 LOC24; TY536238 LOC25; TY537847 LOC26; TY536235 LOC27; gentypeinfoaux_537027_839829468(m0, typ0, typ0, name0); nodeptrs0 = gettempname_534598_839829468(m0); length0 = sonslen_296351_850551059((*typ0).n); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = nodeptrs0; LOC1[1] = rope_179401_2381377266(((NI64) (length0))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC1, 2); enumnames0 = (Ropeobj179006*)0; specialcases0 = (Ropeobj179006*)0; firstnimnode0 = (*m0).typenodes; hasholes0 = NIM_FALSE; { NI i_537624_839829468; NI HEX3Atmp_537860_839829468; NI res_537863_839829468; i_537624_839829468 = (NI)0; HEX3Atmp_537860_839829468 = (NI)0; HEX3Atmp_537860_839829468 = (NI)(length0 - ((NI) 1)); res_537863_839829468 = ((NI) 0); { while (1) { Tsym293834* field0; Ropeobj179006* elemnode0; if (!(res_537863_839829468 <= HEX3Atmp_537860_839829468)) goto LA4; i_537624_839829468 = res_537863_839829468; field0 = (*(*(*typ0).n).kindU.S6.sons->data[i_537624_839829468]).kindU.S4.sym; elemnode0 = getnimnode_536945_839829468(m0); { Ropeobj179006* LOC9; if (!((*field0).ast == NIM_NIL)) goto LA7; LOC9 = (Ropeobj179006*)0; LOC9 = makecstring_192638_155036129((*(*field0).name).s); add_179482_2381377266(&enumnames0, LOC9); } goto LA5; LA7: ; { Ropeobj179006* LOC11; LOC11 = (Ropeobj179006*)0; LOC11 = makecstring_192638_155036129((*(*field0).ast).kindU.S3.strval); add_179482_2381377266(&enumnames0, LOC11); } LA5: ; { NimStringDesc* LOC16; if (!(i_537624_839829468 < (NI)(length0 - ((NI) 1)))) goto LA14; LOC16 = (NimStringDesc*)0; LOC16 = rawNewString(tnl_177644_4151366050->Sup.len + 2); appendString(LOC16, ((NimStringDesc*) &T839829468_110)); appendString(LOC16, tnl_177644_4151366050); add_179487_2381377266(&enumnames0, LOC16); } LA14: ; { NIM_BOOL LOC19; TY533811 LOC23; LOC19 = (NIM_BOOL)0; LOC19 = !(((*field0).position == i_537624_839829468)); if (LOC19) goto LA20; LOC19 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 5))&31U)))!=0); LA20: ; if (!LOC19) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = elemnode0; LOC23[1] = rope_179401_2381377266(((NI64) ((*field0).position))); addf_180205_2381377266(&specialcases0, ((NimStringDesc*) &T839829468_194), LOC23, 2); hasholes0 = NIM_TRUE; } LA21: ; res_537863_839829468 += ((NI) 1); } LA4: ; } } enumarray0 = gettempname_534598_839829468(m0); counter0 = gettempname_534598_839829468(m0); memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = counter0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 12))- 0], ((NimStringDesc*) &T839829468_195), LOC24, 1); memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = enumarray0; LOC25[1] = rope_179401_2381377266(((NI64) (length0))); LOC25[2] = enumnames0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 12))- 0], ((NimStringDesc*) &T839829468_196), LOC25, 3); memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = counter0; LOC26[1] = rope_179401_2381377266(((NI64) (length0))); LOC26[2] = (*m0).typenodesname; LOC26[3] = rope_179401_2381377266(((NI64) (firstnimnode0))); LOC26[4] = enumarray0; LOC26[5] = nodeptrs0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_197), LOC26, 6); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], specialcases0); memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = getnimnode_536945_839829468(m0); LOC27[1] = rope_179401_2381377266(((NI64) (length0))); LOC27[2] = nodeptrs0; LOC27[3] = name0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_198), LOC27, 4); { TY179507 LOC32; if (!hasholes0) goto LA30; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = name0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_199), LOC32, 1); } LA30: ; } N_NIMCALL(Ropeobj179006*, discriminatortablename_537057_839829468)(Tcgen530027* m0, Ttype293840* objtype_537060_839829468, Tsym293834* d0) { Ropeobj179006* result0; Ttype293840* objtype0; TY533811 LOC8; NimStringDesc* LOC9; result0 = (Ropeobj179006*)0; objtype0 = objtype_537060_839829468; { while (1) { Tsym293834* LOC3; LOC3 = (Tsym293834*)0; LOC3 = lookupinrecord_300119_2984716966((*objtype0).n, (*d0).name); if (!(LOC3 == NIM_NIL)) goto LA2; objtype0 = (*objtype0).sons->data[((NI) 0)]; } LA2: ; } { if (!((*objtype0).sym == NIM_NIL)) goto LA6; internalerror_197100_155036129((*d0).info, ((NimStringDesc*) &T839829468_200)); } LA6: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rope_179401_2381377266(((NI64) ((*objtype0).Sup.id))); LOC9 = (NimStringDesc*)0; LOC9 = mangle_529847_2036603609((*(*d0).name).s); LOC8[1] = rope_179277_2381377266(LOC9); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_201), LOC8, 2); return result0; } N_NIMCALL(void, genobjectfields_537104_839829468)(Tcgen530027* m0, Ttype293840* typ0, Tnode293802* n0, Ropeobj179006* expr0) { switch ((*n0).kind) { case ((Tnodekind293020) 138): { NI L0; L0 = sonslen_296351_850551059(n0); { if (!(L0 == ((NI) 1))) goto LA4; genobjectfields_537104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[((NI) 0)], expr0); } goto LA2; LA4: ; { Ropeobj179006* tmp0; TY533811 LOC9; TY536238 LOC14; if (!(((NI) 0) < L0)) goto LA7; tmp0 = gettempname_534598_839829468(m0); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = tmp0; LOC9[1] = rope_179401_2381377266(((NI64) (L0))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC9, 2); { NI i_537127_839829468; NI HEX3Atmp_537482_839829468; NI res_537485_839829468; i_537127_839829468 = (NI)0; HEX3Atmp_537482_839829468 = (NI)0; HEX3Atmp_537482_839829468 = (NI)(L0 - ((NI) 1)); res_537485_839829468 = ((NI) 0); { while (1) { Ropeobj179006* tmp20; TY536238 LOC13; if (!(res_537485_839829468 <= HEX3Atmp_537482_839829468)) goto LA12; i_537127_839829468 = res_537485_839829468; tmp20 = getnimnode_536945_839829468(m0); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = tmp0; LOC13[1] = rope_179401_2381377266(((NI64) (i_537127_839829468))); LOC13[2] = tmp20; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC13, 3); genobjectfields_537104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[i_537127_839829468], tmp20); res_537485_839829468 += ((NI) 1); } LA12: ; } } memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = expr0; LOC14[1] = rope_179401_2381377266(((NI64) (L0))); LOC14[2] = tmp0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC14, 3); } goto LA2; LA7: ; { TY533811 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = expr0; LOC16[1] = rope_179401_2381377266(((NI64) (L0))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC16, 2); } LA2: ; } break; case ((Tnodekind293020) 139): { Tsym293834* field0; Ropeobj179006* tmp0; NI64 L0; TY537401 LOC18; TY533811 LOC19; field0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; tmp0 = discriminatortablename_537057_839829468(m0, typ0, field0); L0 = lengthord_321007_3876443242((*field0).typ); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = expr0; LOC18[1] = gettypedesc_536673_839829468(m0, typ0); LOC18[2] = (*field0).loc.r; LOC18[3] = gentypeinfo_536941_839829468(m0, (*field0).typ); LOC18[4] = makecstring_192638_155036129((*(*field0).name).s); LOC18[5] = tmp0; LOC18[6] = rope_179401_2381377266(L0); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_202), LOC18, 7); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = tmp0; LOC19[1] = rope_179401_2381377266((NI64)(L0 + IL64(1))); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_203), LOC19, 2); { NI i_537421_839829468; NI HEX3Atmp_537501_839829468; NI LOC21; NI res_537504_839829468; i_537421_839829468 = (NI)0; HEX3Atmp_537501_839829468 = (NI)0; LOC21 = (NI)0; LOC21 = sonslen_296351_850551059(n0); HEX3Atmp_537501_839829468 = (NI)(LOC21 - ((NI) 1)); res_537504_839829468 = ((NI) 1); { while (1) { Tnode293802* b0; Ropeobj179006* tmp20; Tnode293802* LOC24; if (!(res_537504_839829468 <= HEX3Atmp_537501_839829468)) goto LA23; i_537421_839829468 = res_537504_839829468; b0 = (*n0).kindU.S6.sons->data[i_537421_839829468]; tmp20 = getnimnode_536945_839829468(m0); LOC24 = (Tnode293802*)0; LOC24 = lastson_296364_850551059(b0); genobjectfields_537104_839829468(m0, typ0, LOC24, tmp20); switch ((*b0).kind) { case ((Tnodekind293020) 85): { { NI LOC28; LOC28 = (NI)0; LOC28 = sonslen_296351_850551059(b0); if (!(LOC28 < ((NI) 2))) goto LA29; internalerror_197100_155036129((*b0).info, ((NimStringDesc*) &T839829468_204)); } LA29: ; { NI j_537436_839829468; NI HEX3Atmp_537494_839829468; NI LOC32; NI res_537497_839829468; j_537436_839829468 = (NI)0; HEX3Atmp_537494_839829468 = (NI)0; LOC32 = (NI)0; LOC32 = sonslen_296351_850551059(b0); HEX3Atmp_537494_839829468 = (NI)(LOC32 - ((NI) 2)); res_537497_839829468 = ((NI) 0); { while (1) { if (!(res_537497_839829468 <= HEX3Atmp_537494_839829468)) goto LA34; j_537436_839829468 = res_537497_839829468; { NI x0; NI64 LOC39; NI y0; NI64 LOC40; if (!((*(*b0).kindU.S6.sons->data[j_537436_839829468]).kind == ((Tnodekind293020) 44))) goto LA37; LOC39 = (NI64)0; LOC39 = getordvalue_321129_3876443242((*(*b0).kindU.S6.sons->data[j_537436_839829468]).kindU.S6.sons->data[((NI) 0)]); x0 = ((NI) (LOC39)); LOC40 = (NI64)0; LOC40 = getordvalue_321129_3876443242((*(*b0).kindU.S6.sons->data[j_537436_839829468]).kindU.S6.sons->data[((NI) 1)]); y0 = ((NI) (LOC40)); { while (1) { TY536238 LOC43; if (!(x0 <= y0)) goto LA42; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = tmp0; LOC43[1] = rope_179401_2381377266(((NI64) (x0))); LOC43[2] = tmp20; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC43, 3); x0 += ((NI) 1); } LA42: ; } } goto LA35; LA37: ; { TY536238 LOC45; NI64 LOC46; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = tmp0; LOC46 = (NI64)0; LOC46 = getordvalue_321129_3876443242((*b0).kindU.S6.sons->data[j_537436_839829468]); LOC45[1] = rope_179401_2381377266(LOC46); LOC45[2] = tmp20; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC45, 3); } LA35: ; res_537497_839829468 += ((NI) 1); } LA34: ; } } } break; case ((Tnodekind293020) 88): { TY536238 LOC48; memset((void*)LOC48, 0, sizeof(LOC48)); LOC48[0] = tmp0; LOC48[1] = rope_179401_2381377266(L0); LOC48[2] = tmp20; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC48, 3); } break; default: { internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_205)); } break; } res_537504_839829468 += ((NI) 1); } LA23: ; } } } break; case ((Tnodekind293020) 3): { Tsym293834* field0; field0 = (*n0).kindU.S4.sym; { TY537475 LOC55; if (!((*field0).kindU.S4.bitsize == ((NI) 0))) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = expr0; LOC55[1] = gettypedesc_536673_839829468(m0, typ0); LOC55[2] = (*field0).loc.r; LOC55[3] = gentypeinfo_536941_839829468(m0, (*field0).typ); LOC55[4] = makecstring_192638_155036129((*(*field0).name).s); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_206), LOC55, 5); } LA53: ; } break; default: { internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_207)); } break; } } N_NIMCALL(void, genobjectinfo_537508_839829468)(Tcgen530027* m0, Ttype293840* typ0, Ttype293840* origtype0, Ropeobj179006* name0) { Ropeobj179006* tmp0; TY533811 LOC12; Ttype293840* t0; { if (!((*typ0).kind == ((Ttypekind293244) 17))) goto LA3; gentypeinfoaux_537027_839829468(m0, typ0, origtype0, name0); } goto LA1; LA3: ; { Ropeobj179006* LOC6; LOC6 = (Ropeobj179006*)0; LOC6 = rope_179277_2381377266(((NimStringDesc*) &T839829468_18)); gentypeinfoauxbase_536960_839829468(m0, typ0, origtype0, name0, LOC6); } LA1: ; tmp0 = getnimnode_536945_839829468(m0); { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = isimportedcpptype_534478_839829468(typ0); if (!!(LOC9)) goto LA10; genobjectfields_537104_839829468(m0, typ0, (*typ0).n, tmp0); } LA10: ; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = name0; LOC12[1] = tmp0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC12, 2); t0 = (*typ0).sons->data[((NI) 0)]; { while (1) { if (!!((t0 == NIM_NIL))) goto LA14; t0 = skiptypes_297099_850551059(t0, IL64(211106247215360)); (*t0).flags |= ((NU32)1)<<((((Ttypeflag293431) 5))%(sizeof(NU32)*8)); t0 = (*t0).sons->data[((NI) 0)]; } LA14: ; } } N_NIMCALL(void, gendeepcopyproc_539066_839829468)(Tcgen530027* m0, Tsym293834* s0, Ropeobj179006* result0) { TY533811 LOC1; genproc_533951_839829468(m0, s0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = result0; LOC1[1] = (*s0).loc.r; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_208), LOC1, 2); } N_NIMCALL(Ropeobj179006*, gentypeinfo_536941_839829468)(Tcgen530027* m0, Ttype293840* t_536944_839829468) { Ropeobj179006* result0; Ttype293840* origtype0; Ttype293840* t0; TY179507 LOC1; Tsym293834* owner0; Ttype293840* LOC12; Ropeobj179006* LOC66; Ropeobj179006* LOC67; Ropeobj179006* LOC68; { result0 = (Ropeobj179006*)0; origtype0 = t_536944_839829468; t0 = getuniquetype_529640_2036603609(t_536944_839829468); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rope_179401_2381377266(((NI64) ((*t0).Sup.id))); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_127), LOC1, 1); { NIM_BOOL LOC4; Ropeobj179006* LOC7; Ropeobj179006* LOC8; Ropeobj179006* LOC9; LOC4 = (NIM_BOOL)0; LOC4 = containsorincl_269862_2627731572((&(*m0).typeinfomarker), (*t0).Sup.id); if (!LOC4) goto LA5; LOC7 = (Ropeobj179006*)0; LOC7 = rope_179277_2381377266(((NimStringDesc*) &T839829468_128)); LOC8 = (Ropeobj179006*)0; LOC8 = HEX26_179418_2381377266(LOC7, result0); LOC9 = (Ropeobj179006*)0; LOC9 = rope_179277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_179418_2381377266(LOC8, LOC9); goto BeforeRet; } LA5: ; { while (1) { if (!((*t0).kind == ((Ttypekind293244) 13))) goto LA11; t0 = lastson_296377_850551059(t0); } LA11: ; } LOC12 = (Ttype293840*)0; LOC12 = skiptypes_297099_850551059(t0, IL64(211106247256320)); owner0 = getmodule_300123_2984716966((*LOC12).owner); { Tcgen530027* LOC17; Ropeobj179006* LOC18; Ropeobj179006* LOC19; Ropeobj179006* LOC20; TY533811 LOC21; NimStringDesc* LOC22; Ropeobj179006* LOC23; Ropeobj179006* LOC24; Ropeobj179006* LOC25; if (!!((owner0 == (*m0).module))) goto LA15; LOC17 = (Tcgen530027*)0; LOC17 = bmod_530201_3723162438(owner0); LOC18 = (Ropeobj179006*)0; LOC18 = gentypeinfo_536941_839829468(LOC17, t0); LOC19 = (Ropeobj179006*)0; LOC19 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_129)); LOC20 = (Ropeobj179006*)0; LOC20 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_130)); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = result0; LOC22 = (NimStringDesc*)0; LOC22 = typetostring_321017_3876443242(t0, ((Tprefereddesc321011) 0)); LOC21[1] = rope_179277_2381377266(LOC22); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_131), LOC21, 2); LOC23 = (Ropeobj179006*)0; LOC23 = rope_179277_2381377266(((NimStringDesc*) &T839829468_128)); LOC24 = (Ropeobj179006*)0; LOC24 = HEX26_179418_2381377266(LOC23, result0); LOC25 = (Ropeobj179006*)0; LOC25 = rope_179277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_179418_2381377266(LOC24, LOC25); goto BeforeRet; } LA15: ; switch ((*t0).kind) { case ((Ttypekind293244) 3): case ((Ttypekind293244) 62): { result0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_132)); } break; case ((Ttypekind293244) 26): case ((Ttypekind293244) 1): case ((Ttypekind293244) 2): case ((Ttypekind293244) 29): case ((Ttypekind293244) 28): case ((Ttypekind293244) 31) ... ((Ttypekind293244) 44): case ((Ttypekind293244) 23): { Ropeobj179006* LOC28; LOC28 = (Ropeobj179006*)0; LOC28 = rope_179277_2381377266(((NimStringDesc*) &T839829468_132)); gentypeinfoauxbase_536960_839829468(m0, t0, t0, result0, LOC28); } break; case ((Ttypekind293244) 59): { { Ttype293840* LOC34; if (!!(((*t0).n == NIM_NIL))) goto LA32; LOC34 = (Ttype293840*)0; LOC34 = lastson_296377_850551059(t0); result0 = gentypeinfo_536941_839829468(m0, LOC34); } goto LA30; LA32: ; { NimStringDesc* LOC36; LOC36 = (NimStringDesc*)0; LOC36 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI293244))->Sup.len + 13); appendString(LOC36, ((NimStringDesc*) &T839829468_137)); appendString(LOC36, reprEnum((NI)(*t0).kind, (&NTI293244))); appendChar(LOC36, 41); internalerror_197113_155036129(LOC36); } LA30: ; } break; case ((Ttypekind293244) 25): { { Ropeobj179006* LOC42; if (!!(((*t0).callconv == ((Tcallingconvention293002) 8)))) goto LA40; LOC42 = (Ropeobj179006*)0; LOC42 = rope_179277_2381377266(((NimStringDesc*) &T839829468_132)); gentypeinfoauxbase_536960_839829468(m0, t0, t0, result0, LOC42); } goto LA38; LA40: ; { Ttype293840* LOC44; LOC44 = (Ttype293840*)0; LOC44 = fakeclosuretype_538010_839829468((*t0).owner); gentupleinfo_537551_839829468(m0, LOC44, result0); } LA38: ; } break; case ((Ttypekind293244) 24): case ((Ttypekind293244) 22): { gentypeinfoaux_537027_839829468(m0, t0, t0, result0); { Ropeobj179006* markerproc0; TY533811 LOC50; if (!(((Tgcmode170080) 4) <= gselectedgc_170133_2607990831)) goto LA48; markerproc0 = gentraverseproc_538632_839829468(m0, t0, ((Ttypeinforeason538016) 0)); memset((void*)LOC50, 0, sizeof(LOC50)); LOC50[0] = result0; LOC50[1] = markerproc0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_192), LOC50, 2); } LA48: ; } break; case ((Ttypekind293244) 21): case ((Ttypekind293244) 20): { gentypeinfoaux_537027_839829468(m0, t0, t0, result0); } break; case ((Ttypekind293244) 4): case ((Ttypekind293244) 16): { genarrayinfo_538005_839829468(m0, t0, result0); } break; case ((Ttypekind293244) 19): { gensetinfo_537867_839829468(m0, t0, result0); } break; case ((Ttypekind293244) 14): { genenuminfo_537599_839829468(m0, t0, result0); } break; case ((Ttypekind293244) 17): { genobjectinfo_537508_839829468(m0, t0, origtype0, result0); } break; case ((Ttypekind293244) 18): { gentupleinfo_537551_839829468(m0, t0, result0); } break; default: { NimStringDesc* LOC58; LOC58 = (NimStringDesc*)0; LOC58 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI293244))->Sup.len + 13); appendString(LOC58, ((NimStringDesc*) &T839829468_137)); appendString(LOC58, reprEnum((NI)(*t0).kind, (&NTI293244))); appendChar(LOC58, 41); internalerror_197113_155036129(LOC58); } break; } { if (!!(((*t0).deepcopy == NIM_NIL))) goto LA61; gendeepcopyproc_539066_839829468(m0, (*t0).deepcopy, result0); } goto LA59; LA61: ; { if (!!(((*origtype0).deepcopy == NIM_NIL))) goto LA64; gendeepcopyproc_539066_839829468(m0, (*origtype0).deepcopy, result0); } goto LA59; LA64: ; LA59: ; LOC66 = (Ropeobj179006*)0; LOC66 = rope_179277_2381377266(((NimStringDesc*) &T839829468_128)); LOC67 = (Ropeobj179006*)0; LOC67 = HEX26_179418_2381377266(LOC66, result0); LOC68 = (Ropeobj179006*)0; LOC68 = rope_179277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_179418_2381377266(LOC67, LOC68); }BeforeRet: ; return result0; } N_NIMCALL(void, localdebuginfo_539449_839829468)(Tcproc530021* p0, Tsym293834* s0) { Ropeobj179006* a0; TY536235 LOC16; NimStringDesc* LOC17; { { if (!!(((163840 & (*p0).options) == 163840))) goto LA3; goto BeforeRet; } LA3: ; { Ttype293840* LOC7; LOC7 = (Ttype293840*)0; LOC7 = skiptypes_297099_850551059((*s0).typ, IL64(211106240964864)); if (!((IL64(281475110928384) &((NU64)1<<((NU)((*LOC7).kind)&63U)))!=0)) goto LA8; goto BeforeRet; } LA8: ; a0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_52), (*s0).loc.r); { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*s0).kind == ((Tsymkind293435) 3)); if (!(LOC12)) goto LA13; LOC12 = ccgintroducedptr_534611_839829468(s0); LA13: ; if (!LOC12) goto LA14; a0 = (*s0).loc.r; } LA14: ; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rope_179401_2381377266(((NI64) ((*p0).maxframelen))); LOC17 = (NimStringDesc*)0; LOC17 = nsuNormalize((*(*s0).name).s); LOC16[1] = makecstring_192638_155036129(LOC17); LOC16[2] = a0; LOC16[3] = gentypeinfo_536941_839829468((*p0).module, (*s0).loc.t); linef_533700_839829468(p0, ((Tcprocsection530011) 1), ((NimStringDesc*) &T839829468_126), LOC16, 4); (*p0).maxframelen += ((NI) 1); (*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].framelen += ((NI) 1); }BeforeRet: ; } N_NIMCALL(void, assignlocalvar_539614_839829468)(Tcproc530021* p0, Tsym293834* s0) { Ropeobj179006* decl0; Ropeobj179006* LOC1; Ropeobj179006* LOC2; LOC1 = (Ropeobj179006*)0; LOC1 = localvardecl_539532_839829468(p0, s0); LOC2 = (Ropeobj179006*)0; LOC2 = HEX26_179447_2381377266(LOC1, ((NimStringDesc*) &T839829468_125)); decl0 = HEX26_179447_2381377266(LOC2, tnl_177644_4151366050); line_533690_839829468(p0, ((Tcprocsection530011) 0), decl0); localdebuginfo_539449_839829468(p0, s0); } N_NIMCALL(void, initlocalvar_539398_839829468)(Tcproc530021* p0, Tsym293834* v0, NIM_BOOL immediateasgn0) { { if (!!((((*v0).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0))) goto LA3; { if (!!(immediateasgn0)) goto LA7; constructloc_539388_839829468(p0, (&(*v0).loc), NIM_FALSE); } LA7: ; } LA3: ; } N_NIMCALL(void, fillresult_534865_839829468)(Tsym293834* param0) { TY534289 LOC1; Ropeobj179006* LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (Ropeobj179006*)0; LOC2 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_210), LOC1, 0); fillloc_533282_839829468((&(*param0).loc), ((Tlockind293808) 4), (*param0).typ, LOC2, ((Tstorageloc293812) 2)); { NIM_BOOL LOC5; Tctypekind530007 LOC6; LOC5 = (NIM_BOOL)0; LOC6 = (Tctypekind530007)0; LOC6 = mapreturntype_534447_839829468((*param0).typ); LOC5 = !((LOC6 == ((Tctypekind530007) 17))); if (!(LOC5)) goto LA7; LOC5 = isinvalidreturntype_534550_839829468((*param0).typ); LA7: ; if (!LOC5) goto LA8; (*param0).loc.flags |= ((NU16)1)<<((((Tlocflag293810) 0))%(sizeof(NU16)*8)); (*param0).loc.s = ((Tstorageloc293812) 0); } LA8: ; } N_NIMCALL(void, assignparam_539994_839829468)(Tcproc530021* p0, Tsym293834* s0) { localdebuginfo_539449_839829468(p0, s0); } N_NIMCALL(void, closuresetup_561158_839829468)(Tcproc530021* p0, Tsym293834* prc0) { Tnode293802* ls0; Tnode293802* LOC5; Tsym293834* env0; TY533811 LOC10; { { if (!!((((*(*prc0).typ).flags &(1U<<((NU)(((Ttypeflag293431) 11))&31U)))!=0))) goto LA3; goto BeforeRet; } LA3: ; LOC5 = (Tnode293802*)0; LOC5 = HEX5BHEX5D_294238_850551059((*prc0).ast, ((NI) 3)); ls0 = lastson_296364_850551059(LOC5); { if (!!(((*ls0).kind == ((Tnodekind293020) 3)))) goto LA8; internalerror_197100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_211)); } LA8: ; env0 = (*ls0).kindU.S4.sym; assignlocalvar_539614_839829468(p0, env0); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_539188_839829468((&(*env0).loc)); LOC10[1] = gettypedesc_536673_839829468((*p0).module, (*env0).typ); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_212), LOC10, 2); }BeforeRet: ; } N_NIMCALL(Ropeobj179006*, initgcframe_539435_839829468)(Tcproc530021* p0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { TY179507 LOC5; if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = (*p0).gcframetype; result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_217), LOC5, 1); } LA3: ; return result0; } N_NIMCALL(Ropeobj179006*, initframe_561140_839829468)(Tcproc530021* p0, Ropeobj179006* procname0, Ropeobj179006* filename0) { Ropeobj179006* result0; Ropeobj179006* LOC1; result0 = (Ropeobj179006*)0; LOC1 = (Ropeobj179006*)0; LOC1 = cgsym_533403_839829468((*p0).module, ((NimStringDesc*) &T839829468_218)); { Ropeobj179006* LOC6; TY536235 LOC7; if (!(((NI) 0) < (*p0).maxframelen)) goto LA4; LOC6 = (Ropeobj179006*)0; LOC6 = cgsym_533403_839829468((*p0).module, ((NimStringDesc*) &T839829468_219)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = procname0; LOC7[1] = filename0; LOC7[2] = rope_179401_2381377266(((NI64) ((*p0).maxframelen))); LOC7[3] = rope_179401_2381377266(((NI64) ((*p0).blocks->data[((NI) 0)].framelen))); result0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_220), LOC7, 4); } goto LA2; LA4: ; { TY533811 LOC9; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = procname0; LOC9[1] = filename0; result0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_221), LOC9, 2); } LA2: ; return result0; } N_NIMCALL(void, appcg_533648_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0) { Ropeobj179006** LOC1; Ropeobj179006* LOC2; LOC1 = (Ropeobj179006**)0; LOC1 = s_530179_3723162438(p0, s0); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, frmt0, args0, args0Len0); add_179482_2381377266(LOC1, LOC2); } N_NIMCALL(Ropeobj179006*, deinitgcframe_539441_839829468)(Tcproc530021* p0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { TY534289 LOC5; if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); result0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_225), LOC5, 0); } LA3: ; return result0; } N_NIMCALL(Ropeobj179006*, deinitframe_561150_839829468)(Tcproc530021* p0) { Ropeobj179006* result0; TY534289 LOC1; result0 = (Ropeobj179006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); result0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_226), LOC1, 0); return result0; } N_NIMCALL(void, genprocaux_561284_839829468)(Tcgen530027* m0, Tsym293834* prc0) { Tcproc530021* p0; Ropeobj179006* header0; Ropeobj179006* returnstmt0; Tnode293802* LOC51; Ropeobj179006* generatedproc0; p0 = newproc_530206_3723162438(prc0, m0); header0 = genprocheader_536867_839829468(m0, prc0); returnstmt0 = NIM_NIL; { NIM_BOOL LOC3; Tsym293834* res0; LOC3 = (NIM_BOOL)0; LOC3 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 9))&31U)))!=0)); if (!(LOC3)) goto LA4; LOC3 = !(((*(*prc0).typ).sons->data[((NI) 0)] == NIM_NIL)); LA4: ; if (!LOC3) goto LA5; { NI LOC9; LOC9 = (NI)0; LOC9 = len_294081_850551059((*prc0).ast); if (!(LOC9 <= ((NI) 7))) goto LA10; internalerror_197100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_120)); } LA10: ; res0 = (*(*(*prc0).ast).kindU.S6.sons->data[((NI) 7)]).kindU.S4.sym; { NIM_BOOL LOC14; TY179507 LOC34; LOC14 = (NIM_BOOL)0; LOC14 = isinvalidreturntype_534550_839829468((*(*prc0).typ).sons->data[((NI) 0)]); if (!!(LOC14)) goto LA15; { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0)) goto LA19; (*res0).flags |= ((NU32)1)<<((((Tsymflag293184) 12))%(sizeof(NU32)*8)); } LA19: ; { NIM_BOOL LOC23; NIM_BOOL LOC24; NIM_BOOL LOC26; Tnode293802* val0; Tnode293802* LOC29; Ropeobj179006* decl0; Tloc293816 a0; TY533811 LOC32; LOC23 = (NIM_BOOL)0; LOC24 = (NIM_BOOL)0; LOC24 = (((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0); if (!(LOC24)) goto LA25; LOC26 = (NIM_BOOL)0; LOC26 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC26) goto LA27; LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA27: ; LOC24 = LOC26; LA25: ; LOC23 = LOC24; if (!(LOC23)) goto LA28; LOC29 = (Tnode293802*)0; LOC29 = getbody_336226_1724185294(prc0); val0 = easyresultasgn_561191_839829468(LOC29); LOC23 = !((val0 == NIM_NIL)); LA28: ; if (!LOC23) goto LA30; decl0 = localvardecl_539532_839829468(p0, res0); memset((void*)(&a0), 0, sizeof(a0)); initlocexprsingleuse_540289_839829468(p0, val0, (&a0)); memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = decl0; LOC32[1] = rdloc_539188_839829468((&a0)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC32, 2); } goto LA21; LA30: ; { assignlocalvar_539614_839829468(p0, res0); initlocalvar_539398_839829468(p0, res0, NIM_FALSE); } LA21: ; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = rdloc_539188_839829468((&(*res0).loc)); returnstmt0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_209), LOC34, 1); } goto LA12; LA15: ; { fillresult_534865_839829468(res0); assignparam_539994_839829468(p0, res0); { Ttype293840* LOC38; LOC38 = (Ttype293840*)0; LOC38 = skiptypes_297099_850551059((*res0).typ, IL64(211106232576256)); if (!((*LOC38).kind == ((Ttypekind293244) 16))) goto LA39; (*res0).loc.s = ((Tstorageloc293812) 0); } LA39: ; } LA12: ; } LA5: ; { NI i_561627_839829468; NI HEX3Atmp_561743_839829468; NI LOC42; NI res_561746_839829468; i_561627_839829468 = (NI)0; HEX3Atmp_561743_839829468 = (NI)0; LOC42 = (NI)0; LOC42 = sonslen_296351_850551059((*(*prc0).typ).n); HEX3Atmp_561743_839829468 = (NI)(LOC42 - ((NI) 1)); res_561746_839829468 = ((NI) 1); { while (1) { if (!(res_561746_839829468 <= HEX3Atmp_561743_839829468)) goto LA44; i_561627_839829468 = res_561746_839829468; { Tsym293834* param0; param0 = (*(*(*(*prc0).typ).n).kindU.S6.sons->data[i_561627_839829468]).kindU.S4.sym; { NIM_BOOL LOC48; LOC48 = (NIM_BOOL)0; LOC48 = iscompiletimeonly_329706_3876443242((*param0).typ); if (!LOC48) goto LA49; goto LA45; } LA49: ; assignparam_539994_839829468(p0, param0); } LA45: ; res_561746_839829468 += ((NI) 1); } LA44: ; } } closuresetup_561158_839829468(p0, prc0); LOC51 = (Tnode293802*)0; LOC51 = getbody_336226_1724185294(prc0); genstmts_540244_839829468(p0, LOC51); generatedproc0 = (Ropeobj179006*)0; { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 14))&31U)))!=0)) goto LA54; { if (!((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 6))&7U)))!=0)) goto LA58; header0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_213), header0); } LA58: ; } LA54: ; { TY536235 LOC68; Ropeobj179006** LOC69; Ropeobj179006** LOC70; Ropeobj179006** LOC71; if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 9))&31U)))!=0)) goto LA62; { if (!((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 6))&7U)))!=0)) goto LA66; header0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_214), header0); } LA66: ; memset((void*)LOC68, 0, sizeof(LOC68)); LOC68[0] = header0; LOC69 = (Ropeobj179006**)0; LOC69 = s_530179_3723162438(p0, ((Tcprocsection530011) 0)); LOC68[1] = (*LOC69); LOC70 = (Ropeobj179006**)0; LOC70 = s_530179_3723162438(p0, ((Tcprocsection530011) 1)); LOC68[2] = (*LOC70); LOC71 = (Ropeobj179006**)0; LOC71 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); LOC68[3] = (*LOC71); generatedproc0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_215), LOC68, 4); } goto LA60; LA62: ; { TY179507 LOC73; Ropeobj179006* LOC74; Ropeobj179006** LOC93; Ropeobj179006** LOC94; Ropeobj179006* LOC101; TY534289 LOC107; Ropeobj179006* LOC108; memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = header0; generatedproc0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_216), LOC73, 1); LOC74 = (Ropeobj179006*)0; LOC74 = initgcframe_539435_839829468(p0); add_179482_2381377266(&generatedproc0, LOC74); { Ropeobj179006** LOC79; Ropeobj179006* procname0; Ropeobj179006* LOC80; Ropeobj179006* LOC81; if (!(((*prc0).options &(1U<<((NU)(((Toption170009) 15))&31U)))!=0)) goto LA77; LOC79 = (Ropeobj179006**)0; LOC79 = s_530179_3723162438(p0, ((Tcprocsection530011) 0)); add_179482_2381377266(&generatedproc0, (*LOC79)); procname0 = makecstring_192638_155036129((*(*prc0).name).s); LOC80 = (Ropeobj179006*)0; LOC80 = quotedfilename_197818_155036129((*prc0).info); LOC81 = (Ropeobj179006*)0; LOC81 = initframe_561140_839829468(p0, procname0, LOC80); add_179482_2381377266(&generatedproc0, LOC81); } goto LA75; LA77: ; { Ropeobj179006** LOC83; LOC83 = (Ropeobj179006**)0; LOC83 = s_530179_3723162438(p0, ((Tcprocsection530011) 0)); add_179482_2381377266(&generatedproc0, (*LOC83)); } LA75: ; { TY534289 LOC88; if (!(((*prc0).options &(1U<<((NU)(((Toption170009) 19))&31U)))!=0)) goto LA86; memset((void*)LOC88, 0, sizeof(LOC88)); appcg_533648_839829468(p0, ((Tcprocsection530011) 1), ((NimStringDesc*) &T839829468_222), LOC88, 0); } LA86: ; { if (!(*p0).beforeretneeded) goto LA91; add_179487_2381377266(&generatedproc0, ((NimStringDesc*) &T839829468_223)); } LA91: ; LOC93 = (Ropeobj179006**)0; LOC93 = s_530179_3723162438(p0, ((Tcprocsection530011) 1)); add_179482_2381377266(&generatedproc0, (*LOC93)); LOC94 = (Ropeobj179006**)0; LOC94 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179482_2381377266(&generatedproc0, (*LOC94)); { TY534289 LOC99; Ropeobj179006* LOC100; if (!(*p0).beforeretneeded) goto LA97; memset((void*)LOC99, 0, sizeof(LOC99)); LOC100 = (Ropeobj179006*)0; LOC100 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_224), LOC99, 0); add_179482_2381377266(&generatedproc0, LOC100); } LA97: ; LOC101 = (Ropeobj179006*)0; LOC101 = deinitgcframe_539441_839829468(p0); add_179482_2381377266(&generatedproc0, LOC101); { Ropeobj179006* LOC106; if (!(((*prc0).options &(1U<<((NU)(((Toption170009) 15))&31U)))!=0)) goto LA104; LOC106 = (Ropeobj179006*)0; LOC106 = deinitframe_561150_839829468(p0); add_179482_2381377266(&generatedproc0, LOC106); } LA104: ; add_179482_2381377266(&generatedproc0, returnstmt0); memset((void*)LOC107, 0, sizeof(LOC107)); LOC108 = (Ropeobj179006*)0; LOC108 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_227), LOC107, 0); add_179482_2381377266(&generatedproc0, LOC108); } LA60: ; add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 10))- 0], generatedproc0); } N_NIMCALL(Tcgen530027*, findpendingmodule_533241_839829468)(Tcgen530027* m0, Tsym293834* s0) { Tcgen530027* result0; Tsym293834* ms0; result0 = (Tcgen530027*)0; ms0 = getmodule_300123_2984716966(s0); result0 = gmodules_530170_3723162438->data[(*ms0).position]; return result0; } N_NIMCALL(NIM_BOOL, isgetprocaddr_560443_839829468)(Tlib293820* lib0) { NIM_BOOL result0; Tnode293802* n0; NIM_BOOL LOC1; NIM_BOOL LOC2; result0 = (NIM_BOOL)0; n0 = (*lib0).path; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = ((*n0).kind == ((Tnodekind293020) 27) || (*n0).kind == ((Tnodekind293020) 29) || (*n0).kind == ((Tnodekind293020) 30) || (*n0).kind == ((Tnodekind293020) 31) || (*n0).kind == ((Tnodekind293020) 26) || (*n0).kind == ((Tnodekind293020) 28) || (*n0).kind == ((Tnodekind293020) 32)); if (!(LOC2)) goto LA3; LOC2 = !(((*n0).typ == NIM_NIL)); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA4; LOC1 = ((100663296 &((NU64)1<<((NU)((*(*n0).typ).kind)&63U)))!=0); LA4: ; result0 = LOC1; return result0; } N_NIMCALL(void, initlocexpr_540283_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* result0) { initloc_533273_839829468(result0, ((Tlockind293808) 0), (*e0).typ, ((Tstorageloc293812) 0)); expr_540248_839829468(p0, e0, result0); } N_NIMCALL(void, loaddynamiclib_560481_839829468)(Tcgen530027* m0, Tlib293820* lib0) { { Ropeobj179006* tmp0; TY179507 LOC5; if (!!((*lib0).generated)) goto LA3; (*lib0).generated = NIM_TRUE; tmp0 = gettempname_534598_839829468(m0); asgnRefNoCycle((void**) (&(*lib0).name), tmp0); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = tmp0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_228), LOC5, 1); { TY135002* s0; Ropeobj179006* loadlib0; TY533811 LOC18; if (!((*(*lib0).path).kind >= ((Tnodekind293020) 20) && (*(*lib0).path).kind <= ((Tnodekind293020) 22))) goto LA8; s0 = (TY135002*) newSeq((&NTI135002), 0); libcandidates_171605_2607990831((*(*lib0).path).kindU.S3.strval, (&s0)); rawmessage_195612_155036129(((Tmsgkind192002) 286), (*(*lib0).path).kindU.S3.strval); loadlib0 = NIM_NIL; { NI i_560847_839829468; NI HEX3Atmp_560902_839829468; NI res_560905_839829468; i_560847_839829468 = (NI)0; HEX3Atmp_560902_839829468 = (NI)0; HEX3Atmp_560902_839829468 = (s0 ? (s0->Sup.len-1) : -1); res_560905_839829468 = ((NI) 0); { while (1) { TY533811 LOC17; if (!(res_560905_839829468 <= HEX3Atmp_560902_839829468)) goto LA12; i_560847_839829468 = res_560905_839829468; (*m0).labels += ((NI) 1); { if (!(((NI) 0) < i_560847_839829468)) goto LA15; add_179487_2381377266(&loadlib0, ((NimStringDesc*) &T839829468_229)); } LA15: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = tmp0; LOC17[1] = getstrlit_550468_839829468(m0, s0->data[i_560847_839829468]); appcg_533632_839829468(m0, &loadlib0, ((NimStringDesc*) &T839829468_230), LOC17, 2); res_560905_839829468 += ((NI) 1); } LA12: ; } } memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = loadlib0; LOC18[1] = getstrlit_550468_839829468(m0, (*(*lib0).path).kindU.S3.strval); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 16))- 0], ((NimStringDesc*) &T839829468_231), LOC18, 2); } goto LA6; LA8: ; { Tcproc530021* p0; Tloc293816 dest0; Ropeobj179006** LOC20; Ropeobj179006** LOC21; Ropeobj179006** LOC22; TY533811 LOC23; p0 = newproc_530206_3723162438(NIM_NIL, m0); (*p0).options = ((*p0).options & ~ 163840); memset((void*)(&dest0), 0, sizeof(dest0)); initlocexpr_540283_839829468(p0, (*lib0).path, (&dest0)); LOC20 = (Ropeobj179006**)0; LOC20 = s_530179_3723162438(p0, ((Tcprocsection530011) 0)); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], (*LOC20)); LOC21 = (Ropeobj179006**)0; LOC21 = s_530179_3723162438(p0, ((Tcprocsection530011) 1)); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 16))- 0], (*LOC21)); LOC22 = (Ropeobj179006**)0; LOC22 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 16))- 0], (*LOC22)); memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = tmp0; LOC23[1] = rdloc_539188_839829468((&dest0)); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 16))- 0], ((NimStringDesc*) &T839829468_232), LOC23, 2); } LA6: ; } LA3: ; { if (!((*lib0).name == NIM_NIL)) goto LA26; internalerror_197113_155036129(((NimStringDesc*) &T839829468_233)); } LA26: ; } N_NIMCALL(Ropeobj179006*, mangledynlibproc_539816_839829468)(Tsym293834* sym0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 16))&31U)))!=0)) goto LA3; result0 = rope_179277_2381377266((*(*sym0).name).s); } goto LA1; LA3: ; { TY179507 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_179401_2381377266(((NI64) ((*sym0).Sup.id))); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_234), LOC6, 1); } LA1: ; return result0; } N_NIMCALL(void, symindynamiclib_560929_839829468)(Tcgen530027* m0, Tsym293834* sym0) { Tlib293820* lib0; NIM_BOOL iscall0; Ropeobj179006* extname0; Ropeobj179006* tmp0; TY533811 LOC43; lib0 = (*sym0).annex; iscall0 = isgetprocaddr_560443_839829468(lib0); extname0 = (*sym0).loc.r; { if (!!(iscall0)) goto LA3; loaddynamiclib_560481_839829468(m0, lib0); } LA3: ; tmp0 = mangledynlibproc_539816_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0); asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL); (*m0).labels += ((NI) 2); { Tnode293802* n0; Tloc293816 a0; Tnode293802* LOC9; Ropeobj179006* params0; Ropeobj179006* LOC10; Ropeobj179006* load0; TY536235 LOC17; NimStringDesc* LOC18; Tnode293802* last0; NimStringDesc* idx0; if (!iscall0) goto LA7; n0 = (*lib0).path; memset((void*)(&a0), 0, sizeof(a0)); LOC9 = (Tnode293802*)0; LOC9 = HEX5BHEX5D_294238_850551059(n0, ((NI) 0)); initlocexpr_540283_839829468((*m0).initproc, LOC9, (&a0)); LOC10 = (Ropeobj179006*)0; LOC10 = rdloc_539188_839829468((&a0)); params0 = HEX26_179447_2381377266(LOC10, ((NimStringDesc*) &T839829468_118)); { NI i_560964_839829468; NI HEX3Atmp_561025_839829468; NI LOC12; NI res_561028_839829468; i_560964_839829468 = (NI)0; HEX3Atmp_561025_839829468 = (NI)0; LOC12 = (NI)0; LOC12 = len_294081_850551059(n0); HEX3Atmp_561025_839829468 = (NI)(LOC12 - ((NI) 2)); res_561028_839829468 = ((NI) 1); { while (1) { Tnode293802* LOC15; Ropeobj179006* LOC16; if (!(res_561028_839829468 <= HEX3Atmp_561025_839829468)) goto LA14; i_560964_839829468 = res_561028_839829468; LOC15 = (Tnode293802*)0; LOC15 = HEX5BHEX5D_294238_850551059(n0, i_560964_839829468); initlocexpr_540283_839829468((*m0).initproc, LOC15, (&a0)); LOC16 = (Ropeobj179006*)0; LOC16 = rdloc_539188_839829468((&a0)); add_179482_2381377266(&params0, LOC16); add_179487_2381377266(&params0, ((NimStringDesc*) &T839829468_110)); res_561028_839829468 += ((NI) 1); } LA14: ; } } memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = tmp0; LOC17[1] = gettypedesc_536673_839829468(m0, (*sym0).typ); LOC17[2] = params0; LOC18 = (NimStringDesc*)0; LOC18 = HEX24_179856_2381377266(extname0); LOC17[3] = makecstring_192638_155036129(LOC18); load0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_235), LOC17, 4); last0 = lastson_296364_850551059(n0); { if (!((*last0).kind == ((Tnodekind293020) 58))) goto LA21; last0 = (*last0).kindU.S6.sons->data[((NI) 1)]; } LA21: ; { NimStringDesc* LOC27; if (!!(((*last0).kind == ((Tnodekind293020) 20)))) goto LA25; LOC27 = (NimStringDesc*)0; LOC27 = HEX24_197185_1689653243(T839829468_236); internalerror_197113_155036129(LOC27); } LA25: ; idx0 = (*last0).kindU.S3.strval; { Ropeobj179006** LOC32; if (!((idx0 ? idx0->Sup.len : 0) == ((NI) 0))) goto LA30; LOC32 = (Ropeobj179006**)0; LOC32 = s_530179_3723162438((*m0).initproc, ((Tcprocsection530011) 2)); add_179482_2381377266(LOC32, load0); } goto LA28; LA30: ; { NIM_BOOL LOC34; LOC34 = (NIM_BOOL)0; LOC34 = ((idx0 ? idx0->Sup.len : 0) == ((NI) 1)); if (!(LOC34)) goto LA35; LOC34 = (((NU8)(idx0->data[((NI) 0)])) >= ((NU8)(48)) && ((NU8)(idx0->data[((NI) 0)])) <= ((NU8)(57))); LA35: ; if (!LOC34) goto LA36; add_179482_2381377266(&(*m0).extensionloaders[(((NU8)(idx0->data[((NI) 0)])))- 48], load0); } goto LA28; LA36: ; { NimStringDesc* LOC39; LOC39 = (NimStringDesc*)0; LOC39 = rawNewString(idx0->Sup.len + 13); appendString(LOC39, ((NimStringDesc*) &T839829468_237)); appendString(LOC39, idx0); internalerror_197100_155036129((*sym0).info, LOC39); } LA28: ; } goto LA5; LA7: ; { TY536235 LOC41; NimStringDesc* LOC42; memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = tmp0; LOC41[1] = gettypedesc_536673_839829468(m0, (*sym0).typ); LOC41[2] = (*lib0).name; LOC42 = (NimStringDesc*)0; LOC42 = HEX24_179856_2381377266(extname0); LOC41[3] = makecstring_192638_155036129(LOC42); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 16))- 0], ((NimStringDesc*) &T839829468_238), LOC41, 4); } LA5: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = (*sym0).loc.r; LOC43[1] = gettypedesc_536673_839829468(m0, (*sym0).loc.t); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_239), LOC43, 2); } N_NIMCALL(void, symindynamiclibpartial_561071_839829468)(Tcgen530027* m0, Tsym293834* sym0) { asgnRefNoCycle((void**) (&(*sym0).loc.r), mangledynlibproc_539816_839829468(sym0)); asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL); } N_NIMCALL(void, genprocnoforward_561906_839829468)(Tcgen530027* m0, Tsym293834* prc0) { { fillprocloc_540201_839829468(prc0); useheader_533369_839829468(m0, prc0); { Ropeobj179006* LOC5; if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag293810) 7))&15U)))!=0)) goto LA3; LOC5 = (Ropeobj179006*)0; LOC5 = cgsym_533403_839829468(m0, (*(*prc0).name).s); goto BeforeRet; } LA3: ; genprocprototype_540254_839829468(m0, prc0); { if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0)) goto LA8; } goto LA6; LA8: ; { if (!((*(*prc0).typ).callconv == ((Tcallingconvention293002) 5))) goto LA11; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = containsorincl_269862_2627731572((&(*m0).declaredthings), (*prc0).Sup.id); if (!!(LOC15)) goto LA16; genprocaux_561284_839829468(m0, prc0); } LA16: ; } goto LA6; LA11: ; { Tcgen530027* q0; if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag293810) 4))&15U)))!=0)) goto LA19; q0 = findpendingmodule_533241_839829468(m0, prc0); { NIM_BOOL LOC23; NIM_BOOL LOC25; LOC23 = (NIM_BOOL)0; LOC23 = !((q0 == NIM_NIL)); if (!(LOC23)) goto LA24; LOC25 = (NIM_BOOL)0; LOC25 = containsorincl_269862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id); LOC23 = !(LOC25); LA24: ; if (!LOC23) goto LA26; symindynamiclib_560929_839829468(q0, prc0); } goto LA21; LA26: ; { symindynamiclibpartial_561071_839829468(m0, prc0); } LA21: ; } goto LA6; LA19: ; { Tcgen530027* q0; if (!!((((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 5))&31U)))!=0))) goto LA30; q0 = findpendingmodule_533241_839829468(m0, prc0); { NIM_BOOL LOC34; NIM_BOOL LOC36; LOC34 = (NIM_BOOL)0; LOC34 = !((q0 == NIM_NIL)); if (!(LOC34)) goto LA35; LOC36 = (NIM_BOOL)0; LOC36 = containsorincl_269862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id); LOC34 = !(LOC36); LA35: ; if (!LOC34) goto LA37; genprocaux_561284_839829468(q0, prc0); } LA37: ; } goto LA6; LA30: ; LA6: ; }BeforeRet: ; } N_NIMCALL(void, genproc_533951_839829468)(Tcgen530027* m0, Tsym293834* prc0) { { { NIM_BOOL LOC3; NIM_BOOL LOC5; LOC3 = (NIM_BOOL)0; LOC3 = (((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 26))&31U)))!=0); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = isactivated_562431_839829468(prc0); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; goto BeforeRet; } LA6: ; fillprocloc_540201_839829468(prc0); { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 4))&31U)))!=0)) goto LA10; addforwardedproc_533203_839829468(m0, prc0); } goto LA8; LA10: ; { genprocnoforward_561906_839829468(m0, prc0); { NIM_BOOL LOC15; NIM_BOOL LOC16; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC16 = ((65600 & (*prc0).flags) == 64); if (!(LOC16)) goto LA17; LOC16 = !((generatedheader_533201_839829468 == NIM_NIL)); LA17: ; LOC15 = LOC16; if (!(LOC15)) goto LA18; LOC15 = !((((*prc0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0)); LA18: ; if (!LOC15) goto LA19; genprocprototype_540254_839829468(generatedheader_533201_839829468, prc0); { if (!((*(*prc0).typ).callconv == ((Tcallingconvention293002) 5))) goto LA23; { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = containsorincl_269862_2627731572((&(*generatedheader_533201_839829468).declaredthings), (*prc0).Sup.id); if (!!(LOC27)) goto LA28; genprocaux_561284_839829468(generatedheader_533201_839829468, prc0); } LA28: ; } LA23: ; } LA19: ; } LA8: ; }BeforeRet: ; } static N_INLINE(NIM_BOOL, emulatedthreadvars_533949_839829468)(void) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((71303168 & ~ gglobaloptions_170130_2607990831)==0); return result0; } N_NIMCALL(void, declarethreadvar_539676_839829468)(Tcgen530027* m0, Tsym293834* s0, NIM_BOOL isextern0) { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = emulatedthreadvars_533949_839829468(); if (!LOC3) goto LA4; { NIM_BOOL LOC8; TY533811 LOC11; LOC8 = (NIM_BOOL)0; LOC8 = containsorincl_269862_2627731572((&nimtvdeclared_539675_839829468), (*s0).Sup.id); if (!!(LOC8)) goto LA9; nimtvdeps_539674_839829468 = (Ttypeseq293836*) incrSeqV2(&(nimtvdeps_539674_839829468)->Sup, sizeof(Ttype293840*)); asgnRefNoCycle((void**) (&nimtvdeps_539674_839829468->data[nimtvdeps_539674_839829468->Sup.len]), (*s0).loc.t); ++nimtvdeps_539674_839829468->Sup.len; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_536673_839829468(m0, (*s0).loc.t); LOC11[1] = (*s0).loc.r; addf_180205_2381377266(&nimtv_539656_839829468, ((NimStringDesc*) &T839829468_54), LOC11, 2); } LA9: ; } goto LA1; LA4: ; { Ropeobj179006* LOC21; TY179507 LOC22; { if (!isextern0) goto LA15; add_179487_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_240)); } LA15: ; { if (!((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 22))&63U)))!=0)) goto LA19; add_179487_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_241)); } LA19: ; LOC21 = (Ropeobj179006*)0; LOC21 = gettypedesc_536673_839829468(m0, (*s0).loc.t); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], LOC21); memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = (*s0).loc.r; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC22, 1); } LA1: ; } N_NIMCALL(void, genvarprototypeaux_545254_839829468)(Tcgen530027* m0, Tsym293834* sym0) { Ropeobj179006* LOC1; { useheader_533369_839829468(m0, sym0); LOC1 = (Ropeobj179006*)0; LOC1 = manglename_534205_839829468(sym0); fillloc_533282_839829468((&(*sym0).loc), ((Tlockind293808) 3), (*sym0).typ, LOC1, ((Tstorageloc293812) 3)); { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (((*sym0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0); if (LOC4) goto LA5; LOC4 = containsorincl_269862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LA5: ; if (!LOC4) goto LA6; goto BeforeRet; } LA6: ; { if (!!(((*(*sym0).owner).Sup.id == (*(*m0).module).Sup.id))) goto LA10; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 22))&31U)))!=0)) goto LA14; declarethreadvar_539676_839829468(m0, sym0, NIM_TRUE); } goto LA12; LA14: ; { Ropeobj179006* LOC17; TY179507 LOC30; add_179487_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_240)); LOC17 = (Ropeobj179006*)0; LOC17 = gettypedesc_536673_839829468(m0, (*sym0).loc.t); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], LOC17); { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag293810) 4))&15U)))!=0)) goto LA20; add_179487_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_53)); } LA20: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 8))&31U)))!=0)) goto LA24; add_179487_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_121)); } LA24: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 7))&31U)))!=0)) goto LA28; add_179487_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_122)); } LA28: ; memset((void*)LOC30, 0, sizeof(LOC30)); LOC30[0] = (*sym0).loc.r; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC30, 1); } LA12: ; } LA10: ; }BeforeRet: ; } N_NIMCALL(void, genvarprototype_540236_839829468)(Tcgen530027* m0, Tsym293834* sym0) { genvarprototypeaux_545254_839829468(m0, sym0); } N_NIMCALL(Ropeobj179006*, cgsym_533403_839829468)(Tcgen530027* m0, NimStringDesc* name0) { Ropeobj179006* result0; Tsym293834* sym0; result0 = (Ropeobj179006*)0; sym0 = getcompilerproc_339748_3937434831(name0); { if (!!((sym0 == NIM_NIL))) goto LA3; switch ((*sym0).kind) { case ((Tsymkind293435) 12): case ((Tsymkind293435) 13): case ((Tsymkind293435) 15): case ((Tsymkind293435) 14): { genproc_533951_839829468(m0, sym0); } break; case ((Tsymkind293435) 8): case ((Tsymkind293435) 11): case ((Tsymkind293435) 9): { genvarprototype_540236_839829468(m0, sym0); } break; case ((Tsymkind293435) 7): { Ropeobj179006* LOC8; LOC8 = (Ropeobj179006*)0; LOC8 = gettypedesc_536673_839829468(m0, (*sym0).typ); } break; default: { NimStringDesc* LOC10; LOC10 = (NimStringDesc*)0; LOC10 = rawNewString(name0->Sup.len + reprEnum((NI)(*sym0).kind, (&NTI293435))->Sup.len + 9); appendString(LOC10, ((NimStringDesc*) &T839829468_243)); appendString(LOC10, name0); appendString(LOC10, ((NimStringDesc*) &T839829468_244)); appendString(LOC10, reprEnum((NI)(*sym0).kind, (&NTI293435))); internalerror_197113_155036129(LOC10); } break; } } goto LA1; LA3: ; { rawmessage_195612_155036129(((Tmsgkind192002) 68), name0); } LA1: ; result0 = (*sym0).loc.r; return result0; } N_NIMCALL(Ropeobj179006*, ropecg_533407_839829468)(Tcgen530027* m0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0) { Ropeobj179006* result0; NI i0; NI length0; NI num0; result0 = (Ropeobj179006*)0; i0 = ((NI) 0); length0 = (frmt0 ? frmt0->Sup.len : 0); result0 = NIM_NIL; num0 = ((NI) 0); { while (1) { NI start0; if (!(i0 < length0)) goto LA2; { if (!((NU8)(frmt0->data[i0]) == (NU8)(36))) goto LA5; i0 += ((NI) 1); switch (((NU8)(frmt0->data[i0]))) { case 36: { add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_19)); i0 += ((NI) 1); } break; case 35: { i0 += ((NI) 1); add_179482_2381377266(&result0, args0[num0]); num0 += ((NI) 1); } break; case 48 ... 57: { NI j0; j0 = ((NI) 0); { while (1) { j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48)); i0 += ((NI) 1); { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = (length0 <= i0); if (LOC14) goto LA15; LOC14 = !((((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57)))); LA15: ; if (!LOC14) goto LA16; goto LA10; } LA16: ; } } LA10: ; num0 = j0; { NimStringDesc* LOC22; NimStringDesc* LOC23; if (!((NI)((args0Len0-1) + ((NI) 1)) < j0)) goto LA20; LOC22 = (NimStringDesc*)0; LOC23 = (NimStringDesc*)0; LOC23 = nimIntToStr(j0); LOC22 = rawNewString(LOC23->Sup.len + 30); appendString(LOC22, ((NimStringDesc*) &T839829468_20)); appendString(LOC22, LOC23); internalerror_197113_155036129(LOC22); } LA20: ; add_179482_2381377266(&result0, args0[(NI)(j0 - ((NI) 1))]); } break; case 110: { { if (!!(((goptions_170128_2607990831 &(1U<<((NU)(((Toption170009) 10))&31U)))!=0))) goto LA27; add_179482_2381377266(&result0, rnl_179903_2381377266); } LA27: ; i0 += ((NI) 1); } break; case 78: { add_179482_2381377266(&result0, rnl_179903_2381377266); i0 += ((NI) 1); } break; default: { NimStringDesc* LOC31; LOC31 = (NimStringDesc*)0; LOC31 = rawNewString(31); appendString(LOC31, ((NimStringDesc*) &T839829468_20)); appendChar(LOC31, frmt0->data[i0]); internalerror_197113_155036129(LOC31); } break; } } goto LA3; LA5: ; { NIM_BOOL LOC33; NI j0; NimStringDesc* ident0; Ropeobj179006* LOC39; LOC33 = (NIM_BOOL)0; LOC33 = ((NU8)(frmt0->data[i0]) == (NU8)(35)); if (!(LOC33)) goto LA34; LOC33 = (((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(97)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(122)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(65)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(90)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(95))); LA34: ; if (!LOC33) goto LA35; i0 += ((NI) 1); j0 = i0; { while (1) { if (!(((NU8)(frmt0->data[j0])) >= ((NU8)(97)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(122)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(65)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(90)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(57)) || ((NU8)(frmt0->data[j0])) == ((NU8)(95)))) goto LA38; j0 += ((NI) 1); } LA38: ; } ident0 = copyStrLast(frmt0, i0, (NI)(j0 - ((NI) 1))); i0 = j0; LOC39 = (Ropeobj179006*)0; LOC39 = cgsym_533403_839829468(m0, ident0); add_179482_2381377266(&result0, LOC39); } goto LA3; LA35: ; { NIM_BOOL LOC41; NI j0; NimStringDesc* LOC47; Ropeobj179006* LOC48; LOC41 = (NIM_BOOL)0; LOC41 = ((NU8)(frmt0->data[i0]) == (NU8)(35)); if (!(LOC41)) goto LA42; LOC41 = ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(36)); LA42: ; if (!LOC41) goto LA43; i0 += ((NI) 2); j0 = ((NI) 0); { while (1) { if (!(((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57)))) goto LA46; j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48)); i0 += ((NI) 1); } LA46: ; } LOC47 = (NimStringDesc*)0; LOC47 = HEX24_179856_2381377266(args0[(NI)(j0 - ((NI) 1))]); LOC48 = (Ropeobj179006*)0; LOC48 = cgsym_533403_839829468(m0, LOC47); add_179482_2381377266(&result0, LOC48); } goto LA3; LA43: ; LA3: ; start0 = i0; { while (1) { if (!(i0 < length0)) goto LA50; { NIM_BOOL LOC53; LOC53 = (NIM_BOOL)0; LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(36))); if (!(LOC53)) goto LA54; LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(35))); LA54: ; if (!LOC53) goto LA55; i0 += ((NI) 1); } goto LA51; LA55: ; { goto LA49; } LA51: ; } LA50: ; } LA49: ; { NimStringDesc* LOC62; if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA60; LOC62 = (NimStringDesc*)0; LOC62 = copyStrLast(frmt0, start0, (NI)(i0 - ((NI) 1))); add_179487_2381377266(&result0, LOC62); } LA60: ; } LA2: ; } return result0; } static N_INLINE(NIM_BOOL, crossescppboundary_561754_839829468)(Tcgen530027* m0, Tsym293834* sym0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; Tsym293834* LOC4; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); if (!(LOC2)) goto LA3; LOC4 = (Tsym293834*)0; LOC4 = getmodule_300123_2984716966(sym0); LOC2 = !((((*LOC4).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0)); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA5; LOC1 = !((gcmd_170132_2607990831 == ((Tcommands170076) 2))); LA5: ; result0 = LOC1; return result0; } N_NIMCALL(void, genprocprototype_540254_839829468)(Tcgen530027* m0, Tsym293834* sym0) { { useheader_533369_839829468(m0, sym0); { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0)) goto LA3; goto BeforeRet; } LA3: ; { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag293810) 4))&15U)))!=0)) goto LA7; { NIM_BOOL LOC11; Tsym293834* LOC12; NIM_BOOL LOC14; TY533811 LOC17; Ropeobj179006* LOC18; LOC11 = (NIM_BOOL)0; LOC12 = (Tsym293834*)0; LOC12 = getmodule_300123_2984716966(sym0); LOC11 = !(((*LOC12).Sup.id == (*(*m0).module).Sup.id)); if (!(LOC11)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_269862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LOC11 = !(LOC14); LA13: ; if (!LOC11) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_536673_839829468(m0, (*sym0).loc.t); LOC17[1] = mangledynlibproc_539816_839829468(sym0); LOC18 = (Ropeobj179006*)0; LOC18 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_245), LOC17, 2); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], LOC18); } LA15: ; } goto LA5; LA7: ; { NIM_BOOL LOC20; Ropeobj179006* header0; TY179507 LOC47; Ropeobj179006* LOC48; LOC20 = (NIM_BOOL)0; LOC20 = containsorincl_269862_2627731572((&(*m0).declaredprotos), (*sym0).Sup.id); if (!!(LOC20)) goto LA21; header0 = genprocheader_536867_839829468(m0, sym0); { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = (((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 14))&31U)))!=0); if (!(LOC25)) goto LA26; LOC25 = ((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 6))&7U)))!=0); LA26: ; if (!LOC25) goto LA27; header0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_213), header0); } LA27: ; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = !(((*(*sym0).typ).callconv == ((Tcallingconvention293002) 5))); if (!(LOC31)) goto LA32; LOC31 = crossescppboundary_561754_839829468(m0, sym0); LA32: ; if (!LOC31) goto LA33; header0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_246), header0); } LA33: ; { NIM_BOOL LOC37; LOC37 = (NIM_BOOL)0; LOC37 = (((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 9))&31U)))!=0); if (!(LOC37)) goto LA38; LOC37 = ((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 7))&7U)))!=0); LA38: ; if (!LOC37) goto LA39; add_179487_2381377266(&header0, ((NimStringDesc*) &T839829468_247)); } LA39: ; { NIM_BOOL LOC43; LOC43 = (NIM_BOOL)0; LOC43 = (((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 14))&31U)))!=0); if (!(LOC43)) goto LA44; LOC43 = ((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 7))&7U)))!=0); LA44: ; if (!LOC43) goto LA45; add_179487_2381377266(&header0, ((NimStringDesc*) &T839829468_248)); } LA45: ; memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = header0; LOC48 = (Ropeobj179006*)0; LOC48 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_191), LOC47, 1); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 7))- 0], LOC48); } goto LA5; LA21: ; LA5: ; }BeforeRet: ; } static N_INLINE(NIM_BOOL, usesnativegc_170177_2607990831)(void) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = (((Tgcmode170080) 5) <= gselectedgc_170133_2607990831); return result0; } N_NIMCALL(void, genrefassign_539311_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; TY533811 LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((*dest0).s == ((Tstorageloc293812) 2)); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = usesnativegc_170177_2607990831(); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_539188_839829468(dest0); LOC8[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC8, 2); } goto LA1; LA6: ; { if (!((*dest0).s == ((Tstorageloc293812) 3))) goto LA10; { NIM_BOOL LOC14; TY533811 LOC17; LOC14 = (NIM_BOOL)0; LOC14 = canformacycle_321123_3876443242((*dest0).t); if (!LOC14) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_539204_839829468(dest0); LOC17[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_249), LOC17, 2); } goto LA12; LA15: ; { TY533811 LOC19; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_539204_839829468(dest0); LOC19[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_250), LOC19, 2); } LA12: ; } goto LA1; LA10: ; { TY533811 LOC21; memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = addrloc_539204_839829468(dest0); LOC21[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_251), LOC21, 2); } LA1: ; } N_NIMCALL(void, optasgnloc_550789_839829468)(Tloc293816* a0, Ttype293840* t0, Ropeobj179006* field0, Tloc293816* Result) { Ropeobj179006* LOC1; Ropeobj179006* LOC2; (*Result).k = ((Tlockind293808) 5); (*Result).s = (*a0).s; unsureAsgnRef((void**) (&(*Result).t), t0); LOC1 = (Ropeobj179006*)0; LOC1 = rdloc_539188_839829468(a0); LOC2 = (Ropeobj179006*)0; LOC2 = HEX26_179447_2381377266(LOC1, ((NimStringDesc*) &T839829468_257)); unsureAsgnRef((void**) (&(*Result).r), HEX26_179418_2381377266(LOC2, field0)); } N_NIMCALL(void, genoptasgntuple_551001_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0) { Tassignmentflag539302Set newflags0; Ttype293840* t_551053_839829468; Ttype293840* LOC9; { if (!((*src0).s == ((Tstorageloc293812) 1))) goto LA3; newflags0 = (flags0 | 1); } goto LA1; LA3: ; { if (!(((*(*dest0).t).flags &(1U<<((NU)(((Ttypeflag293431) 6))&31U)))!=0)) goto LA6; newflags0 = (flags0 & ~ 1); } goto LA1; LA6: ; { newflags0 = flags0; } LA1: ; LOC9 = (Ttype293840*)0; LOC9 = skiptypes_297099_850551059((*dest0).t, IL64(211106232576256)); t_551053_839829468 = getuniquetype_529640_2036603609(LOC9); { NI i_551071_839829468; NI HEX3Atmp_551077_839829468; NI LOC11; NI res_551080_839829468; i_551071_839829468 = (NI)0; HEX3Atmp_551077_839829468 = (NI)0; LOC11 = (NI)0; LOC11 = len_296339_850551059(t_551053_839829468); HEX3Atmp_551077_839829468 = (LOC11 - 1); res_551080_839829468 = ((NI) 0); { while (1) { Ttype293840* t0; Ropeobj179006* field0; TY179507 LOC14; Tloc293816 LOC15; Tloc293816 LOC16; if (!(res_551080_839829468 <= HEX3Atmp_551077_839829468)) goto LA13; i_551071_839829468 = res_551080_839829468; t0 = (*t_551053_839829468).sons->data[i_551071_839829468]; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_179401_2381377266(((NI64) (i_551071_839829468))); field0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_260), LOC14, 1); memset((void*)(&LOC15), 0, sizeof(LOC15)); optasgnloc_550789_839829468(dest0, t0, field0, (&LOC15)); memset((void*)(&LOC16), 0, sizeof(LOC16)); optasgnloc_550789_839829468(src0, t0, field0, (&LOC16)); genassignment_540264_839829468(p0, (&LOC15), (&LOC16), newflags0); res_551080_839829468 += ((NI) 1); } LA13: ; } } } N_NIMCALL(void, gengenericasgn_551167_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0) { { NIM_BOOL LOC3; Ttype293840* LOC5; LOC3 = (NIM_BOOL)0; LOC3 = !(((flags0 &(1U<<((NU)(((Tassignmentflag539302) 0))&7U)))!=0)); if (LOC3) goto LA4; LOC5 = (Ttype293840*)0; LOC5 = skiptypes_297099_850551059((*dest0).t, IL64(211106242013440)); LOC3 = (((*LOC5).flags &(1U<<((NU)(((Ttypeflag293431) 6))&31U)))!=0); LA4: ; if (!LOC3) goto LA6; { NIM_BOOL LOC10; NIM_BOOL LOC12; TY536238 LOC15; LOC10 = (NIM_BOOL)0; LOC10 = ((*dest0).s == ((Tstorageloc293812) 2)); if (LOC10) goto LA11; LOC12 = (NIM_BOOL)0; LOC12 = usesnativegc_170177_2607990831(); LOC10 = !(LOC12); LA11: ; if (!LOC10) goto LA13; usestringh_533345_839829468((*p0).module); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = addrloc_539204_839829468(dest0); LOC15[1] = addrloc_539204_839829468(src0); LOC15[2] = rdloc_539188_839829468(dest0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_261), LOC15, 3); } goto LA8; LA13: ; { TY536238 LOC17; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_539204_839829468(dest0); LOC17[1] = addrloc_539204_839829468(src0); LOC17[2] = gentypeinfo_536941_839829468((*p0).module, (*dest0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_262), LOC17, 3); } LA8: ; } goto LA1; LA6: ; { TY536238 LOC19; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_539204_839829468(dest0); LOC19[1] = addrloc_539204_839829468(src0); LOC19[2] = gentypeinfo_536941_839829468((*p0).module, (*dest0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_263), LOC19, 3); } LA1: ; } N_NIMCALL(NI, asgncomplexity_550751_839829468)(Tnode293802* n0) { NI result0; result0 = (NI)0; { if (!!((n0 == NIM_NIL))) goto LA3; switch ((*n0).kind) { case ((Tnodekind293020) 3): { result0 = ((NI) 1); } break; case ((Tnodekind293020) 139): { result0 = ((NI) 100); } break; case ((Tnodekind293020) 138): { { Tnode293802* t_550768_839829468; t_550768_839829468 = (Tnode293802*)0; { NI i_550782_839829468; NI HEX3Atmp_550784_839829468; NI LOC10; NI res_550786_839829468; i_550782_839829468 = (NI)0; HEX3Atmp_550784_839829468 = (NI)0; LOC10 = (NI)0; LOC10 = len_294081_850551059(n0); HEX3Atmp_550784_839829468 = (LOC10 - 1); res_550786_839829468 = ((NI) 0); { while (1) { NI LOC13; if (!(res_550786_839829468 <= HEX3Atmp_550784_839829468)) goto LA12; i_550782_839829468 = res_550786_839829468; t_550768_839829468 = (*n0).kindU.S6.sons->data[i_550782_839829468]; LOC13 = (NI)0; LOC13 = asgncomplexity_550751_839829468(t_550768_839829468); result0 += LOC13; res_550786_839829468 += ((NI) 1); } LA12: ; } } } } break; default: { } break; } } LA3: ; return result0; } N_NIMCALL(void, genoptasgnobject_551084_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0, Tnode293802* t0) { Tassignmentflag539302Set newflags0; { { if (!(t0 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; { if (!((*src0).s == ((Tstorageloc293812) 1))) goto LA7; newflags0 = (flags0 | 1); } goto LA5; LA7: ; { if (!(((*(*dest0).t).flags &(1U<<((NU)(((Ttypeflag293431) 6))&31U)))!=0)) goto LA10; newflags0 = (flags0 & ~ 1); } goto LA5; LA10: ; { newflags0 = flags0; } LA5: ; switch ((*t0).kind) { case ((Tnodekind293020) 3): { Tsym293834* field0; Tloc293816 LOC14; Tloc293816 LOC15; field0 = (*t0).kindU.S4.sym; memset((void*)(&LOC14), 0, sizeof(LOC14)); optasgnloc_550789_839829468(dest0, (*field0).typ, (*field0).loc.r, (&LOC14)); memset((void*)(&LOC15), 0, sizeof(LOC15)); optasgnloc_550789_839829468(src0, (*field0).typ, (*field0).loc.r, (&LOC15)); genassignment_540264_839829468(p0, (&LOC14), (&LOC15), newflags0); } break; case ((Tnodekind293020) 138): { { Tnode293802* child_551155_839829468; child_551155_839829468 = (Tnode293802*)0; { NI i_551160_839829468; NI HEX3Atmp_551162_839829468; NI LOC19; NI res_551164_839829468; i_551160_839829468 = (NI)0; HEX3Atmp_551162_839829468 = (NI)0; LOC19 = (NI)0; LOC19 = len_294081_850551059(t0); HEX3Atmp_551162_839829468 = (LOC19 - 1); res_551164_839829468 = ((NI) 0); { while (1) { if (!(res_551164_839829468 <= HEX3Atmp_551162_839829468)) goto LA21; i_551160_839829468 = res_551164_839829468; child_551155_839829468 = (*t0).kindU.S6.sons->data[i_551160_839829468]; genoptasgnobject_551084_839829468(p0, dest0, src0, newflags0, child_551155_839829468); res_551164_839829468 += ((NI) 1); } LA21: ; } } } } break; default: { } break; } }BeforeRet: ; } N_NIMCALL(void, genassignment_540264_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0, Tassignmentflag539302Set flags0) { Ttype293840* ty0; { { NIM_BOOL LOC3; TY533811 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = !(((*src0).t == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = ((*(*src0).t).kind == ((Ttypekind293244) 21)); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_539188_839829468(dest0); LOC7[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC7, 2); goto BeforeRet; } LA5: ; ty0 = skiptypes_297099_850551059((*dest0).t, IL64(211106233624832)); switch ((*ty0).kind) { case ((Ttypekind293244) 22): { genrefassign_539311_839829468(p0, dest0, src0, flags0); } break; case ((Ttypekind293244) 24): { { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = !(((flags0 &(1U<<((NU)(((Tassignmentflag539302) 0))&7U)))!=0)); if (!(LOC12)) goto LA13; LOC12 = !(((*src0).s == ((Tstorageloc293812) 1))); LA13: ; if (!LOC12) goto LA14; genrefassign_539311_839829468(p0, dest0, src0, flags0); } goto LA10; LA14: ; { TY536238 LOC17; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_539204_839829468(dest0); LOC17[1] = rdloc_539188_839829468(src0); LOC17[2] = gentypeinfo_536941_839829468((*p0).module, (*dest0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_252), LOC17, 3); } LA10: ; } break; case ((Ttypekind293244) 28): { { NIM_BOOL LOC21; LOC21 = (NIM_BOOL)0; LOC21 = !(((flags0 &(1U<<((NU)(((Tassignmentflag539302) 0))&7U)))!=0)); if (!(LOC21)) goto LA22; LOC21 = !(((*src0).s == ((Tstorageloc293812) 1))); LA22: ; if (!LOC21) goto LA23; genrefassign_539311_839829468(p0, dest0, src0, flags0); } goto LA19; LA23: ; { { NIM_BOOL LOC28; NIM_BOOL LOC30; TY533811 LOC33; LOC28 = (NIM_BOOL)0; LOC28 = ((*dest0).s == ((Tstorageloc293812) 2)); if (LOC28) goto LA29; LOC30 = (NIM_BOOL)0; LOC30 = usesnativegc_170177_2607990831(); LOC28 = !(LOC30); LA29: ; if (!LOC28) goto LA31; memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rdloc_539188_839829468(dest0); LOC33[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_253), LOC33, 2); } goto LA26; LA31: ; { Tloc293816 tmp0; TY536238 LOC37; TY179507 LOC38; if (!((*dest0).s == ((Tstorageloc293812) 3))) goto LA35; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_538032_839829468(p0, ty0, (&tmp0), NIM_FALSE); memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = rdloc_539188_839829468(dest0); LOC37[1] = rdloc_539188_839829468(src0); LOC37[2] = rdloc_539188_839829468((&tmp0)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_254), LOC37, 3); memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = rdloc_539188_839829468((&tmp0)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_255), LOC38, 1); } goto LA26; LA35: ; { TY533811 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = addrloc_539204_839829468(dest0); LOC40[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_256), LOC40, 2); } LA26: ; } LA19: ; } break; case ((Ttypekind293244) 25): { { NIM_BOOL LOC44; Tloc293816 a0; Ropeobj179006* LOC47; Tloc293816 LOC48; Tloc293816 b0; Ropeobj179006* LOC49; Tloc293816 LOC50; TY533811 LOC51; LOC44 = (NIM_BOOL)0; LOC44 = needscomplexassignment_534511_839829468((*dest0).t); if (!LOC44) goto LA45; memset((void*)(&a0), 0, sizeof(a0)); LOC47 = (Ropeobj179006*)0; LOC47 = rope_179277_2381377266(((NimStringDesc*) &T839829468_258)); memset((void*)(&LOC48), 0, sizeof(LOC48)); optasgnloc_550789_839829468(dest0, (*dest0).t, LOC47, (&LOC48)); memcpy((void*)(&a0), (NIM_CONST void*)(&LOC48), sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); LOC49 = (Ropeobj179006*)0; LOC49 = rope_179277_2381377266(((NimStringDesc*) &T839829468_258)); memset((void*)(&LOC50), 0, sizeof(LOC50)); optasgnloc_550789_839829468(src0, (*dest0).t, LOC49, (&LOC50)); memcpy((void*)(&b0), (NIM_CONST void*)(&LOC50), sizeof(b0)); genrefassign_539311_839829468(p0, (&a0), (&b0), flags0); memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = rdloc_539188_839829468(dest0); LOC51[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_259), LOC51, 2); } goto LA42; LA45: ; { TY533811 LOC53; memset((void*)LOC53, 0, sizeof(LOC53)); LOC53[0] = rdloc_539188_839829468(dest0); LOC53[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC53, 2); } LA42: ; } break; case ((Ttypekind293244) 18): { { NIM_BOOL LOC57; LOC57 = (NIM_BOOL)0; LOC57 = needscomplexassignment_534511_839829468((*dest0).t); if (!LOC57) goto LA58; { NI LOC62; LOC62 = (NI)0; LOC62 = len_296339_850551059((*dest0).t); if (!(LOC62 <= ((NI) 4))) goto LA63; genoptasgntuple_551001_839829468(p0, dest0, src0, flags0); } goto LA60; LA63: ; { gengenericasgn_551167_839829468(p0, dest0, src0, flags0); } LA60: ; } goto LA55; LA58: ; { TY533811 LOC67; memset((void*)LOC67, 0, sizeof(LOC67)); LOC67[0] = rdloc_539188_839829468(dest0); LOC67[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC67, 2); } LA55: ; } break; case ((Ttypekind293244) 17): { { NIM_BOOL LOC71; TY533811 LOC74; LOC71 = (NIM_BOOL)0; LOC71 = isimportedcpptype_534478_839829468(ty0); if (!LOC71) goto LA72; memset((void*)LOC74, 0, sizeof(LOC74)); LOC74[0] = rdloc_539188_839829468(dest0); LOC74[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC74, 2); } goto LA69; LA72: ; { NIM_BOOL LOC76; LOC76 = (NIM_BOOL)0; LOC76 = isobjlackingtypefield_534515_839829468(ty0); if (!!(LOC76)) goto LA77; gengenericasgn_551167_839829468(p0, dest0, src0, flags0); } goto LA69; LA77: ; { NIM_BOOL LOC80; LOC80 = (NIM_BOOL)0; LOC80 = needscomplexassignment_534511_839829468(ty0); if (!LOC80) goto LA81; { NIM_BOOL LOC85; NI LOC87; Ropeobj179006* LOC90; LOC85 = (NIM_BOOL)0; LOC85 = (*ty0).sons->data[((NI) 0)] == 0; if (!(LOC85)) goto LA86; LOC87 = (NI)0; LOC87 = asgncomplexity_550751_839829468((*ty0).n); LOC85 = (LOC87 <= ((NI) 4)); LA86: ; if (!LOC85) goto LA88; LOC90 = (Ropeobj179006*)0; LOC90 = gettypedesc_536673_839829468((*p0).module, ty0); ty0 = getuniquetype_529640_2036603609(ty0); { NimStringDesc* LOC95; if (!!(!(((*ty0).n == NIM_NIL)))) goto LA93; LOC95 = (NimStringDesc*)0; LOC95 = HEX24_197185_1689653243(T839829468_264); internalerror_197113_155036129(LOC95); } LA93: ; genoptasgnobject_551084_839829468(p0, dest0, src0, flags0, (*ty0).n); } goto LA83; LA88: ; { gengenericasgn_551167_839829468(p0, dest0, src0, flags0); } LA83: ; } goto LA69; LA81: ; { TY533811 LOC98; memset((void*)LOC98, 0, sizeof(LOC98)); LOC98[0] = rdloc_539188_839829468(dest0); LOC98[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC98, 2); } LA69: ; } break; case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { { NIM_BOOL LOC102; LOC102 = (NIM_BOOL)0; LOC102 = needscomplexassignment_534511_839829468((*dest0).t); if (!LOC102) goto LA103; gengenericasgn_551167_839829468(p0, dest0, src0, flags0); } goto LA100; LA103: ; { TY536238 LOC106; usestringh_533345_839829468((*p0).module); memset((void*)LOC106, 0, sizeof(LOC106)); LOC106[0] = rdloc_539188_839829468(dest0); LOC106[1] = rdloc_539188_839829468(src0); LOC106[2] = gettypedesc_536673_839829468((*p0).module, ty0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_261), LOC106, 3); } LA100: ; } break; case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { { NIM_BOOL LOC110; TY536238 LOC113; LOC110 = (NIM_BOOL)0; LOC110 = needscomplexassignment_534511_839829468((*dest0).t); if (!LOC110) goto LA111; memset((void*)LOC113, 0, sizeof(LOC113)); LOC113[0] = addrloc_539204_839829468(dest0); LOC113[1] = addrloc_539204_839829468(src0); LOC113[2] = gentypeinfo_536941_839829468((*p0).module, (*dest0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_266), LOC113, 3); } goto LA108; LA111: ; { TY533811 LOC115; usestringh_533345_839829468((*p0).module); memset((void*)LOC115, 0, sizeof(LOC115)); LOC115[0] = rdloc_539188_839829468(dest0); LOC115[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_267), LOC115, 2); } LA108: ; } break; case ((Ttypekind293244) 19): { { Tctypekind530007 LOC119; TY536238 LOC122; NI64 LOC123; LOC119 = (Tctypekind530007)0; LOC119 = maptype_534394_839829468(ty0); if (!(LOC119 == ((Tctypekind530007) 17))) goto LA120; usestringh_533345_839829468((*p0).module); memset((void*)LOC122, 0, sizeof(LOC122)); LOC122[0] = rdloc_539188_839829468(dest0); LOC122[1] = rdloc_539188_839829468(src0); LOC123 = (NI64)0; LOC123 = getsize_321135_3876443242((*dest0).t); LOC122[2] = rope_179401_2381377266(LOC123); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_268), LOC122, 3); } goto LA117; LA120: ; { TY533811 LOC125; memset((void*)LOC125, 0, sizeof(LOC125)); LOC125[0] = rdloc_539188_839829468(dest0); LOC125[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC125, 2); } LA117: ; } break; case ((Ttypekind293244) 21): case ((Ttypekind293244) 26): case ((Ttypekind293244) 2): case ((Ttypekind293244) 1): case ((Ttypekind293244) 14): case ((Ttypekind293244) 29): case ((Ttypekind293244) 31) ... ((Ttypekind293244) 44): case ((Ttypekind293244) 20): case ((Ttypekind293244) 23): { TY533811 LOC127; memset((void*)LOC127, 0, sizeof(LOC127)); LOC127[0] = rdloc_539188_839829468(dest0); LOC127[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC127, 2); } break; default: { NimStringDesc* LOC129; LOC129 = (NimStringDesc*)0; LOC129 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI293244))->Sup.len + 15); appendString(LOC129, ((NimStringDesc*) &T839829468_269)); appendString(LOC129, reprEnum((NI)(*ty0).kind, (&NTI293244))); internalerror_197113_155036129(LOC129); } break; } }BeforeRet: ; } N_NIMCALL(void, putlocintodest_540258_839829468)(Tcproc530021* p0, Tloc293816* d0, Tloc293816* s0) { { if (!!(((*d0).k == ((Tlockind293808) 0)))) goto LA3; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag293810) 2))&15U)))!=0)) goto LA7; genassignment_540264_839829468(p0, (&(*d0)), s0, 0); } goto LA5; LA7: ; { genassignment_540264_839829468(p0, (&(*d0)), s0, 1); } LA5: ; } goto LA1; LA3: ; { genericAssign((void*)(&(*d0)), (void*)s0, (&NTI293816)); } LA1: ; } N_NIMCALL(NIM_BOOL, issimpleconst_533311_839829468)(Ttype293840* typ0) { NIM_BOOL result0; Ttype293840* t0; NIM_BOOL LOC1; NIM_BOOL LOC3; result0 = (NIM_BOOL)0; t0 = skiptypes_297099_850551059(typ0, IL64(211106240964864)); LOC1 = (NIM_BOOL)0; LOC1 = !(((17760272 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)); if (!(LOC1)) goto LA2; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind293244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention293002) 8)); LA4: ; LOC1 = !(LOC3); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, putintodest_551468_839829468)(Tcproc530021* p0, Tloc293816* d0, Ttype293840* t0, Ropeobj179006* r0, Tstorageloc293812 s0) { Tloc293816 a0; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind293808) 0)))) goto LA3; initloc_533273_839829468((&a0), ((Tlockind293808) 6), t0, s0); a0.r = r0; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag293810) 2))&15U)))!=0)) goto LA7; genassignment_540264_839829468(p0, (&(*d0)), (&a0), 0); } goto LA5; LA7: ; { genassignment_540264_839829468(p0, (&(*d0)), (&a0), 1); } LA5: ; } goto LA1; LA3: ; { (*d0).k = ((Tlockind293808) 6); unsureAsgnRef((void**) (&(*d0).t), t0); unsureAsgnRef((void**) (&(*d0).r), r0); } LA1: ; } N_NIMCALL(NI64, bitsettoword_550578_839829468)(Tbitset340004* s0, NI size0) { NI64 result0; result0 = (NI64)0; result0 = IL64(0); { NI j_550612_839829468; NI HEX3Atmp_550622_839829468; NI res_550625_839829468; j_550612_839829468 = (NI)0; HEX3Atmp_550622_839829468 = (NI)0; HEX3Atmp_550622_839829468 = (NI)(size0 - ((NI) 1)); res_550625_839829468 = ((NI) 0); { while (1) { if (!(res_550625_839829468 <= HEX3Atmp_550622_839829468)) goto LA3; j_550612_839829468 = res_550625_839829468; { if (!(j_550612_839829468 < (s0 ? s0->Sup.len : 0))) goto LA6; result0 = (NI64)(result0 | (NI64)((NU64)(((NI64)(NU64)(NU8)(s0->data[j_550612_839829468]))) << (NU64)(((NI64) ((NI)(j_550612_839829468 * ((NI) 8))))))); } LA6: ; res_550625_839829468 += ((NI) 1); } LA3: ; } } return result0; } N_NIMCALL(Ropeobj179006*, genrawsetdata_550629_839829468)(Tbitset340004* cs0, NI size0) { Ropeobj179006* result0; NimStringDesc* frmt0; result0 = (Ropeobj179006*)0; frmt0 = (NimStringDesc*)0; { TY534289 LOC5; if (!(((NI) 8) < size0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_273), LOC5, 0); { NI i_550649_839829468; NI HEX3Atmp_550657_839829468; NI res_550660_839829468; i_550649_839829468 = (NI)0; HEX3Atmp_550657_839829468 = (NI)0; HEX3Atmp_550657_839829468 = (NI)(size0 - ((NI) 1)); res_550660_839829468 = ((NI) 0); { while (1) { TY179507 LOC19; NimStringDesc* LOC20; if (!(res_550660_839829468 <= HEX3Atmp_550657_839829468)) goto LA8; i_550649_839829468 = res_550660_839829468; { if (!(i_550649_839829468 < (NI)(size0 - ((NI) 1)))) goto LA11; { if (!(((NI) ((NI)((NI)(i_550649_839829468 + ((NI) 1)) % ((NI) 8)))) == ((NI) 0))) goto LA15; frmt0 = copyString(((NimStringDesc*) &T839829468_274)); } goto LA13; LA15: ; { frmt0 = copyString(((NimStringDesc*) &T839829468_275)); } LA13: ; } goto LA9; LA11: ; { frmt0 = copyString(((NimStringDesc*) &T839829468_276)); } LA9: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (NimStringDesc*)0; LOC20 = nsuToHex(((NI64)(NU64)(NU8)(cs0->data[i_550649_839829468])), ((NI) 2)); LOC19[0] = rope_179277_2381377266(LOC20); addf_180205_2381377266(&result0, frmt0, LOC19, 1); res_550660_839829468 += ((NI) 1); } LA8: ; } } } goto LA1; LA3: ; { NI64 LOC22; LOC22 = (NI64)0; LOC22 = bitsettoword_550578_839829468(cs0, size0); result0 = intliteral_540270_839829468(LOC22); } LA1: ; return result0; } N_NIMCALL(void, appcg_533640_839829468)(Tcgen530027* m0, Tcfilesection530005 s0, NimStringDesc* frmt0, Ropeobj179006** args0, NI args0Len0) { Ropeobj179006* LOC1; LOC1 = (Ropeobj179006*)0; LOC1 = ropecg_533407_839829468(m0, frmt0, args0, args0Len0); add_179482_2381377266(&(*m0).s[(s0)- 0], LOC1); } N_NIMCALL(Ropeobj179006*, genconstseq_560371_839829468)(Tcproc530021* p0, Tnode293802* n0, Ttype293840* t0) { Ropeobj179006* result0; Ropeobj179006* data0; TY179507 LOC1; NI LOC2; TY536235 LOC18; NI LOC19; TY533811 LOC20; result0 = (Ropeobj179006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = len_294081_850551059(n0); LOC1[0] = rope_179401_2381377266(((NI64) (LOC2))); data0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_277), LOC1, 1); { NI LOC5; LOC5 = (NI)0; LOC5 = len_294081_850551059(n0); if (!(((NI) 0) < LOC5)) goto LA6; add_179487_2381377266(&data0, ((NimStringDesc*) &T839829468_278)); { NI i_560395_839829468; NI HEX3Atmp_560411_839829468; NI LOC9; NI res_560414_839829468; i_560395_839829468 = (NI)0; HEX3Atmp_560411_839829468 = (NI)0; LOC9 = (NI)0; LOC9 = len_294081_850551059(n0); HEX3Atmp_560411_839829468 = (NI)(LOC9 - ((NI) 1)); res_560414_839829468 = ((NI) 0); { while (1) { Ropeobj179006* LOC17; if (!(res_560414_839829468 <= HEX3Atmp_560411_839829468)) goto LA11; i_560395_839829468 = res_560414_839829468; { TY534289 LOC16; if (!(((NI) 0) < i_560395_839829468)) goto LA14; memset((void*)LOC16, 0, sizeof(LOC16)); addf_180205_2381377266(&data0, ((NimStringDesc*) &T839829468_279), LOC16, 0); } LA14: ; LOC17 = (Ropeobj179006*)0; LOC17 = genconstexpr_555849_839829468(p0, (*n0).kindU.S6.sons->data[i_560395_839829468]); add_179482_2381377266(&data0, LOC17); res_560414_839829468 += ((NI) 1); } LA11: ; } } add_179487_2381377266(&data0, ((NimStringDesc*) &T839829468_280)); } LA6: ; add_179487_2381377266(&data0, ((NimStringDesc*) &T839829468_280)); result0 = gettempname_534598_839829468((*p0).module); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = gettypedesc_536673_839829468((*p0).module, (*t0).sons->data[((NI) 0)]); LOC19 = (NI)0; LOC19 = len_294081_850551059(n0); LOC18[1] = rope_179401_2381377266(((NI64) (LOC19))); LOC18[2] = result0; LOC18[3] = data0; appcg_533640_839829468((*p0).module, ((Tcfilesection530005) 8), ((NimStringDesc*) &T839829468_281), LOC18, 4); memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC20[1] = result0; result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_282), LOC20, 2); return result0; } N_NIMCALL(Ropeobj179006*, gennamedconstexpr_560284_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { if (!((*n0).kind == ((Tnodekind293020) 34))) goto LA3; result0 = genconstexpr_555849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]); } goto LA1; LA3: ; { result0 = genconstexpr_555849_839829468(p0, n0); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, genconstsimplelist_560299_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; NI length0; TY534289 LOC10; result0 = (Ropeobj179006*)0; length0 = sonslen_296351_850551059(n0); result0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_223)); { NI i_560333_839829468; NI HEX3Atmp_560362_839829468; NI HEX3Atmp_560363_839829468; NI res_560366_839829468; i_560333_839829468 = (NI)0; HEX3Atmp_560362_839829468 = (NI)0; HEX3Atmp_560363_839829468 = (NI)0; HEX3Atmp_560362_839829468 = ((*n0).kind == ((Tnodekind293020) 38)); HEX3Atmp_560363_839829468 = (NI)(length0 - ((NI) 2)); res_560366_839829468 = ((NI) (HEX3Atmp_560362_839829468)); { while (1) { TY179507 LOC4; if (!(res_560366_839829468 <= HEX3Atmp_560363_839829468)) goto LA3; i_560333_839829468 = res_560366_839829468; memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = gennamedconstexpr_560284_839829468(p0, (*n0).kindU.S6.sons->data[i_560333_839829468]); addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_283), LOC4, 1); res_560366_839829468 += ((NI) 1); } LA3: ; } } { Ropeobj179006* LOC9; if (!(((NI) (((*n0).kind == ((Tnodekind293020) 38)))) < length0)) goto LA7; LOC9 = (Ropeobj179006*)0; LOC9 = gennamedconstexpr_560284_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))]); add_179482_2381377266(&result0, LOC9); } LA7: ; memset((void*)LOC10, 0, sizeof(LOC10)); addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_160), LOC10, 0); return result0; } N_NIMCALL(Ropeobj179006*, genconstexpr_555849_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; switch ((*n0).kind) { case ((Tnodekind293020) 58): case ((Tnodekind293020) 59): { result0 = genconstexpr_555849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]); } break; case ((Tnodekind293020) 39): { Tbitset340004* cs0; NI64 LOC3; cs0 = (Tbitset340004*)0; tobitset_341001_452470228(n0, (&cs0)); LOC3 = (NI64)0; LOC3 = getsize_321135_3876443242((*n0).typ); result0 = genrawsetdata_550629_839829468(cs0, ((NI) (LOC3))); } break; case ((Tnodekind293020) 41): case ((Tnodekind293020) 37): case ((Tnodekind293020) 155): case ((Tnodekind293020) 38): { Ttype293840* t0; t0 = skiptypes_297099_850551059((*n0).typ, IL64(211106232576256)); { if (!((*t0).kind == ((Ttypekind293244) 24))) goto LA7; result0 = genconstseq_560371_839829468(p0, n0, t0); } goto LA5; LA7: ; { result0 = genconstsimplelist_560299_839829468(p0, n0); } LA5: ; } break; default: { Tloc293816 d0; memset((void*)(&d0), 0, sizeof(d0)); initlocexpr_540283_839829468(p0, n0, (&d0)); result0 = rdloc_539188_839829468((&d0)); } break; } return result0; } N_NIMCALL(void, requestconstimpl_540240_839829468)(Tcproc530021* p0, Tsym293834* sym0) { Tcgen530027* m0; Tcgen530027* q0; { m0 = (*p0).module; useheader_533369_839829468(m0, sym0); { Ropeobj179006* LOC5; if (!((*sym0).loc.k == ((Tlockind293808) 0))) goto LA3; LOC5 = (Ropeobj179006*)0; LOC5 = manglename_534205_839829468(sym0); fillloc_533282_839829468((&(*sym0).loc), ((Tlockind293808) 8), (*sym0).typ, LOC5, ((Tstorageloc293812) 1)); } LA3: ; { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0)) goto LA8; goto BeforeRet; } LA8: ; q0 = findpendingmodule_533241_839829468(m0, sym0); { NIM_BOOL LOC12; NIM_BOOL LOC14; TY536238 LOC17; LOC12 = (NIM_BOOL)0; LOC12 = !((q0 == NIM_NIL)); if (!(LOC12)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_269862_2627731572((&(*q0).declaredthings), (*sym0).Sup.id); LOC12 = !(LOC14); LA13: ; if (!LOC12) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_536673_839829468(q0, (*sym0).typ); LOC17[1] = (*sym0).loc.r; LOC17[2] = genconstexpr_555849_839829468((*q0).initproc, (*sym0).ast); addf_180205_2381377266(&(*q0).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3); } LA15: ; { NIM_BOOL LOC20; NIM_BOOL LOC22; Ropeobj179006* headerdecl0; TY533811 LOC25; LOC20 = (NIM_BOOL)0; LOC20 = !((q0 == m0)); if (!(LOC20)) goto LA21; LOC22 = (NIM_BOOL)0; LOC22 = containsorincl_269862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LOC20 = !(LOC22); LA21: ; if (!LOC20) goto LA23; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = gettypedesc_536673_839829468(m0, (*sym0).loc.t); LOC25[1] = (*sym0).loc.r; headerdecl0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_284), LOC25, 2); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 8))- 0], headerdecl0); { NIM_BOOL LOC28; LOC28 = (NIM_BOOL)0; LOC28 = (((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 6))&31U)))!=0); if (!(LOC28)) goto LA29; LOC28 = !((generatedheader_533201_839829468 == NIM_NIL)); LA29: ; if (!LOC28) goto LA30; add_179482_2381377266(&(*generatedheader_533201_839829468).s[(((Tcfilesection530005) 8))- 0], headerdecl0); } LA30: ; } LA23: ; }BeforeRet: ; } N_NIMCALL(void, gencomplexconst_559249_839829468)(Tcproc530021* p0, Tsym293834* sym0, Tloc293816* d0) { requestconstimpl_540240_839829468(p0, sym0); putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } static N_INLINE(Ropeobj179006**, procsec_530194_3723162438)(Tcproc530021* p0, Tcprocsection530011 s0) { Ropeobj179006** result0; result0 = (Ropeobj179006**)0; result0 = &(*p0).blocks->data[((NI) 0)].sections[(s0)- 0]; return result0; } N_NIMCALL(void, accessthreadlocalvar_533945_839829468)(Tcproc530021* p0, Tsym293834* s0) { { NIM_BOOL LOC3; Ropeobj179006** LOC7; TY534289 LOC8; Ropeobj179006** LOC9; TY534289 LOC10; Ropeobj179006* LOC11; LOC3 = (NIM_BOOL)0; LOC3 = emulatedthreadvars_533949_839829468(); if (!(LOC3)) goto LA4; LOC3 = !((*p0).threadvaraccessed); LA4: ; if (!LOC3) goto LA5; (*p0).threadvaraccessed = NIM_TRUE; (*(*p0).module).flags |= ((NU8)1)<<((((Codegenflag530025) 1))%(sizeof(NU8)*8)); LOC7 = (Ropeobj179006**)0; LOC7 = procsec_530194_3723162438(p0, ((Tcprocsection530011) 0)); memset((void*)LOC8, 0, sizeof(LOC8)); addf_180205_2381377266(LOC7, ((NimStringDesc*) &T839829468_286), LOC8, 0); LOC9 = (Ropeobj179006**)0; LOC9 = procsec_530194_3723162438(p0, ((Tcprocsection530011) 1)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC11 = (Ropeobj179006*)0; LOC11 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_287), LOC10, 0); add_179482_2381377266(LOC9, LOC11); } LA5: ; } static N_INLINE(NIM_BOOL, isemptytype_298441_850551059)(Ttype293840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = (t0 == NIM_NIL); if (LOC1) goto LA2; LOC1 = ((IL64(4611686018427388032) &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, putdataintodest_551436_839829468)(Tcproc530021* p0, Tloc293816* d0, Ttype293840* t0, Ropeobj179006* r0) { Tloc293816 a0; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind293808) 0)))) goto LA3; initloc_533273_839829468((&a0), ((Tlockind293808) 8), t0, ((Tstorageloc293812) 1)); a0.r = r0; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag293810) 2))&15U)))!=0)) goto LA7; genassignment_540264_839829468(p0, (&(*d0)), (&a0), 0); } goto LA5; LA7: ; { genassignment_540264_839829468(p0, (&(*d0)), (&a0), 1); } LA5: ; } goto LA1; LA3: ; { (*d0).k = ((Tlockind293808) 8); unsureAsgnRef((void**) (&(*d0).t), t0); unsureAsgnRef((void**) (&(*d0).r), r0); } LA1: ; } N_NIMCALL(NIM_BOOL, freshlineinfo_533818_839829468)(Tcproc530021* p0, Tlineinfo192336 info0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*p0).lastlineinfo.line == info0.line)); if (LOC3) goto LA4; LOC3 = !(((*p0).lastlineinfo.fileindex == info0.fileindex)); LA4: ; if (!LOC3) goto LA5; (*p0).lastlineinfo.line = info0.line; (*p0).lastlineinfo.fileindex = info0.fileindex; result0 = NIM_TRUE; } LA5: ; return result0; } N_NIMCALL(void, genlinedir_533823_839829468)(Tcproc530021* p0, Tnode293802* t0) { NI line0; Ropeobj179006** LOC11; NimStringDesc* LOC12; line0 = safelinenm_533721_839829468((*t0).info); { Ropeobj179006** LOC5; TY534289 LOC6; Ropeobj179006* LOC7; Ropeobj179006* LOC8; Ropeobj179006* LOC9; Ropeobj179006* LOC10; if (!((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 28))&63U)))!=0)) goto LA3; LOC5 = (Ropeobj179006**)0; LOC5 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); memset((void*)LOC6, 0, sizeof(LOC6)); LOC7 = (Ropeobj179006*)0; LOC7 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_293), LOC6, 0); LOC8 = (Ropeobj179006*)0; LOC8 = sourceline_193065_155036129((*t0).info); LOC9 = (Ropeobj179006*)0; LOC9 = HEX26_179418_2381377266(LOC7, LOC8); LOC10 = (Ropeobj179006*)0; LOC10 = HEX26_179418_2381377266(LOC9, rnl_179903_2381377266); add_179482_2381377266(LOC5, LOC10); } LA3: ; LOC11 = (Ropeobj179006**)0; LOC11 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); LOC12 = (NimStringDesc*)0; LOC12 = tofullpath_193261_155036129((*t0).info.fileindex); genclinedir_533725_839829468(LOC11, LOC12, line0); { NIM_BOOL LOC15; NIM_BOOL LOC17; LOC15 = (NIM_BOOL)0; LOC15 = ((163840 & (*p0).options) == 163840); if (!(LOC15)) goto LA16; LOC17 = (NIM_BOOL)0; LOC17 = ((*p0).prc == NIM_NIL); if (LOC17) goto LA18; LOC17 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag293184) 9))&31U)))!=0)); LA18: ; LOC15 = LOC17; LA16: ; if (!LOC15) goto LA19; { NIM_BOOL LOC23; TY533811 LOC26; NimStringDesc* LOC27; LOC23 = (NIM_BOOL)0; LOC23 = freshlineinfo_533818_839829468(p0, (*t0).info); if (!LOC23) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rope_179401_2381377266(((NI64) (line0))); LOC27 = (NimStringDesc*)0; LOC27 = tofilename_193257_155036129((*t0).info.fileindex); LOC26[1] = makecstring_192638_155036129(LOC27); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_294), LOC26, 2); } LA24: ; } goto LA13; LA19: ; { NIM_BOOL LOC29; NIM_BOOL LOC30; NIM_BOOL LOC32; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((98304 & (*p0).options) == 98304); if (!(LOC30)) goto LA31; LOC32 = (NIM_BOOL)0; LOC32 = ((*p0).prc == NIM_NIL); if (LOC32) goto LA33; LOC32 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag293184) 9))&31U)))!=0)); LA33: ; LOC30 = LOC32; LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA34; LOC29 = (((NI32) 0) <= (*t0).info.fileindex); LA34: ; if (!LOC29) goto LA35; { NIM_BOOL LOC39; TY533811 LOC42; LOC39 = (NIM_BOOL)0; LOC39 = freshlineinfo_533818_839829468(p0, (*t0).info); if (!LOC39) goto LA40; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = rope_179401_2381377266(((NI64) (line0))); LOC42[1] = quotedfilename_197818_155036129((*t0).info); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_295), LOC42, 2); } LA40: ; } goto LA13; LA35: ; LA13: ; } N_NIMCALL(Ropeobj179006*, getlabel_540217_839829468)(Tcproc530021* p0) { Ropeobj179006* result0; Ropeobj179006* LOC1; result0 = (Ropeobj179006*)0; (*p0).labels += ((NI) 1); LOC1 = (Ropeobj179006*)0; LOC1 = rope_179401_2381377266(((NI64) ((*p0).labels))); result0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_296), LOC1); return result0; } N_NIMCALL(void, fixlabel_540230_839829468)(Tcproc530021* p0, Ropeobj179006* labl0) { TY179507 LOC1; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = labl0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_299), LOC1, 1); } N_NIMCALL(void, genandor_555311_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0) { Ropeobj179006* L0; Tloc293816 tmp0; L0 = (Ropeobj179006*)0; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_538032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE); (*p0).splitdecls += ((NI) 1); expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); L0 = getlabel_540217_839829468(p0); { TY533811 LOC5; if (!(m0 == ((Tmagic293524) 127))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468((&tmp0)); LOC5[1] = L0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_297), LOC5, 2); } goto LA1; LA3: ; { TY533811 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_539188_839829468((&tmp0)); LOC7[1] = L0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_298), LOC7, 2); } LA1: ; expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&tmp0)); fixlabel_540230_839829468(p0, L0); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA10; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI293816)); } goto LA8; LA10: ; { genassignment_540264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA8: ; (*p0).splitdecls -= ((NI) 1); } N_NIMCALL(void, unaryarith_553646_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0) { Tloc293816 a0; Ttype293840* t0; TY536238 LOC1; NI64 LOC2; Ropeobj179006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); t0 = (Ttype293840*)0; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_297099_850551059((*e0).typ, IL64(211106233624832)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&a0)); LOC2 = (NI64)0; LOC2 = getsize_321135_3876443242(t0); LOC1[1] = rope_179401_2381377266((NI64)(LOC2 * IL64(8))); LOC1[2] = getsimpletypedesc_534936_839829468((*p0).module, (*e0).typ); LOC3 = (Ropeobj179006*)0; LOC3 = HEX25_179905_2381377266(unarithtab_553653_839829468[(op0)- 99], LOC1, 3); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC3, ((Tstorageloc293812) 0)); } N_NIMCALL(void, unaryarithoverflow_552633_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0) { Tloc293816 a0; Ttype293840* t0; TY533811 LOC7; NI64 LOC8; Ropeobj179006* LOC9; memset((void*)(&a0), 0, sizeof(a0)); t0 = (Ttype293840*)0; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_297099_850551059((*e0).typ, IL64(211106233624832)); { TY533811 LOC5; NI64 LOC6; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 5))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468((&a0)); LOC6 = (NI64)0; LOC6 = firstord_321001_3876443242(t0); LOC5[1] = intliteral_540270_839829468(LOC6); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_317), LOC5, 2); } LA3: ; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_539188_839829468((&a0)); LOC8 = (NI64)0; LOC8 = getsize_321135_3876443242(t0); LOC7[1] = rope_179401_2381377266((NI64)(LOC8 * IL64(8))); LOC9 = (Ropeobj179006*)0; LOC9 = HEX25_179905_2381377266(opr_552640_839829468[(m0)- 96], LOC7, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC9, ((Tstorageloc293812) 0)); } N_NIMCALL(void, binaryarith_552819_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0) { Tloc293816 a0; Tloc293816 b0; NI64 s0; NI64 LOC1; NI64 LOC2; TY536235 LOC3; Ropeobj179006* LOC4; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); s0 = (NI64)0; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); LOC1 = (NI64)0; LOC1 = getsize_321135_3876443242(a0.t); LOC2 = (NI64)0; LOC2 = getsize_321135_3876443242(b0.t); s0 = (NI64)(((LOC1 >= LOC2) ? LOC1 : LOC2) * IL64(8)); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = rdloc_539188_839829468((&a0)); LOC3[1] = rdloc_539188_839829468((&b0)); LOC3[2] = rope_179401_2381377266(s0); LOC3[3] = getsimpletypedesc_534936_839829468((*p0).module, (*e0).typ); LOC4 = (Ropeobj179006*)0; LOC4 = HEX25_179905_2381377266(binarithtab_552826_839829468[(op0)- 52], LOC3, 4); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC4, ((Tstorageloc293812) 0)); } N_NIMCALL(void, binaryfloatarith_557729_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0) { { Tloc293816 a0; Tloc293816 b0; TY536235 LOC5; Tnode293802* LOC6; Ropeobj179006* LOC7; if (!!(((384 & (*p0).options) == 0))) goto LA3; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_179277_2381377266(opr_557763_839829468[(m0)- 52]); LOC5[1] = rdloc_539188_839829468((&a0)); LOC5[2] = rdloc_539188_839829468((&b0)); LOC6 = (Tnode293802*)0; LOC6 = HEX5BHEX5D_294238_850551059(e0, ((NI) 1)); LOC5[3] = getsimpletypedesc_534936_839829468((*p0).module, (*LOC6).typ); LOC7 = (Ropeobj179006*)0; LOC7 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_319), LOC5, 4); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc293812) 0)); { TY179507 LOC12; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 7))&31U)))!=0)) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_539188_839829468((&(*d0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_323), LOC12, 1); } LA10: ; { TY179507 LOC17; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 8))&31U)))!=0)) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_539188_839829468((&(*d0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_324), LOC17, 1); } LA15: ; } goto LA1; LA3: ; { binaryarith_552819_839829468(p0, e0, d0, m0); } LA1: ; } N_NIMCALL(void, geneqproc_553214_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { Ttype293840* LOC3; TY533811 LOC6; Ropeobj179006* LOC7; LOC3 = (Ttype293840*)0; LOC3 = skiptypes_297099_850551059(a0.t, IL64(211106232576256)); if (!((*LOC3).callconv == ((Tcallingconvention293002) 8))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rdloc_539188_839829468((&a0)); LOC6[1] = rdloc_539188_839829468((&b0)); LOC7 = (Ropeobj179006*)0; LOC7 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_352), LOC6, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc293812) 0)); } goto LA1; LA4: ; { TY533811 LOC9; Ropeobj179006* LOC10; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = rdloc_539188_839829468((&a0)); LOC9[1] = rdloc_539188_839829468((&b0)); LOC10 = (Ropeobj179006*)0; LOC10 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_341), LOC9, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC10, ((Tstorageloc293812) 0)); } LA1: ; } N_NIMCALL(Ropeobj179006*, rdcharloc_539227_839829468)(Tloc293816* a0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = rdloc_539188_839829468(a0); { Ttype293840* LOC3; TY179507 LOC6; LOC3 = (Ttype293840*)0; LOC3 = skiptypes_297099_850551059((*a0).t, IL64(211106233624832)); if (!((*LOC3).kind == ((Ttypekind293244) 2))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = result0; result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_358), LOC6, 1); } LA4: ; return result0; } N_NIMCALL(Ropeobj179006*, binaryarithoverflowraw_552235_839829468)(Tcproc530021* p0, Ttype293840* t0, Tloc293816* a0, Tloc293816* b0, NimStringDesc* frmt0) { Ropeobj179006* result0; NI64 size0; Ropeobj179006* storage0; TY533811 LOC6; TY536238 LOC7; result0 = (Ropeobj179006*)0; size0 = getsize_321135_3876443242(t0); { if (!(size0 < ((NI64) (intsize_177641_4151366050)))) goto LA3; storage0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_36)); } goto LA1; LA3: ; { storage0 = gettypedesc_536673_839829468((*p0).module, t0); } LA1: ; result0 = gettempname_534598_839829468((*p0).module); memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = storage0; LOC6[1] = result0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 0), ((NimStringDesc*) &T839829468_54), LOC6, 2); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = result0; LOC7[1] = rdcharloc_539227_839829468(a0); LOC7[2] = rdcharloc_539227_839829468(b0); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), frmt0, LOC7, 3); { NIM_BOOL LOC10; TY536238 LOC14; NI64 LOC15; NI64 LOC16; LOC10 = (NIM_BOOL)0; LOC10 = (size0 < ((NI64) (intsize_177641_4151366050))); if (LOC10) goto LA11; LOC10 = ((1064960 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); LA11: ; if (!LOC10) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = result0; LOC15 = (NI64)0; LOC15 = firstord_321001_3876443242(t0); LOC14[1] = intliteral_540270_839829468(LOC15); LOC16 = (NI64)0; LOC16 = lastord_321004_3876443242(t0); LOC14[2] = intliteral_540270_839829468(LOC16); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_359), LOC14, 3); } LA12: ; return result0; } N_NIMCALL(void, binaryarithoverflow_552262_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 m0) { Tloc293816 a0; Tloc293816 b0; Ttype293840* t0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); t0 = skiptypes_297099_850551059((*e0).typ, IL64(211106233624832)); { Ropeobj179006* res0; TY536238 LOC5; if (!!((((*p0).options &(1U<<((NU)(((Toption170009) 5))&31U)))!=0))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC5[1] = rdloc_539188_839829468((&a0)); LOC5[2] = rdloc_539188_839829468((&b0)); res0 = HEX25_179905_2381377266(opr_552279_839829468[(m0)- 45], LOC5, 3); putintodest_551468_839829468(p0, d0, (*e0).typ, res0, ((Tstorageloc293812) 0)); } goto LA1; LA3: ; { Ropeobj179006* res0; NimStringDesc* LOC7; TY533811 LOC13; Ropeobj179006* LOC14; LOC7 = (NimStringDesc*)0; { if (!((*t0).kind == ((Ttypekind293244) 35))) goto LA10; LOC7 = copyString(prc64_552274_839829468[(m0)- 45]); } goto LA8; LA10: ; { LOC7 = copyString(prc_552269_839829468[(m0)- 45]); } LA8: ; res0 = binaryarithoverflowraw_552235_839829468(p0, t0, (&a0), (&b0), LOC7); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC13[1] = res0; LOC14 = (Ropeobj179006*)0; LOC14 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_370), LOC13, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC14, ((Tstorageloc293812) 0)); } LA1: ; } N_NIMCALL(Ropeobj179006*, lenfield_540305_839829468)(Tcproc530021* p0) { Ropeobj179006* result0; NimStringDesc* LOC1; result0 = (Ropeobj179006*)0; LOC1 = (NimStringDesc*)0; { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC4) goto LA5; LOC4 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA5: ; if (!LOC4) goto LA6; LOC1 = copyString(((NimStringDesc*) &T839829468_157)); } goto LA2; LA6: ; { LOC1 = copyString(((NimStringDesc*) &T839829468_158)); } LA2: ; result0 = rope_179277_2381377266(LOC1); return result0; } N_NIMCALL(void, gcusage_555439_839829468)(Tnode293802* n0) { { NimStringDesc* LOC5; if (!(gselectedgc_170133_2607990831 == ((Tgcmode170080) 0))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = rendertree_312044_382274130(n0, 0); message_197095_155036129((*n0).info, ((Tmsgkind192002) 263), LOC5); } LA3: ; } N_NIMCALL(void, genrepr_556339_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Ttype293840* t0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); switch ((*t0).kind) { case ((Ttypekind293244) 31) ... ((Ttypekind293244) 35): case ((Ttypekind293244) 40) ... ((Ttypekind293244) 44): { TY179507 LOC2; Ropeobj179006* LOC3; memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_539188_839829468((&a0)); LOC3 = (Ropeobj179006*)0; LOC3 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_371), LOC2, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC3, a0.s); } break; case ((Ttypekind293244) 36) ... ((Ttypekind293244) 39): { TY179507 LOC5; Ropeobj179006* LOC6; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468((&a0)); LOC6 = (Ropeobj179006*)0; LOC6 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_372), LOC5, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC6, a0.s); } break; case ((Ttypekind293244) 1): { TY179507 LOC8; Ropeobj179006* LOC9; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_539188_839829468((&a0)); LOC9 = (Ropeobj179006*)0; LOC9 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_373), LOC8, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC9, a0.s); } break; case ((Ttypekind293244) 2): { TY179507 LOC11; Ropeobj179006* LOC12; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdloc_539188_839829468((&a0)); LOC12 = (Ropeobj179006*)0; LOC12 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_374), LOC11, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC12, a0.s); } break; case ((Ttypekind293244) 14): case ((Ttypekind293244) 15): { TY533811 LOC14; Ropeobj179006* LOC15; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_539188_839829468((&a0)); LOC14[1] = gentypeinfo_536941_839829468((*p0).module, t0); LOC15 = (Ropeobj179006*)0; LOC15 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_375), LOC14, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC15, a0.s); } break; case ((Ttypekind293244) 28): { TY179507 LOC17; Ropeobj179006* LOC18; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_539188_839829468((&a0)); LOC18 = (Ropeobj179006*)0; LOC18 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_376), LOC17, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC18, a0.s); } break; case ((Ttypekind293244) 19): { TY533811 LOC20; Ropeobj179006* LOC21; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = addrloc_539204_839829468((&a0)); LOC20[1] = gentypeinfo_536941_839829468((*p0).module, t0); LOC21 = (Ropeobj179006*)0; LOC21 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_377), LOC20, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC21, a0.s); } break; case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { Tloc293816 b0; TY533811 LOC34; Ttype293840* LOC35; Ropeobj179006* LOC36; memset((void*)(&b0), 0, sizeof(b0)); switch ((*a0.t).kind) { case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { TY179507 LOC24; Ropeobj179006* LOC25; memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = rdloc_539188_839829468((&a0)); LOC25 = (Ropeobj179006*)0; LOC25 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_378), LOC24, 1); putintodest_551468_839829468(p0, (&b0), (*e0).typ, LOC25, a0.s); } break; case ((Ttypekind293244) 28): case ((Ttypekind293244) 24): { TY533811 LOC27; Ropeobj179006* LOC28; memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = rdloc_539188_839829468((&a0)); LOC27[1] = lenfield_540305_839829468(p0); LOC28 = (Ropeobj179006*)0; LOC28 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_379), LOC27, 2); putintodest_551468_839829468(p0, (&b0), (*e0).typ, LOC28, a0.s); } break; case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { TY533811 LOC30; NI64 LOC31; Ropeobj179006* LOC32; memset((void*)LOC30, 0, sizeof(LOC30)); LOC30[0] = rdloc_539188_839829468((&a0)); LOC31 = (NI64)0; LOC31 = lengthord_321007_3876443242(a0.t); LOC30[1] = rope_179401_2381377266(LOC31); LOC32 = (Ropeobj179006*)0; LOC32 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_380), LOC30, 2); putintodest_551468_839829468(p0, (&b0), (*e0).typ, LOC32, a0.s); } break; default: { internalerror_197100_155036129((*(*e0).kindU.S6.sons->data[((NI) 0)]).info, ((NimStringDesc*) &T839829468_381)); } break; } memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = rdloc_539188_839829468((&b0)); LOC35 = (Ttype293840*)0; LOC35 = elemtype_321394_3876443242(t0); LOC34[1] = gentypeinfo_536941_839829468((*p0).module, LOC35); LOC36 = (Ropeobj179006*)0; LOC36 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_382), LOC34, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC36, a0.s); } break; case ((Ttypekind293244) 29): case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): case ((Ttypekind293244) 22): case ((Ttypekind293244) 21): case ((Ttypekind293244) 26): case ((Ttypekind293244) 5): case ((Ttypekind293244) 24): { TY533811 LOC38; Ropeobj179006* LOC39; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = rdloc_539188_839829468((&a0)); LOC38[1] = gentypeinfo_536941_839829468((*p0).module, t0); LOC39 = (Ropeobj179006*)0; LOC39 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC38, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC39, a0.s); } break; case ((Ttypekind293244) 3): case ((Ttypekind293244) 62): { localerror_197085_155036129((*e0).info, ((NimStringDesc*) &T839829468_384)); } break; default: { TY533811 LOC42; Ropeobj179006* LOC43; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = addrloc_539204_839829468((&a0)); LOC42[1] = gentypeinfo_536941_839829468((*p0).module, t0); LOC43 = (Ropeobj179006*)0; LOC43 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC42, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC43, a0.s); } break; } gcusage_555439_839829468(e0); } N_NIMCALL(void, gengettypeinfo_556383_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Ttype293840* t0; Ropeobj179006* LOC1; t0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); LOC1 = (Ropeobj179006*)0; LOC1 = gentypeinfo_536941_839829468((*p0).module, t0); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC1, ((Tstorageloc293812) 0)); } N_NIMCALL(void, genswap_556638_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Tloc293816 tmp0; Ttype293840* LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); LOC1 = (Ttype293840*)0; LOC1 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); gettemp_538032_839829468(p0, LOC1, (&tmp0), NIM_FALSE); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); genassignment_540264_839829468(p0, (&tmp0), (&a0), 0); genassignment_540264_839829468(p0, (&a0), (&b0), 0); genassignment_540264_839829468(p0, (&b0), (&tmp0), 0); } N_NIMCALL(void, unaryexpr_552209_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; TY179507 LOC1; Ropeobj179006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&a0)); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, frmt0, LOC1, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc293812) 0)); } N_NIMCALL(void, binarystmt_551501_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; Tloc293816 b0; TY533811 LOC5; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); { if (!!(((*d0).k == ((Tlockind293808) 0)))) goto LA3; internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_387)); } LA3: ; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468((&a0)); LOC5[1] = rdloc_539188_839829468((&b0)); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), frmt0, LOC5, 2); } N_NIMCALL(void, genstrconcat_555452_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 tmp0; NI L0; Ropeobj179006* appends0; Ropeobj179006* lens0; TY536238 LOC21; Ropeobj179006** LOC22; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_538032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE); L0 = ((NI) 0); appends0 = NIM_NIL; lens0 = NIM_NIL; { NI i_555475_839829468; NI HEX3Atmp_555547_839829468; NI LOC2; NI res_555550_839829468; i_555475_839829468 = (NI)0; HEX3Atmp_555547_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(e0); HEX3Atmp_555547_839829468 = (NI)(LOC2 - ((NI) 2)); res_555550_839829468 = ((NI) 0); { while (1) { if (!(res_555550_839829468 <= HEX3Atmp_555547_839829468)) goto LA4; i_555475_839829468 = res_555550_839829468; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_555475_839829468 + ((NI) 1))], (&a0)); { Ttype293840* LOC7; TY533811 LOC10; Ropeobj179006* LOC11; LOC7 = (Ttype293840*)0; LOC7 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_555475_839829468 + ((NI) 1))]).typ, IL64(211106242013440)); if (!((*LOC7).kind == ((Ttypekind293244) 2))) goto LA8; L0 += ((NI) 1); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = tmp0.r; LOC10[1] = rdloc_539188_839829468((&a0)); LOC11 = (Ropeobj179006*)0; LOC11 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2); add_179482_2381377266(&appends0, LOC11); } goto LA5; LA8: ; { TY533811 LOC19; Ropeobj179006* LOC20; { if (!((*(*e0).kindU.S6.sons->data[(NI)(i_555475_839829468 + ((NI) 1))]).kind >= ((Tnodekind293020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_555475_839829468 + ((NI) 1))]).kind <= ((Tnodekind293020) 22))) goto LA15; L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_555475_839829468 + ((NI) 1))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_555475_839829468 + ((NI) 1))]).kindU.S3.strval->Sup.len : 0); } goto LA13; LA15: ; { TY533811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_539188_839829468((&a0)); LOC18[1] = lenfield_540305_839829468(p0); addf_180205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2); } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = tmp0.r; LOC19[1] = rdloc_539188_839829468((&a0)); LOC20 = (Ropeobj179006*)0; LOC20 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2); add_179482_2381377266(&appends0, LOC20); } LA5: ; res_555550_839829468 += ((NI) 1); } LA4: ; } } memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = tmp0.r; LOC21[1] = lens0; LOC21[2] = rope_179401_2381377266(((NI64) (L0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_393), LOC21, 3); LOC22 = (Ropeobj179006**)0; LOC22 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179482_2381377266(LOC22, appends0); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA25; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI293816)); } goto LA23; LA25: ; { genassignment_540264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA23: ; gcusage_555439_839829468(e0); } N_NIMCALL(void, genstrappend_555554_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 dest0; Ropeobj179006* appends0; Ropeobj179006* lens0; NI L0; TY536238 LOC21; Ropeobj179006** LOC22; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&dest0), 0, sizeof(dest0)); appends0 = (Ropeobj179006*)0; lens0 = (Ropeobj179006*)0; L0 = ((NI) 0); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&dest0)); { NI i_555615_839829468; NI HEX3Atmp_555676_839829468; NI LOC2; NI res_555679_839829468; i_555615_839829468 = (NI)0; HEX3Atmp_555676_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(e0); HEX3Atmp_555676_839829468 = (NI)(LOC2 - ((NI) 3)); res_555679_839829468 = ((NI) 0); { while (1) { if (!(res_555679_839829468 <= HEX3Atmp_555676_839829468)) goto LA4; i_555615_839829468 = res_555679_839829468; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_555615_839829468 + ((NI) 2))], (&a0)); { Ttype293840* LOC7; TY533811 LOC10; Ropeobj179006* LOC11; LOC7 = (Ttype293840*)0; LOC7 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_555615_839829468 + ((NI) 2))]).typ, IL64(211106242013440)); if (!((*LOC7).kind == ((Ttypekind293244) 2))) goto LA8; L0 += ((NI) 1); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_539188_839829468((&dest0)); LOC10[1] = rdloc_539188_839829468((&a0)); LOC11 = (Ropeobj179006*)0; LOC11 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2); add_179482_2381377266(&appends0, LOC11); } goto LA5; LA8: ; { TY533811 LOC19; Ropeobj179006* LOC20; { if (!((*(*e0).kindU.S6.sons->data[(NI)(i_555615_839829468 + ((NI) 2))]).kind >= ((Tnodekind293020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_555615_839829468 + ((NI) 2))]).kind <= ((Tnodekind293020) 22))) goto LA15; L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_555615_839829468 + ((NI) 2))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_555615_839829468 + ((NI) 2))]).kindU.S3.strval->Sup.len : 0); } goto LA13; LA15: ; { TY533811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_539188_839829468((&a0)); LOC18[1] = lenfield_540305_839829468(p0); addf_180205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2); } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_539188_839829468((&dest0)); LOC19[1] = rdloc_539188_839829468((&a0)); LOC20 = (Ropeobj179006*)0; LOC20 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2); add_179482_2381377266(&appends0, LOC20); } LA5: ; res_555679_839829468 += ((NI) 1); } LA4: ; } } memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdloc_539188_839829468((&dest0)); LOC21[1] = lens0; LOC21[2] = rope_179401_2381377266(((NI64) (L0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_395), LOC21, 3); LOC22 = (Ropeobj179006**)0; LOC22 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179482_2381377266(LOC22, appends0); gcusage_555439_839829468(e0); } N_NIMCALL(void, genseqelemappend_555683_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { NimStringDesc* seqappendpattern0; Tloc293816 a0; Tloc293816 b0; Tloc293816 dest0; Ttype293840* bt0; TY536238 LOC8; Ttype293840* LOC9; TY533811 LOC10; TY533811 LOC11; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_396)); } goto LA1; LA5: ; { seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_397)); } LA1: ; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&dest0), 0, sizeof(dest0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); bt0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 2)]).typ, IL64(211106240964864)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_539188_839829468((&a0)); LOC9 = (Ttype293840*)0; LOC9 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC8[1] = gettypedesc_536673_839829468((*p0).module, LOC9); LOC8[2] = gettypedesc_536673_839829468((*p0).module, bt0); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), seqappendpattern0, LOC8, 3); initloc_533273_839829468((&dest0), ((Tlockind293808) 6), bt0, ((Tstorageloc293812) 3)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_539188_839829468((&a0)); LOC10[1] = lenfield_540305_839829468(p0); dest0.r = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_398), LOC10, 2); genassignment_540264_839829468(p0, (&dest0), (&b0), 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdloc_539188_839829468((&a0)); LOC11[1] = lenfield_540305_839829468(p0); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_399), LOC11, 2); gcusage_555439_839829468(e0); } N_NIMCALL(void, binaryexpr_551549_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; Tloc293816 b0; TY533811 LOC1; Ropeobj179006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&a0)); LOC1[1] = rdloc_539188_839829468((&b0)); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, frmt0, LOC1, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc293812) 0)); } N_NIMCALL(void, genstrequals_557667_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 x0; Tnode293802* a0; Tnode293802* b0; memset((void*)(&x0), 0, sizeof(x0)); a0 = (*e0).kindU.S6.sons->data[((NI) 1)]; b0 = (*e0).kindU.S6.sons->data[((NI) 2)]; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*a0).kind == ((Tnodekind293020) 23)); if (LOC3) goto LA4; LOC3 = ((*b0).kind == ((Tnodekind293020) 23)); LA4: ; if (!LOC3) goto LA5; binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341)); } goto LA1; LA5: ; { NIM_BOOL LOC8; TY533811 LOC12; Ropeobj179006* LOC13; LOC8 = (NIM_BOOL)0; LOC8 = ((*a0).kind >= ((Tnodekind293020) 20) && (*a0).kind <= ((Tnodekind293020) 22)); if (!(LOC8)) goto LA9; LOC8 = (((*a0).kindU.S3.strval) && ((*a0).kindU.S3.strval)->Sup.len == 0); LA9: ; if (!LOC8) goto LA10; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&x0)); memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_539188_839829468((&x0)); LOC12[1] = lenfield_540305_839829468(p0); LOC13 = (Ropeobj179006*)0; LOC13 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC12, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC13, ((Tstorageloc293812) 0)); } goto LA1; LA10: ; { NIM_BOOL LOC15; TY533811 LOC19; Ropeobj179006* LOC20; LOC15 = (NIM_BOOL)0; LOC15 = ((*b0).kind >= ((Tnodekind293020) 20) && (*b0).kind <= ((Tnodekind293020) 22)); if (!(LOC15)) goto LA16; LOC15 = (((*b0).kindU.S3.strval) && ((*b0).kindU.S3.strval)->Sup.len == 0); LA16: ; if (!LOC15) goto LA17; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&x0)); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_539188_839829468((&x0)); LOC19[1] = lenfield_540305_839829468(p0); LOC20 = (Ropeobj179006*)0; LOC20 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC19, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC20, ((Tstorageloc293812) 0)); } goto LA1; LA17: ; { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_401)); } LA1: ; } N_NIMCALL(void, genisnil_553620_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Ttype293840* t0; t0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind293244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention293002) 8)); LA4: ; if (!LOC3) goto LA5; unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_404)); } goto LA1; LA5: ; { unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_405)); } LA1: ; } N_NIMCALL(void, gendollar_556391_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; TY179507 LOC1; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&a0)); a0.r = ropecg_533407_839829468((*p0).module, frmt0, LOC1, 1); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA4; gettemp_538032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA4: ; genassignment_540264_839829468(p0, (&(*d0)), (&a0), 0); gcusage_555439_839829468(n0); } N_NIMCALL(Ropeobj179006*, genofhelper_556140_839829468)(Tcproc530021* p0, Ttype293840* dest0, Ropeobj179006* a0) { Ropeobj179006* result0; Ropeobj179006* ti0; result0 = (Ropeobj179006*)0; ti0 = gentypeinfo_536941_839829468((*p0).module, dest0); { NIM_BOOL LOC3; NIM_BOOL LOC5; TY533811 LOC9; LOC3 = (NIM_BOOL)0; LOC3 = (((*dest0).flags &(1U<<((NU)(((Ttypeflag293431) 2))&31U)))!=0); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = (((*(*p0).module).flags &(1U<<((NU)(((Codegenflag530025) 5))&7U)))!=0); if (!(LOC5)) goto LA6; LOC5 = !((((*dest0).flags &(1U<<((NU)(((Ttypeflag293431) 5))&31U)))!=0)); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = a0; LOC9[1] = ti0; result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_414), LOC9, 2); } goto LA1; LA7: ; { Ropeobj179006* LOC11; Ropeobj179006* cache0; Ropeobj179006* LOC12; TY179507 LOC13; TY536238 LOC14; LOC11 = (Ropeobj179006*)0; LOC11 = cgsym_533403_839829468((*p0).module, ((NimStringDesc*) &T839829468_129)); (*(*p0).module).labels += ((NI) 1); LOC12 = (Ropeobj179006*)0; LOC12 = rope_179401_2381377266(((NI64) ((*(*p0).module).labels))); cache0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_415), LOC12); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = cache0; addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_416), LOC13, 1); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = a0; LOC14[1] = ti0; LOC14[2] = cache0; result0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_417), LOC14, 3); } LA1: ; return result0; } N_NIMCALL(void, genof_556201_839829468)(Tcproc530021* p0, Tnode293802* x0, Ttype293840* typ0, Tloc293816* d0) { Tloc293816 a0; Ttype293840* dest0; Ropeobj179006* r0; Ropeobj179006* nilcheck0; Ttype293840* t0; Ttype293840* LOC41; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, x0, (&a0)); dest0 = skiptypes_297099_850551059(typ0, IL64(211106247256320)); r0 = rdloc_539188_839829468((&a0)); nilcheck0 = NIM_NIL; t0 = skiptypes_297099_850551059(a0.t, IL64(211106232576256)); { while (1) { Ttype293840* LOC16; if (!((14680064 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)) goto LA2; { if (!!(((*t0).kind == ((Ttypekind293244) 23)))) goto LA5; nilcheck0 = r0; } LA5: ; { NIM_BOOL LOC9; NIM_BOOL LOC11; TY179507 LOC15; LOC9 = (NIM_BOOL)0; LOC9 = !(((*t0).kind == ((Ttypekind293244) 23))); if (LOC9) goto LA10; LOC11 = (NIM_BOOL)0; LOC11 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC11) goto LA12; LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA12: ; LOC9 = !(LOC11); LA10: ; if (!LOC9) goto LA13; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = r0; r0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC15, 1); } LA13: ; LOC16 = (Ttype293840*)0; LOC16 = lastson_296377_850551059(t0); t0 = skiptypes_297099_850551059(LOC16, IL64(211106232576256)); } LA2: ; } { NIM_BOOL LOC19; LOC19 = (NIM_BOOL)0; LOC19 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC19) goto LA20; LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA20: ; if (!!(LOC19)) goto LA21; { while (1) { NIM_BOOL LOC25; TY534289 LOC27; Ropeobj179006* LOC28; LOC25 = (NIM_BOOL)0; LOC25 = ((*t0).kind == ((Ttypekind293244) 17)); if (!(LOC25)) goto LA26; LOC25 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); LA26: ; if (!LOC25) goto LA24; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Ropeobj179006*)0; LOC28 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_153), LOC27, 0); add_179482_2381377266(&r0, LOC28); t0 = skiptypes_297099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360)); } LA24: ; } } LA21: ; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = isobjlackingtypefield_534515_839829468(t0); if (!LOC31) goto LA32; globalerror_197071_155036129((*x0).info, ((Tmsgkind192002) 4), ((NimStringDesc*) &T839829468_412)); } LA32: ; { TY533811 LOC38; if (!!((nilcheck0 == NIM_NIL))) goto LA36; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = nilcheck0; LOC38[1] = genofhelper_556140_839829468(p0, dest0, r0); r0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_413), LOC38, 2); } goto LA34; LA36: ; { TY179507 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = genofhelper_556140_839829468(p0, dest0, r0); r0 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_418), LOC40, 1); } LA34: ; LOC41 = (Ttype293840*)0; LOC41 = getsystype_339150_3937434831(((Ttypekind293244) 1)); putintodest_551468_839829468(p0, d0, LOC41, r0, a0.s); } N_NIMCALL(void, genof_556331_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { genof_556201_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (*(*n0).kindU.S6.sons->data[((NI) 2)]).typ, d0); } N_NIMCALL(void, rawgennew_555741_839829468)(Tcproc530021* p0, Tloc293816* a0, Ropeobj179006* sizeexpr_555745_839829468) { Ropeobj179006* sizeexpr0; Ttype293840* reftype0; Tloc293816 b0; TY536238 args0; Ttype293840* bt0; sizeexpr0 = sizeexpr_555745_839829468; reftype0 = skiptypes_297099_850551059((*a0).t, IL64(211106242013440)); memset((void*)(&b0), 0, sizeof(b0)); initloc_533273_839829468((&b0), ((Tlockind293808) 6), (*a0).t, ((Tstorageloc293812) 3)); { TY179507 LOC5; Ttype293840* LOC6; if (!sizeexpr0 == 0) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (Ttype293840*)0; LOC6 = skiptypes_297099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832)); LOC5[0] = gettypedesc_536673_839829468((*p0).module, LOC6); sizeexpr0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_419), LOC5, 1); } LA3: ; memset((void*)args0, 0, sizeof(args0)); args0[0] = gettypedesc_536673_839829468((*p0).module, reftype0); args0[1] = gentypeinfo_536941_839829468((*p0).module, reftype0); args0[2] = sizeexpr0; { NIM_BOOL LOC9; TY533811 LOC21; LOC9 = (NIM_BOOL)0; LOC9 = ((*a0).s == ((Tstorageloc293812) 3)); if (!(LOC9)) goto LA10; LOC9 = usesnativegc_170177_2607990831(); LA10: ; if (!LOC9) goto LA11; { NIM_BOOL LOC15; TY179507 LOC18; LOC15 = (NIM_BOOL)0; LOC15 = canformacycle_321123_3876443242((*a0).t); if (!LOC15) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_539188_839829468(a0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_420), LOC18, 1); } goto LA13; LA16: ; { TY179507 LOC20; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rdloc_539188_839829468(a0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_255), LOC20, 1); } LA13: ; b0.r = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_421), args0, 3); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdloc_539188_839829468(a0); LOC21[1] = rdloc_539188_839829468((&b0)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC21, 2); } goto LA7; LA11: ; { b0.r = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_422), args0, 3); genassignment_540264_839829468(p0, a0, (&b0), 0); } LA7: ; bt0 = skiptypes_297099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832)); genobjectinit_539242_839829468(p0, ((Tcprocsection530011) 2), bt0, a0, NIM_FALSE); } N_NIMCALL(void, gennew_555782_839829468)(Tcproc530021* p0, Tnode293802* e0) { Tloc293816 a0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); { NI LOC3; Tloc293816 se0; Ropeobj179006* LOC6; LOC3 = (NI)0; LOC3 = len_294081_850551059(e0); if (!(LOC3 == ((NI) 3))) goto LA4; memset((void*)(&se0), 0, sizeof(se0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&se0)); LOC6 = (Ropeobj179006*)0; LOC6 = rdloc_539188_839829468((&se0)); rawgennew_555741_839829468(p0, (&a0), LOC6); } goto LA1; LA4: ; { rawgennew_555741_839829468(p0, (&a0), NIM_NIL); } LA1: ; gcusage_555439_839829468(e0); } N_NIMCALL(void, gennewfinalize_556111_839829468)(Tcproc530021* p0, Tnode293802* e0) { Tloc293816 a0; Tloc293816 b0; Tloc293816 f0; Ttype293840* reftype0; Ttype293840* bt0; Ropeobj179006* ti0; TY533811 LOC1; TY536238 LOC2; Ttype293840* LOC3; Ttype293840* LOC4; Ttype293840* LOC5; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&f0), 0, sizeof(f0)); reftype0 = (Ttype293840*)0; bt0 = (Ttype293840*)0; ti0 = (Ropeobj179006*)0; reftype0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&f0)); initloc_533273_839829468((&b0), ((Tlockind293808) 6), a0.t, ((Tstorageloc293812) 3)); ti0 = gentypeinfo_536941_839829468((*p0).module, reftype0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = ti0; LOC1[1] = rdloc_539188_839829468((&f0)); addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 14))- 0], ((NimStringDesc*) &T839829468_423), LOC1, 2); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = gettypedesc_536673_839829468((*p0).module, reftype0); LOC2[1] = ti0; LOC3 = (Ttype293840*)0; LOC3 = lastson_296377_850551059(reftype0); LOC4 = (Ttype293840*)0; LOC4 = skiptypes_297099_850551059(LOC3, IL64(211106233624832)); LOC2[2] = gettypedesc_536673_839829468((*p0).module, LOC4); b0.r = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_424), LOC2, 3); genassignment_540264_839829468(p0, (&a0), (&b0), 0); LOC5 = (Ttype293840*)0; LOC5 = lastson_296377_850551059(reftype0); bt0 = skiptypes_297099_850551059(LOC5, IL64(211106233624832)); genobjectinit_539242_839829468(p0, ((Tcprocsection530011) 2), bt0, (&a0), NIM_FALSE); gcusage_555439_839829468(e0); } N_NIMCALL(void, gennewseqaux_555795_839829468)(Tcproc530021* p0, Tloc293816* dest0, Ropeobj179006* length0) { Ttype293840* seqtype0; TY536238 args0; Tloc293816 call0; seqtype0 = skiptypes_297099_850551059((*dest0).t, IL64(211106242013440)); memset((void*)args0, 0, sizeof(args0)); args0[0] = gettypedesc_536673_839829468((*p0).module, seqtype0); args0[1] = gentypeinfo_536941_839829468((*p0).module, seqtype0); args0[2] = length0; memset((void*)(&call0), 0, sizeof(call0)); initloc_533273_839829468((&call0), ((Tlockind293808) 6), (*dest0).t, ((Tstorageloc293812) 3)); { NIM_BOOL LOC3; TY533811 LOC15; LOC3 = (NIM_BOOL)0; LOC3 = ((*dest0).s == ((Tstorageloc293812) 3)); if (!(LOC3)) goto LA4; LOC3 = usesnativegc_170177_2607990831(); LA4: ; if (!LOC3) goto LA5; { NIM_BOOL LOC9; TY179507 LOC12; LOC9 = (NIM_BOOL)0; LOC9 = canformacycle_321123_3876443242((*dest0).t); if (!LOC9) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_539188_839829468(dest0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_420), LOC12, 1); } goto LA7; LA10: ; { TY179507 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_539188_839829468(dest0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_255), LOC14, 1); } LA7: ; call0.r = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_425), args0, 3); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = rdloc_539188_839829468(dest0); LOC15[1] = rdloc_539188_839829468((&call0)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC15, 2); } goto LA1; LA5: ; { call0.r = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_426), args0, 3); genassignment_540264_839829468(p0, dest0, (&call0), 0); } LA1: ; } N_NIMCALL(void, gennewseq_555824_839829468)(Tcproc530021* p0, Tnode293802* e0) { Tloc293816 a0; Tloc293816 b0; Ropeobj179006* LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); LOC1 = (Ropeobj179006*)0; LOC1 = rdloc_539188_839829468((&b0)); gennewseqaux_555795_839829468(p0, (&a0), LOC1); gcusage_555439_839829468(e0); } N_NIMCALL(void, gennewseqofcap_555836_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Ttype293840* seqtype0; Tloc293816 a0; TY536238 LOC1; Ropeobj179006* LOC2; seqtype0 = skiptypes_297099_850551059((*e0).typ, IL64(211106242013440)); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = gettypedesc_536673_839829468((*p0).module, seqtype0); LOC1[1] = gentypeinfo_536941_839829468((*p0).module, seqtype0); LOC1[2] = rdloc_539188_839829468((&a0)); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_427), LOC1, 3); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc293812) 0)); gcusage_555439_839829468(e0); } N_NIMCALL(Ropeobj179006*, getclosuretype_536685_839829468)(Tcgen530027* m0, Ttype293840* t0, Tclosuretypekind536681 kind0) { Ropeobj179006* result0; Intset269030 check0; Ropeobj179006* rettype0; Ropeobj179006* desc0; result0 = (Ropeobj179006*)0; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_269885_2627731572((&check0)); result0 = gettempname_534598_839829468(m0); rettype0 = (Ropeobj179006*)0; desc0 = (Ropeobj179006*)0; genprocparams_535115_839829468(m0, t0, &rettype0, &desc0, (&check0), !((kind0 == ((Tclosuretypekind536681) 0))), NIM_FALSE); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isimportedtype_534451_839829468(t0); if (!!(LOC3)) goto LA4; { NIM_BOOL LOC8; TY536235 LOC12; LOC8 = (NIM_BOOL)0; LOC8 = !(((*t0).callconv == ((Tcallingconvention293002) 8))); if (LOC8) goto LA9; LOC8 = !((kind0 == ((Tclosuretypekind536681) 2))); LA9: ; if (!LOC8) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_179277_2381377266(Callingconvtostr_534587_839829468[((*t0).callconv)- 0]); LOC12[1] = rettype0; LOC12[2] = result0; LOC12[3] = desc0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC12, 4); } goto LA6; LA10: ; { TY536238 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = result0; LOC14[1] = rettype0; LOC14[2] = desc0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC14, 3); } LA6: ; } LA4: ; return result0; } N_NIMCALL(void, gensomecast_557481_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Ttype293840* etyp0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); etyp0 = skiptypes_297099_850551059((*e0).typ, IL64(211106233624832)); { NIM_BOOL LOC3; TY533811 LOC7; Ropeobj179006* LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((IL64(281475111387152) &((NU64)1<<((NU)((*etyp0).kind)&63U)))!=0); if (!(LOC3)) goto LA4; LOC3 = !(((a0.flags &(1U<<((NU)(((Tlocflag293810) 0))&15U)))!=0)); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_536673_839829468((*p0).module, (*e0).typ); LOC7[1] = addrloc_539204_839829468((&a0)); LOC8 = (Ropeobj179006*)0; LOC8 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_429), LOC7, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC8, a0.s); } goto LA1; LA5: ; { NIM_BOOL LOC10; TY533811 LOC14; Ropeobj179006* LOC15; LOC10 = (NIM_BOOL)0; LOC10 = ((*etyp0).kind == ((Ttypekind293244) 25)); if (!(LOC10)) goto LA11; LOC10 = ((*etyp0).callconv == ((Tcallingconvention293002) 8)); LA11: ; if (!LOC10) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = getclosuretype_536685_839829468((*p0).module, etyp0, ((Tclosuretypekind536681) 1)); LOC14[1] = rdcharloc_539227_839829468((&a0)); LOC15 = (Ropeobj179006*)0; LOC15 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_430), LOC14, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC15, a0.s); } goto LA1; LA12: ; { TY533811 LOC17; Ropeobj179006* LOC18; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_536673_839829468((*p0).module, (*e0).typ); LOC17[1] = rdcharloc_539227_839829468((&a0)); LOC18 = (Ropeobj179006*)0; LOC18 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_430), LOC17, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC18, a0.s); } LA1: ; } N_NIMCALL(void, unaryexprchar_552222_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; TY179507 LOC1; Ropeobj179006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdcharloc_539227_839829468((&a0)); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, frmt0, LOC1, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc293812) 0)); } N_NIMCALL(void, genord_557475_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { unaryexprchar_552222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_301)); } N_NIMCALL(void, genarraylen_556415_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0) { Tnode293802* a0; Ttype293840* typ0; a0 = (*e0).kindU.S6.sons->data[((NI) 1)]; { if (!((*a0).kind == ((Tnodekind293020) 64))) goto LA3; a0 = (*a0).kindU.S6.sons->data[((NI) 0)]; } LA3: ; typ0 = skiptypes_297099_850551059((*a0).typ, IL64(211106240964864)); switch ((*typ0).kind) { case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { { if (!(op0 == ((Tmagic293524) 8))) goto LA8; unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_431)); } goto LA6; LA8: ; { unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_432)); } LA6: ; } break; case ((Ttypekind293244) 29): { usestringh_533345_839829468((*p0).module); { if (!(op0 == ((Tmagic293524) 8))) goto LA14; unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_433)); } goto LA12; LA14: ; { unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_434)); } LA12: ; } break; case ((Ttypekind293244) 28): case ((Ttypekind293244) 24): { { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC20) goto LA21; LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA21: ; if (!!(LOC20)) goto LA22; { if (!(op0 == ((Tmagic293524) 8))) goto LA26; unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_435)); } goto LA24; LA26: ; { unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_436)); } LA24: ; } goto LA18; LA22: ; { { if (!(op0 == ((Tmagic293524) 8))) goto LA32; unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_437)); } goto LA30; LA32: ; { unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_438)); } LA30: ; } LA18: ; } break; case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { { NI64 LOC40; Ropeobj179006* LOC41; if (!(op0 == ((Tmagic293524) 8))) goto LA38; LOC40 = (NI64)0; LOC40 = lastord_321004_3876443242(typ0); LOC41 = (Ropeobj179006*)0; LOC41 = rope_179401_2381377266(LOC40); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC41, ((Tstorageloc293812) 0)); } goto LA36; LA38: ; { NI64 LOC43; Ropeobj179006* LOC44; LOC43 = (NI64)0; LOC43 = lengthord_321007_3876443242(typ0); LOC44 = (Ropeobj179006*)0; LOC44 = rope_179401_2381377266(LOC43); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC44, ((Tstorageloc293812) 0)); } LA36: ; } break; default: { internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_439)); } break; } } N_NIMCALL(void, unarystmt_551527_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; TY179507 LOC5; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind293808) 0)))) goto LA3; internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_442)); } LA3: ; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468((&a0)); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), frmt0, LOC5, 1); } N_NIMCALL(void, gensetlengthstr_556632_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { binarystmt_551501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_445)); gcusage_555439_839829468(e0); } N_NIMCALL(void, gensetlengthseq_556500_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Ttype293840* t0; NimStringDesc* setlenpattern0; TY536235 LOC8; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); t0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; setlenpattern0 = copyString(((NimStringDesc*) &T839829468_446)); } goto LA1; LA5: ; { setlenpattern0 = copyString(((NimStringDesc*) &T839829468_447)); } LA1: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_539188_839829468((&a0)); LOC8[1] = rdloc_539188_839829468((&b0)); LOC8[2] = gettypedesc_536673_839829468((*p0).module, t0); LOC8[3] = gettypedesc_536673_839829468((*p0).module, (*t0).sons->data[((NI) 0)]); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), setlenpattern0, LOC8, 4); gcusage_555439_839829468(e0); } N_NIMCALL(Ropeobj179006*, rdsetelemloc_556662_839829468)(Tloc293816* a0, Ttype293840* settype0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = rdcharloc_539227_839829468(a0); { NI64 LOC3; TY533811 LOC6; NI64 LOC7; LOC3 = (NI64)0; LOC3 = firstord_321001_3876443242(settype0); if (!!((LOC3 == IL64(0)))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = result0; LOC7 = (NI64)0; LOC7 = firstord_321001_3876443242(settype0); LOC6[1] = rope_179401_2381377266(LOC7); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_448), LOC6, 2); } LA4: ; return result0; } N_NIMCALL(void, binarystmtinexcl_556858_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; Tloc293816 b0; TY533811 LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&a0)); LOC1[1] = rdsetelemloc_556662_839829468((&b0), a0.t); linef_533700_839829468(p0, ((Tcprocsection530011) 2), frmt0, LOC1, 2); } N_NIMCALL(void, binaryexprchar_551809_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NimStringDesc* frmt0) { Tloc293816 a0; Tloc293816 b0; TY533811 LOC1; Ropeobj179006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdcharloc_539227_839829468((&a0)); LOC1[1] = rdcharloc_539227_839829468((&b0)); LOC2 = (Ropeobj179006*)0; LOC2 = ropecg_533407_839829468((*p0).module, frmt0, LOC1, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc293812) 0)); } N_NIMCALL(NIM_BOOL, fewcmps_556803_839829468)(Tnode293802* s0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { if (!!(((*s0).kind == ((Tnodekind293020) 39)))) goto LA3; internalerror_197100_155036129((*s0).info, ((NimStringDesc*) &T839829468_463)); } LA3: ; { NIM_BOOL LOC7; NI64 LOC8; LOC7 = (NIM_BOOL)0; LOC8 = (NI64)0; LOC8 = getsize_321135_3876443242((*s0).typ); LOC7 = (LOC8 <= ((NI64) (intsize_177641_4151366050))); if (!(LOC7)) goto LA9; LOC7 = (((*s0).flags &(1U<<((NU)(((Tnodeflag293427) 4))&15U)))!=0); LA9: ; if (!LOC7) goto LA10; result0 = NIM_FALSE; } goto LA5; LA10: ; { Ttype293840* LOC13; LOC13 = (Ttype293840*)0; LOC13 = elemtype_321394_3876443242((*s0).typ); if (!((IL64(62277025792) &((NU64)1<<((NU)((*LOC13).kind)&63U)))!=0)) goto LA14; result0 = NIM_TRUE; } goto LA5; LA14: ; { NI LOC17; LOC17 = (NI)0; LOC17 = sonslen_296351_850551059(s0); result0 = (LOC17 <= ((NI) 8)); } LA5: ; return result0; } N_NIMCALL(void, binaryexprin_556837_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* a0, Tloc293816* b0, Tloc293816* d0, NimStringDesc* frmt0) { TY533811 LOC1; Ropeobj179006* LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&(*a0))); LOC1[1] = rdsetelemloc_556662_839829468((&(*b0)), (*a0).t); LOC2 = (Ropeobj179006*)0; LOC2 = HEX25_179905_2381377266(frmt0, LOC1, 2); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc293812) 0)); } N_NIMCALL(void, geninexpraux_554496_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* a0, Tloc293816* b0, Tloc293816* d0) { Ttype293840* LOC1; NI64 LOC2; LOC1 = (Ttype293840*)0; LOC1 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC2 = (NI64)0; LOC2 = getsize_321135_3876443242(LOC1); switch (((NI) (LOC2))) { case ((NI) 1): { binaryexprin_556837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_467)); } break; case ((NI) 2): { binaryexprin_556837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_468)); } break; case ((NI) 4): { binaryexprin_556837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_469)); } break; case ((NI) 8): { binaryexprin_556837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_470)); } break; default: { binaryexprin_556837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_471)); } break; } } N_NIMCALL(void, geninop_557009_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Tloc293816 x0; Tloc293816 y0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&x0), 0, sizeof(x0)); memset((void*)(&y0), 0, sizeof(y0)); { NIM_BOOL LOC3; Tnode293802* ea0; NI length0; LOC3 = (NIM_BOOL)0; LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind293020) 39)); if (!(LOC3)) goto LA4; LOC3 = fewcmps_556803_839829468((*e0).kindU.S6.sons->data[((NI) 1)]); LA4: ; if (!LOC3) goto LA5; { if (!((*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind293020) 70) || (*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind293020) 69))) goto LA9; ea0 = (*(*e0).kindU.S6.sons->data[((NI) 2)]).kindU.S6.sons->data[((NI) 0)]; } goto LA7; LA9: ; { ea0 = (*e0).kindU.S6.sons->data[((NI) 2)]; } LA7: ; initlocexpr_540283_839829468(p0, ea0, (&a0)); initloc_533273_839829468((&b0), ((Tlockind293808) 6), (*e0).typ, ((Tstorageloc293812) 0)); b0.r = rope_179277_2381377266(((NimStringDesc*) &T839829468_118)); length0 = sonslen_296351_850551059((*e0).kindU.S6.sons->data[((NI) 1)]); { NI i_557061_839829468; NI HEX3Atmp_557412_839829468; NI res_557415_839829468; i_557061_839829468 = (NI)0; HEX3Atmp_557412_839829468 = (NI)0; HEX3Atmp_557412_839829468 = (NI)(length0 - ((NI) 1)); res_557415_839829468 = ((NI) 0); { while (1) { if (!(res_557415_839829468 <= HEX3Atmp_557412_839829468)) goto LA14; i_557061_839829468 = res_557415_839829468; { TY536238 LOC19; if (!((*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_557061_839829468]).kind == ((Tnodekind293020) 44))) goto LA17; initlocexpr_540283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_557061_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0)); initlocexpr_540283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_557061_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0)); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdcharloc_539227_839829468((&a0)); LOC19[1] = rdcharloc_539227_839829468((&x0)); LOC19[2] = rdcharloc_539227_839829468((&y0)); addf_180205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_464), LOC19, 3); } goto LA15; LA17: ; { TY533811 LOC21; initlocexpr_540283_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_557061_839829468], (&x0)); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdcharloc_539227_839829468((&a0)); LOC21[1] = rdcharloc_539227_839829468((&x0)); addf_180205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_465), LOC21, 2); } LA15: ; { if (!(i_557061_839829468 < (NI)(length0 - ((NI) 1)))) goto LA24; add_179487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_466)); } LA24: ; res_557415_839829468 += ((NI) 1); } LA14: ; } } add_179487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_117)); putintodest_551468_839829468(p0, d0, (*e0).typ, b0.r, ((Tstorageloc293812) 0)); } goto LA1; LA5: ; { initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); geninexpraux_554496_839829468(p0, e0, (&a0), (&b0), d0); } LA1: ; } N_NIMCALL(void, gensetop_557419_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0) { Tloc293816 a0; Tloc293816 b0; Tloc293816 i0; Ttype293840* settype0; NI size0; NI64 LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&i0), 0, sizeof(i0)); settype0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC1 = (NI64)0; LOC1 = getsize_321135_3876443242(settype0); size0 = ((NI) (LOC1)); switch (size0) { case ((NI) 1): case ((NI) 2): case ((NI) 4): case ((NI) 8): { switch (op0) { case ((Tmagic293524) 39): { NimStringDesc* ts0; NimStringDesc* LOC4; NimStringDesc* LOC5; NimStringDesc* LOC6; LOC4 = (NimStringDesc*)0; LOC5 = (NimStringDesc*)0; LOC5 = nimIntToStr((NI)(size0 * ((NI) 8))); LOC4 = rawNewString(LOC5->Sup.len + 2); appendString(LOC4, ((NimStringDesc*) &T839829468_45)); appendString(LOC4, LOC5); ts0 = LOC4; LOC6 = (NimStringDesc*)0; LOC6 = rawNewString(ts0->Sup.len + ts0->Sup.len + 35); appendString(LOC6, ((NimStringDesc*) &T839829468_449)); appendString(LOC6, ts0); appendString(LOC6, ((NimStringDesc*) &T839829468_450)); appendString(LOC6, ts0); appendString(LOC6, ((NimStringDesc*) &T839829468_451)); binarystmtinexcl_556858_839829468(p0, e0, d0, LOC6); } break; case ((Tmagic293524) 40): { NimStringDesc* ts0; NimStringDesc* LOC8; NimStringDesc* LOC9; NimStringDesc* LOC10; LOC8 = (NimStringDesc*)0; LOC9 = (NimStringDesc*)0; LOC9 = nimIntToStr((NI)(size0 * ((NI) 8))); LOC8 = rawNewString(LOC9->Sup.len + 2); appendString(LOC8, ((NimStringDesc*) &T839829468_45)); appendString(LOC8, LOC9); ts0 = LOC8; LOC10 = (NimStringDesc*)0; LOC10 = rawNewString(ts0->Sup.len + ts0->Sup.len + 42); appendString(LOC10, ((NimStringDesc*) &T839829468_452)); appendString(LOC10, ts0); appendString(LOC10, ((NimStringDesc*) &T839829468_453)); appendString(LOC10, ts0); appendString(LOC10, ((NimStringDesc*) &T839829468_454)); binarystmtinexcl_556858_839829468(p0, e0, d0, LOC10); } break; case ((Tmagic293524) 41): { { if (!(size0 <= ((NI) 4))) goto LA14; unaryexprchar_552222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_455)); } goto LA12; LA14: ; { unaryexprchar_552222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_456)); } LA12: ; } break; case ((Tmagic293524) 133): { binaryexprchar_551809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_457)); } break; case ((Tmagic293524) 132): { binaryexprchar_551809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_458)); } break; case ((Tmagic293524) 131): { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341)); } break; case ((Tmagic293524) 134): { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_459)); } break; case ((Tmagic293524) 135): { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_460)); } break; case ((Tmagic293524) 136): { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_461)); } break; case ((Tmagic293524) 137): { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_462)); } break; case ((Tmagic293524) 148): { geninop_557009_839829468(p0, e0, d0); } break; default: { internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_472)); } break; } } break; default: { switch (op0) { case ((Tmagic293524) 39): { binarystmtinexcl_556858_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_473)); } break; case ((Tmagic293524) 40): { binarystmtinexcl_556858_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_474)); } break; case ((Tmagic293524) 41): { NimStringDesc* LOC30; NimStringDesc* LOC31; LOC30 = (NimStringDesc*)0; LOC31 = (NimStringDesc*)0; LOC31 = nimIntToStr(size0); LOC30 = rawNewString(LOC31->Sup.len + 14); appendString(LOC30, ((NimStringDesc*) &T839829468_475)); appendString(LOC30, LOC31); appendChar(LOC30, 41); unaryexprchar_552222_839829468(p0, e0, d0, LOC30); } break; case ((Tmagic293524) 133): case ((Tmagic293524) 132): { Ttype293840* LOC33; TY537475 LOC39; LOC33 = (Ttype293840*)0; LOC33 = getsystype_339150_3937434831(((Ttypekind293244) 31)); gettemp_538032_839829468(p0, LOC33, (&i0), NIM_FALSE); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { Ttype293840* LOC38; if (!((*d0).k == ((Tlockind293808) 0))) goto LA36; LOC38 = (Ttype293840*)0; LOC38 = getsystype_339150_3937434831(((Ttypekind293244) 1)); gettemp_538032_839829468(p0, LOC38, d0, NIM_FALSE); } LA36: ; memset((void*)LOC39, 0, sizeof(LOC39)); LOC39[0] = rdloc_539188_839829468((&i0)); LOC39[1] = rope_179401_2381377266(((NI64) (size0))); LOC39[2] = rdloc_539188_839829468((&(*d0))); LOC39[3] = rdloc_539188_839829468((&a0)); LOC39[4] = rdloc_539188_839829468((&b0)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), lookupopr_557426_839829468[(op0)- 132], LOC39, 5); } break; case ((Tmagic293524) 131): { NimStringDesc* LOC41; NimStringDesc* LOC42; usestringh_533345_839829468((*p0).module); LOC41 = (NimStringDesc*)0; LOC42 = (NimStringDesc*)0; LOC42 = nimIntToStr(size0); LOC41 = rawNewString(LOC42->Sup.len + 21); appendString(LOC41, ((NimStringDesc*) &T839829468_481)); appendString(LOC41, LOC42); appendString(LOC41, ((NimStringDesc*) &T839829468_482)); binaryexprchar_551809_839829468(p0, e0, d0, LOC41); } break; case ((Tmagic293524) 134): case ((Tmagic293524) 135): case ((Tmagic293524) 136): case ((Tmagic293524) 137): { Ttype293840* LOC44; TY537847 LOC49; LOC44 = (Ttype293840*)0; LOC44 = getsystype_339150_3937434831(((Ttypekind293244) 31)); gettemp_538032_839829468(p0, LOC44, (&i0), NIM_FALSE); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA47; gettemp_538032_839829468(p0, a0.t, d0, NIM_FALSE); } LA47: ; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_539188_839829468((&i0)); LOC49[1] = rope_179401_2381377266(((NI64) (size0))); LOC49[2] = rdloc_539188_839829468((&(*d0))); LOC49[3] = rdloc_539188_839829468((&a0)); LOC49[4] = rdloc_539188_839829468((&b0)); LOC49[5] = rope_179277_2381377266(lookupopr_557426_839829468[(op0)- 132]); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_483), LOC49, 6); } break; case ((Tmagic293524) 148): { geninop_557009_839829468(p0, e0, d0); } break; default: { internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_484)); } break; } } break; } } static N_INLINE(Ropeobj179006*, genargstringtocstring_540776_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; Tloc293816 a0; TY179507 LOC1; result0 = (Ropeobj179006*)0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&a0)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_485), LOC1, 1); return result0; } N_NIMCALL(Ropeobj179006*, openarrayloc_540665_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; Tloc293816 a0; Tnode293802* q0; result0 = (Ropeobj179006*)0; memset((void*)(&a0), 0, sizeof(a0)); q0 = skipconv_329882_3876443242(n0); { Tmagic293524 LOC3; Tloc293816 b0; Tloc293816 c0; Tnode293802* LOC6; Tnode293802* LOC7; Tnode293802* LOC8; NimStringDesc* fmt0; Ttype293840* LOC9; TY536238 LOC25; LOC3 = (Tmagic293524)0; LOC3 = getmagic_319502_2616423590(q0); if (!(LOC3 == ((Tmagic293524) 139))) goto LA4; memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&c0), 0, sizeof(c0)); LOC6 = (Tnode293802*)0; LOC6 = HEX5BHEX5D_294238_850551059(q0, ((NI) 1)); initlocexpr_540283_839829468(p0, LOC6, (&a0)); LOC7 = (Tnode293802*)0; LOC7 = HEX5BHEX5D_294238_850551059(q0, ((NI) 2)); initlocexpr_540283_839829468(p0, LOC7, (&b0)); LOC8 = (Tnode293802*)0; LOC8 = HEX5BHEX5D_294238_850551059(q0, ((NI) 3)); initlocexpr_540283_839829468(p0, LOC8, (&c0)); LOC9 = (Ttype293840*)0; LOC9 = skiptypes_297099_850551059(a0.t, IL64(211106243062016)); switch ((*LOC9).kind) { case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { fmt0 = copyString(((NimStringDesc*) &T839829468_486)); } break; case ((Ttypekind293244) 28): case ((Ttypekind293244) 24): { { NIM_BOOL LOC14; Ttype293840* LOC15; NIM_BOOL LOC17; LOC14 = (NIM_BOOL)0; LOC15 = (Ttype293840*)0; LOC15 = skiptypes_297099_850551059((*n0).typ, IL64(211106232576256)); LOC14 = ((*LOC15).kind == ((Ttypekind293244) 23)); if (!(LOC14)) goto LA16; LOC17 = (NIM_BOOL)0; LOC17 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC17) goto LA18; LOC17 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA18: ; LOC14 = !(LOC17); LA16: ; if (!LOC14) goto LA19; fmt0 = copyString(((NimStringDesc*) &T839829468_487)); } goto LA12; LA19: ; { fmt0 = copyString(((NimStringDesc*) &T839829468_488)); } LA12: ; } break; default: { NimStringDesc* LOC23; NimStringDesc* LOC24; LOC23 = (NimStringDesc*)0; LOC24 = (NimStringDesc*)0; LOC24 = typetostring_321017_3876443242(a0.t, ((Tprefereddesc321011) 0)); LOC23 = rawNewString(LOC24->Sup.len + 14); appendString(LOC23, ((NimStringDesc*) &T839829468_489)); appendString(LOC23, LOC24); internalerror_197113_155036129(LOC23); fmt0 = copyString(((NimStringDesc*) &T839829468_490)); } break; } memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = rdloc_539188_839829468((&a0)); LOC25[1] = rdloc_539188_839829468((&b0)); LOC25[2] = rdloc_539188_839829468((&c0)); result0 = HEX25_179905_2381377266(fmt0, LOC25, 3); } goto LA1; LA4: ; { Ttype293840* LOC27; initlocexpr_540283_839829468(p0, n0, (&a0)); LOC27 = (Ttype293840*)0; LOC27 = skiptypes_297099_850551059(a0.t, IL64(211106240964864)); switch ((*LOC27).kind) { case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { TY179507 LOC29; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdloc_539188_839829468((&a0)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_378), LOC29, 1); } break; case ((Ttypekind293244) 28): case ((Ttypekind293244) 24): { { NIM_BOOL LOC33; Ttype293840* LOC34; NIM_BOOL LOC36; TY533811 LOC40; LOC33 = (NIM_BOOL)0; LOC34 = (Ttype293840*)0; LOC34 = skiptypes_297099_850551059((*n0).typ, IL64(211106232576256)); LOC33 = ((*LOC34).kind == ((Ttypekind293244) 23)); if (!(LOC33)) goto LA35; LOC36 = (NIM_BOOL)0; LOC36 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC36) goto LA37; LOC36 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA37: ; LOC33 = !(LOC36); LA35: ; if (!LOC33) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = rdloc_539188_839829468((&a0)); LOC40[1] = lenfield_540305_839829468(p0); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_491), LOC40, 2); } goto LA31; LA38: ; { TY533811 LOC42; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = rdloc_539188_839829468((&a0)); LOC42[1] = lenfield_540305_839829468(p0); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_379), LOC42, 2); } LA31: ; } break; case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { TY533811 LOC44; NI64 LOC45; memset((void*)LOC44, 0, sizeof(LOC44)); LOC44[0] = rdloc_539188_839829468((&a0)); LOC45 = (NI64)0; LOC45 = lengthord_321007_3876443242(a0.t); LOC44[1] = rope_179401_2381377266(LOC45); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_380), LOC44, 2); } break; case ((Ttypekind293244) 21): case ((Ttypekind293244) 22): { Ttype293840* LOC47; LOC47 = (Ttype293840*)0; LOC47 = lastson_296377_850551059(a0.t); switch ((*LOC47).kind) { case ((Ttypekind293244) 28): case ((Ttypekind293244) 24): { TY533811 LOC49; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_539188_839829468((&a0)); LOC49[1] = lenfield_540305_839829468(p0); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_491), LOC49, 2); } break; case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { TY533811 LOC51; Ttype293840* LOC52; NI64 LOC53; memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = rdloc_539188_839829468((&a0)); LOC52 = (Ttype293840*)0; LOC52 = lastson_296377_850551059(a0.t); LOC53 = (NI64)0; LOC53 = lengthord_321007_3876443242(LOC52); LOC51[1] = rope_179401_2381377266(LOC53); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_380), LOC51, 2); } break; default: { NimStringDesc* LOC55; NimStringDesc* LOC56; LOC55 = (NimStringDesc*)0; LOC56 = (NimStringDesc*)0; LOC56 = typetostring_321017_3876443242(a0.t, ((Tprefereddesc321011) 0)); LOC55 = rawNewString(LOC56->Sup.len + 14); appendString(LOC55, ((NimStringDesc*) &T839829468_489)); appendString(LOC55, LOC56); internalerror_197113_155036129(LOC55); } break; } } break; default: { NimStringDesc* LOC58; NimStringDesc* LOC59; LOC58 = (NimStringDesc*)0; LOC59 = (NimStringDesc*)0; LOC59 = typetostring_321017_3876443242(a0.t, ((Tprefereddesc321011) 0)); LOC58 = rawNewString(LOC59->Sup.len + 14); appendString(LOC58, ((NimStringDesc*) &T839829468_489)); appendString(LOC58, LOC59); internalerror_197113_155036129(LOC58); } break; } } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, genarg_540787_839829468)(Tcproc530021* p0, Tnode293802* n_540790_839829468, Tsym293834* param0, Tnode293802* call0) { Ropeobj179006* result0; Tloc293816 a0; result0 = (Ropeobj179006*)0; memset((void*)(&a0), 0, sizeof(a0)); { if (!((*n_540790_839829468).kind == ((Tnodekind293020) 71))) goto LA3; result0 = genargstringtocstring_540776_839829468(p0, n_540790_839829468); } goto LA1; LA3: ; { Ttype293840* LOC6; Tnode293802* n0; LOC6 = (Ttype293840*)0; LOC6 = skiptypes_297099_850551059((*param0).typ, IL64(211106240964864)); if (!((IL64(281475110928384) &((NU64)1<<((NU)((*LOC6).kind)&63U)))!=0)) goto LA7; { if (!!(((*n_540790_839829468).kind == ((Tnodekind293020) 64)))) goto LA11; n0 = n_540790_839829468; } goto LA9; LA11: ; { n0 = (*n_540790_839829468).kindU.S6.sons->data[((NI) 0)]; } LA9: ; result0 = openarrayloc_540665_839829468(p0, n0); } goto LA1; LA7: ; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = ccgintroducedptr_534611_839829468(param0); if (!LOC15) goto LA16; initlocexpr_540283_839829468(p0, n_540790_839829468, (&a0)); result0 = addrloc_539204_839829468((&a0)); } goto LA1; LA16: ; { NIM_BOOL LOC19; NIM_BOOL LOC20; NIM_BOOL LOC21; Tnode293802* callee0; LOC19 = (NIM_BOOL)0; LOC20 = (NIM_BOOL)0; LOC21 = (NIM_BOOL)0; LOC21 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC21) goto LA22; LOC21 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA22: ; LOC20 = LOC21; if (!(LOC20)) goto LA23; LOC20 = ((*(*param0).typ).kind == ((Ttypekind293244) 23)); LA23: ; LOC19 = LOC20; if (!(LOC19)) goto LA24; LOC19 = ((*n_540790_839829468).kind == ((Tnodekind293020) 64)); LA24: ; if (!LOC19) goto LA25; initlocexprsingleuse_540289_839829468(p0, (*n_540790_839829468).kindU.S6.sons->data[((NI) 0)], (&a0)); callee0 = (*call0).kindU.S6.sons->data[((NI) 0)]; { NIM_BOOL LOC29; NIM_BOOL LOC30; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((*callee0).kind == ((Tnodekind293020) 3)); if (!(LOC30)) goto LA31; LOC30 = ((134283296 & (*(*callee0).kindU.S4.sym).flags) == 32); LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA32; LOC29 = !(((72 & (*(*callee0).kindU.S4.sym).loc.flags) == 0)); LA32: ; if (!LOC29) goto LA33; result0 = addrloc_539204_839829468((&a0)); } goto LA27; LA33: ; { result0 = rdloc_539188_839829468((&a0)); } LA27: ; } goto LA1; LA25: ; { initlocexprsingleuse_540289_839829468(p0, n_540790_839829468, (&a0)); result0 = rdloc_539188_839829468((&a0)); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, genargnoparam_540938_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; Tloc293816 a0; result0 = (Ropeobj179006*)0; memset((void*)(&a0), 0, sizeof(a0)); { if (!((*n0).kind == ((Tnodekind293020) 71))) goto LA3; result0 = genargstringtocstring_540776_839829468(p0, n0); } goto LA1; LA3: ; { initlocexprsingleuse_540289_839829468(p0, n0, (&a0)); result0 = rdloc_539188_839829468((&a0)); } LA1: ; return result0; } N_NIMCALL(Ropeobj179006*, getrawproctype_541459_839829468)(Tcproc530021* p0, Ttype293840* t0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = getclosuretype_536685_839829468((*p0).module, t0, ((Tclosuretypekind536681) 0)); return result0; } N_NIMCALL(NIM_BOOL, leftappearsonrightside_540329_839829468)(Tnode293802* le0, Tnode293802* ri0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!!((le0 == NIM_NIL))) goto LA3; { NI i_540364_839829468; NI HEX3Atmp_540376_839829468; NI LOC6; NI res_540379_839829468; i_540364_839829468 = (NI)0; HEX3Atmp_540376_839829468 = (NI)0; LOC6 = (NI)0; LOC6 = len_294081_850551059(ri0); HEX3Atmp_540376_839829468 = (LOC6 - 1); res_540379_839829468 = ((NI) 1); { while (1) { Tnode293802* r0; if (!(res_540379_839829468 <= HEX3Atmp_540376_839829468)) goto LA8; i_540364_839829468 = res_540379_839829468; r0 = HEX5BHEX5D_294238_850551059(ri0, i_540364_839829468); { Tanalysisresult474003 LOC11; LOC11 = (Tanalysisresult474003)0; LOC11 = ispartof_474340_788060399(le0, r0); if (!!((LOC11 == ((Tanalysisresult474003) 0)))) goto LA12; result0 = NIM_TRUE; goto BeforeRet; } LA12: ; res_540379_839829468 += ((NI) 1); } LA8: ; } } } LA3: ; }BeforeRet: ; return result0; } static N_INLINE(NIM_BOOL, hasnoinit_540383_839829468)(Tnode293802* call0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((*(*call0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC1)) goto LA2; LOC1 = (((*(*(*call0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, resetloc_539350_839829468)(Tcproc530021* p0, Tloc293816* loc0) { NIM_BOOL containsgcref0; Ttype293840* typ0; { containsgcref0 = containsgarbagecollectedref_321117_3876443242((*loc0).t); typ0 = skiptypes_297099_850551059((*loc0).t, IL64(211106242013440)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isimportedcpptype_534478_839829468(typ0); if (!LOC3) goto LA4; goto BeforeRet; } LA4: ; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = iscomplexvaluetype_539317_839829468(typ0); if (!!(LOC8)) goto LA9; { Tloc293816 nilloc0; if (!containsgcref0) goto LA13; memset((void*)(&nilloc0), 0, sizeof(nilloc0)); initloc_533273_839829468((&nilloc0), ((Tlockind293808) 1), (*loc0).t, ((Tstorageloc293812) 2)); nilloc0.r = rope_179277_2381377266(((NimStringDesc*) &T839829468_174)); genrefassign_539311_839829468(p0, (&(*loc0)), (&nilloc0), 8); } goto LA11; LA13: ; { TY179507 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_539188_839829468((&(*loc0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_494), LOC16, 1); } LA11: ; } goto LA6; LA9: ; { { TY179507 LOC22; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 6))&31U)))!=0)) goto LA20; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = addrloc_539204_839829468((&(*loc0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_495), LOC22, 1); } LA20: ; { TY533811 LOC27; if (!!(((*loc0).s == ((Tstorageloc293812) 2)))) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = addrloc_539204_839829468((&(*loc0))); LOC27[1] = gentypeinfo_536941_839829468((*p0).module, (*loc0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_496), LOC27, 2); genobjectinit_539242_839829468(p0, ((Tcprocsection530011) 2), (*loc0).t, (&(*loc0)), NIM_TRUE); } goto LA23; LA25: ; { TY533811 LOC29; usestringh_533345_839829468((*p0).module); memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = addrloc_539204_839829468((&(*loc0))); LOC29[1] = rdloc_539188_839829468((&(*loc0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_152), LOC29, 2); genobjectinit_539242_839829468(p0, ((Tcprocsection530011) 2), (*loc0).t, (&(*loc0)), NIM_TRUE); } LA23: ; } LA6: ; }BeforeRet: ; } N_NIMCALL(Ropeobj179006*, addcomma_541464_839829468)(Ropeobj179006* r0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { if (!(r0 == NIM_NIL)) goto LA3; result0 = r0; } goto LA1; LA3: ; { TY534289 LOC6; Ropeobj179006* LOC7; memset((void*)LOC6, 0, sizeof(LOC6)); LOC7 = (Ropeobj179006*)0; LOC7 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC6, 0); result0 = HEX26_179418_2381377266(r0, LOC7); } LA1: ; return result0; } N_NIMCALL(void, genclosurecall_541452_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0) { Tloc293816 op0; Ropeobj179006* pl0; Ttype293840* typ0; NI length0; Ropeobj179006* rawproc0; NimStringDesc* callpattern0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_540283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); pl0 = (Ropeobj179006*)0; typ0 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_296351_850551059(ri0); { NI i_541613_839829468; NI HEX3Atmp_542214_839829468; NI res_542217_839829468; i_541613_839829468 = (NI)0; HEX3Atmp_542214_839829468 = (NI)0; HEX3Atmp_542214_839829468 = (NI)(length0 - ((NI) 1)); res_542217_839829468 = ((NI) 1); { while (1) { if (!(res_542217_839829468 <= HEX3Atmp_542214_839829468)) goto LA3; i_541613_839829468 = res_542217_839829468; { NI LOC6; Tnode293802* paramtype0; LOC6 = (NI)0; LOC6 = sonslen_296327_850551059(typ0); if (!(i_541613_839829468 < LOC6)) goto LA7; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_541613_839829468]; { NIM_BOOL LOC11; Ropeobj179006* LOC20; LOC11 = (NIM_BOOL)0; LOC11 = iscompiletimeonly_329706_3876443242((*paramtype0).typ); if (!!(LOC11)) goto LA12; { TY534289 LOC18; Ropeobj179006* LOC19; if (!!((pl0 == NIM_NIL))) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (Ropeobj179006*)0; LOC19 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0); add_179482_2381377266(&pl0, LOC19); } LA16: ; LOC20 = (Ropeobj179006*)0; LOC20 = genarg_540787_839829468(p0, (*ri0).kindU.S6.sons->data[i_541613_839829468], (*paramtype0).kindU.S4.sym, ri0); add_179482_2381377266(&pl0, LOC20); } LA12: ; } goto LA4; LA7: ; { Ropeobj179006* LOC28; { TY534289 LOC26; Ropeobj179006* LOC27; if (!!((pl0 == NIM_NIL))) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC27 = (Ropeobj179006*)0; LOC27 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0); add_179482_2381377266(&pl0, LOC27); } LA24: ; LOC28 = (Ropeobj179006*)0; LOC28 = genargnoparam_540938_839829468(p0, (*ri0).kindU.S6.sons->data[i_541613_839829468]); add_179482_2381377266(&pl0, LOC28); } LA4: ; res_542217_839829468 += ((NI) 1); } LA3: ; } } rawproc0 = getrawproctype_541459_839829468(p0, typ0); { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 14))&31U)))!=0)) goto LA31; callpattern0 = copyString(((NimStringDesc*) &T839829468_492)); } goto LA29; LA31: ; { callpattern0 = copyString(((NimStringDesc*) &T839829468_493)); } LA29: ; { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA36; { NIM_BOOL LOC40; LOC40 = (NIM_BOOL)0; LOC40 = isinvalidreturntype_534550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC40) goto LA41; { NI LOC45; TY534289 LOC48; Ropeobj179006* LOC49; LOC45 = (NI)0; LOC45 = sonslen_296351_850551059(ri0); if (!(((NI) 1) < LOC45)) goto LA46; memset((void*)LOC48, 0, sizeof(LOC48)); LOC49 = (Ropeobj179006*)0; LOC49 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC48, 0); add_179482_2381377266(&pl0, LOC49); } LA46: ; { NIM_BOOL LOC52; NIM_BOOL LOC54; Ropeobj179006* LOC67; NimStringDesc* LOC68; TY536235 LOC69; LOC52 = (NIM_BOOL)0; LOC52 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0); if (LOC52) goto LA53; LOC54 = (NIM_BOOL)0; LOC54 = leftappearsonrightside_540329_839829468(le0, ri0); LOC52 = !(LOC54); LA53: ; if (!LOC52) goto LA55; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA59; gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } goto LA57; LA59: ; { NIM_BOOL LOC62; NIM_BOOL LOC64; LOC62 = (NIM_BOOL)0; LOC62 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0)); if (!(LOC62)) goto LA63; LOC64 = (NIM_BOOL)0; LOC64 = hasnoinit_540383_839829468(ri0); LOC62 = !(LOC64); LA63: ; if (!LOC62) goto LA65; resetloc_539350_839829468(p0, d0); } goto LA57; LA65: ; LA57: ; LOC67 = (Ropeobj179006*)0; LOC67 = addrloc_539204_839829468((&(*d0))); add_179482_2381377266(&pl0, LOC67); LOC68 = (NimStringDesc*)0; LOC68 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC68, callpattern0); appendString(LOC68, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC69, 0, sizeof(LOC69)); LOC69[0] = op0.r; LOC69[1] = pl0; LOC69[2] = addcomma_541464_839829468(pl0); LOC69[3] = rawproc0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), LOC68, LOC69, 4); } goto LA50; LA55: ; { Tloc293816 tmp0; Ropeobj179006* LOC71; NimStringDesc* LOC72; TY536235 LOC73; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC71 = (Ropeobj179006*)0; LOC71 = addrloc_539204_839829468((&tmp0)); add_179482_2381377266(&pl0, LOC71); LOC72 = (NimStringDesc*)0; LOC72 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC72, callpattern0); appendString(LOC72, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = op0.r; LOC73[1] = pl0; LOC73[2] = addcomma_541464_839829468(pl0); LOC73[3] = rawproc0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), LOC72, LOC73, 4); genassignment_540264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA50: ; } goto LA38; LA41: ; { Tloc293816 list0; TY536235 LOC79; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA77; gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA77: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_533273_839829468((&list0), ((Tlockind293808) 9), (*d0).t, ((Tstorageloc293812) 0)); memset((void*)LOC79, 0, sizeof(LOC79)); LOC79[0] = op0.r; LOC79[1] = pl0; LOC79[2] = addcomma_541464_839829468(pl0); LOC79[3] = rawproc0; list0.r = HEX25_179905_2381377266(callpattern0, LOC79, 4); genassignment_540264_839829468(p0, (&(*d0)), (&list0), 0); } LA38: ; } goto LA34; LA36: ; { NimStringDesc* LOC81; TY536235 LOC82; LOC81 = (NimStringDesc*)0; LOC81 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC81, callpattern0); appendString(LOC81, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC82, 0, sizeof(LOC82)); LOC82[0] = op0.r; LOC82[1] = pl0; LOC82[2] = addcomma_541464_839829468(pl0); LOC82[3] = rawproc0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), LOC81, LOC82, 4); } LA34: ; } N_NIMCALL(Ropeobj179006*, genotherarg_540277_839829468)(Tcproc530021* p0, Tnode293802* ri0, NI i0, Ttype293840* typ0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NI LOC3; Tnode293802* paramtype0; LOC3 = (NI)0; LOC3 = sonslen_296327_850551059(typ0); if (!(i0 < LOC3)) goto LA4; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i0]; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = iscompiletimeonly_329706_3876443242((*paramtype0).typ); if (!LOC8) goto LA9; result0 = NIM_NIL; } goto LA6; LA9: ; { NIM_BOOL LOC12; Tnode293802* LOC16; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*typ0).sons->data[i0]).kind == ((Ttypekind293244) 23)); if (!(LOC12)) goto LA13; LOC12 = ((*(*ri0).kindU.S6.sons->data[i0]).kind == ((Tnodekind293020) 64)); LA13: ; if (!LOC12) goto LA14; LOC16 = (Tnode293802*)0; LOC16 = HEX5BHEX5D_294238_850551059((*ri0).kindU.S6.sons->data[i0], ((NI) 0)); result0 = genargnoparam_540938_839829468(p0, LOC16); } goto LA6; LA14: ; { result0 = genargnoparam_540938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]); } LA6: ; } goto LA1; LA4: ; { { if (!!((((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 0))&31U)))!=0))) goto LA21; localerror_197085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_501)); result0 = NIM_NIL; } goto LA19; LA21: ; { result0 = genargnoparam_540938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]); } LA19: ; } LA1: ; return result0; } N_NIMCALL(Tnode293802*, skipaddrderef_542433_839829468)(Tnode293802* node0) { Tnode293802* result0; Tnode293802* n0; NIM_BOOL isaddr0; { result0 = (Tnode293802*)0; n0 = node0; isaddr0 = NIM_FALSE; switch ((*n0).kind) { case ((Tnodekind293020) 63): case ((Tnodekind293020) 64): { n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; isaddr0 = NIM_TRUE; } break; case ((Tnodekind293020) 47): case ((Tnodekind293020) 65): { n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } break; default: { result0 = n0; goto BeforeRet; } break; } { if (!((*n0).kind == ((Tnodekind293020) 66))) goto LA6; n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } LA6: ; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = isaddr0; if (!(LOC10)) goto LA11; LOC10 = ((*n0).kind == ((Tnodekind293020) 47) || (*n0).kind == ((Tnodekind293020) 65)); LA11: ; if (!LOC10) goto LA12; result0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } goto LA8; LA12: ; { if (!((*n0).kind == ((Tnodekind293020) 63) || (*n0).kind == ((Tnodekind293020) 64))) goto LA15; result0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } goto LA8; LA15: ; { result0 = node0; } LA8: ; }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj179006*, genthisarg_542475_839829468)(Tcproc530021* p0, Tnode293802* ri_542478_839829468, NI i0, Ttype293840* typ0) { Ropeobj179006* result0; Tnode293802* ri0; Ttype293840* t0; result0 = (Ropeobj179006*)0; { NI LOC3; NimStringDesc* LOC6; LOC3 = (NI)0; LOC3 = sonslen_296327_850551059(typ0); if (!!((i0 < LOC3))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_197185_1689653243(T839829468_503); internalerror_197113_155036129(LOC6); } LA4: ; ri0 = HEX5BHEX5D_294238_850551059(ri_542478_839829468, i0); { while (1) { if (!((*ri0).kind == ((Tnodekind293020) 66))) goto LA8; ri0 = HEX5BHEX5D_294238_850551059(ri0, ((NI) 0)); } LA8: ; } t0 = skiptypes_297099_850551059((*typ0).sons->data[i0], 2048); { Tnode293802* x0; if (!((*t0).kind == ((Ttypekind293244) 23))) goto LA11; { if (!((*ri0).kind == ((Tnodekind293020) 64))) goto LA15; x0 = HEX5BHEX5D_294238_850551059(ri0, ((NI) 0)); } goto LA13; LA15: ; { x0 = ri0; } LA13: ; { if (!((*(*x0).typ).kind == ((Ttypekind293244) 21))) goto LA20; result0 = genargnoparam_540938_839829468(p0, x0); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } goto LA18; LA20: ; { NIM_BOOL LOC23; Tnode293802* LOC25; Tnode293802* LOC28; LOC23 = (NIM_BOOL)0; LOC23 = ((*x0).kind == ((Tnodekind293020) 65) || (*x0).kind == ((Tnodekind293020) 47)); if (!(LOC23)) goto LA24; LOC25 = (Tnode293802*)0; LOC25 = HEX5BHEX5D_294238_850551059(x0, ((NI) 0)); LOC23 = ((*(*LOC25).typ).kind == ((Ttypekind293244) 21)); LA24: ; if (!LOC23) goto LA26; LOC28 = (Tnode293802*)0; LOC28 = HEX5BHEX5D_294238_850551059(x0, ((NI) 0)); result0 = genargnoparam_540938_839829468(p0, LOC28); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } goto LA18; LA26: ; { result0 = genargnoparam_540938_839829468(p0, x0); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } LA18: ; } goto LA9; LA11: ; { if (!((*t0).kind == ((Ttypekind293244) 21))) goto LA31; { Tnode293802* LOC37; if (!((*ri0).kind == ((Tnodekind293020) 63) || (*ri0).kind == ((Tnodekind293020) 64))) goto LA35; LOC37 = (Tnode293802*)0; LOC37 = HEX5BHEX5D_294238_850551059(ri0, ((NI) 0)); result0 = genargnoparam_540938_839829468(p0, LOC37); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } goto LA33; LA35: ; { result0 = genargnoparam_540938_839829468(p0, ri0); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } LA33: ; } goto LA9; LA31: ; { ri0 = skipaddrderef_542433_839829468(ri0); { if (!((*ri0).kind == ((Tnodekind293020) 63) || (*ri0).kind == ((Tnodekind293020) 64))) goto LA42; ri0 = HEX5BHEX5D_294238_850551059(ri0, ((NI) 0)); } LA42: ; result0 = genargnoparam_540938_839829468(p0, ri0); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } LA9: ; return result0; } N_NIMCALL(Ropeobj179006*, genpatterncall_542699_839829468)(Tcproc530021* p0, Tnode293802* ri_542702_839829468, NimStringDesc* pat0, Ttype293840* typ_542704_839829468) { Ropeobj179006* result0; NI i0; NI j0; result0 = (Ropeobj179006*)0; i0 = ((NI) 0); j0 = ((NI) 1); { while (1) { if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA2; switch (((NU8)(pat0->data[i0]))) { case 64: { { NI LOC6; Ropeobj179006* LOC9; LOC6 = (NI)0; LOC6 = len_294081_850551059(ri_542702_839829468); if (!(j0 < LOC6)) goto LA7; LOC9 = (Ropeobj179006*)0; LOC9 = genotherarg_540277_839829468(p0, ri_542702_839829468, j0, typ_542704_839829468); add_179482_2381377266(&result0, LOC9); { NI k_542728_839829468; NI HEX3Atmp_542904_839829468; NI HEX3Atmp_542905_839829468; NI LOC11; NI res_542908_839829468; k_542728_839829468 = (NI)0; HEX3Atmp_542904_839829468 = (NI)0; HEX3Atmp_542905_839829468 = (NI)0; HEX3Atmp_542904_839829468 = (NI)(j0 + ((NI) 1)); LOC11 = (NI)0; LOC11 = len_294081_850551059(ri_542702_839829468); HEX3Atmp_542905_839829468 = (LOC11 - 1); res_542908_839829468 = HEX3Atmp_542904_839829468; { while (1) { TY534289 LOC14; Ropeobj179006* LOC15; Ropeobj179006* LOC16; if (!(res_542908_839829468 <= HEX3Atmp_542905_839829468)) goto LA13; k_542728_839829468 = res_542908_839829468; memset((void*)LOC14, 0, sizeof(LOC14)); LOC15 = (Ropeobj179006*)0; LOC15 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC14, 0); add_179482_2381377266(&result0, LOC15); LOC16 = (Ropeobj179006*)0; LOC16 = genotherarg_540277_839829468(p0, ri_542702_839829468, k_542728_839829468, typ_542704_839829468); add_179482_2381377266(&result0, LOC16); res_542908_839829468 += ((NI) 1); } LA13: ; } } } LA7: ; i0 += ((NI) 1); } break; case 35: { { Tnode293802* ri0; if (!(((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(43)) || ((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(64)))) goto LA20; ri0 = HEX5BHEX5D_294238_850551059(ri_542702_839829468, j0); { Ttype293840* typ0; TY534289 LOC31; Ropeobj179006* LOC32; TY534289 LOC46; Ropeobj179006* LOC47; if (!((*ri0).kind == ((Tnodekind293020) 27) || (*ri0).kind == ((Tnodekind293020) 29) || (*ri0).kind == ((Tnodekind293020) 30) || (*ri0).kind == ((Tnodekind293020) 31) || (*ri0).kind == ((Tnodekind293020) 26) || (*ri0).kind == ((Tnodekind293020) 28) || (*ri0).kind == ((Tnodekind293020) 32))) goto LA24; typ0 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { Ropeobj179006* LOC30; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(43))) goto LA28; LOC30 = (Ropeobj179006*)0; LOC30 = genargnoparam_540938_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)]); add_179482_2381377266(&result0, LOC30); } LA28: ; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj179006*)0; LOC32 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_118), LOC31, 0); add_179482_2381377266(&result0, LOC32); { NI LOC35; Ropeobj179006* LOC38; LOC35 = (NI)0; LOC35 = len_294081_850551059(ri0); if (!(((NI) 1) < LOC35)) goto LA36; LOC38 = (Ropeobj179006*)0; LOC38 = genotherarg_540277_839829468(p0, ri0, ((NI) 1), typ0); add_179482_2381377266(&result0, LOC38); } LA36: ; { NI k_542793_839829468; NI HEX3Atmp_542915_839829468; NI HEX3Atmp_542916_839829468; NI LOC40; NI res_542919_839829468; k_542793_839829468 = (NI)0; HEX3Atmp_542915_839829468 = (NI)0; HEX3Atmp_542916_839829468 = (NI)0; HEX3Atmp_542915_839829468 = (NI)(j0 + ((NI) 1)); LOC40 = (NI)0; LOC40 = len_294081_850551059(ri0); HEX3Atmp_542916_839829468 = (LOC40 - 1); res_542919_839829468 = HEX3Atmp_542915_839829468; { while (1) { TY534289 LOC43; Ropeobj179006* LOC44; Ropeobj179006* LOC45; if (!(res_542919_839829468 <= HEX3Atmp_542916_839829468)) goto LA42; k_542793_839829468 = res_542919_839829468; memset((void*)LOC43, 0, sizeof(LOC43)); LOC44 = (Ropeobj179006*)0; LOC44 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC43, 0); add_179482_2381377266(&result0, LOC44); LOC45 = (Ropeobj179006*)0; LOC45 = genotherarg_540277_839829468(p0, ri0, k_542793_839829468, typ0); add_179482_2381377266(&result0, LOC45); res_542919_839829468 += ((NI) 1); } LA42: ; } } memset((void*)LOC46, 0, sizeof(LOC46)); LOC47 = (Ropeobj179006*)0; LOC47 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_117), LOC46, 0); add_179482_2381377266(&result0, LOC47); } goto LA22; LA24: ; { localerror_197085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_502)); } LA22: ; i0 += ((NI) 1); } goto LA18; LA20: ; { Ropeobj179006* LOC52; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(46))) goto LA50; LOC52 = (Ropeobj179006*)0; LOC52 = genthisarg_542475_839829468(p0, ri_542702_839829468, j0, typ_542704_839829468); add_179482_2381377266(&result0, LOC52); i0 += ((NI) 1); } goto LA18; LA50: ; { Tnode293802* arg0; Ropeobj179006* LOC58; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(91))) goto LA54; arg0 = skipaddrderef_542433_839829468((*ri_542702_839829468).kindU.S6.sons->data[j0]); { while (1) { if (!((*arg0).kind == ((Tnodekind293020) 63) || (*arg0).kind == ((Tnodekind293020) 64) || (*arg0).kind == ((Tnodekind293020) 66))) goto LA57; arg0 = HEX5BHEX5D_294238_850551059(arg0, ((NI) 0)); } LA57: ; } LOC58 = (Ropeobj179006*)0; LOC58 = genargnoparam_540938_839829468(p0, arg0); add_179482_2381377266(&result0, LOC58); } goto LA18; LA54: ; { Ropeobj179006* LOC60; LOC60 = (Ropeobj179006*)0; LOC60 = genotherarg_540277_839829468(p0, ri_542702_839829468, j0, typ_542704_839829468); add_179482_2381377266(&result0, LOC60); } LA18: ; j0 += ((NI) 1); i0 += ((NI) 1); } break; case 39: { NI idx0; NI stars0; idx0 = (NI)0; stars0 = (NI)0; { NIM_BOOL LOC64; Ttype293840* t0; LOC64 = (NIM_BOOL)0; LOC64 = scancppgenericslot_535827_839829468(pat0, (&i0), (&idx0), (&stars0)); if (!LOC64) goto LA65; t0 = resolvestarsincpptype_535891_839829468(typ_542704_839829468, idx0, stars0); { TY534289 LOC71; Ropeobj179006* LOC72; if (!(t0 == NIM_NIL)) goto LA69; memset((void*)LOC71, 0, sizeof(LOC71)); LOC72 = (Ropeobj179006*)0; LOC72 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_26), LOC71, 0); add_179482_2381377266(&result0, LOC72); } goto LA67; LA69: ; { Ropeobj179006* LOC74; LOC74 = (Ropeobj179006*)0; LOC74 = gettypedesc_536673_839829468((*p0).module, t0); add_179482_2381377266(&result0, LOC74); } LA67: ; } LA65: ; } break; default: { NI start0; start0 = i0; { while (1) { if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA77; { if (!!((((NU8)(pat0->data[i0])) == ((NU8)(64)) || ((NU8)(pat0->data[i0])) == ((NU8)(35)) || ((NU8)(pat0->data[i0])) == ((NU8)(39))))) goto LA80; i0 += ((NI) 1); } goto LA78; LA80: ; { goto LA76; } LA78: ; } LA77: ; } LA76: ; { NimStringDesc* LOC87; if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA85; LOC87 = (NimStringDesc*)0; LOC87 = copyStrLast(pat0, start0, (NI)(i0 - ((NI) 1))); add_179487_2381377266(&result0, LOC87); } LA85: ; } break; } } LA2: ; } return result0; } N_NIMCALL(void, fixupcall_540410_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0, Ropeobj179006* callee0, Ropeobj179006* params0) { Ropeobj179006* pl0; TY534289 LOC1; Ropeobj179006* LOC2; Ropeobj179006* LOC3; Ttype293840* typ0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (Ropeobj179006*)0; LOC2 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_118), LOC1, 0); LOC3 = (Ropeobj179006*)0; LOC3 = HEX26_179418_2381377266(callee0, LOC2); pl0 = HEX26_179418_2381377266(LOC3, params0); typ0 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA6; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = isinvalidreturntype_534550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC10) goto LA11; { TY534289 LOC17; Ropeobj179006* LOC18; if (!!((params0 == NIM_NIL))) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC18 = (Ropeobj179006*)0; LOC18 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC17, 0); add_179482_2381377266(&pl0, LOC18); } LA15: ; { NIM_BOOL LOC21; NIM_BOOL LOC23; Ropeobj179006* LOC36; TY534289 LOC37; Ropeobj179006* LOC38; LOC21 = (NIM_BOOL)0; LOC21 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0); if (LOC21) goto LA22; LOC23 = (NIM_BOOL)0; LOC23 = leftappearsonrightside_540329_839829468(le0, ri0); LOC21 = !(LOC23); LA22: ; if (!LOC21) goto LA24; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA28; gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } goto LA26; LA28: ; { NIM_BOOL LOC31; NIM_BOOL LOC33; LOC31 = (NIM_BOOL)0; LOC31 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0)); if (!(LOC31)) goto LA32; LOC33 = (NIM_BOOL)0; LOC33 = hasnoinit_540383_839829468(ri0); LOC31 = !(LOC33); LA32: ; if (!LOC31) goto LA34; resetloc_539350_839829468(p0, d0); } goto LA26; LA34: ; LA26: ; LOC36 = (Ropeobj179006*)0; LOC36 = addrloc_539204_839829468((&(*d0))); add_179482_2381377266(&pl0, LOC36); memset((void*)LOC37, 0, sizeof(LOC37)); LOC38 = (Ropeobj179006*)0; LOC38 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_505), LOC37, 0); add_179482_2381377266(&pl0, LOC38); line_533690_839829468(p0, ((Tcprocsection530011) 2), pl0); } goto LA19; LA24: ; { Tloc293816 tmp0; Ropeobj179006* LOC40; TY534289 LOC41; Ropeobj179006* LOC42; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC40 = (Ropeobj179006*)0; LOC40 = addrloc_539204_839829468((&tmp0)); add_179482_2381377266(&pl0, LOC40); memset((void*)LOC41, 0, sizeof(LOC41)); LOC42 = (Ropeobj179006*)0; LOC42 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_505), LOC41, 0); add_179482_2381377266(&pl0, LOC42); line_533690_839829468(p0, ((Tcprocsection530011) 2), pl0); genassignment_540264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA19: ; } goto LA8; LA11: ; { TY534289 LOC44; Ropeobj179006* LOC45; memset((void*)LOC44, 0, sizeof(LOC44)); LOC45 = (Ropeobj179006*)0; LOC45 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_117), LOC44, 0); add_179482_2381377266(&pl0, LOC45); { NIM_BOOL LOC48; NIM_BOOL LOC49; LOC48 = (NIM_BOOL)0; LOC49 = (NIM_BOOL)0; LOC49 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC49) goto LA50; LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA50: ; LOC48 = LOC49; if (!(LOC48)) goto LA51; LOC48 = (((*d0).flags &(1U<<((NU)(((Tlocflag293810) 8))&15U)))!=0); LA51: ; if (!LOC48) goto LA52; (*d0).k = ((Tlockind293808) 9); unsureAsgnRef((void**) (&(*d0).r), pl0); (*d0).flags &= ~(((NU16)1) << ((((Tlocflag293810) 8)) % (sizeof(NU16)*8))); } goto LA46; LA52: ; { Tloc293816 list0; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA57; gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA57: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_533273_839829468((&list0), ((Tlockind293808) 9), (*d0).t, ((Tstorageloc293812) 0)); list0.r = pl0; genassignment_540264_839829468(p0, (&(*d0)), (&list0), 0); } LA46: ; } LA8: ; } goto LA4; LA6: ; { TY534289 LOC60; Ropeobj179006* LOC61; memset((void*)LOC60, 0, sizeof(LOC60)); LOC61 = (Ropeobj179006*)0; LOC61 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_505), LOC60, 0); add_179482_2381377266(&pl0, LOC61); line_533690_839829468(p0, ((Tcprocsection530011) 2), pl0); } LA4: ; } N_NIMCALL(void, geninfixcall_542929_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0) { Tloc293816 op0; Ttype293840* typ_542940_839829468; NI length0; NimStringDesc* pat0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_540283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); typ_542940_839829468 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_296351_850551059(ri0); pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data; { NimStringDesc* LOC5; if (!!(!((pat0 == NIM_NIL)))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_197185_1689653243(T839829468_498); internalerror_197113_155036129(LOC5); } LA3: ; { NIM_BOOL LOC8; Ropeobj179006* pl0; Ttype293840* typ0; LOC8 = (NIM_BOOL)0; LOC8 = contains_110056_4286263276(pat0, T839829468_500); if (!LOC8) goto LA9; pl0 = genpatterncall_542699_839829468(p0, ri0, pat0, typ_542940_839829468); typ0 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA13; { NIM_BOOL LOC17; NIM_BOOL LOC18; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC18) goto LA19; LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA19: ; LOC17 = LOC18; if (!(LOC17)) goto LA20; LOC17 = (((*d0).flags &(1U<<((NU)(((Tlocflag293810) 8))&15U)))!=0); LA20: ; if (!LOC17) goto LA21; (*d0).k = ((Tlockind293808) 9); unsureAsgnRef((void**) (&(*d0).r), pl0); (*d0).flags &= ~(((NU16)1) << ((((Tlocflag293810) 8)) % (sizeof(NU16)*8))); } goto LA15; LA21: ; { Tloc293816 list0; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA26; gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA26: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_533273_839829468((&list0), ((Tlockind293808) 9), (*d0).t, ((Tstorageloc293812) 0)); list0.r = pl0; genassignment_540264_839829468(p0, (&(*d0)), (&list0), 0); } LA15: ; } goto LA11; LA13: ; { TY534289 LOC29; Ropeobj179006* LOC30; memset((void*)LOC29, 0, sizeof(LOC29)); LOC30 = (Ropeobj179006*)0; LOC30 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_497), LOC29, 0); add_179482_2381377266(&pl0, LOC30); line_533690_839829468(p0, ((Tcprocsection530011) 2), pl0); } LA11: ; } goto LA6; LA9: ; { Ropeobj179006* pl0; Ropeobj179006* params0; pl0 = NIM_NIL; { NI LOC34; Ropeobj179006* LOC37; LOC34 = (NI)0; LOC34 = len_294081_850551059(ri0); if (!(((NI) 1) < LOC34)) goto LA35; LOC37 = (Ropeobj179006*)0; LOC37 = genthisarg_542475_839829468(p0, ri0, ((NI) 1), typ_542940_839829468); add_179482_2381377266(&pl0, LOC37); } LA35: ; add_179482_2381377266(&pl0, op0.r); params0 = (Ropeobj179006*)0; { NI i_543425_839829468; NI HEX3Atmp_543609_839829468; NI res_543612_839829468; i_543425_839829468 = (NI)0; HEX3Atmp_543609_839829468 = (NI)0; HEX3Atmp_543609_839829468 = (NI)(length0 - ((NI) 1)); res_543612_839829468 = ((NI) 2); { while (1) { Ropeobj179006* LOC47; if (!(res_543612_839829468 <= HEX3Atmp_543609_839829468)) goto LA40; i_543425_839829468 = res_543612_839829468; { TY534289 LOC45; Ropeobj179006* LOC46; if (!!((params0 == NIM_NIL))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (Ropeobj179006*)0; LOC46 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC45, 0); add_179482_2381377266(&params0, LOC46); } LA43: ; LOC47 = (Ropeobj179006*)0; LOC47 = genotherarg_540277_839829468(p0, ri0, i_543425_839829468, typ_542940_839829468); add_179482_2381377266(&params0, LOC47); res_543612_839829468 += ((NI) 1); } LA40: ; } } fixupcall_540410_839829468(p0, le0, ri0, d0, pl0, params0); } LA6: ; } N_NIMCALL(void, gennamedparamcall_543616_839829468)(Tcproc530021* p0, Tnode293802* ri0, Tloc293816* d0) { Tloc293816 op0; Ropeobj179006* pl0; TY534289 LOC1; Ttype293840* typ0; NI length0; NimStringDesc* pat0; NI start0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_540283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); memset((void*)LOC1, 0, sizeof(LOC1)); pl0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_506), LOC1, 0); typ0 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_296351_850551059(ri0); pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data; { NimStringDesc* LOC6; if (!!(!((pat0 == NIM_NIL)))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_197185_1689653243(T839829468_507); internalerror_197113_155036129(LOC6); } LA4: ; start0 = ((NI) 3); { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = contains_110046_4286263276(pat0, 32); if (!LOC9) goto LA10; start0 = ((NI) 1); add_179482_2381377266(&pl0, op0.r); { TY534289 LOC16; Ropeobj179006* LOC17; Ropeobj179006* LOC18; if (!(((NI) 1) < length0)) goto LA14; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (Ropeobj179006*)0; LOC17 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_244), LOC16, 0); add_179482_2381377266(&pl0, LOC17); LOC18 = (Ropeobj179006*)0; LOC18 = genarg_540787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0); add_179482_2381377266(&pl0, LOC18); start0 = ((NI) 2); } LA14: ; } goto LA7; LA10: ; { { Ropeobj179006* LOC24; TY534289 LOC25; Ropeobj179006* LOC26; if (!(((NI) 1) < length0)) goto LA22; LOC24 = (Ropeobj179006*)0; LOC24 = genarg_540787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0); add_179482_2381377266(&pl0, LOC24); memset((void*)LOC25, 0, sizeof(LOC25)); LOC26 = (Ropeobj179006*)0; LOC26 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_111), LOC25, 0); add_179482_2381377266(&pl0, LOC26); } LA22: ; add_179482_2381377266(&pl0, op0.r); { TY534289 LOC31; Ropeobj179006* LOC32; Ropeobj179006* LOC33; if (!(((NI) 2) < length0)) goto LA29; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj179006*)0; LOC32 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_244), LOC31, 0); add_179482_2381377266(&pl0, LOC32); LOC33 = (Ropeobj179006*)0; LOC33 = genarg_540787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 2)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 2)]).kindU.S4.sym, ri0); add_179482_2381377266(&pl0, LOC33); } LA29: ; } LA7: ; { NI i_544051_839829468; NI HEX3Atmp_544617_839829468; NI res_544620_839829468; i_544051_839829468 = (NI)0; HEX3Atmp_544617_839829468 = (NI)0; HEX3Atmp_544617_839829468 = (NI)(length0 - ((NI) 1)); res_544620_839829468 = start0; { while (1) { Tsym293834* param0; TY534289 LOC42; Ropeobj179006* LOC43; TY534289 LOC44; Ropeobj179006* LOC45; Ropeobj179006* LOC46; if (!(res_544620_839829468 <= HEX3Atmp_544617_839829468)) goto LA36; i_544051_839829468 = res_544620_839829468; { NI LOC39; LOC39 = (NI)0; LOC39 = sonslen_296327_850551059(typ0); if (!(LOC39 <= i_544051_839829468)) goto LA40; internalerror_197100_155036129((*ri0).info, ((NimStringDesc*) &T839829468_508)); } LA40: ; param0 = (*(*(*typ0).n).kindU.S6.sons->data[i_544051_839829468]).kindU.S4.sym; memset((void*)LOC42, 0, sizeof(LOC42)); LOC43 = (Ropeobj179006*)0; LOC43 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_111), LOC42, 0); add_179482_2381377266(&pl0, LOC43); add_179487_2381377266(&pl0, (*(*param0).name).s); memset((void*)LOC44, 0, sizeof(LOC44)); LOC45 = (Ropeobj179006*)0; LOC45 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_244), LOC44, 0); add_179482_2381377266(&pl0, LOC45); LOC46 = (Ropeobj179006*)0; LOC46 = genarg_540787_839829468(p0, (*ri0).kindU.S6.sons->data[i_544051_839829468], param0, ri0); add_179482_2381377266(&pl0, LOC46); res_544620_839829468 += ((NI) 1); } LA36: ; } } { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA49; { NIM_BOOL LOC53; LOC53 = (NIM_BOOL)0; LOC53 = isinvalidreturntype_534550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC53) goto LA54; { NI LOC58; TY534289 LOC61; Ropeobj179006* LOC62; LOC58 = (NI)0; LOC58 = sonslen_296351_850551059(ri0); if (!(((NI) 1) < LOC58)) goto LA59; memset((void*)LOC61, 0, sizeof(LOC61)); LOC62 = (Ropeobj179006*)0; LOC62 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_111), LOC61, 0); add_179482_2381377266(&pl0, LOC62); } LA59: ; { TY534289 LOC71; Ropeobj179006* LOC72; Ropeobj179006* LOC73; TY534289 LOC74; Ropeobj179006* LOC75; if (!((3 &(1U<<((NU)((*d0).k)&15U)))!=0)) goto LA65; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA69; gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } LA69: ; memset((void*)LOC71, 0, sizeof(LOC71)); LOC72 = (Ropeobj179006*)0; LOC72 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_509), LOC71, 0); add_179482_2381377266(&pl0, LOC72); LOC73 = (Ropeobj179006*)0; LOC73 = addrloc_539204_839829468((&(*d0))); add_179482_2381377266(&pl0, LOC73); memset((void*)LOC74, 0, sizeof(LOC74)); LOC75 = (Ropeobj179006*)0; LOC75 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_510), LOC74, 0); add_179482_2381377266(&pl0, LOC75); line_533690_839829468(p0, ((Tcprocsection530011) 2), pl0); } goto LA63; LA65: ; { Tloc293816 tmp0; Ropeobj179006* LOC77; TY534289 LOC78; Ropeobj179006* LOC79; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC77 = (Ropeobj179006*)0; LOC77 = addrloc_539204_839829468((&tmp0)); add_179482_2381377266(&pl0, LOC77); memset((void*)LOC78, 0, sizeof(LOC78)); LOC79 = (Ropeobj179006*)0; LOC79 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_510), LOC78, 0); add_179482_2381377266(&pl0, LOC79); line_533690_839829468(p0, ((Tcprocsection530011) 2), pl0); genassignment_540264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA63: ; } goto LA51; LA54: ; { TY534289 LOC81; Ropeobj179006* LOC82; Tloc293816 list0; memset((void*)LOC81, 0, sizeof(LOC81)); LOC82 = (Ropeobj179006*)0; LOC82 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_511), LOC81, 0); add_179482_2381377266(&pl0, LOC82); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA85; gettemp_538032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA85: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_533273_839829468((&list0), ((Tlockind293808) 9), NIM_NIL, ((Tstorageloc293812) 0)); list0.r = pl0; genassignment_540264_839829468(p0, (&(*d0)), (&list0), 0); } LA51: ; } goto LA47; LA49: ; { TY534289 LOC88; Ropeobj179006* LOC89; memset((void*)LOC88, 0, sizeof(LOC88)); LOC89 = (Ropeobj179006*)0; LOC89 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_510), LOC88, 0); add_179482_2381377266(&pl0, LOC89); line_533690_839829468(p0, ((Tcprocsection530011) 2), pl0); } LA47: ; } N_NIMCALL(void, genprefixcall_540960_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0) { Tloc293816 op0; Ropeobj179006* params0; Ttype293840* typ0; NI length0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_540283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); params0 = (Ropeobj179006*)0; typ0 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_296351_850551059(ri0); { NI i_541213_839829468; NI HEX3Atmp_541445_839829468; NI res_541448_839829468; i_541213_839829468 = (NI)0; HEX3Atmp_541445_839829468 = (NI)0; HEX3Atmp_541445_839829468 = (NI)(length0 - ((NI) 1)); res_541448_839829468 = ((NI) 1); { while (1) { if (!(res_541448_839829468 <= HEX3Atmp_541445_839829468)) goto LA3; i_541213_839829468 = res_541448_839829468; { NI LOC6; Tnode293802* paramtype0; LOC6 = (NI)0; LOC6 = sonslen_296327_850551059(typ0); if (!(i_541213_839829468 < LOC6)) goto LA7; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_541213_839829468]; { NIM_BOOL LOC11; Ropeobj179006* LOC20; LOC11 = (NIM_BOOL)0; LOC11 = iscompiletimeonly_329706_3876443242((*paramtype0).typ); if (!!(LOC11)) goto LA12; { TY534289 LOC18; Ropeobj179006* LOC19; if (!!((params0 == NIM_NIL))) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (Ropeobj179006*)0; LOC19 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0); add_179482_2381377266(&params0, LOC19); } LA16: ; LOC20 = (Ropeobj179006*)0; LOC20 = genarg_540787_839829468(p0, (*ri0).kindU.S6.sons->data[i_541213_839829468], (*paramtype0).kindU.S4.sym, ri0); add_179482_2381377266(&params0, LOC20); } LA12: ; } goto LA4; LA7: ; { Ropeobj179006* LOC28; { TY534289 LOC26; Ropeobj179006* LOC27; if (!!((params0 == NIM_NIL))) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC27 = (Ropeobj179006*)0; LOC27 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0); add_179482_2381377266(&params0, LOC27); } LA24: ; LOC28 = (Ropeobj179006*)0; LOC28 = genargnoparam_540938_839829468(p0, (*ri0).kindU.S6.sons->data[i_541213_839829468]); add_179482_2381377266(&params0, LOC28); } LA4: ; res_541448_839829468 += ((NI) 1); } LA3: ; } } fixupcall_540410_839829468(p0, le0, ri0, d0, op0.r, params0); } static N_INLINE(void, poststmtactions_533942_839829468)(Tcproc530021* p0) { Ropeobj179006** LOC1; LOC1 = (Ropeobj179006**)0; LOC1 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179482_2381377266(LOC1, (*(*p0).module).injectstmt); } N_NIMCALL(void, gencall_544632_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { { Ttype293840* LOC3; LOC3 = (Ttype293840*)0; LOC3 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, 2048); if (!((*LOC3).callconv == ((Tcallingconvention293002) 8))) goto LA4; genclosurecall_541452_839829468(p0, NIM_NIL, e0, d0); } goto LA1; LA4: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC7)) goto LA8; LOC7 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; geninfixcall_542929_839829468(p0, NIM_NIL, e0, d0); } goto LA1; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC12)) goto LA13; LOC12 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 28))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; gennamedparamcall_543616_839829468(p0, e0, d0); } goto LA1; LA14: ; { genprefixcall_540960_839829468(p0, NIM_NIL, e0, d0); } LA1: ; poststmtactions_533942_839829468(p0); } N_NIMCALL(void, genreset_555731_839829468)(Tcproc530021* p0, Tnode293802* n0) { Tloc293816 a0; TY533811 LOC1; Ttype293840* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = addrloc_539204_839829468((&a0)); LOC2 = (Ttype293840*)0; LOC2 = skiptypes_297099_850551059(a0.t, IL64(211106242013440)); LOC1[1] = gentypeinfo_536941_839829468((*p0).module, LOC2); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_496), LOC1, 2); } N_NIMCALL(void, genecho_555369_839829468)(Tcproc530021* p0, Tnode293802* n0) { NIM_BOOL LOC6; Ropeobj179006* args0; Tloc293816 a0; TY533811 LOC18; NimStringDesc* LOC19; NI LOC20; NimStringDesc* LOC21; TY534289 LOC22; { NimStringDesc* LOC5; if (!!(((*n0).kind == ((Tnodekind293020) 41)))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_197185_1689653243(T839829468_512); internalerror_197113_155036129(LOC5); } LA3: ; LOC6 = (NIM_BOOL)0; LOC6 = includestr_147249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_513)); args0 = NIM_NIL; memset((void*)(&a0), 0, sizeof(a0)); { NI i_555404_839829468; NI HEX3Atmp_555431_839829468; NI LOC8; NI res_555434_839829468; i_555404_839829468 = (NI)0; HEX3Atmp_555431_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = len_294081_850551059(n0); HEX3Atmp_555431_839829468 = (NI)(LOC8 - ((NI) 1)); res_555434_839829468 = ((NI) 0); { while (1) { if (!(res_555434_839829468 <= HEX3Atmp_555431_839829468)) goto LA10; i_555404_839829468 = res_555434_839829468; { Tnode293802* LOC13; LOC13 = (Tnode293802*)0; LOC13 = skipconv_329882_3876443242((*n0).kindU.S6.sons->data[i_555404_839829468]); if (!((*LOC13).kind == ((Tnodekind293020) 23))) goto LA14; add_179487_2381377266(&args0, ((NimStringDesc*) &T839829468_514)); } goto LA11; LA14: ; { TY179507 LOC17; initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[i_555404_839829468], (&a0)); memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_539188_839829468((&a0)); addf_180205_2381377266(&args0, ((NimStringDesc*) &T839829468_515), LOC17, 1); } LA11: ; res_555434_839829468 += ((NI) 1); } LA10: ; } } memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (NimStringDesc*)0; LOC20 = (NI)0; LOC20 = len_294081_850551059(n0); LOC21 = (NimStringDesc*)0; LOC21 = nsuRepeatStr(((NimStringDesc*) &T839829468_517), ((NI) (LOC20))); LOC19 = rawNewString(LOC21->Sup.len + tnl_177644_4151366050->Sup.len + 0); appendString(LOC19, LOC21); appendString(LOC19, tnl_177644_4151366050); LOC18[0] = makecstring_192638_155036129(LOC19); LOC18[1] = args0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_516), LOC18, 2); memset((void*)LOC22, 0, sizeof(LOC22)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_518), LOC22, 0); } N_NIMCALL(void, genseqconstr_556004_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0) { Tloc293816 arr0; NI LOC5; Ropeobj179006* LOC6; memset((void*)(&arr0), 0, sizeof(arr0)); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA3; gettemp_538032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA3: ; LOC5 = (NI)0; LOC5 = sonslen_296351_850551059(t0); LOC6 = (Ropeobj179006*)0; LOC6 = intliteral_540270_839829468(((NI64) (LOC5))); gennewseqaux_555795_839829468(p0, (&(*d0)), LOC6); { NI i_556031_839829468; NI HEX3Atmp_556039_839829468; NI LOC8; NI res_556042_839829468; i_556031_839829468 = (NI)0; HEX3Atmp_556039_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = sonslen_296351_850551059(t0); HEX3Atmp_556039_839829468 = (NI)(LOC8 - ((NI) 1)); res_556042_839829468 = ((NI) 0); { while (1) { Ttype293840* LOC11; Ttype293840* LOC12; TY533811 LOC13; if (!(res_556042_839829468 <= HEX3Atmp_556039_839829468)) goto LA10; i_556031_839829468 = res_556042_839829468; LOC11 = (Ttype293840*)0; LOC11 = skiptypes_297099_850551059((*t0).typ, IL64(211106232576256)); LOC12 = (Ttype293840*)0; LOC12 = elemtype_321394_3876443242(LOC11); initloc_533273_839829468((&arr0), ((Tlockind293808) 6), LOC12, ((Tstorageloc293812) 3)); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = rdloc_539188_839829468((&(*d0))); LOC13[1] = intliteral_540270_839829468(((NI64) (i_556031_839829468))); arr0.r = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC13, 2); arr0.s = ((Tstorageloc293812) 3); expr_540248_839829468(p0, (*t0).kindU.S6.sons->data[i_556031_839829468], (&arr0)); res_556042_839829468 += ((NI) 1); } LA10: ; } } gcusage_555439_839829468(t0); } N_NIMCALL(void, genarrtoseq_556046_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0) { Tloc293816 elem0; Tloc293816 a0; Tloc293816 arr0; NI L0; NI64 LOC9; Ropeobj179006* LOC10; { memset((void*)(&elem0), 0, sizeof(elem0)); memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&arr0), 0, sizeof(arr0)); { if (!((*t0).kind == ((Tnodekind293020) 41))) goto LA3; asgnRefNoCycle((void**) (&(*(*t0).kindU.S6.sons->data[((NI) 1)]).typ), (*t0).typ); genseqconstr_556004_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], d0); goto BeforeRet; } LA3: ; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA7; gettemp_538032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA7: ; LOC9 = (NI64)0; LOC9 = lengthord_321007_3876443242((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ); L0 = ((NI) (LOC9)); LOC10 = (Ropeobj179006*)0; LOC10 = intliteral_540270_839829468(((NI64) (L0))); gennewseqaux_555795_839829468(p0, (&(*d0)), LOC10); initlocexpr_540283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], (&a0)); { NI i_556090_839829468; NI HEX3Atmp_556104_839829468; NI res_556107_839829468; i_556090_839829468 = (NI)0; HEX3Atmp_556104_839829468 = (NI)0; HEX3Atmp_556104_839829468 = (NI)(L0 - ((NI) 1)); res_556107_839829468 = ((NI) 0); { while (1) { Ttype293840* LOC14; Ttype293840* LOC15; TY533811 LOC16; Ttype293840* LOC17; Ttype293840* LOC18; TY533811 LOC19; if (!(res_556107_839829468 <= HEX3Atmp_556104_839829468)) goto LA13; i_556090_839829468 = res_556107_839829468; LOC14 = (Ttype293840*)0; LOC14 = skiptypes_297099_850551059((*t0).typ, IL64(211106232576256)); LOC15 = (Ttype293840*)0; LOC15 = elemtype_321394_3876443242(LOC14); initloc_533273_839829468((&elem0), ((Tlockind293808) 6), LOC15, ((Tstorageloc293812) 3)); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_539188_839829468((&(*d0))); LOC16[1] = intliteral_540270_839829468(((NI64) (i_556090_839829468))); elem0.r = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC16, 2); elem0.s = ((Tstorageloc293812) 3); LOC17 = (Ttype293840*)0; LOC17 = skiptypes_297099_850551059((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106232576256)); LOC18 = (Ttype293840*)0; LOC18 = elemtype_321394_3876443242(LOC17); initloc_533273_839829468((&arr0), ((Tlockind293808) 6), LOC18, a0.s); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_539188_839829468((&a0)); LOC19[1] = intliteral_540270_839829468(((NI64) (i_556090_839829468))); arr0.r = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC19, 2); genassignment_540264_839829468(p0, (&elem0), (&arr0), 3); res_556107_839829468 += ((NI) 1); } LA13: ; } } }BeforeRet: ; } N_NIMCALL(void, gendeepcopy_551374_839829468)(Tcproc530021* p0, Tloc293816* dest0, Tloc293816* src0) { Ttype293840* ty0; ty0 = skiptypes_297099_850551059((*dest0).t, IL64(211106242013440)); switch ((*ty0).kind) { case ((Ttypekind293244) 21): case ((Ttypekind293244) 22): case ((Ttypekind293244) 25): case ((Ttypekind293244) 18): case ((Ttypekind293244) 17): case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { TY536238 LOC2; memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = addrloc_539204_839829468(dest0); LOC2[1] = addrloc_539204_839829468(src0); LOC2[2] = gentypeinfo_536941_839829468((*p0).module, (*dest0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_519), LOC2, 3); } break; case ((Ttypekind293244) 24): case ((Ttypekind293244) 28): { TY536238 LOC4; memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = addrloc_539204_839829468(dest0); LOC4[1] = rdloc_539188_839829468(src0); LOC4[2] = gentypeinfo_536941_839829468((*p0).module, (*dest0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_520), LOC4, 3); } break; case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { TY536238 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = addrloc_539204_839829468(dest0); LOC6[1] = addrloc_539204_839829468(src0); LOC6[2] = gentypeinfo_536941_839829468((*p0).module, (*dest0).t); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_521), LOC6, 3); } break; case ((Ttypekind293244) 19): { { Tctypekind530007 LOC10; TY536238 LOC13; NI64 LOC14; LOC10 = (Tctypekind530007)0; LOC10 = maptype_534394_839829468(ty0); if (!(LOC10 == ((Tctypekind530007) 17))) goto LA11; usestringh_533345_839829468((*p0).module); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = rdloc_539188_839829468(dest0); LOC13[1] = rdloc_539188_839829468(src0); LOC14 = (NI64)0; LOC14 = getsize_321135_3876443242((*dest0).t); LOC13[2] = rope_179401_2381377266(LOC14); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_268), LOC13, 3); } goto LA8; LA11: ; { TY533811 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_539188_839829468(dest0); LOC16[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC16, 2); } LA8: ; } break; case ((Ttypekind293244) 26): case ((Ttypekind293244) 2): case ((Ttypekind293244) 1): case ((Ttypekind293244) 14): case ((Ttypekind293244) 29): case ((Ttypekind293244) 31) ... ((Ttypekind293244) 44): case ((Ttypekind293244) 20): case ((Ttypekind293244) 23): { TY533811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_539188_839829468(dest0); LOC18[1] = rdloc_539188_839829468(src0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_123), LOC18, 2); } break; default: { NimStringDesc* LOC20; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI293244))->Sup.len + 13); appendString(LOC20, ((NimStringDesc*) &T839829468_522)); appendString(LOC20, reprEnum((NI)(*ty0).kind, (&NTI293244))); internalerror_197113_155036129(LOC20); } break; } } N_NIMCALL(void, genmagicexpr_558033_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tmagic293524 op0) { switch (op0) { case ((Tmagic293524) 127): case ((Tmagic293524) 126): { genandor_555311_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 99) ... ((Tmagic293524) 117): { unaryarith_553646_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 96) ... ((Tmagic293524) 98): { unaryarithoverflow_552633_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 52) ... ((Tmagic293524) 55): { binaryfloatarith_557729_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 56) ... ((Tmagic293524) 93): { binaryarith_552819_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 95): { geneqproc_553214_839829468(p0, e0, d0); } break; case ((Tmagic293524) 45) ... ((Tmagic293524) 51): { binaryarithoverflow_552262_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 149): { genrepr_556339_839829468(p0, e0, d0); } break; case ((Tmagic293524) 259): { gengettypeinfo_556383_839829468(p0, e0, d0); } break; case ((Tmagic293524) 156): { genswap_556638_839829468(p0, e0, d0); } break; case ((Tmagic293524) 25): { { if (!!((((*p0).options &(1U<<((NU)(((Toption170009) 5))&31U)))!=0))) goto LA14; unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_385)); } goto LA12; LA14: ; { unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_386)); } LA12: ; } break; case ((Tmagic293524) 26): case ((Tmagic293524) 27): { Ttype293840* underlying0; underlying0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 9439232); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = !((((*p0).options &(1U<<((NU)(((Toption170009) 5))&31U)))!=0)); if (LOC20) goto LA21; LOC20 = ((IL64(34084860461056) &((NU64)1<<((NU)((*underlying0).kind)&63U)))!=0); LA21: ; if (!LOC20) goto LA22; binarystmt_551501_839829468(p0, e0, d0, opr_558050_839829468[(op0)- 26]); } goto LA18; LA22: ; { Tloc293816 a0; Tloc293816 b0; Ttype293840* ranged0; Ropeobj179006* res0; NimStringDesc* LOC25; TY533811 LOC31; Ropeobj179006* LOC32; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); ranged0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 8390656); LOC25 = (NimStringDesc*)0; { if (!((*underlying0).kind == ((Ttypekind293244) 35))) goto LA28; LOC25 = copyString(fun64_558055_839829468[(op0)- 26]); } goto LA26; LA28: ; { LOC25 = copyString(fun_558060_839829468[(op0)- 26]); } LA26: ; res0 = binaryarithoverflowraw_552235_839829468(p0, ranged0, (&a0), (&b0), LOC25); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = gettypedesc_536673_839829468((*p0).module, ranged0); LOC31[1] = res0; LOC32 = (Ropeobj179006*)0; LOC32 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_370), LOC31, 2); putintodest_551468_839829468(p0, (&a0), ranged0, LOC32, ((Tstorageloc293812) 0)); } LA18: ; } break; case ((Tmagic293524) 138): { genstrconcat_555452_839829468(p0, e0, d0); } break; case ((Tmagic293524) 144): { binarystmt_551501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_394)); } break; case ((Tmagic293524) 145): { genstrappend_555554_839829468(p0, e0, d0); } break; case ((Tmagic293524) 146): { genseqelemappend_555683_839829468(p0, e0, d0); } break; case ((Tmagic293524) 128): { genstrequals_557667_839829468(p0, e0, d0); } break; case ((Tmagic293524) 129): { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_402)); } break; case ((Tmagic293524) 130): { binaryexpr_551549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_403)); } break; case ((Tmagic293524) 157): { genisnil_553620_839829468(p0, e0, d0); } break; case ((Tmagic293524) 120): { gendollar_556391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_406)); } break; case ((Tmagic293524) 121): { gendollar_556391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_407)); } break; case ((Tmagic293524) 119): { gendollar_556391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_408)); } break; case ((Tmagic293524) 118): { gendollar_556391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_409)); } break; case ((Tmagic293524) 122): { gendollar_556391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_410)); } break; case ((Tmagic293524) 123): { gendollar_556391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_411)); } break; case ((Tmagic293524) 124): { expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Tmagic293524) 125): { genrepr_556339_839829468(p0, e0, d0); } break; case ((Tmagic293524) 12): { genof_556331_839829468(p0, e0, d0); } break; case ((Tmagic293524) 29): { gennew_555782_839829468(p0, e0); } break; case ((Tmagic293524) 30): { gennewfinalize_556111_839829468(p0, e0); } break; case ((Tmagic293524) 31): { gennewseq_555824_839829468(p0, e0); } break; case ((Tmagic293524) 32): { gennewseqofcap_555836_839829468(p0, e0, d0); } break; case ((Tmagic293524) 9): { Ttype293840* t0; TY179507 LOC55; Ropeobj179006* LOC56; t0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 256); memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC56 = (Ropeobj179006*)0; LOC56 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_428), LOC55, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC56, ((Tstorageloc293812) 0)); } break; case ((Tmagic293524) 42): { gensomecast_557481_839829468(p0, e0, d0); } break; case ((Tmagic293524) 28): { genord_557475_839829468(p0, e0, d0); } break; case ((Tmagic293524) 35): case ((Tmagic293524) 8): case ((Tmagic293524) 34): case ((Tmagic293524) 36): case ((Tmagic293524) 33): { genarraylen_556415_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 37): case ((Tmagic293524) 38): { { NIM_BOOL LOC63; LOC63 = (NIM_BOOL)0; LOC63 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC63) goto LA64; LOC63 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA64: ; if (!!(LOC63)) goto LA65; unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_440)); } goto LA61; LA65: ; { unaryexpr_552209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_441)); } LA61: ; } break; case ((Tmagic293524) 43): { unarystmt_551527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_443)); } break; case ((Tmagic293524) 44): { unarystmt_551527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_444)); } break; case ((Tmagic293524) 151): { gensetlengthstr_556632_839829468(p0, e0, d0); } break; case ((Tmagic293524) 152): { gensetlengthseq_556500_839829468(p0, e0, d0); } break; case ((Tmagic293524) 39): case ((Tmagic293524) 40): case ((Tmagic293524) 41): case ((Tmagic293524) 133): case ((Tmagic293524) 132): case ((Tmagic293524) 131): case ((Tmagic293524) 134): case ((Tmagic293524) 135): case ((Tmagic293524) 136): case ((Tmagic293524) 148): { gensetop_557419_839829468(p0, e0, d0, op0); } break; case ((Tmagic293524) 161): case ((Tmagic293524) 162): case ((Tmagic293524) 159): case ((Tmagic293524) 160): case ((Tmagic293524) 150): case ((Tmagic293524) 163): { Tsym293834* opr0; opr0 = (*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NimStringDesc* LOC78; Ropeobj179006* LOC79; if (!!((((*opr0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0))) goto LA76; LOC78 = (NimStringDesc*)0; LOC78 = HEX24_179856_2381377266((*opr0).loc.r); LOC79 = (Ropeobj179006*)0; LOC79 = cgsym_533403_839829468((*p0).module, LOC78); } LA76: ; gencall_544632_839829468(p0, e0, d0); } break; case ((Tmagic293524) 164): { genreset_555731_839829468(p0, e0); } break; case ((Tmagic293524) 17): { Tnode293802* LOC82; Tnode293802* LOC83; LOC82 = (Tnode293802*)0; LOC82 = HEX5BHEX5D_294238_850551059(e0, ((NI) 1)); LOC83 = (Tnode293802*)0; LOC83 = skipconv_329882_3876443242(LOC82); genecho_555369_839829468(p0, LOC83); } break; case ((Tmagic293524) 158): { genarrtoseq_556046_839829468(p0, e0, d0); } break; case ((Tmagic293524) 223) ... ((Tmagic293524) 257): case ((Tmagic293524) 19) ... ((Tmagic293524) 24): { localerror_197080_155036129((*e0).info, ((Tmsgkind192002) 229), (*(*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s); } break; case ((Tmagic293524) 208): { Tnode293802* n0; n0 = wrapprocforspawn_436501_2218250499((*(*p0).module).module, e0, (*e0).typ, NIM_NIL, NIM_NIL); expr_540248_839829468(p0, n0, d0); } break; case ((Tmagic293524) 155): { Tnode293802* n0; n0 = liftparallel_479822_1773027539((*(*p0).module).module, e0); expr_540248_839829468(p0, n0, d0); } break; case ((Tmagic293524) 209): { Tloc293816 a0; Tloc293816 b0; Tnode293802* x0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); { Tnode293802* LOC91; Tnode293802* LOC94; LOC91 = (Tnode293802*)0; LOC91 = HEX5BHEX5D_294238_850551059(e0, ((NI) 1)); if (!((*LOC91).kind == ((Tnodekind293020) 63) || (*LOC91).kind == ((Tnodekind293020) 64))) goto LA92; LOC94 = (Tnode293802*)0; LOC94 = HEX5BHEX5D_294238_850551059(e0, ((NI) 1)); x0 = HEX5BHEX5D_294238_850551059(LOC94, ((NI) 0)); } goto LA89; LA92: ; { x0 = HEX5BHEX5D_294238_850551059(e0, ((NI) 1)); } LA89: ; initlocexpr_540283_839829468(p0, x0, (&a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); gendeepcopy_551374_839829468(p0, (&a0), (&b0)); } break; case ((Tmagic293524) 140): case ((Tmagic293524) 94): { gencall_544632_839829468(p0, e0, d0); } break; default: { NimStringDesc* LOC98; LOC98 = (NimStringDesc*)0; LOC98 = rawNewString(reprEnum((NI)op0, (&NTI293524))->Sup.len + 14); appendString(LOC98, ((NimStringDesc*) &T839829468_523)); appendString(LOC98, reprEnum((NI)op0, (&NTI293524))); internalerror_197100_155036129((*e0).info, LOC98); } break; } } N_NIMCALL(Ropeobj179006*, gensetnode_550664_839829468)(Tcproc530021* p0, Tnode293802* n0) { Ropeobj179006* result0; Tbitset340004* cs0; NI size0; NI64 LOC1; result0 = (Ropeobj179006*)0; cs0 = (Tbitset340004*)0; LOC1 = (NI64)0; LOC1 = getsize_321135_3876443242((*n0).typ); size0 = ((NI) (LOC1)); tobitset_341001_452470228(n0, (&cs0)); { NI id0; Ropeobj179006* LOC6; if (!(((NI) 8) < size0)) goto LA4; id0 = nodetabletestorset_343682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC6 = (Ropeobj179006*)0; LOC6 = rope_179401_2381377266(((NI64) (id0))); result0 = HEX26_179418_2381377266((*(*p0).module).tmpbase, LOC6); { TY536238 LOC11; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA9; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_536673_839829468((*p0).module, (*n0).typ); LOC11[1] = result0; LOC11[2] = genrawsetdata_550629_839829468(cs0, size0); addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC11, 3); } LA9: ; } goto LA2; LA4: ; { result0 = genrawsetdata_550629_839829468(cs0, size0); } LA2: ; return result0; } N_NIMCALL(void, gensetconstr_558496_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Tloc293816 idx0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&idx0), 0, sizeof(idx0)); { Ropeobj179006* LOC5; if (!(((*e0).flags &(1U<<((NU)(((Tnodeflag293427) 4))&15U)))!=0)) goto LA3; LOC5 = (Ropeobj179006*)0; LOC5 = gensetnode_550664_839829468(p0, e0); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC5, ((Tstorageloc293812) 0)); } goto LA1; LA3: ; { { if (!((*d0).k == ((Tlockind293808) 0))) goto LA9; gettemp_538032_839829468(p0, (*e0).typ, d0, NIM_FALSE); } LA9: ; { NI64 LOC13; TY179507 LOC16; LOC13 = (NI64)0; LOC13 = getsize_321135_3876443242((*e0).typ); if (!(IL64(8) < LOC13)) goto LA14; usestringh_533345_839829468((*p0).module); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_539188_839829468((&(*d0))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_525), LOC16, 1); { NI i_558537_839829468; NI HEX3Atmp_558603_839829468; NI LOC18; NI res_558606_839829468; i_558537_839829468 = (NI)0; HEX3Atmp_558603_839829468 = (NI)0; LOC18 = (NI)0; LOC18 = sonslen_296351_850551059(e0); HEX3Atmp_558603_839829468 = (NI)(LOC18 - ((NI) 1)); res_558606_839829468 = ((NI) 0); { while (1) { if (!(res_558606_839829468 <= HEX3Atmp_558603_839829468)) goto LA20; i_558537_839829468 = res_558606_839829468; { Ttype293840* LOC25; TY536235 LOC26; if (!((*(*e0).kindU.S6.sons->data[i_558537_839829468]).kind == ((Tnodekind293020) 44))) goto LA23; LOC25 = (Ttype293840*)0; LOC25 = getsystype_339150_3937434831(((Ttypekind293244) 31)); gettemp_538032_839829468(p0, LOC25, (&idx0), NIM_FALSE); initlocexpr_540283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_558537_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_540283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_558537_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0)); memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rdloc_539188_839829468((&idx0)); LOC26[1] = rdloc_539188_839829468((&(*d0))); LOC26[2] = rdsetelemloc_556662_839829468((&a0), (*e0).typ); LOC26[3] = rdsetelemloc_556662_839829468((&b0), (*e0).typ); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_526), LOC26, 4); } goto LA21; LA23: ; { TY533811 LOC28; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[i_558537_839829468], (&a0)); memset((void*)LOC28, 0, sizeof(LOC28)); LOC28[0] = rdloc_539188_839829468((&(*d0))); LOC28[1] = rdsetelemloc_556662_839829468((&a0), (*e0).typ); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_527), LOC28, 2); } LA21: ; res_558606_839829468 += ((NI) 1); } LA20: ; } } } goto LA11; LA14: ; { NimStringDesc* ts0; NimStringDesc* LOC30; NI64 LOC31; NimStringDesc* LOC32; TY179507 LOC33; LOC30 = (NimStringDesc*)0; LOC31 = (NI64)0; LOC31 = getsize_321135_3876443242((*e0).typ); LOC32 = (NimStringDesc*)0; LOC32 = nimInt64ToStr((NI64)(LOC31 * IL64(8))); LOC30 = rawNewString(LOC32->Sup.len + 2); appendString(LOC30, ((NimStringDesc*) &T839829468_45)); appendString(LOC30, LOC32); ts0 = LOC30; memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rdloc_539188_839829468((&(*d0))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_494), LOC33, 1); { NI i_558575_839829468; NI HEX3Atmp_558611_839829468; NI LOC35; NI res_558614_839829468; i_558575_839829468 = (NI)0; HEX3Atmp_558611_839829468 = (NI)0; LOC35 = (NI)0; LOC35 = sonslen_296351_850551059(e0); HEX3Atmp_558611_839829468 = (NI)(LOC35 - ((NI) 1)); res_558614_839829468 = ((NI) 0); { while (1) { if (!(res_558614_839829468 <= HEX3Atmp_558611_839829468)) goto LA37; i_558575_839829468 = res_558614_839829468; { Ttype293840* LOC42; NimStringDesc* LOC43; TY536235 LOC44; if (!((*(*e0).kindU.S6.sons->data[i_558575_839829468]).kind == ((Tnodekind293020) 44))) goto LA40; LOC42 = (Ttype293840*)0; LOC42 = getsystype_339150_3937434831(((Ttypekind293244) 31)); gettemp_538032_839829468(p0, LOC42, (&idx0), NIM_FALSE); initlocexpr_540283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_558575_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_540283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_558575_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0)); LOC43 = (NimStringDesc*)0; LOC43 = rawNewString(ts0->Sup.len + ts0->Sup.len + 68); appendString(LOC43, ((NimStringDesc*) &T839829468_528)); appendString(LOC43, ts0); appendString(LOC43, ((NimStringDesc*) &T839829468_529)); appendString(LOC43, ts0); appendString(LOC43, ((NimStringDesc*) &T839829468_454)); memset((void*)LOC44, 0, sizeof(LOC44)); LOC44[0] = rdloc_539188_839829468((&idx0)); LOC44[1] = rdloc_539188_839829468((&(*d0))); LOC44[2] = rdsetelemloc_556662_839829468((&a0), (*e0).typ); LOC44[3] = rdsetelemloc_556662_839829468((&b0), (*e0).typ); linef_533700_839829468(p0, ((Tcprocsection530011) 2), LOC43, LOC44, 4); } goto LA38; LA40: ; { NimStringDesc* LOC46; TY533811 LOC47; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[i_558575_839829468], (&a0)); LOC46 = (NimStringDesc*)0; LOC46 = rawNewString(ts0->Sup.len + ts0->Sup.len + 36); appendString(LOC46, ((NimStringDesc*) &T839829468_530)); appendString(LOC46, ts0); appendString(LOC46, ((NimStringDesc*) &T839829468_531)); appendString(LOC46, ts0); appendString(LOC46, ((NimStringDesc*) &T839829468_454)); memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = rdloc_539188_839829468((&(*d0))); LOC47[1] = rdsetelemloc_556662_839829468((&a0), (*e0).typ); linef_533700_839829468(p0, ((Tcprocsection530011) 2), LOC46, LOC47, 2); } LA38: ; res_558614_839829468 += ((NI) 1); } LA37: ; } } } LA11: ; } LA1: ; } N_NIMCALL(void, exprcomplexconst_559684_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Ttype293840* t0; Ropeobj179006* LOC1; NI id0; Ropeobj179006* tmp0; Ropeobj179006* LOC2; t0 = getuniquetype_529640_2036603609((*n0).typ); LOC1 = (Ropeobj179006*)0; LOC1 = gettypedesc_536673_839829468((*p0).module, t0); id0 = nodetabletestorset_343682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC2 = (Ropeobj179006*)0; LOC2 = rope_179401_2381377266(((NI64) (id0))); tmp0 = HEX26_179418_2381377266((*(*p0).module).tmpbase, LOC2); { TY536238 LOC7; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA5; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC7[1] = tmp0; LOC7[2] = genconstexpr_555849_839829468(p0, n0); addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC7, 3); } LA5: ; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA10; fillloc_533282_839829468(d0, ((Tlockind293808) 8), t0, tmp0, ((Tstorageloc293812) 1)); } goto LA8; LA10: ; { putdataintodest_551436_839829468(p0, d0, t0, tmp0); { if (!!(((285212672 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0))) goto LA15; (*d0).s = ((Tstorageloc293812) 1); } LA15: ; } LA8: ; } N_NIMCALL(NIM_BOOL, handleconstexpr_555853_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; NI LOC6; Ttype293840* t0; Ropeobj179006* LOC10; NI id0; Ropeobj179006* LOC11; Ropeobj179006* LOC12; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = ((*d0).k == ((Tlockind293808) 0)); if (!(LOC4)) goto LA5; LOC6 = (NI)0; LOC6 = len_294081_850551059(n0); LOC4 = (((NI) (((*n0).kind == ((Tnodekind293020) 38)))) < LOC6); LA5: ; LOC3 = LOC4; if (!(LOC3)) goto LA7; LOC3 = isdeepconstexpr_319566_2616423590(n0); LA7: ; if (!LOC3) goto LA8; t0 = getuniquetype_529640_2036603609((*n0).typ); LOC10 = (Ropeobj179006*)0; LOC10 = gettypedesc_536673_839829468((*p0).module, t0); id0 = nodetabletestorset_343682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC11 = (Ropeobj179006*)0; LOC11 = rope_179401_2381377266(((NI64) (id0))); LOC12 = (Ropeobj179006*)0; LOC12 = HEX26_179418_2381377266((*(*p0).module).tmpbase, LOC11); fillloc_533282_839829468(d0, ((Tlockind293808) 8), t0, LOC12, ((Tstorageloc293812) 1)); { TY536238 LOC17; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA15; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_536673_839829468((*p0).module, t0); LOC17[1] = (*d0).r; LOC17[2] = genconstexpr_555849_839829468(p0, n0); addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3); } LA15: ; result0 = NIM_TRUE; } goto LA1; LA8: ; { result0 = NIM_FALSE; } LA1: ; return result0; } N_NIMCALL(void, genarrayconstr_559207_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Tloc293816 arr0; memset((void*)(&arr0), 0, sizeof(arr0)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_555853_839829468(p0, n0, d0); if (!!(LOC3)) goto LA4; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA8; gettemp_538032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA8: ; { NI i_559234_839829468; NI HEX3Atmp_559242_839829468; NI LOC11; NI res_559245_839829468; i_559234_839829468 = (NI)0; HEX3Atmp_559242_839829468 = (NI)0; LOC11 = (NI)0; LOC11 = sonslen_296351_850551059(n0); HEX3Atmp_559242_839829468 = (NI)(LOC11 - ((NI) 1)); res_559245_839829468 = ((NI) 0); { while (1) { Ttype293840* LOC14; Ttype293840* LOC15; TY533811 LOC16; if (!(res_559245_839829468 <= HEX3Atmp_559242_839829468)) goto LA13; i_559234_839829468 = res_559245_839829468; LOC14 = (Ttype293840*)0; LOC14 = skiptypes_297099_850551059((*n0).typ, IL64(211106232576256)); LOC15 = (Ttype293840*)0; LOC15 = elemtype_321394_3876443242(LOC14); initloc_533273_839829468((&arr0), ((Tlockind293808) 6), LOC15, (*d0).s); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_539188_839829468((&(*d0))); LOC16[1] = intliteral_540270_839829468(((NI64) (i_559234_839829468))); arr0.r = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_138), LOC16, 2); expr_540248_839829468(p0, (*n0).kindU.S6.sons->data[i_559234_839829468], (&arr0)); res_559245_839829468 += ((NI) 1); } LA13: ; } } } LA4: ; } N_NIMCALL(void, gentupleconstr_558618_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Tloc293816 rec0; memset((void*)(&rec0), 0, sizeof(rec0)); { NIM_BOOL LOC3; Ttype293840* t0; Ropeobj179006* LOC6; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_555853_839829468(p0, n0, d0); if (!!(LOC3)) goto LA4; t0 = getuniquetype_529640_2036603609((*n0).typ); LOC6 = (Ropeobj179006*)0; LOC6 = gettypedesc_536673_839829468((*p0).module, t0); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA9; gettemp_538032_839829468(p0, t0, d0, NIM_FALSE); } LA9: ; { NI i_558646_839829468; NI HEX3Atmp_558803_839829468; NI LOC12; NI res_558806_839829468; i_558646_839829468 = (NI)0; HEX3Atmp_558803_839829468 = (NI)0; LOC12 = (NI)0; LOC12 = sonslen_296351_850551059(n0); HEX3Atmp_558803_839829468 = (NI)(LOC12 - ((NI) 1)); res_558806_839829468 = ((NI) 0); { while (1) { Tnode293802* it0; TY533811 LOC19; if (!(res_558806_839829468 <= HEX3Atmp_558803_839829468)) goto LA14; i_558646_839829468 = res_558806_839829468; it0 = (*n0).kindU.S6.sons->data[i_558646_839829468]; { if (!((*it0).kind == ((Tnodekind293020) 34))) goto LA17; it0 = (*it0).kindU.S6.sons->data[((NI) 1)]; } LA17: ; initloc_533273_839829468((&rec0), ((Tlockind293808) 6), (*it0).typ, (*d0).s); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_539188_839829468((&(*d0))); LOC19[1] = rope_179401_2381377266(((NI64) (i_558646_839829468))); rec0.r = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_185), LOC19, 2); expr_540248_839829468(p0, it0, (&rec0)); res_558806_839829468 += ((NI) 1); } LA14: ; } } } LA4: ; } N_NIMCALL(Tsym293834*, lookupfieldagain_554154_839829468)(Tcproc530021* p0, Ttype293840* ty_554157_839829468, Tsym293834* field0, Ropeobj179006** r0) { Tsym293834* result0; Ttype293840* ty0; result0 = (Tsym293834*)0; ty0 = ty_554157_839829468; { while (1) { if (!!((ty0 == NIM_NIL))) goto LA2; ty0 = skiptypes_297099_850551059(ty0, IL64(211106247215360)); result0 = lookupinrecord_300119_2984716966((*ty0).n, (*field0).name); { if (!!((result0 == NIM_NIL))) goto LA5; goto LA1; } LA5: ; { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC9) goto LA10; LOC9 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA10: ; if (!!(LOC9)) goto LA11; add_179487_2381377266(r0, ((NimStringDesc*) &T839829468_153)); } LA11: ; ty0 = getuniquetype_529640_2036603609((*ty0).sons->data[((NI) 0)]); } LA2: ; } LA1: ; { if (!(result0 == NIM_NIL)) goto LA15; internalerror_197100_155036129((*field0).info, ((NimStringDesc*) &T839829468_532)); } LA15: ; return result0; } N_NIMCALL(void, genfieldcheck_554504_839829468)(Tcproc530021* p0, Tnode293802* e0, Ropeobj179006* obj0, Tsym293834* field0, Ttype293840* origty0) { Tloc293816 test0; Tloc293816 u0; Tloc293816 v0; memset((void*)(&test0), 0, sizeof(test0)); memset((void*)(&u0), 0, sizeof(u0)); memset((void*)(&v0), 0, sizeof(v0)); { NI i_554525_839829468; NI HEX3Atmp_555039_839829468; NI LOC2; NI res_555042_839829468; i_554525_839829468 = (NI)0; HEX3Atmp_555039_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(e0); HEX3Atmp_555039_839829468 = (NI)(LOC2 - ((NI) 1)); res_555042_839829468 = ((NI) 1); { while (1) { Tnode293802* it0; Tsym293834* op0; Tnode293802* disc0; Ropeobj179006* o0; Tsym293834* d0; NI id0; Tnode293802* LOC9; Ropeobj179006* strlit0; if (!(res_555042_839829468 <= HEX3Atmp_555039_839829468)) goto LA4; i_554525_839829468 = res_555042_839829468; it0 = (*e0).kindU.S6.sons->data[i_554525_839829468]; op0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { if (!((*op0).magic == ((Tmagic293524) 99))) goto LA7; it0 = (*it0).kindU.S6.sons->data[((NI) 1)]; } LA7: ; disc0 = skipconv_329882_3876443242((*it0).kindU.S6.sons->data[((NI) 2)]); initloc_533273_839829468((&test0), ((Tlockind293808) 0), (*it0).typ, ((Tstorageloc293812) 2)); initlocexpr_540283_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&u0)); o0 = obj0; d0 = lookupfieldagain_554154_839829468(p0, origty0, (*disc0).kindU.S4.sym, &o0); initloc_533273_839829468((&v0), ((Tlockind293808) 6), (*d0).typ, ((Tstorageloc293812) 0)); v0.r = o0; add_179487_2381377266(&v0.r, ((NimStringDesc*) &T839829468_257)); add_179482_2381377266(&v0.r, (*d0).loc.r); geninexpraux_554496_839829468(p0, it0, (&u0), (&v0), (&test0)); LOC9 = (Tnode293802*)0; LOC9 = newstrnode_294677_850551059(((Tnodekind293020) 20), (*(*field0).name).s); id0 = nodetabletestorset_343682_1142335848((&(*(*p0).module).datacache), LOC9, ((NI) ((*(*p0).module).labels))); { if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA12; strlit0 = getstrlit_550468_839829468((*p0).module, (*(*field0).name).s); } goto LA10; LA12: ; { Ropeobj179006* LOC15; LOC15 = (Ropeobj179006*)0; LOC15 = rope_179401_2381377266(((NI64) (id0))); strlit0 = HEX26_179418_2381377266((*(*p0).module).tmpbase, LOC15); } LA10: ; { TY533811 LOC20; if (!((*op0).magic == ((Tmagic293524) 99))) goto LA18; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rdloc_539188_839829468((&test0)); LOC20[1] = strlit0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_534), LOC20, 2); } goto LA16; LA18: ; { TY533811 LOC22; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = rdloc_539188_839829468((&test0)); LOC22[1] = strlit0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_535), LOC22, 2); } LA16: ; res_555042_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, genobjconstr_555903_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 tmp0; Ttype293840* t0; NIM_BOOL isref0; Ropeobj179006* r0; Ropeobj179006* LOC13; Ttype293840* ty0; { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_555853_839829468(p0, e0, d0); if (!LOC3) goto LA4; goto BeforeRet; } LA4: ; memset((void*)(&tmp0), 0, sizeof(tmp0)); t0 = skiptypes_297099_850551059((*e0).typ, IL64(211106232576256)); gettemp_538032_839829468(p0, t0, (&tmp0), NIM_FALSE); isref0 = ((*t0).kind == ((Ttypekind293244) 22)); r0 = rdloc_539188_839829468((&tmp0)); { Ttype293840* LOC10; TY179507 LOC11; if (!isref0) goto LA8; rawgennew_555741_839829468(p0, (&tmp0), NIM_NIL); LOC10 = (Ttype293840*)0; LOC10 = lastson_296377_850551059(t0); t0 = skiptypes_297099_850551059(LOC10, IL64(211106232576256)); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = r0; r0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_124), LOC11, 1); gcusage_555439_839829468(e0); } goto LA6; LA8: ; { constructloc_539388_839829468(p0, (&tmp0), NIM_FALSE); } LA6: ; LOC13 = (Ropeobj179006*)0; LOC13 = gettypedesc_536673_839829468((*p0).module, t0); ty0 = getuniquetype_529640_2036603609(t0); { NI i_555944_839829468; NI HEX3Atmp_555997_839829468; NI LOC15; NI res_556000_839829468; i_555944_839829468 = (NI)0; HEX3Atmp_555997_839829468 = (NI)0; LOC15 = (NI)0; LOC15 = len_294081_850551059(e0); HEX3Atmp_555997_839829468 = (LOC15 - 1); res_556000_839829468 = ((NI) 1); { while (1) { Tnode293802* it0; Tloc293816 tmp20; Tsym293834* field0; if (!(res_556000_839829468 <= HEX3Atmp_555997_839829468)) goto LA17; i_555944_839829468 = res_556000_839829468; it0 = (*e0).kindU.S6.sons->data[i_555944_839829468]; memset((void*)(&tmp20), 0, sizeof(tmp20)); tmp20.r = r0; field0 = lookupfieldagain_554154_839829468(p0, ty0, (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym, &tmp20.r); { if (!((*field0).loc.r == NIM_NIL)) goto LA20; internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_533)); } LA20: ; { NIM_BOOL LOC24; NI LOC25; LOC24 = (NIM_BOOL)0; LOC25 = (NI)0; LOC25 = len_294081_850551059(it0); LOC24 = (LOC25 == ((NI) 3)); if (!(LOC24)) goto LA26; LOC24 = (((*p0).options &(1U<<((NU)(((Toption170009) 2))&31U)))!=0); LA26: ; if (!LOC24) goto LA27; genfieldcheck_554504_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 2)], r0, field0, ty0); } LA27: ; add_179487_2381377266(&tmp20.r, ((NimStringDesc*) &T839829468_257)); add_179482_2381377266(&tmp20.r, (*field0).loc.r); tmp20.k = ((Tlockind293808) 1); tmp20.t = (*field0).loc.t; { if (!isref0) goto LA31; tmp20.s = ((Tstorageloc293812) 3); } goto LA29; LA31: ; { tmp20.s = ((Tstorageloc293812) 2); } LA29: ; expr_540248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&tmp20)); res_556000_839829468 += ((NI) 1); } LA17: ; } } { if (!((*d0).k == ((Tlockind293808) 0))) goto LA36; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI293816)); } goto LA34; LA36: ; { genassignment_540264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA34: ; }BeforeRet: ; } N_NIMCALL(void, gencast_557538_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Ttype293840* destt0; Ttype293840* srct0; destt0 = skiptypes_297099_850551059((*e0).typ, IL64(211106233624832)); srct0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832)); { NIM_BOOL LOC3; Ropeobj179006* lbl0; Tloc293816 tmp0; TY179507 LOC7; TY536238 LOC8; TY179507 LOC9; Ropeobj179006* LOC10; LOC3 = (NIM_BOOL)0; LOC3 = ((IL64(1030792609808) &((NU64)1<<((NU)((*destt0).kind)&63U)))!=0); if (LOC3) goto LA4; LOC3 = ((IL64(1030792609808) &((NU64)1<<((NU)((*srct0).kind)&63U)))!=0); LA4: ; if (!LOC3) goto LA5; (*p0).labels += ((NI) 1); lbl0 = rope_179401_2381377266(((NI64) ((*p0).labels))); memset((void*)(&tmp0), 0, sizeof(tmp0)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = lbl0; tmp0.r = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_536), LOC7, 1); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = gettypedesc_536673_839829468((*p0).module, srct0); LOC8[1] = gettypedesc_536673_839829468((*p0).module, destt0); LOC8[2] = lbl0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 0), ((NimStringDesc*) &T839829468_537), LOC8, 3); tmp0.k = ((Tlockind293808) 6); tmp0.t = srct0; tmp0.s = ((Tstorageloc293812) 2); tmp0.flags = 0; expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = lbl0; LOC10 = (Ropeobj179006*)0; LOC10 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_538), LOC9, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC10, tmp0.s); } goto LA1; LA5: ; { gensomecast_557481_839829468(p0, e0, d0); } LA1: ; } N_NIMCALL(void, genconv_557633_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Ttype293840* desttype0; desttype0 = skiptypes_297099_850551059((*e0).typ, 8390656); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = comparetypes_327214_3876443242(desttype0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, ((Tdistinctcompare325427) 1), 0); if (!LOC3) goto LA4; expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0); } goto LA1; LA4: ; { gensomecast_557481_839829468(p0, e0, d0); } LA1: ; } static N_INLINE(NIM_BOOL, iscppref_553807_839829468)(Tcproc530021* p0, Ttype293840* typ0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; NIM_BOOL LOC3; Ttype293840* LOC6; Ttype293840* LOC8; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA4: ; LOC2 = LOC3; if (!(LOC2)) goto LA5; LOC6 = (Ttype293840*)0; LOC6 = skiptypes_297099_850551059(typ0, IL64(211106232576256)); LOC2 = ((*LOC6).kind == ((Ttypekind293244) 23)); LA5: ; LOC1 = LOC2; if (!(LOC1)) goto LA7; LOC8 = (Ttype293840*)0; LOC8 = skiptypes_297099_850551059(typ0, IL64(211106232576256)); LOC1 = !((((*LOC8).flags &(1U<<((NU)(((Ttypeflag293431) 18))&31U)))!=0)); LA7: ; result0 = LOC1; return result0; } N_NIMCALL(void, genaddr_554051_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { { Ttype293840* LOC3; Tloc293816 a0; Ropeobj179006* LOC6; LOC3 = (Ttype293840*)0; LOC3 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); if (!((6291456 &((NU64)1<<((NU)((*LOC3).kind)&63U)))!=0)) goto LA4; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC6 = (Ropeobj179006*)0; LOC6 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_52), a0.r); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC6, a0.s); } goto LA1; LA4: ; { NIM_BOOL LOC8; Tctypekind530007 LOC9; LOC8 = (NIM_BOOL)0; LOC9 = (Tctypekind530007)0; LOC9 = maptype_534394_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); LOC8 = (LOC9 == ((Tctypekind530007) 17)); if (LOC8) goto LA10; LOC8 = iscppref_553807_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); LA10: ; if (!LOC8) goto LA11; expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); } goto LA1; LA11: ; { Tloc293816 a0; Ropeobj179006* LOC14; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC14 = (Ropeobj179006*)0; LOC14 = addrloc_539204_839829468((&a0)); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC14, a0.s); } LA1: ; } N_NIMCALL(void, genarrayelem_555093_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Ttype293840* ty0; Ttype293840* LOC1; Ropeobj179006* first0; NI64 LOC2; Ttype293840* LOC47; Ttype293840* LOC48; TY536238 LOC49; Ropeobj179006* LOC50; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, x0, (&a0)); initlocexpr_540283_839829468(p0, y0, (&b0)); LOC1 = (Ttype293840*)0; LOC1 = skiptypes_297099_850551059(a0.t, IL64(211106242013440)); ty0 = skiptypes_297099_850551059(LOC1, IL64(211106247256320)); LOC2 = (NI64)0; LOC2 = firstord_321001_3876443242(ty0); first0 = intliteral_540270_839829468(LOC2); { NIM_BOOL LOC5; LOC5 = (NIM_BOOL)0; LOC5 = (((*p0).options &(1U<<((NU)(((Toption170009) 4))&31U)))!=0); if (!(LOC5)) goto LA6; LOC5 = !((((*ty0).flags &(1U<<((NU)(((Ttypeflag293431) 0))&31U)))!=0)); LA6: ; if (!LOC5) goto LA7; { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = isconstexpr_319510_2616423590(y0); if (!!(LOC11)) goto LA12; { NI64 LOC16; LOC16 = (NI64)0; LOC16 = firstord_321001_3876443242(ty0); if (!(LOC16 == IL64(0))) goto LA17; { NIM_BOOL LOC21; NI64 LOC22; NI64 LOC23; NI64 LOC25; NI64 LOC26; TY533811 LOC29; NI64 LOC30; LOC21 = (NIM_BOOL)0; LOC22 = (NI64)0; LOC22 = firstord_321001_3876443242(b0.t); LOC23 = (NI64)0; LOC23 = firstord_321001_3876443242(ty0); LOC21 = (LOC22 < LOC23); if (LOC21) goto LA24; LOC25 = (NI64)0; LOC25 = lastord_321004_3876443242(ty0); LOC26 = (NI64)0; LOC26 = lastord_321004_3876443242(b0.t); LOC21 = (LOC25 < LOC26); LA24: ; if (!LOC21) goto LA27; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdcharloc_539227_839829468((&b0)); LOC30 = (NI64)0; LOC30 = lastord_321004_3876443242(ty0); LOC29[1] = intliteral_540270_839829468(LOC30); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_539), LOC29, 2); } LA27: ; } goto LA14; LA17: ; { TY536238 LOC32; NI64 LOC33; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = rdcharloc_539227_839829468((&b0)); LOC32[1] = first0; LOC33 = (NI64)0; LOC33 = lastord_321004_3876443242(ty0); LOC32[2] = intliteral_540270_839829468(LOC33); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_540), LOC32, 3); } LA14: ; } goto LA9; LA12: ; { NI64 idx0; idx0 = getordvalue_321129_3876443242(y0); { NIM_BOOL LOC37; NI64 LOC38; NI64 LOC40; LOC37 = (NIM_BOOL)0; LOC38 = (NI64)0; LOC38 = firstord_321001_3876443242(ty0); LOC37 = (idx0 < LOC38); if (LOC37) goto LA39; LOC40 = (NI64)0; LOC40 = lastord_321004_3876443242(ty0); LOC37 = (LOC40 < idx0); LA39: ; if (!LOC37) goto LA41; localerror_197080_155036129((*x0).info, ((Tmsgkind192002) 86), ((NimStringDesc*) &T839829468_490)); } LA41: ; } LA9: ; } LA7: ; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA45; (*d0).s = a0.s; } LA45: ; LOC47 = (Ttype293840*)0; LOC47 = skiptypes_297099_850551059(ty0, IL64(211106240964864)); LOC48 = (Ttype293840*)0; LOC48 = elemtype_321394_3876443242(LOC47); memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_539188_839829468((&a0)); LOC49[1] = rdcharloc_539227_839829468((&b0)); LOC49[2] = first0; LOC50 = (Ropeobj179006*)0; LOC50 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_541), LOC49, 3); putintodest_551468_839829468(p0, d0, LOC48, LOC50, a0.s); } N_NIMCALL(void, genopenarrayelem_555169_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Ttype293840* LOC10; Ttype293840* LOC11; TY533811 LOC12; Ropeobj179006* LOC13; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, x0, (&a0)); initlocexpr_540283_839829468(p0, y0, (&b0)); { TY533811 LOC5; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 4))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468((&b0)); LOC5[1] = rdloc_539188_839829468((&a0)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_542), LOC5, 2); } LA3: ; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA8; (*d0).s = a0.s; } LA8: ; LOC10 = (Ttype293840*)0; LOC10 = skiptypes_297099_850551059(a0.t, IL64(211106240964864)); LOC11 = (Ttype293840*)0; LOC11 = elemtype_321394_3876443242(LOC10); memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_539188_839829468((&a0)); LOC12[1] = rdcharloc_539227_839829468((&b0)); LOC13 = (Ropeobj179006*)0; LOC13 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC12, 2); putintodest_551468_839829468(p0, d0, LOC11, LOC13, a0.s); } N_NIMCALL(void, genseqelem_555205_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Ttype293840* ty0; Ttype293840* LOC27; Ttype293840* LOC28; TY533811 LOC29; Ropeobj179006* LOC30; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, x0, (&a0)); initlocexpr_540283_839829468(p0, y0, (&b0)); ty0 = skiptypes_297099_850551059(a0.t, IL64(211106242013440)); { Ttype293840* LOC5; if (!((6291456 &((NU64)1<<((NU)((*ty0).kind)&63U)))!=0)) goto LA3; LOC5 = (Ttype293840*)0; LOC5 = lastson_296377_850551059(ty0); ty0 = skiptypes_297099_850551059(LOC5, IL64(211106242013440)); } LA3: ; { if (!(((*p0).options &(1U<<((NU)(((Toption170009) 4))&31U)))!=0)) goto LA8; { TY536238 LOC14; if (!((*ty0).kind == ((Ttypekind293244) 28))) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_539188_839829468((&b0)); LOC14[1] = rdloc_539188_839829468((&a0)); LOC14[2] = lenfield_540305_839829468(p0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_543), LOC14, 3); } goto LA10; LA12: ; { TY536238 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_539188_839829468((&b0)); LOC16[1] = rdloc_539188_839829468((&a0)); LOC16[2] = lenfield_540305_839829468(p0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_544), LOC16, 3); } LA10: ; } LA8: ; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA19; (*d0).s = ((Tstorageloc293812) 3); } LA19: ; { Ttype293840* LOC23; TY179507 LOC26; LOC23 = (Ttype293840*)0; LOC23 = skiptypes_297099_850551059(a0.t, IL64(211106240964864)); if (!((6291456 &((NU64)1<<((NU)((*LOC23).kind)&63U)))!=0)) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = a0.r; a0.r = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC26, 1); } LA24: ; LOC27 = (Ttype293840*)0; LOC27 = skiptypes_297099_850551059(a0.t, IL64(211106240964864)); LOC28 = (Ttype293840*)0; LOC28 = elemtype_321394_3876443242(LOC27); memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdloc_539188_839829468((&a0)); LOC29[1] = rdcharloc_539227_839829468((&b0)); LOC30 = (Ropeobj179006*)0; LOC30 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC29, 2); putintodest_551468_839829468(p0, d0, LOC28, LOC30, a0.s); } N_NIMCALL(void, gencstringelem_555144_839829468)(Tcproc530021* p0, Tnode293802* x0, Tnode293802* y0, Tloc293816* d0) { Tloc293816 a0; Tloc293816 b0; Ttype293840* ty0; Ttype293840* LOC5; Ttype293840* LOC6; TY533811 LOC7; Ropeobj179006* LOC8; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, x0, (&a0)); initlocexpr_540283_839829468(p0, y0, (&b0)); ty0 = skiptypes_297099_850551059(a0.t, IL64(211106242013440)); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA3; (*d0).s = a0.s; } LA3: ; LOC5 = (Ttype293840*)0; LOC5 = skiptypes_297099_850551059(ty0, IL64(211106240964864)); LOC6 = (Ttype293840*)0; LOC6 = elemtype_321394_3876443242(LOC5); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_539188_839829468((&a0)); LOC7[1] = rdcharloc_539227_839829468((&b0)); LOC8 = (Ropeobj179006*)0; LOC8 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC7, 2); putintodest_551468_839829468(p0, d0, LOC6, LOC8, a0.s); } N_NIMCALL(void, gentupleelem_554124_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; NI i0; Ropeobj179006* LOC5; Ttype293840* ty0; Ropeobj179006* r0; TY179507 LOC8; memset((void*)(&a0), 0, sizeof(a0)); i0 = (NI)0; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); { if (!((*d0).k == ((Tlockind293808) 0))) goto LA3; (*d0).s = a0.s; } LA3: ; LOC5 = (Ropeobj179006*)0; LOC5 = gettypedesc_536673_839829468((*p0).module, a0.t); ty0 = getuniquetype_529640_2036603609(a0.t); r0 = rdloc_539188_839829468((&a0)); switch ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind) { case ((Tnodekind293020) 6) ... ((Tnodekind293020) 15): { i0 = ((NI) ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval)); } break; default: { internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_545)); } break; } memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rope_179401_2381377266(((NI64) (i0))); addf_180205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC8, 1); putintodest_551468_839829468(p0, d0, (*ty0).sons->data[i0], r0, a0.s); } N_NIMCALL(void, genbracketexpr_555277_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Ttype293840* ty0; ty0 = skiptypes_297099_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440)); { Ttype293840* LOC5; if (!((6291456 &((NU64)1<<((NU)((*ty0).kind)&63U)))!=0)) goto LA3; LOC5 = (Ttype293840*)0; LOC5 = lastson_296377_850551059(ty0); ty0 = skiptypes_297099_850551059(LOC5, IL64(211106242013440)); } LA3: ; switch ((*ty0).kind) { case ((Ttypekind293244) 16): case ((Ttypekind293244) 4): { genarrayelem_555093_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind293244) 27): case ((Ttypekind293244) 48): { genopenarrayelem_555169_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind293244) 24): case ((Ttypekind293244) 28): { genseqelem_555205_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind293244) 29): { gencstringelem_555144_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind293244) 18): { gentupleelem_554124_839829468(p0, n0, d0); } break; default: { NimStringDesc* LOC12; LOC12 = (NimStringDesc*)0; LOC12 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI293244))->Sup.len + 21); appendString(LOC12, ((NimStringDesc*) &T839829468_547)); appendString(LOC12, reprEnum((NI)(*ty0).kind, (&NTI293244))); appendChar(LOC12, 41); internalerror_197100_155036129((*n0).info, LOC12); } break; } } N_NIMCALL(void, genderef_544921_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, NIM_BOOL enforcederef0) { Tctypekind530007 mt0; { mt0 = maptype_534394_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((393216 &(1U<<((NU)(mt0)&31U)))!=0); if (!(LOC3)) goto LA4; LOC3 = !(enforcederef0); LA4: ; if (!LOC3) goto LA5; expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); { Ttype293840* LOC9; LOC9 = (Ttype293840*)0; LOC9 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); if (!((*LOC9).kind == ((Ttypekind293244) 22))) goto LA10; (*d0).s = ((Tstorageloc293812) 3); } LA10: ; } goto LA1; LA5: ; { Tloc293816 a0; Ttype293840* typ0; memset((void*)(&a0), 0, sizeof(a0)); typ0 = skiptypes_297099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { NIM_BOOL LOC15; NIM_BOOL LOC16; NIM_BOOL LOC17; NIM_BOOL LOC20; Tnode293802* LOC25; Tnode293802* LOC26; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC17 = (NIM_BOOL)0; LOC17 = ((*typ0).kind == ((Ttypekind293244) 23)); if (!(LOC17)) goto LA18; LOC17 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 18))&31U)))!=0)); LA18: ; LOC16 = LOC17; if (!(LOC16)) goto LA19; LOC20 = (NIM_BOOL)0; LOC20 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC20) goto LA21; LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA21: ; LOC16 = LOC20; LA19: ; LOC15 = LOC16; if (!(LOC15)) goto LA22; LOC15 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 64)); LA22: ; if (!LOC15) goto LA23; LOC25 = (Tnode293802*)0; LOC25 = HEX5BHEX5D_294238_850551059(e0, ((NI) 0)); LOC26 = (Tnode293802*)0; LOC26 = HEX5BHEX5D_294238_850551059(LOC25, ((NI) 0)); initlocexprsingleuse_540289_839829468(p0, LOC26, d0); goto BeforeRet; } goto LA13; LA23: ; { initlocexprsingleuse_540289_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA13: ; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA30; switch ((*typ0).kind) { case ((Ttypekind293244) 22): { (*d0).s = ((Tstorageloc293812) 3); } break; case ((Ttypekind293244) 23): { (*d0).s = ((Tstorageloc293812) 0); { NIM_BOOL LOC36; NIM_BOOL LOC37; NIM_BOOL LOC39; Ropeobj179006* LOC44; LOC36 = (NIM_BOOL)0; LOC37 = (NIM_BOOL)0; LOC37 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 18))&31U)))!=0)); if (!(LOC37)) goto LA38; LOC39 = (NIM_BOOL)0; LOC39 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC39) goto LA40; LOC39 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA40: ; LOC37 = LOC39; LA38: ; LOC36 = LOC37; if (!(LOC36)) goto LA41; LOC36 = ((*e0).kind == ((Tnodekind293020) 65)); LA41: ; if (!LOC36) goto LA42; LOC44 = (Ropeobj179006*)0; LOC44 = rdloc_539188_839829468((&a0)); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC44, a0.s); goto BeforeRet; } LA42: ; } break; case ((Ttypekind293244) 21): { (*d0).s = ((Tstorageloc293812) 0); } break; default: { NimStringDesc* LOC47; LOC47 = (NimStringDesc*)0; LOC47 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI293244))->Sup.len + 9); appendString(LOC47, ((NimStringDesc*) &T839829468_548)); appendString(LOC47, reprEnum((NI)(*typ0).kind, (&NTI293244))); internalerror_197100_155036129((*e0).info, LOC47); } break; } } goto LA28; LA30: ; { NIM_BOOL LOC49; LOC49 = (NIM_BOOL)0; LOC49 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC49) goto LA50; LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA50: ; if (!LOC49) goto LA51; { NIM_BOOL LOC55; NIM_BOOL LOC56; Ropeobj179006* LOC61; LOC55 = (NIM_BOOL)0; LOC56 = (NIM_BOOL)0; LOC56 = ((*typ0).kind == ((Ttypekind293244) 23)); if (!(LOC56)) goto LA57; LOC56 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag293431) 18))&31U)))!=0)); LA57: ; LOC55 = LOC56; if (!(LOC55)) goto LA58; LOC55 = ((*e0).kind == ((Tnodekind293020) 65)); LA58: ; if (!LOC55) goto LA59; LOC61 = (Ropeobj179006*)0; LOC61 = rdloc_539188_839829468((&a0)); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC61, a0.s); goto BeforeRet; } LA59: ; } goto LA28; LA51: ; LA28: ; { NIM_BOOL LOC64; Ropeobj179006* LOC68; LOC64 = (NIM_BOOL)0; LOC64 = enforcederef0; if (!(LOC64)) goto LA65; LOC64 = (mt0 == ((Tctypekind530007) 18)); LA65: ; if (!LOC64) goto LA66; LOC68 = (Ropeobj179006*)0; LOC68 = rdloc_539188_839829468((&a0)); putintodest_551468_839829468(p0, d0, (*a0.t).sons->data[((NI) 0)], LOC68, a0.s); } goto LA62; LA66: ; { TY179507 LOC70; Ropeobj179006* LOC71; memset((void*)LOC70, 0, sizeof(LOC70)); LOC70[0] = rdloc_539188_839829468((&a0)); LOC71 = (Ropeobj179006*)0; LOC71 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_124), LOC70, 1); putintodest_551468_839829468(p0, d0, (*e0).typ, LOC71, a0.s); } LA62: ; } LA1: ; }BeforeRet: ; } N_NIMCALL(Ttype293840*, genrecordfieldaux_554096_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0, Tloc293816* a0) { Ttype293840* result0; Ropeobj179006* LOC9; result0 = (Ttype293840*)0; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], a0); { if (!!(((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind293020) 3)))) goto LA3; internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_549)); } LA3: ; { if (!((*d0).k == ((Tlockind293808) 0))) goto LA7; (*d0).s = (*a0).s; } LA7: ; LOC9 = (Ropeobj179006*)0; LOC9 = gettypedesc_536673_839829468((*p0).module, (*a0).t); result0 = getuniquetype_529640_2036603609((*a0).t); return result0; } N_NIMCALL(void, genrecordfield_554448_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { Tloc293816 a0; Ttype293840* ty0; Ropeobj179006* r0; Tsym293834* f0; memset((void*)(&a0), 0, sizeof(a0)); ty0 = genrecordfieldaux_554096_839829468(p0, e0, d0, (&a0)); r0 = rdloc_539188_839829468((&a0)); f0 = (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; { TY179507 LOC5; if (!((*ty0).kind == ((Ttypekind293244) 18))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_179401_2381377266(((NI64) ((*f0).position))); addf_180205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC5, 1); putintodest_551468_839829468(p0, d0, (*f0).typ, r0, a0.s); } goto LA1; LA3: ; { Tsym293834* field0; TY179507 LOC11; field0 = lookupfieldagain_554154_839829468(p0, ty0, f0, &r0); { if (!((*field0).loc.r == NIM_NIL)) goto LA9; internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_550)); } LA9: ; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = (*field0).loc.r; addf_180205_2381377266(&r0, ((NimStringDesc*) &T839829468_551), LOC11, 1); putintodest_551468_839829468(p0, d0, (*field0).typ, r0, a0.s); } LA1: ; } N_NIMCALL(void, gencheckedrecordfield_555046_839829468)(Tcproc530021* p0, Tnode293802* e0, Tloc293816* d0) { { Tloc293816 a0; Ttype293840* ty0; Ropeobj179006* r0; Tsym293834* f0; Tsym293834* field0; TY179507 LOC9; Ropeobj179006* LOC10; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 2))&31U)))!=0)) goto LA3; memset((void*)(&a0), 0, sizeof(a0)); ty0 = genrecordfieldaux_554096_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0, (&a0)); r0 = rdloc_539188_839829468((&a0)); f0 = (*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; field0 = lookupfieldagain_554154_839829468(p0, ty0, f0, &r0); { if (!((*field0).loc.r == NIM_NIL)) goto LA7; internalerror_197100_155036129((*e0).info, ((NimStringDesc*) &T839829468_532)); } LA7: ; genfieldcheck_554504_839829468(p0, e0, r0, field0, ty0); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = (*field0).loc.r; LOC10 = (Ropeobj179006*)0; LOC10 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_551), LOC9, 1); add_179482_2381377266(&r0, LOC10); putintodest_551468_839829468(p0, d0, (*field0).typ, r0, a0.s); } goto LA1; LA3: ; { genrecordfield_554448_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); } LA1: ; } N_NIMCALL(NI, startblock_544978_839829468)(Tcproc530021* p0, NimStringDesc* start0, Ropeobj179006** args0, NI args0Len0) { NI result0; result0 = (NI)0; linecg_533707_839829468(p0, ((Tcprocsection530011) 2), start0, args0, args0Len0); (*p0).labels += ((NI) 1); result0 = ((*p0).blocks ? (*p0).blocks->Sup.len : 0); (*p0).blocks = (TY530095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock530019), ((NI) ((NI)(result0 + ((NI) 1))))); (*p0).blocks->data[result0].id = ((NI) ((*p0).labels)); (*p0).blocks->data[result0].nestedtrystmts = ((NI16) (((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0))); (*p0).blocks->data[result0].nestedexceptstmts = ((NI16) ((*p0).inexceptblock)); return result0; } N_NIMCALL(Ropeobj179006*, blockbody_545025_839829468)(Tblock530019* b0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = (*b0).sections[(((Tcprocsection530011) 0))- 0]; { TY179507 LOC5; if (!(((NI16) 0) < (*b0).framelen)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_179401_2381377266(((NI64) ((*b0).framelen))); addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_554), LOC5, 1); } LA3: ; add_179482_2381377266(&result0, (*b0).sections[(((Tcprocsection530011) 1))- 0]); add_179482_2381377266(&result0, (*b0).sections[(((Tcprocsection530011) 2))- 0]); return result0; } N_NIMCALL(void, endblock_545035_839829468)(Tcproc530021* p0, Ropeobj179006* blockend0) { NI topblock0; Ropeobj179006* LOC1; topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); LOC1 = (Ropeobj179006*)0; LOC1 = blockbody_545025_839829468((&(*p0).blocks->data[topblock0])); add_179482_2381377266(&(*p0).blocks->data[(NI)(topblock0 - ((NI) 1))].sections[(((Tcprocsection530011) 2))- 0], LOC1); (*p0).blocks = (TY530095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock530019), ((NI) (topblock0))); line_533690_839829468(p0, ((Tcprocsection530011) 2), blockend0); } N_NIMCALL(void, endblock_545060_839829468)(Tcproc530021* p0) { NI topblock0; Ropeobj179006* blockend0; NI16 framelen0; topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); { TY179507 LOC5; if (!!(((*p0).blocks->data[topblock0].label == NIM_NIL))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = (*p0).blocks->data[topblock0].label; blockend0 = ropecg_533407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_552), LOC5, 1); } goto LA1; LA3: ; { TY534289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); blockend0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_160), LOC7, 0); } LA1: ; framelen0 = (*p0).blocks->data[topblock0].framelen; { TY179507 LOC12; if (!(((NI16) 0) < framelen0)) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_179401_2381377266(((NI64) (framelen0))); addf_180205_2381377266(&blockend0, ((NimStringDesc*) &T839829468_553), LOC12, 1); } LA10: ; endblock_545035_839829468(p0, blockend0); } N_NIMCALL(void, genblock_547083_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { NI oldbreakidx_547099_839829468; TY534289 LOC8; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_298441_850551059((*n0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind293808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_538032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA6: ; oldbreakidx_547099_839829468 = (*p0).breakidx; memset((void*)LOC8, 0, sizeof(LOC8)); (*p0).breakidx = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC8, 0); { Tsym293834* sym0; if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 1)))) goto LA11; sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; (*sym0).loc.k = ((Tlockind293808) 10); (*sym0).position = (NI)((*p0).breakidx + ((NI) 1)); } LA11: ; expr_540248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], d0); endblock_545060_839829468(p0); (*p0).breakidx = oldbreakidx_547099_839829468; } N_NIMCALL(void, genstmtlistexpr_559402_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { NI length0; length0 = sonslen_296351_850551059(n0); { NI i_559420_839829468; NI HEX3Atmp_559424_839829468; NI res_559427_839829468; i_559420_839829468 = (NI)0; HEX3Atmp_559424_839829468 = (NI)0; HEX3Atmp_559424_839829468 = (NI)(length0 - ((NI) 2)); res_559427_839829468 = ((NI) 0); { while (1) { if (!(res_559427_839829468 <= HEX3Atmp_559424_839829468)) goto LA3; i_559420_839829468 = res_559427_839829468; genstmts_540244_839829468(p0, (*n0).kindU.S6.sons->data[i_559420_839829468]); res_559427_839829468 += ((NI) 1); } LA3: ; } } { if (!(((NI) 0) < length0)) goto LA6; expr_540248_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0); } LA6: ; } N_NIMCALL(void, genif_545982_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Tloc293816 a0; Ropeobj179006* lelse0; Ropeobj179006* lend0; memset((void*)(&a0), 0, sizeof(a0)); lelse0 = (Ropeobj179006*)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_298441_850551059((*n0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind293808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_538032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA6: ; genlinedir_533823_839829468(p0, n0); lend0 = getlabel_540217_839829468(p0); { NI i_546011_839829468; NI HEX3Atmp_546435_839829468; NI LOC9; NI res_546438_839829468; i_546011_839829468 = (NI)0; HEX3Atmp_546435_839829468 = (NI)0; LOC9 = (NI)0; LOC9 = sonslen_296351_850551059(n0); HEX3Atmp_546435_839829468 = (NI)(LOC9 - ((NI) 1)); res_546438_839829468 = ((NI) 0); { while (1) { Tnode293802* it0; if (!(res_546438_839829468 <= HEX3Atmp_546435_839829468)) goto LA11; i_546011_839829468 = res_546438_839829468; { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = ((*d0).k == ((Tlockind293808) 1)); if (!(LOC14)) goto LA15; LOC14 = isemptytype_298441_850551059((*n0).typ); LA15: ; if (!LOC14) goto LA16; (*d0).k = ((Tlockind293808) 0); } LA16: ; it0 = (*n0).kindU.S6.sons->data[i_546011_839829468]; { NI LOC20; TY534289 LOC23; NI LOC24; TY533811 LOC25; LOC20 = (NI)0; LOC20 = len_294081_850551059(it0); if (!(LOC20 == ((NI) 2))) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); LOC24 = (NI)0; LOC24 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC23, 0); initlocexprsingleuse_540289_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], (&a0)); lelse0 = getlabel_540217_839829468(p0); (*p0).labels += ((NI) 1); memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = rdloc_539188_839829468((&a0)); LOC25[1] = lelse0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_555), LOC25, 2); { NIM_BOOL LOC28; Ropeobj179006** LOC32; Ropeobj179006** LOC33; LOC28 = (NIM_BOOL)0; LOC28 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC28) goto LA29; LOC28 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA29: ; if (!LOC28) goto LA30; LOC32 = (Ropeobj179006**)0; LOC32 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179487_2381377266(LOC32, ((NimStringDesc*) &T839829468_223)); expr_540248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0); LOC33 = (Ropeobj179006**)0; LOC33 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179487_2381377266(LOC33, ((NimStringDesc*) &T839829468_280)); } goto LA26; LA30: ; { expr_540248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0); } LA26: ; endblock_545060_839829468(p0); { NI LOC37; TY179507 LOC40; LOC37 = (NI)0; LOC37 = sonslen_296351_850551059(n0); if (!(((NI) 1) < LOC37)) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = lend0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_556), LOC40, 1); } LA38: ; fixlabel_540230_839829468(p0, lelse0); } goto LA18; LA21: ; { NI LOC42; TY534289 LOC45; NI LOC46; LOC42 = (NI)0; LOC42 = len_294081_850551059(it0); if (!(LOC42 == ((NI) 1))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (NI)0; LOC46 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0); expr_540248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], d0); endblock_545060_839829468(p0); } goto LA18; LA43: ; { internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_557)); } LA18: ; res_546438_839829468 += ((NI) 1); } LA11: ; } } { NI LOC50; LOC50 = (NI)0; LOC50 = sonslen_296351_850551059(n0); if (!(((NI) 1) < LOC50)) goto LA51; fixlabel_540230_839829468(p0, lend0); } LA51: ; } N_NIMCALL(void, downconv_559581_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; expr_540248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], d0); } goto LA1; LA5: ; { Ttype293840* dest0; Tnode293802* arg0; Ttype293840* src0; Tloc293816 a0; Ropeobj179006* r0; NIM_BOOL isref0; Ttype293840* LOC10; dest0 = skiptypes_297099_850551059((*n0).typ, IL64(211106247256320)); arg0 = (*n0).kindU.S6.sons->data[((NI) 0)]; { while (1) { if (!((*arg0).kind == ((Tnodekind293020) 66))) goto LA9; arg0 = (*arg0).kindU.S6.sons->data[((NI) 0)]; } LA9: ; } src0 = skiptypes_297099_850551059((*arg0).typ, IL64(211106247256320)); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, arg0, (&a0)); r0 = rdloc_539188_839829468((&a0)); LOC10 = (Ttype293840*)0; LOC10 = skiptypes_297099_850551059((*arg0).typ, IL64(211106232576256)); isref0 = ((14680064 &((NU64)1<<((NU)((*LOC10).kind)&63U)))!=0); { if (!isref0) goto LA13; add_179487_2381377266(&r0, ((NimStringDesc*) &T839829468_558)); } goto LA11; LA13: ; { add_179487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); } LA11: ; { NI i_559650_839829468; NI HEX3Atmp_559677_839829468; NI LOC17; NI res_559680_839829468; i_559650_839829468 = (NI)0; HEX3Atmp_559677_839829468 = (NI)0; LOC17 = (NI)0; LOC17 = inheritancediff_327252_3876443242(dest0, src0); HEX3Atmp_559677_839829468 = (LOC17 > 0? (LOC17) : -(LOC17)); res_559680_839829468 = ((NI) 2); { while (1) { if (!(res_559680_839829468 <= HEX3Atmp_559677_839829468)) goto LA19; i_559650_839829468 = res_559680_839829468; add_179487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); res_559680_839829468 += ((NI) 1); } LA19: ; } } { if (!isref0) goto LA22; { NIM_BOOL LOC26; Ttype293840* LOC28; TY533811 LOC31; LOC26 = (NIM_BOOL)0; LOC26 = ((*d0).k == ((Tlockind293808) 0)); if (!(LOC26)) goto LA27; LOC28 = (Ttype293840*)0; LOC28 = skiptypes_297099_850551059((*n0).typ, IL64(211106232576256)); LOC26 = ((14680064 &((NU64)1<<((NU)((*LOC28).kind)&63U)))!=0); LA27: ; if (!LOC26) goto LA29; gettemp_538032_839829468(p0, (*n0).typ, d0, NIM_FALSE); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = rdloc_539188_839829468((&(*d0))); LOC31[1] = r0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_559), LOC31, 2); } goto LA24; LA29: ; { r0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_52), r0); putintodest_551468_839829468(p0, d0, (*n0).typ, r0, a0.s); } LA24: ; } goto LA20; LA22: ; { putintodest_551468_839829468(p0, d0, (*n0).typ, r0, a0.s); } LA20: ; } LA1: ; } N_NIMCALL(void, upconv_559431_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Tloc293816 a0; Ttype293840* dest0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); dest0 = skiptypes_297099_850551059((*n0).typ, IL64(211106247256320)); { NIM_BOOL LOC3; NIM_BOOL LOC5; Ropeobj179006* r0; Ropeobj179006* nilcheck0; Ttype293840* t0; LOC3 = (NIM_BOOL)0; LOC3 = (((*p0).options &(1U<<((NU)(((Toption170009) 1))&31U)))!=0); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = isobjlackingtypefield_534515_839829468(dest0); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; r0 = rdloc_539188_839829468((&a0)); nilcheck0 = NIM_NIL; t0 = skiptypes_297099_850551059(a0.t, IL64(211106232576256)); { while (1) { Ttype293840* LOC23; if (!((14680064 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)) goto LA9; { if (!!(((*t0).kind == ((Ttypekind293244) 23)))) goto LA12; nilcheck0 = r0; } LA12: ; { NIM_BOOL LOC16; NIM_BOOL LOC18; TY179507 LOC22; LOC16 = (NIM_BOOL)0; LOC16 = !(((*t0).kind == ((Ttypekind293244) 23))); if (LOC16) goto LA17; LOC18 = (NIM_BOOL)0; LOC18 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC18) goto LA19; LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA19: ; LOC16 = !(LOC18); LA17: ; if (!LOC16) goto LA20; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = r0; r0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_124), LOC22, 1); } LA20: ; LOC23 = (Ttype293840*)0; LOC23 = lastson_296377_850551059(t0); t0 = skiptypes_297099_850551059(LOC23, IL64(211106232576256)); } LA9: ; } { NIM_BOOL LOC26; LOC26 = (NIM_BOOL)0; LOC26 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC26) goto LA27; LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA27: ; if (!!(LOC26)) goto LA28; { while (1) { NIM_BOOL LOC32; LOC32 = (NIM_BOOL)0; LOC32 = ((*t0).kind == ((Ttypekind293244) 17)); if (!(LOC32)) goto LA33; LOC32 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); LA33: ; if (!LOC32) goto LA31; add_179487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); t0 = skiptypes_297099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360)); } LA31: ; } } LA28: ; { TY536238 LOC38; if (!!((nilcheck0 == NIM_NIL))) goto LA36; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = nilcheck0; LOC38[1] = r0; LOC38[2] = gentypeinfo_536941_839829468((*p0).module, dest0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_560), LOC38, 3); } goto LA34; LA36: ; { TY533811 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = r0; LOC40[1] = gentypeinfo_536941_839829468((*p0).module, dest0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_561), LOC40, 2); } LA34: ; } LA6: ; { TY533811 LOC45; Ropeobj179006* LOC46; if (!!(((*(*(*n0).kindU.S6.sons->data[((NI) 0)]).typ).kind == ((Ttypekind293244) 17)))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = gettypedesc_536673_839829468((*p0).module, (*n0).typ); LOC45[1] = rdloc_539188_839829468((&a0)); LOC46 = (Ropeobj179006*)0; LOC46 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_430), LOC45, 2); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC46, a0.s); } goto LA41; LA43: ; { TY533811 LOC48; Ropeobj179006* LOC49; memset((void*)LOC48, 0, sizeof(LOC48)); LOC48[0] = gettypedesc_536673_839829468((*p0).module, dest0); LOC48[1] = addrloc_539204_839829468((&a0)); LOC49 = (Ropeobj179006*)0; LOC49 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_429), LOC48, 2); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC49, a0.s); } LA41: ; } N_NIMCALL(void, genrangechck_557591_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0, NimStringDesc* magic0) { Tloc293816 a0; Ttype293840* dest0; memset((void*)(&a0), 0, sizeof(a0)); dest0 = skiptypes_297099_850551059((*n0).typ, IL64(211106240964864)); { NIM_BOOL LOC3; Ttype293840* LOC5; TY533811 LOC8; Ropeobj179006* LOC9; LOC3 = (NIM_BOOL)0; LOC3 = !((((*p0).options &(1U<<((NU)(((Toption170009) 3))&31U)))!=0)); if (LOC3) goto LA4; LOC5 = (Ttype293840*)0; LOC5 = skiptypes_297099_850551059(dest0, 1048576); LOC3 = ((IL64(34084860461056) &((NU64)1<<((NU)((*LOC5).kind)&63U)))!=0); LA4: ; if (!LOC3) goto LA6; initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = gettypedesc_536673_839829468((*p0).module, dest0); LOC8[1] = rdcharloc_539227_839829468((&a0)); LOC9 = (Ropeobj179006*)0; LOC9 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_430), LOC8, 2); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC9, a0.s); } goto LA1; LA6: ; { TY537475 LOC11; Ropeobj179006* LOC12; initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_536673_839829468((*p0).module, dest0); LOC11[1] = rdcharloc_539227_839829468((&a0)); LOC11[2] = genliteral_550476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], dest0); LOC11[3] = genliteral_550476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 2)], dest0); LOC11[4] = rope_179277_2381377266(magic0); LOC12 = (Ropeobj179006*)0; LOC12 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_562), LOC11, 5); putintodest_551468_839829468(p0, d0, dest0, LOC12, a0.s); } LA1: ; } N_NIMCALL(void, convstrtocstr_557643_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Tloc293816 a0; Ttype293840* LOC1; TY179507 LOC2; Ropeobj179006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (Ttype293840*)0; LOC1 = skiptypes_297099_850551059((*n0).typ, IL64(211106240964864)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_539188_839829468((&a0)); LOC3 = (Ropeobj179006*)0; LOC3 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_485), LOC2, 1); putintodest_551468_839829468(p0, d0, LOC1, LOC3, a0.s); } N_NIMCALL(void, convcstrtostr_557655_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { Tloc293816 a0; Ttype293840* LOC1; TY179507 LOC2; Ropeobj179006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (Ttype293840*)0; LOC1 = skiptypes_297099_850551059((*n0).typ, IL64(211106240964864)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_539188_839829468((&a0)); LOC3 = (Ropeobj179006*)0; LOC3 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_411), LOC2, 1); putintodest_551468_839829468(p0, d0, LOC1, LOC3, a0.s); gcusage_555439_839829468(n0); } static N_INLINE(NIM_BOOL, isroutine_298324_850551059)(Tsym293834* s0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((258048 &(1U<<((NU)((*s0).kind)&31U)))!=0); return result0; } static N_INLINE(NIM_BOOL, isconstclosure_558810_839829468)(Tnode293802* n0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC2)) goto LA3; LOC2 = isroutine_298324_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA4; LOC1 = ((*(*n0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind293020) 23)); LA4: ; result0 = LOC1; return result0; } N_NIMCALL(void, genclosure_558836_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { { NIM_BOOL LOC3; Ropeobj179006* tmp0; Ropeobj179006* LOC6; TY536238 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = isconstclosure_558810_839829468(n0); if (!LOC3) goto LA4; (*(*p0).module).labels += ((NI) 1); LOC6 = (Ropeobj179006*)0; LOC6 = rope_179401_2381377266(((NI64) ((*(*p0).module).labels))); tmp0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_566), LOC6); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_536673_839829468((*p0).module, (*n0).typ); LOC7[1] = tmp0; LOC7[2] = genconstexpr_555849_839829468(p0, n0); addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC7, 3); putintodest_551468_839829468(p0, d0, (*n0).typ, tmp0, ((Tstorageloc293812) 1)); } goto LA1; LA4: ; { Tloc293816 tmp0; Tloc293816 a0; Tloc293816 b0; TY536238 LOC14; memset((void*)(&tmp0), 0, sizeof(tmp0)); memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&b0)); { Tnode293802* LOC11; LOC11 = (Tnode293802*)0; LOC11 = skipconv_329882_3876443242((*n0).kindU.S6.sons->data[((NI) 0)]); if (!((*LOC11).kind == ((Tnodekind293020) 155))) goto LA12; internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_567)); } LA12: ; gettemp_538032_839829468(p0, (*n0).typ, (&tmp0), NIM_FALSE); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_539188_839829468((&tmp0)); LOC14[1] = rdloc_539188_839829468((&a0)); LOC14[2] = rdloc_539188_839829468((&b0)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_568), LOC14, 3); putlocintodest_540258_839829468(p0, d0, (&tmp0)); } LA1: ; } static N_INLINE(Ropeobj179006*, assignlabel_545020_839829468)(Tblock530019* b0) { Ropeobj179006* result0; Ropeobj179006* LOC1; result0 = (Ropeobj179006*)0; LOC1 = (Ropeobj179006*)0; LOC1 = rope_179401_2381377266(((NI64) ((*b0).id))); unsureAsgnRef((void**) (&(*b0).label), HEX26_179452_2381377266(((NimStringDesc*) &T839829468_296), LOC1)); result0 = (*b0).label; return result0; } N_NIMCALL(void, gencomputedgoto_546744_839829468)(Tcproc530021* p0, Tnode293802* n0) { NI casepos0; NI arraysize0; NI id0; Ropeobj179006* tmp0; TY179507 LOC27; Ropeobj179006* gotoarray0; TY533811 LOC28; TY179507 LOC33; NI topblock0; Ropeobj179006* oldbody0; Ropeobj179006* tailb0; Ropeobj179006* taila0; Tnode293802* casestmt0; Tloc293816 a_546871_839829468; TY533811 LOC41; { casepos0 = ((NI) -1); arraysize0 = (NI)0; { NI i_546768_839829468; NI HEX3Atmp_546934_839829468; NI LOC2; NI res_546937_839829468; i_546768_839829468 = (NI)0; HEX3Atmp_546934_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_294081_850551059(n0); HEX3Atmp_546934_839829468 = (LOC2 - 1); res_546937_839829468 = ((NI) 0); { while (1) { Tnode293802* it0; if (!(res_546937_839829468 <= HEX3Atmp_546934_839829468)) goto LA4; i_546768_839829468 = res_546937_839829468; it0 = (*n0).kindU.S6.sons->data[i_546768_839829468]; { NI64 asize0; if (!((*it0).kind == ((Tnodekind293020) 97))) goto LA7; { Tnode293802* LOC11; LOC11 = (Tnode293802*)0; LOC11 = lastson_296364_850551059(it0); if (!!(((*LOC11).kind == ((Tnodekind293020) 85)))) goto LA12; localerror_197085_155036129((*it0).info, ((NimStringDesc*) &T839829468_570)); goto BeforeRet; } LA12: ; casepos0 = i_546768_839829468; asize0 = lengthord_321007_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ); { if (!(IL64(10000) < asize0)) goto LA16; localerror_197085_155036129((*it0).info, ((NimStringDesc*) &T839829468_571)); goto BeforeRet; } LA16: ; arraysize0 = ((NI) (asize0)); { NI64 LOC20; LOC20 = (NI64)0; LOC20 = firstord_321001_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ); if (!!((LOC20 == IL64(0)))) goto LA21; localerror_197085_155036129((*it0).info, ((NimStringDesc*) &T839829468_572)); goto BeforeRet; } LA21: ; } LA7: ; res_546937_839829468 += ((NI) 1); } LA4: ; } } { if (!(casepos0 < ((NI) 0))) goto LA25; localerror_197085_155036129((*n0).info, ((NimStringDesc*) &T839829468_573)); goto BeforeRet; } LA25: ; id0 = (NI)(((NI) ((*p0).labels)) + ((NI) 1)); (*p0).labels += (NI)(arraysize0 + ((NI) 1)); memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = rope_179401_2381377266(((NI64) (id0))); tmp0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_574), LOC27, 1); memset((void*)LOC28, 0, sizeof(LOC28)); LOC28[0] = tmp0; LOC28[1] = rope_179401_2381377266(((NI64) (arraysize0))); gotoarray0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_575), LOC28, 2); { NI i_546819_839829468; NI HEX3Atmp_546942_839829468; NI res_546945_839829468; i_546819_839829468 = (NI)0; HEX3Atmp_546942_839829468 = (NI)0; HEX3Atmp_546942_839829468 = (NI)(arraysize0 - ((NI) 1)); res_546945_839829468 = ((NI) 1); { while (1) { TY179507 LOC32; if (!(res_546945_839829468 <= HEX3Atmp_546942_839829468)) goto LA31; i_546819_839829468 = res_546945_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = rope_179401_2381377266(((NI64) ((NI)(((NI) (id0)) + i_546819_839829468)))); addf_180205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_576), LOC32, 1); res_546945_839829468 += ((NI) 1); } LA31: ; } } memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rope_179401_2381377266(((NI64) ((NI)(((NI) (id0)) + arraysize0)))); addf_180205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_577), LOC33, 1); line_533690_839829468(p0, ((Tcprocsection530011) 0), gotoarray0); topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); oldbody0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection530011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection530011) 2))- 0]), NIM_NIL); { NI j_546854_839829468; NI HEX3Atmp_546950_839829468; NI HEX3Atmp_546951_839829468; NI LOC35; NI res_546954_839829468; j_546854_839829468 = (NI)0; HEX3Atmp_546950_839829468 = (NI)0; HEX3Atmp_546951_839829468 = (NI)0; HEX3Atmp_546950_839829468 = (NI)(casepos0 + ((NI) 1)); LOC35 = (NI)0; LOC35 = len_294081_850551059(n0); HEX3Atmp_546951_839829468 = (LOC35 - 1); res_546954_839829468 = HEX3Atmp_546950_839829468; { while (1) { if (!(res_546954_839829468 <= HEX3Atmp_546951_839829468)) goto LA37; j_546854_839829468 = res_546954_839829468; genstmts_540244_839829468(p0, (*n0).kindU.S6.sons->data[j_546854_839829468]); res_546954_839829468 += ((NI) 1); } LA37: ; } } tailb0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection530011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection530011) 2))- 0]), NIM_NIL); { NI j_546866_839829468; NI HEX3Atmp_546959_839829468; NI res_546962_839829468; j_546866_839829468 = (NI)0; HEX3Atmp_546959_839829468 = (NI)0; HEX3Atmp_546959_839829468 = (NI)(casepos0 - ((NI) 1)); res_546962_839829468 = ((NI) 0); { while (1) { if (!(res_546962_839829468 <= HEX3Atmp_546959_839829468)) goto LA40; j_546866_839829468 = res_546962_839829468; genstmts_540244_839829468(p0, (*n0).kindU.S6.sons->data[j_546866_839829468]); res_546962_839829468 += ((NI) 1); } LA40: ; } } taila0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection530011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection530011) 2))- 0]), HEX26_179418_2381377266(oldbody0, taila0)); casestmt0 = (*n0).kindU.S6.sons->data[casepos0]; memset((void*)(&a_546871_839829468), 0, sizeof(a_546871_839829468)); initlocexpr_540283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a_546871_839829468)); memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = tmp0; LOC41[1] = rdloc_539188_839829468((&a_546871_839829468)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_578), LOC41, 2); { NI i_546894_839829468; NI HEX3Atmp_546978_839829468; NI LOC43; NI res_546981_839829468; i_546894_839829468 = (NI)0; HEX3Atmp_546978_839829468 = (NI)0; LOC43 = (NI)0; LOC43 = len_294081_850551059(casestmt0); HEX3Atmp_546978_839829468 = (LOC43 - 1); res_546981_839829468 = ((NI) 1); { while (1) { TY534289 LOC46; NI LOC47; Tnode293802* it0; Tnode293802* LOC57; Ropeobj179006** LOC58; Ropeobj179006** LOC59; Tloc293816 a0; TY533811 LOC60; if (!(res_546981_839829468 <= HEX3Atmp_546978_839829468)) goto LA45; i_546894_839829468 = res_546981_839829468; memset((void*)LOC46, 0, sizeof(LOC46)); LOC47 = (NI)0; LOC47 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC46, 0); it0 = (*casestmt0).kindU.S6.sons->data[i_546894_839829468]; { NI j_546910_839829468; NI HEX3Atmp_546970_839829468; NI LOC49; NI res_546973_839829468; j_546910_839829468 = (NI)0; HEX3Atmp_546970_839829468 = (NI)0; LOC49 = (NI)0; LOC49 = len_294081_850551059(it0); HEX3Atmp_546970_839829468 = (NI)(LOC49 - ((NI) 2)); res_546973_839829468 = ((NI) 0); { while (1) { NI64 val0; TY179507 LOC56; if (!(res_546973_839829468 <= HEX3Atmp_546970_839829468)) goto LA51; j_546910_839829468 = res_546973_839829468; { if (!((*(*it0).kindU.S6.sons->data[j_546910_839829468]).kind == ((Tnodekind293020) 44))) goto LA54; localerror_197085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579)); goto BeforeRet; } LA54: ; val0 = getordvalue_321129_3876443242((*it0).kindU.S6.sons->data[j_546910_839829468]); memset((void*)LOC56, 0, sizeof(LOC56)); LOC56[0] = intliteral_540270_839829468((NI64)((NI64)(val0 + ((NI64) (id0))) + IL64(1))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_580), LOC56, 1); res_546973_839829468 += ((NI) 1); } LA51: ; } } LOC57 = (Tnode293802*)0; LOC57 = lastson_296364_850551059(it0); genstmts_540244_839829468(p0, LOC57); LOC58 = (Ropeobj179006**)0; LOC58 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179482_2381377266(LOC58, tailb0); LOC59 = (Ropeobj179006**)0; LOC59 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); add_179482_2381377266(LOC59, taila0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC60, 0, sizeof(LOC60)); LOC60[0] = tmp0; LOC60[1] = rdloc_539188_839829468((&a0)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_578), LOC60, 2); endblock_545060_839829468(p0); res_546981_839829468 += ((NI) 1); } LA45: ; } } }BeforeRet: ; } N_NIMCALL(void, genwhilestmt_546985_839829468)(Tcproc530021* p0, Tnode293802* t0) { Tloc293816 a0; NI oldbreakidx_547011_839829468; TY534289 LOC1; Tnode293802* loopbody0; memset((void*)(&a0), 0, sizeof(a0)); (*p0).withinloop += ((NI) 1); genlinedir_533823_839829468(p0, t0); oldbreakidx_547011_839829468 = (*p0).breakidx; memset((void*)LOC1, 0, sizeof(LOC1)); (*p0).breakidx = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_569), LOC1, 0); (*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE; initlocexpr_540283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); { NIM_BOOL LOC4; Ropeobj179006* label0; TY533811 LOC8; LOC4 = (NIM_BOOL)0; LOC4 = !(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 6))); if (LOC4) goto LA5; LOC4 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval == IL64(0)); LA5: ; if (!LOC4) goto LA6; label0 = assignlabel_545020_839829468((&(*p0).blocks->data[(*p0).breakidx])); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_539188_839829468((&a0)); LOC8[1] = label0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_555), LOC8, 2); } LA6: ; loopbody0 = (*t0).kindU.S6.sons->data[((NI) 1)]; { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = stmtscontainpragma_529083_2036603609(loopbody0, ((Tspecialword276003) 182)); if (!(LOC11)) goto LA12; LOC11 = ((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 1))&7U)))!=0); LA12: ; if (!LOC11) goto LA13; { NIM_BOOL LOC17; NI LOC18; LOC17 = (NIM_BOOL)0; LOC18 = (NI)0; LOC18 = len_294081_850551059(loopbody0); LOC17 = (LOC18 == ((NI) 2)); if (!(LOC17)) goto LA19; LOC17 = ((*(*loopbody0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 1)); LA19: ; if (!LOC17) goto LA20; loopbody0 = (*loopbody0).kindU.S6.sons->data[((NI) 1)]; } LA20: ; gencomputedgoto_546744_839829468(p0, loopbody0); } goto LA9; LA13: ; { genstmts_540244_839829468(p0, loopbody0); } LA9: ; { TY534289 LOC27; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 19))&31U)))!=0)) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_581), LOC27, 0); } LA25: ; endblock_545060_839829468(p0); (*p0).breakidx = oldbreakidx_547011_839829468; (*p0).withinloop -= ((NI) 1); } N_NIMCALL(void, gengotovar_545258_839829468)(Tcproc530021* p0, Tnode293802* value0) { { if (!!(((*value0).kind >= ((Tnodekind293020) 5) && (*value0).kind <= ((Tnodekind293020) 15)))) goto LA3; localerror_197085_155036129((*value0).info, ((NimStringDesc*) &T839829468_582)); } goto LA1; LA3: ; { TY179507 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_179401_2381377266((*value0).kindU.S1.intval); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_583), LOC6, 1); } LA1: ; } N_NIMCALL(void, varindynamiclib_539812_839829468)(Tcgen530027* m0, Tsym293834* sym0) { Tlib293820* lib0; Ropeobj179006* extname0; Ropeobj179006* tmp0; TY536235 LOC1; NimStringDesc* LOC2; TY533811 LOC3; lib0 = (*sym0).annex; extname0 = (*sym0).loc.r; loaddynamiclib_560481_839829468(m0, lib0); (*sym0).loc.flags |= ((NU16)1)<<((((Tlocflag293810) 0))%(sizeof(NU16)*8)); tmp0 = mangledynlibproc_539816_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0); (*m0).labels += ((NI) 2); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = tmp0; LOC1[1] = gettypedesc_536673_839829468(m0, (*sym0).typ); LOC1[2] = (*lib0).name; LOC2 = (NimStringDesc*)0; LOC2 = HEX24_179856_2381377266(extname0); LOC1[3] = makecstring_192638_155036129(LOC2); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 16))- 0], ((NimStringDesc*) &T839829468_584), LOC1, 4); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = (*sym0).loc.r; LOC3[1] = gettypedesc_536673_839829468(m0, (*sym0).loc.t); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 9))- 0], ((NimStringDesc*) &T839829468_585), LOC3, 2); } N_NIMCALL(void, assignglobalvar_539819_839829468)(Tcproc530021* p0, Tsym293834* s0) { { { Ropeobj179006* LOC5; if (!((*s0).loc.k == ((Tlockind293808) 0))) goto LA3; LOC5 = (Ropeobj179006*)0; LOC5 = manglename_534205_839829468(s0); fillloc_533282_839829468((&(*s0).loc), ((Tlockind293808) 3), (*s0).typ, LOC5, ((Tstorageloc293812) 3)); } LA3: ; { Tcgen530027* q0; if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag293810) 4))&15U)))!=0)) goto LA8; q0 = findpendingmodule_533241_839829468((*p0).module, s0); { NIM_BOOL LOC12; NIM_BOOL LOC14; LOC12 = (NIM_BOOL)0; LOC12 = !((q0 == NIM_NIL)); if (!(LOC12)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_269862_2627731572((&(*q0).declaredthings), (*s0).Sup.id); LOC12 = !(LOC14); LA13: ; if (!LOC12) goto LA15; varindynamiclib_539812_839829468(q0, s0); } goto LA10; LA15: ; { asgnRefNoCycle((void**) (&(*s0).loc.r), mangledynlibproc_539816_839829468(s0)); } LA10: ; goto BeforeRet; } LA8: ; useheader_533369_839829468((*p0).module, s0); { if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0)) goto LA20; goto BeforeRet; } LA20: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag293184) 22))&31U)))!=0)) goto LA24; declarethreadvar_539676_839829468((*p0).module, s0, (((*s0).flags &(1U<<((NU)(((Tsymflag293184) 5))&31U)))!=0)); } goto LA22; LA24: ; { Ropeobj179006* decl0; Ropeobj179006* td0; decl0 = NIM_NIL; td0 = gettypedesc_536673_839829468((*p0).module, (*s0).loc.t); { TY179507 LOC43; if (!(*s0).constraint == 0) goto LA29; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag293184) 5))&31U)))!=0)) goto LA33; add_179487_2381377266(&decl0, ((NimStringDesc*) &T839829468_240)); } LA33: ; add_179482_2381377266(&decl0, td0); { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag293184) 8))&31U)))!=0)) goto LA37; add_179487_2381377266(&decl0, ((NimStringDesc*) &T839829468_121)); } LA37: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag293184) 7))&31U)))!=0)) goto LA41; add_179487_2381377266(&decl0, ((NimStringDesc*) &T839829468_122)); } LA41: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = (*s0).loc.r; addf_180205_2381377266(&decl0, ((NimStringDesc*) &T839829468_242), LOC43, 1); } goto LA27; LA29: ; { NimStringDesc* LOC45; TY533811 LOC46; LOC45 = (NimStringDesc*)0; LOC45 = rawNewString((*(*s0).constraint).kindU.S3.strval->Sup.len + 3); appendString(LOC45, (*(*s0).constraint).kindU.S3.strval); appendString(LOC45, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC46, 0, sizeof(LOC46)); LOC46[0] = td0; LOC46[1] = (*s0).loc.r; decl0 = HEX25_179905_2381377266(LOC45, LOC46, 2); } LA27: ; add_179482_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 9))- 0], decl0); } LA22: ; { if (!(((NI) 0) < (*p0).withinloop)) goto LA49; resetloc_539350_839829468(p0, (&(*s0).loc)); } LA49: ; { TY536238 LOC55; NimStringDesc* LOC56; NimStringDesc* LOC57; if (!(((*(*(*p0).module).module).options & 163840) == 163840)) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC56 = (NimStringDesc*)0; LOC56 = rawNewString((*(*(*s0).owner).name).s->Sup.len + (*(*s0).name).s->Sup.len + 1); appendString(LOC56, (*(*(*s0).owner).name).s); appendChar(LOC56, 46); appendString(LOC56, (*(*s0).name).s); LOC57 = (NimStringDesc*)0; LOC57 = nsuNormalize(LOC56); LOC55[0] = makecstring_192638_155036129(LOC57); LOC55[1] = (*s0).loc.r; LOC55[2] = gentypeinfo_536941_839829468((*p0).module, (*s0).typ); appcg_533632_839829468((*p0).module, &(*(*p0).module).s[(((Tcfilesection530005) 15))- 0], ((NimStringDesc*) &T839829468_586), LOC55, 3); } LA53: ; }BeforeRet: ; } N_NIMCALL(Ropeobj179006*, gentraverseprocforglobal_539032_839829468)(Tcgen530027* m0, Tsym293834* s0) { Ropeobj179006* result0; Ropeobj179006* LOC1; Ttraversalclosure538019 c0; Tcproc530021* p0; Ropeobj179006* sloc0; Ropeobj179006* header0; TY179507 LOC8; Ropeobj179006* generatedproc0; TY536235 LOC9; Ropeobj179006** LOC10; Ropeobj179006** LOC11; Ropeobj179006** LOC12; TY179507 LOC13; result0 = (Ropeobj179006*)0; LOC1 = (Ropeobj179006*)0; LOC1 = gentypeinfo_536941_839829468(m0, (*s0).loc.t); memset((void*)(&c0), 0, sizeof(c0)); p0 = newproc_530206_3723162438(NIM_NIL, m0); sloc0 = (*s0).loc.r; result0 = gettempname_534598_839829468(m0); { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (((*s0).flags &(1U<<((NU)(((Tsymflag293184) 22))&31U)))!=0); if (!(LOC4)) goto LA5; LOC4 = emulatedthreadvars_533949_839829468(); LA5: ; if (!LOC4) goto LA6; accessthreadlocalvar_533945_839829468(p0, s0); sloc0 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_288), sloc0); } LA6: ; c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_587)); c0.p = p0; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = result0; header0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_588), LOC8, 1); gentraverseproc_538022_839829468((&c0), sloc0, (*s0).loc.t); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = header0; LOC10 = (Ropeobj179006**)0; LOC10 = s_530179_3723162438(p0, ((Tcprocsection530011) 0)); LOC9[1] = (*LOC10); LOC11 = (Ropeobj179006**)0; LOC11 = s_530179_3723162438(p0, ((Tcprocsection530011) 1)); LOC9[2] = (*LOC11); LOC12 = (Ropeobj179006**)0; LOC12 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); LOC9[3] = (*LOC12); generatedproc0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_190), LOC9, 4); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = header0; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC13, 1); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 10))- 0], generatedproc0); return result0; } N_NIMCALL(void, registergcroot_544762_839829468)(Tcproc530021* p0, Tsym293834* v0) { { NIM_BOOL LOC3; Ropeobj179006* prc0; Ropeobj179006** LOC7; TY179507 LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((240 &(1U<<((NU)(gselectedgc_170133_2607990831)&7U)))!=0); if (!(LOC3)) goto LA4; LOC3 = containsgarbagecollectedref_321117_3876443242((*v0).loc.t); LA4: ; if (!LOC3) goto LA5; prc0 = gentraverseprocforglobal_539032_839829468((*p0).module, v0); LOC7 = (Ropeobj179006**)0; LOC7 = procsec_530194_3723162438((*(*p0).module).initproc, ((Tcprocsection530011) 1)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = prc0; appcg_533632_839829468((*p0).module, LOC7, ((NimStringDesc*) &T839829468_589), LOC8, 1); } LA5: ; } static N_INLINE(NIM_BOOL, isassignedimmediately_544781_839829468)(Tnode293802* n0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!((*n0).kind == ((Tnodekind293020) 1))) goto LA3; result0 = NIM_FALSE; goto BeforeRet; } LA3: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = isinvalidreturntype_534550_839829468((*n0).typ); if (!LOC7) goto LA8; result0 = NIM_FALSE; goto BeforeRet; } LA8: ; result0 = NIM_TRUE; }BeforeRet: ; return result0; } N_NIMCALL(void, genasgncall_544695_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* d0) { { Ttype293840* LOC3; LOC3 = (Ttype293840*)0; LOC3 = skiptypes_297099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, 2048); if (!((*LOC3).callconv == ((Tcallingconvention293002) 8))) goto LA4; genclosurecall_541452_839829468(p0, le0, ri0, d0); } goto LA1; LA4: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC7)) goto LA8; LOC7 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; geninfixcall_542929_839829468(p0, le0, ri0, d0); } goto LA1; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC12)) goto LA13; LOC12 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 28))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; gennamedparamcall_543616_839829468(p0, ri0, d0); } goto LA1; LA14: ; { genprefixcall_540960_839829468(p0, le0, ri0, d0); } LA1: ; poststmtactions_533942_839829468(p0); } static N_INLINE(void, loadinto_544928_839829468)(Tcproc530021* p0, Tnode293802* le0, Tnode293802* ri0, Tloc293816* a0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; LOC3 = (NIM_BOOL)0; LOC3 = ((*ri0).kind == ((Tnodekind293020) 27) || (*ri0).kind == ((Tnodekind293020) 29) || (*ri0).kind == ((Tnodekind293020) 30) || (*ri0).kind == ((Tnodekind293020) 31) || (*ri0).kind == ((Tnodekind293020) 26) || (*ri0).kind == ((Tnodekind293020) 28) || (*ri0).kind == ((Tnodekind293020) 32)); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = !(((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3))); if (LOC5) goto LA6; LOC5 = ((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).magic == ((Tmagic293524) 0)); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; genasgncall_544695_839829468(p0, le0, ri0, a0); } goto LA1; LA7: ; { if (!((*ri0).kind == ((Tnodekind293020) 47) || (*ri0).kind == ((Tnodekind293020) 65))) goto LA10; genderef_544921_839829468(p0, ri0, a0, NIM_TRUE); } goto LA1; LA10: ; { expr_540248_839829468(p0, ri0, a0); } LA1: ; } N_NIMCALL(void, gensinglevar_545276_839829468)(Tcproc530021* p0, Tnode293802* a0) { Tsym293834* v0; Tcproc530021* targetproc0; { v0 = (*(*a0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { if (!!(((1082130432 & (*v0).flags) == 0))) goto LA3; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag293184) 30))&31U)))!=0)) goto LA7; gengotovar_545258_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 2)]); } LA7: ; goto BeforeRet; } LA3: ; targetproc0 = p0; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag293184) 3))&31U)))!=0)) goto LA11; { NIM_BOOL LOC15; NIM_BOOL LOC16; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC16 = (((*v0).flags & 96) == 32); if (!(LOC16)) goto LA17; LOC16 = ((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind293020) 1)); LA17: ; LOC15 = LOC16; if (!(LOC15)) goto LA18; LOC15 = !((((*v0).loc.flags & 72) == 0)); LA18: ; if (!LOC15) goto LA19; goto BeforeRet; } LA19: ; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag293184) 9))&31U)))!=0)) goto LA23; targetproc0 = (*(*p0).module).preinitproc; } LA23: ; assignglobalvar_539819_839829468(targetproc0, v0); genobjectinit_539242_839829468((*(*p0).module).preinitproc, ((Tcprocsection530011) 1), (*v0).typ, (&(*v0).loc), NIM_TRUE); { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = (((*v0).flags &(1U<<((NU)(((Tsymflag293184) 6))&31U)))!=0); if (!(LOC27)) goto LA28; LOC27 = !((generatedheader_533201_839829468 == NIM_NIL)); LA28: ; if (!LOC27) goto LA29; genvarprototypeaux_545254_839829468(generatedheader_533201_839829468, v0); } LA29: ; registergcroot_544762_839829468(p0, v0); } goto LA9; LA11: ; { Tnode293802* value0; NIM_BOOL imm0; value0 = (*a0).kindU.S6.sons->data[((NI) 2)]; imm0 = isassignedimmediately_544781_839829468(value0); { NIM_BOOL LOC34; NIM_BOOL LOC35; NIM_BOOL LOC36; NIM_BOOL LOC38; NIM_BOOL LOC42; Ropeobj179006* decl0; Tloc293816 tmp0; LOC34 = (NIM_BOOL)0; LOC35 = (NIM_BOOL)0; LOC36 = (NIM_BOOL)0; LOC36 = imm0; if (!(LOC36)) goto LA37; LOC38 = (NIM_BOOL)0; LOC38 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC38) goto LA39; LOC38 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA39: ; LOC36 = LOC38; LA37: ; LOC35 = LOC36; if (!(LOC35)) goto LA40; LOC35 = ((*p0).splitdecls == ((NI) 0)); LA40: ; LOC34 = LOC35; if (!(LOC34)) goto LA41; LOC42 = (NIM_BOOL)0; LOC42 = containshiddenpointer_321120_3876443242((*v0).typ); LOC34 = !(LOC42); LA41: ; if (!LOC34) goto LA43; genlinedir_533823_839829468(p0, a0); decl0 = localvardecl_539532_839829468(p0, v0); memset((void*)(&tmp0), 0, sizeof(tmp0)); { NIM_BOOL LOC47; NIM_BOOL LOC48; Tnode293802* LOC50; Tnode293802* LOC52; Ropeobj179006* params0; Ttype293840* typ0; TY533811 LOC66; LOC47 = (NIM_BOOL)0; LOC48 = (NIM_BOOL)0; LOC48 = ((*value0).kind == ((Tnodekind293020) 27) || (*value0).kind == ((Tnodekind293020) 29) || (*value0).kind == ((Tnodekind293020) 30) || (*value0).kind == ((Tnodekind293020) 31) || (*value0).kind == ((Tnodekind293020) 26) || (*value0).kind == ((Tnodekind293020) 28) || (*value0).kind == ((Tnodekind293020) 32)); if (!(LOC48)) goto LA49; LOC50 = (Tnode293802*)0; LOC50 = HEX5BHEX5D_294238_850551059(value0, ((NI) 0)); LOC48 = ((*LOC50).kind == ((Tnodekind293020) 3)); LA49: ; LOC47 = LOC48; if (!(LOC47)) goto LA51; LOC52 = (Tnode293802*)0; LOC52 = HEX5BHEX5D_294238_850551059(value0, ((NI) 0)); LOC47 = (((*(*LOC52).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 24))&31U)))!=0); LA51: ; if (!LOC47) goto LA53; params0 = (Ropeobj179006*)0; typ0 = skiptypes_297099_850551059((*(*value0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { NI i_545619_839829468; NI HEX3Atmp_545825_839829468; NI LOC56; NI res_545828_839829468; i_545619_839829468 = (NI)0; HEX3Atmp_545825_839829468 = (NI)0; LOC56 = (NI)0; LOC56 = len_294081_850551059(value0); HEX3Atmp_545825_839829468 = (LOC56 - 1); res_545828_839829468 = ((NI) 1); { while (1) { Ropeobj179006* LOC65; if (!(res_545828_839829468 <= HEX3Atmp_545825_839829468)) goto LA58; i_545619_839829468 = res_545828_839829468; { TY534289 LOC63; Ropeobj179006* LOC64; if (!!((params0 == NIM_NIL))) goto LA61; memset((void*)LOC63, 0, sizeof(LOC63)); LOC64 = (Ropeobj179006*)0; LOC64 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_110), LOC63, 0); add_179482_2381377266(&params0, LOC64); } LA61: ; LOC65 = (Ropeobj179006*)0; LOC65 = genotherarg_540277_839829468(p0, value0, i_545619_839829468, typ0); add_179482_2381377266(&params0, LOC65); res_545828_839829468 += ((NI) 1); } LA58: ; } } memset((void*)LOC66, 0, sizeof(LOC66)); LOC66[0] = decl0; LOC66[1] = params0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_590), LOC66, 2); } goto LA45; LA53: ; { TY533811 LOC68; initlocexprsingleuse_540289_839829468(p0, value0, (&tmp0)); memset((void*)LOC68, 0, sizeof(LOC68)); LOC68[0] = decl0; LOC68[1] = rdloc_539188_839829468((&tmp0)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_591), LOC68, 2); } LA45: ; goto BeforeRet; } LA43: ; assignlocalvar_539614_839829468(p0, v0); initlocalvar_539398_839829468(p0, v0, imm0); } LA9: ; { if (!!(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind293020) 1)))) goto LA71; genlinedir_533823_839829468(targetproc0, a0); loadinto_544928_839829468(targetproc0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&(*v0).loc)); } LA71: ; }BeforeRet: ; } N_NIMCALL(void, genclosurevar_545832_839829468)(Tcproc530021* p0, Tnode293802* a0) { NIM_BOOL immediateasgn0; immediateasgn0 = !(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind293020) 1))); { Tloc293816 v0; if (!immediateasgn0) goto LA3; memset((void*)(&v0), 0, sizeof(v0)); initlocexpr_540283_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (&v0)); genlinedir_533823_839829468(p0, a0); loadinto_544928_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&v0)); } LA3: ; } N_NIMCALL(void, genvartuple_544794_839829468)(Tcproc530021* p0, Tnode293802* n0) { Tloc293816 tup0; Tloc293816 field0; NI L0; NIM_BOOL uselowering0; Ttype293840* t0; { memset((void*)(&tup0), 0, sizeof(tup0)); memset((void*)(&field0), 0, sizeof(field0)); { if (!!(((*n0).kind == ((Tnodekind293020) 36)))) goto LA3; internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592)); } LA3: ; L0 = sonslen_296351_850551059(n0); uselowering0 = NIM_FALSE; { NI i_544822_839829468; NI HEX3Atmp_544905_839829468; NI res_544908_839829468; i_544822_839829468 = (NI)0; HEX3Atmp_544905_839829468 = (NI)0; HEX3Atmp_544905_839829468 = (NI)(L0 - ((NI) 3)); res_544908_839829468 = ((NI) 0); { while (1) { if (!(res_544908_839829468 <= HEX3Atmp_544905_839829468)) goto LA7; i_544822_839829468 = res_544908_839829468; { Tnode293802* LOC10; LOC10 = (Tnode293802*)0; LOC10 = HEX5BHEX5D_294238_850551059(n0, i_544822_839829468); if (!!(((*LOC10).kind == ((Tnodekind293020) 3)))) goto LA11; uselowering0 = NIM_TRUE; goto LA5; } LA11: ; res_544908_839829468 += ((NI) 1); } LA7: ; } } LA5: ; { Tnode293802* LOC17; if (!uselowering0) goto LA15; LOC17 = (Tnode293802*)0; LOC17 = lowertupleunpacking_434037_2218250499(n0, (*p0).prc); genstmts_540244_839829468(p0, LOC17); goto BeforeRet; } LA15: ; genlinedir_533823_839829468(p0, n0); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(L0 - ((NI) 1))], (&tup0)); t0 = getuniquetype_529640_2036603609(tup0.t); { NI i_544846_839829468; NI HEX3Atmp_544914_839829468; NI res_544917_839829468; i_544846_839829468 = (NI)0; HEX3Atmp_544914_839829468 = (NI)0; HEX3Atmp_544914_839829468 = (NI)(L0 - ((NI) 3)); res_544917_839829468 = ((NI) 0); { while (1) { if (!(res_544917_839829468 <= HEX3Atmp_544914_839829468)) goto LA20; i_544846_839829468 = res_544917_839829468; { Tsym293834* v0; v0 = (*(*n0).kindU.S6.sons->data[i_544846_839829468]).kindU.S4.sym; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag293184) 23))&31U)))!=0)) goto LA24; goto LA21; } LA24: ; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag293184) 3))&31U)))!=0)) goto LA28; assignglobalvar_539819_839829468(p0, v0); genobjectinit_539242_839829468(p0, ((Tcprocsection530011) 1), (*v0).typ, (&(*v0).loc), NIM_TRUE); registergcroot_544762_839829468(p0, v0); } goto LA26; LA28: ; { Tnode293802* LOC31; NIM_BOOL LOC32; assignlocalvar_539614_839829468(p0, v0); LOC31 = (Tnode293802*)0; LOC31 = HEX5BHEX5D_294238_850551059(n0, (NI)(L0 - ((NI) 1))); LOC32 = (NIM_BOOL)0; LOC32 = isassignedimmediately_544781_839829468(LOC31); initlocalvar_539398_839829468(p0, v0, LOC32); } LA26: ; initloc_533273_839829468((&field0), ((Tlockind293808) 6), (*t0).sons->data[i_544846_839829468], tup0.s); { TY533811 LOC37; if (!((*t0).kind == ((Ttypekind293244) 18))) goto LA35; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = rdloc_539188_839829468((&tup0)); LOC37[1] = rope_179401_2381377266(((NI64) (i_544846_839829468))); field0.r = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_185), LOC37, 2); } goto LA33; LA35: ; { TY533811 LOC43; { if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_544846_839829468]).kind == ((Tnodekind293020) 3)))) goto LA41; internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592)); } LA41: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = rdloc_539188_839829468((&tup0)); LOC43[1] = manglerecfieldname_535361_839829468((*(*(*t0).n).kindU.S6.sons->data[i_544846_839829468]).kindU.S4.sym, t0); field0.r = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_90), LOC43, 2); } LA33: ; putlocintodest_540258_839829468(p0, (&(*v0).loc), (&field0)); } LA21: ; res_544917_839829468 += ((NI) 1); } LA20: ; } } }BeforeRet: ; } N_NIMCALL(void, genvarstmt_545854_839829468)(Tcproc530021* p0, Tnode293802* n0) { { NI i_545869_839829468; NI HEX3Atmp_545902_839829468; NI LOC2; NI res_545905_839829468; i_545869_839829468 = (NI)0; HEX3Atmp_545902_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(n0); HEX3Atmp_545902_839829468 = (NI)(LOC2 - ((NI) 1)); res_545905_839829468 = ((NI) 0); { while (1) { if (!(res_545905_839829468 <= HEX3Atmp_545902_839829468)) goto LA4; i_545869_839829468 = res_545905_839829468; { Tnode293802* a0; a0 = (*n0).kindU.S6.sons->data[i_545869_839829468]; { if (!((*a0).kind == ((Tnodekind293020) 125))) goto LA8; goto LA5; } LA8: ; { if (!((*a0).kind == ((Tnodekind293020) 35))) goto LA12; { if (!((*(*a0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3))) goto LA16; gensinglevar_545276_839829468(p0, a0); } goto LA14; LA16: ; { genclosurevar_545832_839829468(p0, a0); } LA14: ; } goto LA10; LA12: ; { genvartuple_544794_839829468(p0, a0); } LA10: ; } LA5: ; res_545905_839829468 += ((NI) 1); } LA4: ; } } } static N_INLINE(NIM_BOOL, emitlazily_533248_839829468)(Tsym293834* s0) { NIM_BOOL result0; NIM_BOOL LOC1; Tsym293834* LOC3; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 2))&63U)))!=0); if (LOC1) goto LA2; LOC3 = (Tsym293834*)0; LOC3 = getmodule_300123_2984716966(s0); LOC1 = (((*LOC3).flags &(1U<<((NU)(((Tsymflag293184) 25))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, genconststmt_545909_839829468)(Tcproc530021* p0, Tnode293802* t0) { { NI i_545924_839829468; NI HEX3Atmp_545975_839829468; NI LOC2; NI res_545978_839829468; i_545924_839829468 = (NI)0; HEX3Atmp_545975_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(t0); HEX3Atmp_545975_839829468 = (NI)(LOC2 - ((NI) 1)); res_545978_839829468 = ((NI) 0); { while (1) { if (!(res_545978_839829468 <= HEX3Atmp_545975_839829468)) goto LA4; i_545924_839829468 = res_545978_839829468; { Tnode293802* it0; Tsym293834* c0; it0 = (*t0).kindU.S6.sons->data[i_545924_839829468]; { if (!((*it0).kind == ((Tnodekind293020) 125))) goto LA8; goto LA5; } LA8: ; { if (!!(((*it0).kind == ((Tnodekind293020) 102)))) goto LA12; internalerror_197100_155036129((*t0).info, ((NimStringDesc*) &T839829468_593)); } LA12: ; c0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NIM_BOOL LOC16; LOC16 = (NIM_BOOL)0; LOC16 = containscompiletimeonly_329721_3876443242((*c0).typ); if (!LOC16) goto LA17; goto LA5; } goto LA14; LA17: ; { NIM_BOOL LOC20; NIM_BOOL LOC21; NI LOC24; LOC20 = (NIM_BOOL)0; LOC21 = (NIM_BOOL)0; LOC21 = ((17629200 &((NU64)1<<((NU)((*(*c0).typ).kind)&63U)))!=0); if (!(LOC21)) goto LA22; LOC21 = !((((*c0).loc.flags &(1U<<((NU)(((Tlocflag293810) 3))&15U)))!=0)); LA22: ; LOC20 = LOC21; if (!(LOC20)) goto LA23; LOC24 = (NI)0; LOC24 = len_294081_850551059((*c0).ast); LOC20 = !((LOC24 == ((NI) 0))); LA23: ; if (!LOC20) goto LA25; { NIM_BOOL LOC29; LOC29 = (NIM_BOOL)0; LOC29 = emitlazily_533248_839829468(c0); if (!!(LOC29)) goto LA30; requestconstimpl_540240_839829468(p0, c0); } LA30: ; } goto LA14; LA25: ; LA14: ; } LA5: ; res_545978_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, gencasestringbranch_548100_839829468)(Tcproc530021* p0, Tnode293802* b0, Tloc293816* e0, Ropeobj179006* labl0, Ropeobj179006** branches0, NI branches0Len0) { Tloc293816 x0; NI length0; memset((void*)(&x0), 0, sizeof(x0)); length0 = sonslen_296351_850551059(b0); { NI i_548122_839829468; NI HEX3Atmp_548410_839829468; NI res_548413_839829468; i_548122_839829468 = (NI)0; HEX3Atmp_548410_839829468 = (NI)0; HEX3Atmp_548410_839829468 = (NI)(length0 - ((NI) 2)); res_548413_839829468 = ((NI) 0); { while (1) { NI j0; NI64 LOC4; TY536238 LOC5; if (!(res_548413_839829468 <= HEX3Atmp_548410_839829468)) goto LA3; i_548122_839829468 = res_548413_839829468; initlocexpr_540283_839829468(p0, (*b0).kindU.S6.sons->data[i_548122_839829468], (&x0)); LOC4 = (NI64)0; LOC4 = hashstring_529100_2036603609((*(*b0).kindU.S6.sons->data[i_548122_839829468]).kindU.S3.strval); j0 = ((NI) ((NI64)(LOC4 & ((NI64) ((branches0Len0-1)))))); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468(e0); LOC5[1] = rdloc_539188_839829468((&x0)); LOC5[2] = labl0; appcg_533632_839829468((*p0).module, &branches0[j0], ((NimStringDesc*) &T839829468_595), LOC5, 3); res_548413_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, exprblock_545103_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { TY534289 LOC1; NI LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0); expr_540248_839829468(p0, n0, d0); endblock_545060_839829468(p0); } N_NIMCALL(Ropeobj179006*, gencasesecondpass_547965_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0, NI labid0, NI until0) { Ropeobj179006* result0; Ropeobj179006* lend0; result0 = (Ropeobj179006*)0; lend0 = getlabel_540217_839829468(p0); { NI i_547984_839829468; NI res_548017_839829468; i_547984_839829468 = (NI)0; res_548017_839829468 = ((NI) 1); { while (1) { TY179507 LOC10; if (!(res_548017_839829468 <= until0)) goto LA3; i_547984_839829468 = res_548017_839829468; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = ((*d0).k == ((Tlockind293808) 1)); if (!(LOC6)) goto LA7; LOC6 = isemptytype_298441_850551059((*t0).typ); LA7: ; if (!LOC6) goto LA8; (*d0).k = ((Tlockind293808) 0); } LA8: ; memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rope_179401_2381377266(((NI64) ((NI)(labid0 + i_547984_839829468)))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_599), LOC10, 1); { NI length0; TY179507 LOC15; if (!((*(*t0).kindU.S6.sons->data[i_547984_839829468]).kind == ((Tnodekind293020) 85))) goto LA13; length0 = sonslen_296351_850551059((*t0).kindU.S6.sons->data[i_547984_839829468]); exprblock_545103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_547984_839829468]).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = lend0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_556), LOC15, 1); } goto LA11; LA13: ; { exprblock_545103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_547984_839829468]).kindU.S6.sons->data[((NI) 0)], d0); } LA11: ; res_548017_839829468 += ((NI) 1); } LA3: ; } } result0 = lend0; return result0; } N_NIMCALL(void, gencasegenericbranch_547910_839829468)(Tcproc530021* p0, Tnode293802* b0, Tloc293816* e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj179006* labl0) { Tloc293816 x0; Tloc293816 y0; NI length0; memset((void*)(&x0), 0, sizeof(x0)); memset((void*)(&y0), 0, sizeof(y0)); length0 = sonslen_296351_850551059(b0); { NI i_547932_839829468; NI HEX3Atmp_547958_839829468; NI res_547961_839829468; i_547932_839829468 = (NI)0; HEX3Atmp_547958_839829468 = (NI)0; HEX3Atmp_547958_839829468 = (NI)(length0 - ((NI) 2)); res_547961_839829468 = ((NI) 0); { while (1) { if (!(res_547961_839829468 <= HEX3Atmp_547958_839829468)) goto LA3; i_547932_839829468 = res_547961_839829468; { TY536235 LOC8; if (!((*(*b0).kindU.S6.sons->data[i_547932_839829468]).kind == ((Tnodekind293020) 44))) goto LA6; initlocexpr_540283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_547932_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0)); initlocexpr_540283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_547932_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdcharloc_539227_839829468(e0); LOC8[1] = rdcharloc_539227_839829468((&x0)); LOC8[2] = rdcharloc_539227_839829468((&y0)); LOC8[3] = labl0; linecg_533707_839829468(p0, ((Tcprocsection530011) 2), rangeformat0, LOC8, 4); } goto LA4; LA6: ; { TY536238 LOC10; initlocexpr_540283_839829468(p0, (*b0).kindU.S6.sons->data[i_547932_839829468], (&x0)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdcharloc_539227_839829468(e0); LOC10[1] = rdcharloc_539227_839829468((&x0)); LOC10[2] = labl0; linecg_533707_839829468(p0, ((Tcprocsection530011) 2), eqformat0, LOC10, 3); } LA4: ; res_547961_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(Ropeobj179006*, genifforcaseuntil_548021_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc293816* a0) { Ropeobj179006* result0; NI labid0; result0 = (Ropeobj179006*)0; labid0 = (*p0).labels; { NI i_548042_839829468; NI res_548083_839829468; i_548042_839829468 = (NI)0; res_548083_839829468 = ((NI) 1); { while (1) { if (!(res_548083_839829468 <= until0)) goto LA3; i_548042_839829468 = res_548083_839829468; (*p0).labels += ((NI) 1); { Ropeobj179006* LOC8; Ropeobj179006* LOC9; if (!((*(*t0).kindU.S6.sons->data[i_548042_839829468]).kind == ((Tnodekind293020) 85))) goto LA6; LOC8 = (Ropeobj179006*)0; LOC8 = rope_179401_2381377266(((NI64) ((*p0).labels))); LOC9 = (Ropeobj179006*)0; LOC9 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_296), LOC8); gencasegenericbranch_547910_839829468(p0, (*t0).kindU.S6.sons->data[i_548042_839829468], a0, rangeformat0, eqformat0, LOC9); } goto LA4; LA6: ; { TY179507 LOC11; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rope_179401_2381377266(((NI64) ((*p0).labels))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_598), LOC11, 1); } LA4: ; res_548083_839829468 += ((NI) 1); } LA3: ; } } { NI LOC14; NI gototarget0; TY179507 LOC17; TY179507 LOC18; LOC14 = (NI)0; LOC14 = len_294081_850551059(t0); if (!(until0 < (NI)(LOC14 - ((NI) 1)))) goto LA15; (*p0).labels += ((NI) 1); gototarget0 = (*p0).labels; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rope_179401_2381377266(((NI64) (gototarget0))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_598), LOC17, 1); result0 = gencasesecondpass_547965_839829468(p0, t0, d0, ((NI) (labid0)), until0); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rope_179401_2381377266(((NI64) (gototarget0))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_599), LOC18, 1); } goto LA12; LA15: ; { result0 = gencasesecondpass_547965_839829468(p0, t0, d0, ((NI) (labid0)), until0); } LA12: ; return result0; } N_NIMCALL(void, gencasegeneric_548087_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0) { Tloc293816 a0; Ropeobj179006* lend0; NI LOC1; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (NI)0; LOC1 = sonslen_296351_850551059(t0); lend0 = genifforcaseuntil_548021_839829468(p0, t0, d0, rangeformat0, eqformat0, (NI)(LOC1 - ((NI) 1)), (&a0)); fixlabel_540230_839829468(p0, lend0); } N_NIMCALL(void, genstringcase_548417_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0) { NI strings0; strings0 = ((NI) 0); { NI i_548435_839829468; NI HEX3Atmp_548550_839829468; NI LOC2; NI res_548553_839829468; i_548435_839829468 = (NI)0; HEX3Atmp_548550_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(t0); HEX3Atmp_548550_839829468 = (NI)(LOC2 - ((NI) 1)); res_548553_839829468 = ((NI) 1); { while (1) { if (!(res_548553_839829468 <= HEX3Atmp_548550_839829468)) goto LA4; i_548435_839829468 = res_548553_839829468; { NI LOC9; if (!((*(*t0).kindU.S6.sons->data[i_548435_839829468]).kind == ((Tnodekind293020) 85))) goto LA7; LOC9 = (NI)0; LOC9 = sonslen_296351_850551059((*t0).kindU.S6.sons->data[i_548435_839829468]); strings0 += (NI)(LOC9 - ((NI) 1)); } LA7: ; res_548553_839829468 += ((NI) 1); } LA4: ; } } { NI bitmask0; NI LOC14; TY192350* branches0; Tloc293816 a0; NI labid0; TY533811 LOC26; TY534289 LOC35; Ropeobj179006* lend0; NI LOC42; if (!(((NI) 8) < strings0)) goto LA12; LOC14 = (NI)0; LOC14 = nextpoweroftwo_101629_1009420244(strings0); bitmask0 = (NI)(LOC14 - ((NI) 1)); branches0 = (TY192350*)0; branches0 = (TY192350*) newSeq((&NTI192350), ((NI) ((NI)(bitmask0 + ((NI) 1))))); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); labid0 = (*p0).labels; { NI i_548484_839829468; NI HEX3Atmp_548560_839829468; NI LOC16; NI res_548563_839829468; i_548484_839829468 = (NI)0; HEX3Atmp_548560_839829468 = (NI)0; LOC16 = (NI)0; LOC16 = sonslen_296351_850551059(t0); HEX3Atmp_548560_839829468 = (NI)(LOC16 - ((NI) 1)); res_548563_839829468 = ((NI) 1); { while (1) { if (!(res_548563_839829468 <= HEX3Atmp_548560_839829468)) goto LA18; i_548484_839829468 = res_548563_839829468; (*p0).labels += ((NI) 1); { Ropeobj179006* LOC23; Ropeobj179006* LOC24; if (!((*(*t0).kindU.S6.sons->data[i_548484_839829468]).kind == ((Tnodekind293020) 85))) goto LA21; LOC23 = (Ropeobj179006*)0; LOC23 = rope_179401_2381377266(((NI64) ((*p0).labels))); LOC24 = (Ropeobj179006*)0; LOC24 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_296), LOC23); gencasestringbranch_548100_839829468(p0, (*t0).kindU.S6.sons->data[i_548484_839829468], (&a0), LOC24, branches0->data, branches0->Sup.len); } goto LA19; LA21: ; { } LA19: ; res_548563_839829468 += ((NI) 1); } LA18: ; } } memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rdloc_539188_839829468((&a0)); LOC26[1] = rope_179401_2381377266(((NI64) (bitmask0))); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_596), LOC26, 2); { NI j_548518_839829468; NI HEX3Atmp_548568_839829468; NI res_548571_839829468; j_548518_839829468 = (NI)0; HEX3Atmp_548568_839829468 = (NI)0; HEX3Atmp_548568_839829468 = (branches0 ? (branches0->Sup.len-1) : -1); res_548571_839829468 = ((NI) 0); { while (1) { if (!(res_548571_839829468 <= HEX3Atmp_548568_839829468)) goto LA29; j_548518_839829468 = res_548571_839829468; { TY533811 LOC34; if (!!((branches0->data[j_548518_839829468] == NIM_NIL))) goto LA32; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = intliteral_540270_839829468(((NI64) (j_548518_839829468))); LOC34[1] = branches0->data[j_548518_839829468]; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_597), LOC34, 2); } LA32: ; res_548571_839829468 += ((NI) 1); } LA29: ; } } memset((void*)LOC35, 0, sizeof(LOC35)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_160), LOC35, 0); { NI LOC38; TY179507 LOC41; LOC38 = (NI)0; LOC38 = sonslen_296351_850551059(t0); if (!!(((*(*t0).kindU.S6.sons->data[(NI)(LOC38 - ((NI) 1))]).kind == ((Tnodekind293020) 85)))) goto LA39; memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = rope_179401_2381377266(((NI64) ((*p0).labels))); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_598), LOC41, 1); } LA39: ; LOC42 = (NI)0; LOC42 = sonslen_296351_850551059(t0); lend0 = gencasesecondpass_547965_839829468(p0, t0, d0, ((NI) (labid0)), (NI)(LOC42 - ((NI) 1))); fixlabel_540230_839829468(p0, lend0); } goto LA10; LA12: ; { gencasegeneric_548087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_490), ((NimStringDesc*) &T839829468_595)); } LA10: ; } N_NIMCALL(void, gengotoforcase_546673_839829468)(Tcproc530021* p0, Tnode293802* casestmt0) { { { NI i_546695_839829468; NI HEX3Atmp_546737_839829468; NI LOC2; NI res_546740_839829468; i_546695_839829468 = (NI)0; HEX3Atmp_546737_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_294081_850551059(casestmt0); HEX3Atmp_546737_839829468 = (LOC2 - 1); res_546740_839829468 = ((NI) 1); { while (1) { TY534289 LOC5; NI LOC6; Tnode293802* it0; Tnode293802* LOC16; if (!(res_546740_839829468 <= HEX3Atmp_546737_839829468)) goto LA4; i_546695_839829468 = res_546740_839829468; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (NI)0; LOC6 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC5, 0); it0 = (*casestmt0).kindU.S6.sons->data[i_546695_839829468]; { NI j_546711_839829468; NI HEX3Atmp_546730_839829468; NI LOC8; NI res_546733_839829468; j_546711_839829468 = (NI)0; HEX3Atmp_546730_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = len_294081_850551059(it0); HEX3Atmp_546730_839829468 = (NI)(LOC8 - ((NI) 2)); res_546733_839829468 = ((NI) 0); { while (1) { NI64 val0; TY179507 LOC15; if (!(res_546733_839829468 <= HEX3Atmp_546730_839829468)) goto LA10; j_546711_839829468 = res_546733_839829468; { if (!((*(*it0).kindU.S6.sons->data[j_546711_839829468]).kind == ((Tnodekind293020) 44))) goto LA13; localerror_197085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579)); goto BeforeRet; } LA13: ; val0 = getordvalue_321129_3876443242((*it0).kindU.S6.sons->data[j_546711_839829468]); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = rope_179401_2381377266(val0); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_602), LOC15, 1); res_546733_839829468 += ((NI) 1); } LA10: ; } } LOC16 = (Tnode293802*)0; LOC16 = lastson_296364_850551059(it0); genstmts_540244_839829468(p0, LOC16); endblock_545060_839829468(p0); res_546740_839829468 += ((NI) 1); } LA4: ; } } }BeforeRet: ; } N_NIMCALL(NIM_BOOL, branchhastoobigrange_548576_839829468)(Tnode293802* b0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { NI i_548591_839829468; NI HEX3Atmp_548609_839829468; NI LOC2; NI res_548612_839829468; i_548591_839829468 = (NI)0; HEX3Atmp_548609_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(b0); HEX3Atmp_548609_839829468 = (NI)(LOC2 - ((NI) 2)); res_548612_839829468 = ((NI) 0); { while (1) { if (!(res_548612_839829468 <= HEX3Atmp_548609_839829468)) goto LA4; i_548591_839829468 = res_548612_839829468; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*b0).kindU.S6.sons->data[i_548591_839829468]).kind == ((Tnodekind293020) 44)); if (!(LOC7)) goto LA8; LOC7 = (IL64(256) < (NI64)((*(*(*b0).kindU.S6.sons->data[i_548591_839829468]).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval - (*(*(*b0).kindU.S6.sons->data[i_548591_839829468]).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval)); LA8: ; if (!LOC7) goto LA9; result0 = NIM_TRUE; goto BeforeRet; } LA9: ; res_548612_839829468 += ((NI) 1); } LA4: ; } } }BeforeRet: ; return result0; } N_NIMCALL(NI, ifswitchsplitpoint_548616_839829468)(Tcproc530021* p0, Tnode293802* n0) { NI result0; result0 = (NI)0; { NI i_548631_839829468; NI HEX3Atmp_548655_839829468; NI LOC2; NI res_548658_839829468; i_548631_839829468 = (NI)0; HEX3Atmp_548655_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_294081_850551059(n0); HEX3Atmp_548655_839829468 = (NI)(LOC2 - ((NI) 1)); res_548658_839829468 = ((NI) 1); { while (1) { Tnode293802* branch0; Tnode293802* stmtblock0; if (!(res_548658_839829468 <= HEX3Atmp_548655_839829468)) goto LA4; i_548631_839829468 = res_548658_839829468; branch0 = HEX5BHEX5D_294238_850551059(n0, i_548631_839829468); stmtblock0 = lastson_296364_850551059(branch0); { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = stmtscontainpragma_529083_2036603609(stmtblock0, ((Tspecialword276003) 181)); if (!LOC7) goto LA8; result0 = i_548631_839829468; } goto LA5; LA8: ; { if (!!(((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 0))&7U)))!=0))) goto LA11; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = ((*branch0).kind == ((Tnodekind293020) 85)); if (!(LOC15)) goto LA16; LOC15 = branchhastoobigrange_548576_839829468(branch0); LA16: ; if (!LOC15) goto LA17; result0 = i_548631_839829468; } LA17: ; } goto LA5; LA11: ; LA5: ; res_548658_839829468 += ((NI) 1); } LA4: ; } } return result0; } N_NIMCALL(void, genordinalcase_548725_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { NI splitpoint0; Tloc293816 a0; Ropeobj179006* lend0; splitpoint0 = ifswitchsplitpoint_548616_839829468(p0, n0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); { if (!(((NI) 0) < splitpoint0)) goto LA3; lend0 = genifforcaseuntil_548021_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601), splitpoint0, (&a0)); } goto LA1; LA3: ; { lend0 = NIM_NIL; } LA1: ; { NI LOC8; TY179507 LOC11; NIM_BOOL hasdefault0; TY534289 LOC37; LOC8 = (NI)0; LOC8 = len_294081_850551059(n0); if (!((NI)(splitpoint0 + ((NI) 1)) < LOC8)) goto LA9; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdcharloc_539227_839829468((&a0)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_603), LOC11, 1); hasdefault0 = NIM_FALSE; { NI i_548758_839829468; NI HEX3Atmp_548817_839829468; NI HEX3Atmp_548818_839829468; NI LOC13; NI res_548821_839829468; i_548758_839829468 = (NI)0; HEX3Atmp_548817_839829468 = (NI)0; HEX3Atmp_548818_839829468 = (NI)0; HEX3Atmp_548817_839829468 = (NI)(splitpoint0 + ((NI) 1)); LOC13 = (NI)0; LOC13 = len_294081_850551059(n0); HEX3Atmp_548818_839829468 = (LOC13 - 1); res_548821_839829468 = HEX3Atmp_548817_839829468; { while (1) { Tnode293802* branch0; Tnode293802* LOC28; TY534289 LOC29; if (!(res_548821_839829468 <= HEX3Atmp_548818_839829468)) goto LA15; i_548758_839829468 = res_548821_839829468; { NIM_BOOL LOC18; LOC18 = (NIM_BOOL)0; LOC18 = ((*d0).k == ((Tlockind293808) 1)); if (!(LOC18)) goto LA19; LOC18 = isemptytype_298441_850551059((*n0).typ); LA19: ; if (!LOC18) goto LA20; (*d0).k = ((Tlockind293808) 0); } LA20: ; branch0 = HEX5BHEX5D_294238_850551059(n0, i_548758_839829468); { if (!((*branch0).kind == ((Tnodekind293020) 85))) goto LA24; gencaserange_538028_839829468(p0, branch0); } goto LA22; LA24: ; { TY534289 LOC27; memset((void*)LOC27, 0, sizeof(LOC27)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_181), LOC27, 0); hasdefault0 = NIM_TRUE; } LA22: ; LOC28 = (Tnode293802*)0; LOC28 = lastson_296364_850551059(branch0); exprblock_545103_839829468(p0, LOC28, d0); memset((void*)LOC29, 0, sizeof(LOC29)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_182), LOC29, 0); res_548821_839829468 += ((NI) 1); } LA15: ; } } { NIM_BOOL LOC32; TY534289 LOC36; LOC32 = (NIM_BOOL)0; LOC32 = ((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 3))&7U)))!=0); if (!(LOC32)) goto LA33; LOC32 = !(hasdefault0); LA33: ; if (!LOC32) goto LA34; memset((void*)LOC36, 0, sizeof(LOC36)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_604), LOC36, 0); } LA34: ; memset((void*)LOC37, 0, sizeof(LOC37)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_160), LOC37, 0); } LA9: ; { if (!!((lend0 == NIM_NIL))) goto LA40; fixlabel_540230_839829468(p0, lend0); } LA40: ; } N_NIMCALL(void, gencase_548827_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0) { Ttype293840* LOC8; genlinedir_533823_839829468(p0, t0); { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_298441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind293808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_538032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; LOC8 = (Ttype293840*)0; LOC8 = skiptypes_297099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440)); switch ((*LOC8).kind) { case ((Ttypekind293244) 28): { genstringcase_548417_839829468(p0, t0, d0); } break; case ((Ttypekind293244) 36) ... ((Ttypekind293244) 39): { gencasegeneric_548087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601)); } break; default: { { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC14)) goto LA15; LOC14 = (((*(*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 30))&31U)))!=0); LA15: ; if (!LOC14) goto LA16; gengotoforcase_546673_839829468(p0, t0); } goto LA12; LA16: ; { genordinalcase_548725_839829468(p0, t0, d0); } LA12: ; } break; } } static N_INLINE(Tnode293802*, pop_319246_1689653243)(Tnodeseq293796** s0) { Tnode293802* result0; NI L0; result0 = (Tnode293802*)0; L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1)); result0 = (*s0)->data[L0]; (*s0) = (Tnodeseq293796*) setLengthSeq(&((*s0))->Sup, sizeof(Tnode293802*), ((NI) (L0))); return result0; } N_NIMCALL(void, blockleaveactions_546442_839829468)(Tcproc530021* p0, NI howmanytrys0, NI howmanyexcepts0) { Tnodeseq293796* stack0; NI alreadypoppedcnt0; stack0 = (Tnodeseq293796*)0; stack0 = (Tnodeseq293796*) newSeq((&NTI293796), ((NI) 0)); alreadypoppedcnt0 = (*p0).inexceptblock; { NI i_546471_839829468; NI res_546596_839829468; i_546471_839829468 = (NI)0; res_546596_839829468 = ((NI) 1); { while (1) { Tnode293802* trystmt0; Tnode293802* finallystmt0; if (!(res_546596_839829468 <= howmanytrys0)) goto LA3; i_546471_839829468 = res_546596_839829468; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC6) goto LA7; LOC6 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA7: ; if (!!(LOC6)) goto LA8; { if (!(((NI) 0) < alreadypoppedcnt0)) goto LA12; alreadypoppedcnt0 -= ((NI) 1); } goto LA10; LA12: ; { TY534289 LOC15; memset((void*)LOC15, 0, sizeof(LOC15)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_605), LOC15, 0); } LA10: ; } LA8: ; trystmt0 = pop_319246_1689653243((&(*p0).nestedtrystmts)); stack0 = (Tnodeseq293796*) incrSeqV2(&(stack0)->Sup, sizeof(Tnode293802*)); asgnRefNoCycle((void**) (&stack0->data[stack0->Sup.len]), trystmt0); ++stack0->Sup.len; finallystmt0 = lastson_296364_850551059(trystmt0); { if (!((*finallystmt0).kind == ((Tnodekind293020) 107))) goto LA18; genstmts_540244_839829468(p0, (*finallystmt0).kindU.S6.sons->data[((NI) 0)]); } LA18: ; res_546596_839829468 += ((NI) 1); } LA3: ; } } { NI i_546546_839829468; NI HEX3Atmp_546601_839829468; NI res_546604_839829468; i_546546_839829468 = (NI)0; HEX3Atmp_546601_839829468 = (NI)0; HEX3Atmp_546601_839829468 = (NI)(howmanytrys0 - ((NI) 1)); res_546604_839829468 = HEX3Atmp_546601_839829468; { while (1) { if (!(((NI) 0) <= res_546604_839829468)) goto LA22; i_546546_839829468 = res_546604_839829468; (*p0).nestedtrystmts = (Tnodeseq293796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode293802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), stack0->data[i_546546_839829468]); ++(*p0).nestedtrystmts->Sup.len; res_546604_839829468 -= ((NI) 1); } LA22: ; } } { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC25) goto LA26; LOC25 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA26: ; if (!!(LOC25)) goto LA27; { NI i_546587_839829468; NI HEX3Atmp_546610_839829468; NI res_546613_839829468; i_546587_839829468 = (NI)0; HEX3Atmp_546610_839829468 = (NI)0; HEX3Atmp_546610_839829468 = (NI)(howmanyexcepts0 - ((NI) 1)); res_546613_839829468 = HEX3Atmp_546610_839829468; { while (1) { TY534289 LOC32; if (!(((NI) 0) <= res_546613_839829468)) goto LA31; i_546587_839829468 = res_546613_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_606), LOC32, 0); res_546613_839829468 -= ((NI) 1); } LA31: ; } } } LA27: ; } N_NIMCALL(void, genreturnstmt_546617_839829468)(Tcproc530021* p0, Tnode293802* t0) { TY534289 LOC14; { { if (!(((*t0).flags &(1U<<((NU)(((Tnodeflag293427) 14))&15U)))!=0)) goto LA3; goto BeforeRet; } LA3: ; (*p0).beforeretneeded = NIM_TRUE; genlinedir_533823_839829468(p0, t0); { if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 1)))) goto LA7; genstmts_540244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)]); } LA7: ; blockleaveactions_546442_839829468(p0, ((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0), (*p0).inexceptblock); { Ropeobj179006* safepoint0; TY179507 LOC13; if (!(((NI) 0) < ((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0))) goto LA11; safepoint0 = (*p0).finallysafepoints->data[(NI)(((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0) - ((NI) 1))]; memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_607), LOC13, 1); } LA11: ; memset((void*)LOC14, 0, sizeof(LOC14)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_608), LOC14, 0); }BeforeRet: ; } N_NIMCALL(void, genbreakstmt_547444_839829468)(Tcproc530021* p0, Tnode293802* t0) { NI idx0; Ropeobj179006* label0; TY179507 LOC16; idx0 = (*p0).breakidx; { Tsym293834* sym0; if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 1)))) goto LA3; sym0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; idx0 = (NI)((*sym0).position - ((NI) 1)); } goto LA1; LA3: ; { { while (1) { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = (((NI) 0) <= idx0); if (!(LOC8)) goto LA9; LOC8 = !((*p0).blocks->data[idx0].isloop); LA9: ; if (!LOC8) goto LA7; idx0 -= ((NI) 1); } LA7: ; } { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = (idx0 < ((NI) 0)); if (LOC12) goto LA13; LOC12 = !((*p0).blocks->data[idx0].isloop); LA13: ; if (!LOC12) goto LA14; internalerror_197100_155036129((*t0).info, ((NimStringDesc*) &T839829468_609)); } LA14: ; } LA1: ; label0 = assignlabel_545020_839829468((&(*p0).blocks->data[idx0])); blockleaveactions_546442_839829468(p0, (NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) ((*p0).blocks->data[idx0].nestedtrystmts))), (NI)((*p0).inexceptblock - ((NI) ((*p0).blocks->data[idx0].nestedexceptstmts)))); genlinedir_533823_839829468(p0, t0); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = label0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_556), LOC16, 1); } N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_550080_839829468)(Tcproc530021* p0, Tnode293802* asgn0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { Tnode293802* le0; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 2))&31U)))!=0)) goto LA3; le0 = (*asgn0).kindU.S6.sons->data[((NI) 0)]; { Tsym293834* field0; if (!((*le0).kind == ((Tnodekind293020) 46))) goto LA7; field0 = (*(*(*le0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag293184) 18))&31U)))!=0); } goto LA5; LA7: ; { Tsym293834* field0; if (!((*le0).kind == ((Tnodekind293020) 45))) goto LA10; field0 = (*(*le0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag293184) 18))&31U)))!=0); } goto LA5; LA10: ; LA5: ; } LA3: ; return result0; } N_NIMCALL(Ropeobj179006*, discriminatortabledecl_537094_839829468)(Tcgen530027* m0, Ttype293840* objtype0, Tsym293834* d0) { Ropeobj179006* result0; Ropeobj179006* LOC1; Ropeobj179006* tmp0; TY533811 LOC2; NI64 LOC3; result0 = (Ropeobj179006*)0; LOC1 = (Ropeobj179006*)0; LOC1 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_130)); tmp0 = discriminatortablename_537057_839829468(m0, objtype0, d0); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = tmp0; LOC3 = (NI64)0; LOC3 = lengthord_321007_3876443242((*d0).typ); LOC2[1] = rope_179401_2381377266((NI64)(LOC3 + IL64(1))); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_203), LOC2, 2); return result0; } N_NIMCALL(void, gendiscriminantcheck_550144_839829468)(Tcproc530021* p0, Tloc293816* a0, Tloc293816* tmp0, Ttype293840* objtype0, Tsym293834* field0) { Ttype293840* t0; Ropeobj179006* LOC1; NI64 L0; TY536235 LOC8; t0 = skiptypes_297099_850551059(objtype0, IL64(211106240964864)); LOC1 = (Ropeobj179006*)0; LOC1 = gentypeinfo_536941_839829468((*p0).module, t0); L0 = lengthord_321007_3876443242((*field0).typ); { NIM_BOOL LOC4; TY179507 LOC7; LOC4 = (NIM_BOOL)0; LOC4 = containsorincl_269862_2627731572((&(*(*p0).module).declaredthings), (*field0).Sup.id); if (!!(LOC4)) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = discriminatortabledecl_537094_839829468((*p0).module, t0, field0); appcg_533640_839829468((*p0).module, ((Tcfilesection530005) 9), ((NimStringDesc*) &T839829468_610), LOC7, 1); } LA5: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_539188_839829468(a0); LOC8[1] = rdloc_539188_839829468(tmp0); LOC8[2] = discriminatortablename_537057_839829468((*p0).module, t0, field0); LOC8[3] = intliteral_540270_839829468((NI64)(L0 + IL64(1))); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_611), LOC8, 4); } N_NIMCALL(void, asgnfielddiscriminant_550209_839829468)(Tcproc530021* p0, Tnode293802* e0) { Tloc293816 a0; Tloc293816 tmp0; Tnode293802* dotexpr0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); dotexpr0 = (*e0).kindU.S6.sons->data[((NI) 0)]; { if (!((*dotexpr0).kind == ((Tnodekind293020) 46))) goto LA3; dotexpr0 = (*dotexpr0).kindU.S6.sons->data[((NI) 0)]; } LA3: ; initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); gettemp_538032_839829468(p0, a0.t, (&tmp0), NIM_FALSE); expr_540248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); gendiscriminantcheck_550144_839829468(p0, (&a0), (&tmp0), (*(*dotexpr0).kindU.S6.sons->data[((NI) 0)]).typ, (*(*dotexpr0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym); genassignment_540264_839829468(p0, (&a0), (&tmp0), 0); } N_NIMCALL(void, genasgn_550239_839829468)(Tcproc530021* p0, Tnode293802* e0, NIM_BOOL fastasgn0) { genlinedir_533823_839829468(p0, e0); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 3)); if (!(LOC3)) goto LA4; LOC3 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag293184) 30))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; gengotovar_545258_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)]); } goto LA1; LA5: ; { NIM_BOOL LOC8; Tloc293816 a0; LOC8 = (NIM_BOOL)0; LOC8 = fielddiscriminantcheckneeded_550080_839829468(p0, e0); if (!!(LOC8)) goto LA9; memset((void*)(&a0), 0, sizeof(a0)); { Tnode293802* LOC13; Tnode293802* LOC16; LOC13 = (Tnode293802*)0; LOC13 = HEX5BHEX5D_294238_850551059(e0, ((NI) 0)); if (!((*LOC13).kind == ((Tnodekind293020) 47) || (*LOC13).kind == ((Tnodekind293020) 65))) goto LA14; LOC16 = (Tnode293802*)0; LOC16 = HEX5BHEX5D_294238_850551059(e0, ((NI) 0)); genderef_544921_839829468(p0, LOC16, (&a0), NIM_TRUE); } goto LA11; LA14: ; { initlocexpr_540283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA11: ; { if (!fastasgn0) goto LA20; a0.flags |= ((NU16)1)<<((((Tlocflag293810) 2))%(sizeof(NU16)*8)); } LA20: ; loadinto_544928_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); } goto LA1; LA9: ; { asgnfielddiscriminant_550209_839829468(p0, e0); } LA1: ; } N_NIMCALL(Ropeobj179006*, genasmoremitstmt_549529_839829468)(Tcproc530021* p0, Tnode293802* t0, NIM_BOOL isasmstmt0) { Ropeobj179006* result0; NimStringDesc* res0; result0 = (Ropeobj179006*)0; res0 = copyString(((NimStringDesc*) &T839829468_490)); { NI i_549547_839829468; NI HEX3Atmp_549644_839829468; NI LOC2; NI res_549647_839829468; i_549547_839829468 = (NI)0; HEX3Atmp_549644_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(t0); HEX3Atmp_549644_839829468 = (NI)(LOC2 - ((NI) 1)); res_549647_839829468 = ((NI) 0); { while (1) { if (!(res_549647_839829468 <= HEX3Atmp_549644_839829468)) goto LA4; i_549547_839829468 = res_549647_839829468; switch ((*(*t0).kindU.S6.sons->data[i_549547_839829468]).kind) { case ((Tnodekind293020) 20) ... ((Tnodekind293020) 22): { res0 = resizeString(res0, (*(*t0).kindU.S6.sons->data[i_549547_839829468]).kindU.S3.strval->Sup.len + 0); appendString(res0, (*(*t0).kindU.S6.sons->data[i_549547_839829468]).kindU.S3.strval); } break; case ((Tnodekind293020) 3): { Tsym293834* sym0; sym0 = (*(*t0).kindU.S6.sons->data[i_549547_839829468]).kindU.S4.sym; { Tloc293816 a0; Ropeobj179006* LOC11; NimStringDesc* LOC12; if (!((28672 &(1U<<((NU)((*sym0).kind)&31U)))!=0)) goto LA9; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*t0).kindU.S6.sons->data[i_549547_839829468], (&a0)); LOC11 = (Ropeobj179006*)0; LOC11 = rdloc_539188_839829468((&a0)); LOC12 = (NimStringDesc*)0; LOC12 = HEX24_179856_2381377266(LOC11); res0 = resizeString(res0, LOC12->Sup.len + 0); appendString(res0, LOC12); } goto LA7; LA9: ; { Ropeobj179006* LOC16; NimStringDesc* LOC17; if (!((*sym0).kind == ((Tsymkind293435) 7))) goto LA14; LOC16 = (Ropeobj179006*)0; LOC16 = gettypedesc_536673_839829468((*p0).module, (*sym0).typ); LOC17 = (NimStringDesc*)0; LOC17 = HEX24_179856_2381377266(LOC16); res0 = resizeString(res0, LOC17->Sup.len + 0); appendString(res0, LOC17); } goto LA7; LA14: ; { Ropeobj179006* r0; NimStringDesc* LOC23; r0 = (*sym0).loc.r; { if (!(r0 == NIM_NIL)) goto LA21; r0 = manglename_534205_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), r0); } LA21: ; LOC23 = (NimStringDesc*)0; LOC23 = HEX24_179856_2381377266(r0); res0 = resizeString(res0, LOC23->Sup.len + 0); appendString(res0, LOC23); } LA7: ; } break; default: { internalerror_197100_155036129((*(*t0).kindU.S6.sons->data[i_549547_839829468]).info, ((NimStringDesc*) &T839829468_612)); } break; } res_549647_839829468 += ((NI) 1); } LA4: ; } } { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = isasmstmt0; if (!(LOC27)) goto LA28; LOC27 = ((Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop274004) 5))&7U)))!=0); LA28: ; if (!LOC27) goto LA29; { NimStringDesc* x_549604_839829468; NI first_549656_839829468; NI last_549658_839829468; x_549604_839829468 = (NimStringDesc*)0; first_549656_839829468 = ((NI) 0); last_549658_839829468 = ((NI) 0); { while (1) { NI j0; { while (1) { if (!!((((NU8)(res0->data[last_549658_839829468])) == ((NU8)(0)) || ((NU8)(res0->data[last_549658_839829468])) == ((NU8)(13)) || ((NU8)(res0->data[last_549658_839829468])) == ((NU8)(10))))) goto LA35; last_549658_839829468 += ((NI) 1); } LA35: ; } x_549604_839829468 = copyStrLast(res0, first_549656_839829468, (NI)(last_549658_839829468 - ((NI) 1))); j0 = ((NI) 0); { while (1) { if (!(((NU8)(x_549604_839829468->data[j0])) == ((NU8)(32)) || ((NU8)(x_549604_839829468->data[j0])) == ((NU8)(9)))) goto LA37; j0 += ((NI) 1); } LA37: ; } { if (!(((NU8)(x_549604_839829468->data[j0])) == ((NU8)(34)) || ((NU8)(x_549604_839829468->data[j0])) == ((NU8)(58)))) goto LA40; add_179487_2381377266(&result0, x_549604_839829468); add_179487_2381377266(&result0, tnl_177644_4151366050); } goto LA38; LA40: ; { if (!!(((NU8)(x_549604_839829468->data[j0]) == (NU8)(0)))) goto LA43; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_613)); add_179487_2381377266(&result0, x_549604_839829468); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_614)); } goto LA38; LA43: ; LA38: ; { if (!((NU8)(res0->data[last_549658_839829468]) == (NU8)(10))) goto LA47; last_549658_839829468 += ((NI) 1); } goto LA45; LA47: ; { if (!((NU8)(res0->data[last_549658_839829468]) == (NU8)(13))) goto LA50; last_549658_839829468 += ((NI) 1); { if (!((NU8)(res0->data[last_549658_839829468]) == (NU8)(10))) goto LA54; last_549658_839829468 += ((NI) 1); } LA54: ; } goto LA45; LA50: ; { goto LA32; } LA45: ; first_549656_839829468 = last_549658_839829468; } } LA32: ; } } goto LA25; LA29: ; { res0 = resizeString(res0, tnl_177644_4151366050->Sup.len + 0); appendString(res0, tnl_177644_4151366050); result0 = rope_179277_2381377266(res0); } LA25: ; return result0; } N_NIMCALL(void, genasmstmt_549659_839829468)(Tcproc530021* p0, Tnode293802* t0) { Ropeobj179006* s0; genlinedir_533823_839829468(p0, t0); s0 = genasmoremitstmt_549529_839829468(p0, t0, NIM_TRUE); { TY179507 LOC5; if (!((*p0).prc == NIM_NIL)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = s0; addf_180205_2381377266(&(*(*p0).module).s[(((Tcfilesection530005) 7))- 0], Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field17, LOC5, 1); } goto LA1; LA3: ; { TY179507 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = s0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field17, LOC7, 1); } LA1: ; } static N_INLINE(void, gensimpleblock_545095_839829468)(Tcproc530021* p0, Tnode293802* stmts0) { TY534289 LOC1; NI LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0); genstmts_540244_839829468(p0, stmts0); endblock_545060_839829468(p0); } N_NIMCALL(void, gentrycpp_548866_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0) { Ropeobj179006* exc0; TY534289 LOC16; NI LOC17; NI length0; TY179507 LOC18; Ropeobj179006* LOC19; NI i0; NIM_BOOL catchallpresent0; TY534289 LOC78; Tnode293802* LOC79; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_298441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind293808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_538032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; genlinedir_533823_839829468(p0, t0); exc0 = gettempname_534598_839829468((*p0).module); { Tsym293834* LOC10; Ropeobj179006* LOC13; LOC10 = (Tsym293834*)0; LOC10 = getcompilerproc_339748_3937434831(((NimStringDesc*) &T839829468_615)); if (!!((LOC10 == NIM_NIL))) goto LA11; LOC13 = (Ropeobj179006*)0; LOC13 = cgsym_533403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615)); } goto LA8; LA11: ; { Ropeobj179006* LOC15; LOC15 = (Ropeobj179006*)0; LOC15 = cgsym_533403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616)); } LA8: ; (*p0).nestedtrystmts = (Tnodeseq293796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode293802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0); ++(*p0).nestedtrystmts->Sup.len; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (NI)0; LOC17 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_617), LOC16, 0); expr_540248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0); length0 = sonslen_296351_850551059(t0); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = exc0; LOC19 = (Ropeobj179006*)0; LOC19 = ropecg_533407_839829468((*p0).module, ((NimStringDesc*) &T839829468_618), LOC18, 1); endblock_545035_839829468(p0, LOC19); { TY534289 LOC24; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 15))&31U)))!=0)) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_619), LOC24, 0); } LA22: ; (*p0).inexceptblock += ((NI) 1); i0 = ((NI) 1); catchallpresent0 = NIM_FALSE; { while (1) { NIM_BOOL LOC27; NI blen0; LOC27 = (NIM_BOOL)0; LOC27 = (i0 < length0); if (!(LOC27)) goto LA28; LOC27 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind293020) 87)); LA28: ; if (!LOC27) goto LA26; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = ((*d0).k == ((Tlockind293808) 1)); if (!(LOC31)) goto LA32; LOC31 = isemptytype_298441_850551059((*t0).typ); LA32: ; if (!LOC31) goto LA33; (*d0).k = ((Tlockind293808) 0); } LA33: ; blen0 = sonslen_296351_850551059((*t0).kindU.S6.sons->data[i0]); { Ropeobj179006** LOC39; TY534289 LOC40; if (!(((NI) 1) < i0)) goto LA37; LOC39 = (Ropeobj179006**)0; LOC39 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); memset((void*)LOC40, 0, sizeof(LOC40)); addf_180205_2381377266(LOC39, ((NimStringDesc*) &T839829468_620), LOC40, 0); } LA37: ; { TY534289 LOC45; NI LOC46; TY534289 LOC47; if (!(blen0 == ((NI) 1))) goto LA43; catchallpresent0 = NIM_TRUE; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (NI)0; LOC46 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0); expr_540248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC47, 0, sizeof(LOC47)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_606), LOC47, 0); endblock_545060_839829468(p0); } goto LA41; LA43: ; { Ropeobj179006* orexpr0; TY179507 LOC57; TY534289 LOC58; NI LOC59; TY534289 LOC60; orexpr0 = NIM_NIL; { NI j_548979_839829468; NI HEX3Atmp_549101_839829468; NI res_549104_839829468; j_548979_839829468 = (NI)0; HEX3Atmp_549101_839829468 = (NI)0; HEX3Atmp_549101_839829468 = (NI)(blen0 - ((NI) 2)); res_549104_839829468 = ((NI) 0); { while (1) { TY533811 LOC56; if (!(res_549104_839829468 <= HEX3Atmp_549101_839829468)) goto LA51; j_548979_839829468 = res_549104_839829468; { if (!!((orexpr0 == NIM_NIL))) goto LA54; add_179487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229)); } LA54: ; memset((void*)LOC56, 0, sizeof(LOC56)); LOC56[0] = exc0; LOC56[1] = gentypeinfo_536941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_548979_839829468]).typ); appcg_533632_839829468((*p0).module, &orexpr0, ((NimStringDesc*) &T839829468_621), LOC56, 2); res_549104_839829468 += ((NI) 1); } LA51: ; } } memset((void*)LOC57, 0, sizeof(LOC57)); LOC57[0] = orexpr0; linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_622), LOC57, 1); memset((void*)LOC58, 0, sizeof(LOC58)); LOC59 = (NI)0; LOC59 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC58, 0); expr_540248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0); memset((void*)LOC60, 0, sizeof(LOC60)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_606), LOC60, 0); endblock_545060_839829468(p0); } LA41: ; i0 += ((NI) 1); } LA26: ; } { TY534289 LOC70; NI LOC71; Tnode293802* finallyblock0; TY534289 LOC76; Ropeobj179006* LOC77; if (!!(catchallpresent0)) goto LA63; { TY534289 LOC69; if (!(((NI) 1) < i0)) goto LA67; memset((void*)LOC69, 0, sizeof(LOC69)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_620), LOC69, 0); } LA67: ; memset((void*)LOC70, 0, sizeof(LOC70)); LOC71 = (NI)0; LOC71 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC70, 0); finallyblock0 = lastson_296364_850551059(t0); { if (!((*finallyblock0).kind == ((Tnodekind293020) 107))) goto LA74; genstmts_540244_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]); } LA74: ; memset((void*)LOC76, 0, sizeof(LOC76)); LOC77 = (Ropeobj179006*)0; LOC77 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_623), LOC76, 0); line_533690_839829468(p0, ((Tcprocsection530011) 2), LOC77); endblock_545060_839829468(p0); } LA63: ; memset((void*)LOC78, 0, sizeof(LOC78)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_160), LOC78, 0); (*p0).inexceptblock -= ((NI) 1); LOC79 = (Tnode293802*)0; LOC79 = pop_319246_1689653243((&(*p0).nestedtrystmts)); { NIM_BOOL LOC82; LOC82 = (NIM_BOOL)0; LOC82 = (i0 < length0); if (!(LOC82)) goto LA83; LOC82 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind293020) 107)); LA83: ; if (!LOC82) goto LA84; gensimpleblock_545095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]); } LA84: ; } N_NIMCALL(void, line_533695_839829468)(Tcproc530021* p0, Tcprocsection530011 s0, NimStringDesc* r0) { Ropeobj179006** LOC1; Ropeobj179006* LOC2; Ropeobj179006* LOC3; LOC1 = (Ropeobj179006**)0; LOC1 = s_530179_3723162438(p0, s0); LOC2 = (Ropeobj179006*)0; LOC2 = rope_179277_2381377266(r0); LOC3 = (Ropeobj179006*)0; LOC3 = indentline_533656_839829468(p0, LOC2); add_179482_2381377266(LOC1, LOC3); } static N_INLINE(Ropeobj179006*, pop_179530_1689653243)(TY192350** s0) { Ropeobj179006* result0; NI L0; result0 = (Ropeobj179006*)0; L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1)); result0 = (*s0)->data[L0]; (*s0) = (TY192350*) setLengthSeq(&((*s0))->Sup, sizeof(Ropeobj179006*), ((NI) (L0))); return result0; } N_NIMCALL(void, gentry_549114_839829468)(Tcproc530021* p0, Tnode293802* t0, Tloc293816* d0) { NIM_BOOL LOC8; Ropeobj179006* safepoint0; TY179507 LOC17; TY179507 LOC18; TY179507 LOC37; NI LOC38; NI length0; TY534289 LOC39; TY534289 LOC40; NI LOC41; TY534289 LOC42; NI i0; Tnode293802* LOC95; TY179507 LOC103; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_298441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind293808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_538032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; LOC8 = (NIM_BOOL)0; LOC8 = includestr_147249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_624)); genlinedir_533823_839829468(p0, t0); safepoint0 = gettempname_534598_839829468((*p0).module); { Tsym293834* LOC11; Ropeobj179006* LOC14; LOC11 = (Tsym293834*)0; LOC11 = getcompilerproc_339748_3937434831(((NimStringDesc*) &T839829468_615)); if (!!((LOC11 == NIM_NIL))) goto LA12; LOC14 = (Ropeobj179006*)0; LOC14 = cgsym_533403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615)); } goto LA9; LA12: ; { Ropeobj179006* LOC16; LOC16 = (Ropeobj179006*)0; LOC16 = cgsym_533403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616)); } LA9: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 0), ((NimStringDesc*) &T839829468_625), LOC17, 1); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_626), LOC18, 1); { NIM_BOOL LOC21; TY179507 LOC24; LOC21 = (NIM_BOOL)0; LOC21 = isdefined_201011_1967573533(((NimStringDesc*) &T839829468_627)); if (!LOC21) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_628), LOC24, 1); } goto LA19; LA22: ; { NIM_BOOL LOC26; TY179507 LOC29; LOC26 = (NIM_BOOL)0; LOC26 = isdefined_201011_1967573533(((NimStringDesc*) &T839829468_629)); if (!LOC26) goto LA27; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_630), LOC29, 1); } goto LA19; LA27: ; { NIM_BOOL LOC31; TY179507 LOC34; LOC31 = (NIM_BOOL)0; LOC31 = isdefined_201011_1967573533(((NimStringDesc*) &T839829468_631)); if (!LOC31) goto LA32; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_632), LOC34, 1); } goto LA19; LA32: ; { TY179507 LOC36; memset((void*)LOC36, 0, sizeof(LOC36)); LOC36[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_628), LOC36, 1); } LA19: ; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = safepoint0; LOC38 = (NI)0; LOC38 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_633), LOC37, 1); length0 = sonslen_296351_850551059(t0); (*p0).nestedtrystmts = (Tnodeseq293796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode293802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0); ++(*p0).nestedtrystmts->Sup.len; expr_540248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC39, 0, sizeof(LOC39)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_605), LOC39, 0); endblock_545060_839829468(p0); memset((void*)LOC40, 0, sizeof(LOC40)); LOC41 = (NI)0; LOC41 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_634), LOC40, 0); memset((void*)LOC42, 0, sizeof(LOC42)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_605), LOC42, 0); { TY534289 LOC47; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 15))&31U)))!=0)) goto LA45; memset((void*)LOC47, 0, sizeof(LOC47)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_619), LOC47, 0); } LA45: ; (*p0).inexceptblock += ((NI) 1); i0 = ((NI) 1); { while (1) { NIM_BOOL LOC50; NI blen0; LOC50 = (NIM_BOOL)0; LOC50 = (i0 < length0); if (!(LOC50)) goto LA51; LOC50 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind293020) 87)); LA51: ; if (!LOC50) goto LA49; { NIM_BOOL LOC54; LOC54 = (NIM_BOOL)0; LOC54 = ((*d0).k == ((Tlockind293808) 1)); if (!(LOC54)) goto LA55; LOC54 = isemptytype_298441_850551059((*t0).typ); LA55: ; if (!LOC54) goto LA56; (*d0).k = ((Tlockind293808) 0); } LA56: ; blen0 = sonslen_296351_850551059((*t0).kindU.S6.sons->data[i0]); { TY534289 LOC67; NI LOC68; TY179507 LOC69; TY534289 LOC70; if (!(blen0 == ((NI) 1))) goto LA60; { TY534289 LOC66; if (!(((NI) 1) < i0)) goto LA64; memset((void*)LOC66, 0, sizeof(LOC66)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_635), LOC66, 0); } LA64: ; memset((void*)LOC67, 0, sizeof(LOC67)); LOC68 = (NI)0; LOC68 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC67, 0); memset((void*)LOC69, 0, sizeof(LOC69)); LOC69[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_636), LOC69, 1); expr_540248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC70, 0, sizeof(LOC70)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_606), LOC70, 0); endblock_545060_839829468(p0); } goto LA58; LA60: ; { Ropeobj179006* orexpr0; TY179507 LOC91; NI LOC92; TY179507 LOC93; TY534289 LOC94; orexpr0 = NIM_NIL; { NI j_549247_839829468; NI HEX3Atmp_549521_839829468; NI res_549524_839829468; j_549247_839829468 = (NI)0; HEX3Atmp_549521_839829468 = (NI)0; HEX3Atmp_549521_839829468 = (NI)(blen0 - ((NI) 2)); res_549524_839829468 = ((NI) 0); { while (1) { NimStringDesc* isobjformat0; TY179507 LOC86; if (!(res_549524_839829468 <= HEX3Atmp_549521_839829468)) goto LA74; j_549247_839829468 = res_549524_839829468; { if (!!((orexpr0 == NIM_NIL))) goto LA77; add_179487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229)); } LA77: ; { NIM_BOOL LOC81; LOC81 = (NIM_BOOL)0; LOC81 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC81) goto LA82; LOC81 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA82: ; if (!!(LOC81)) goto LA83; isobjformat0 = copyString(((NimStringDesc*) &T839829468_637)); } goto LA79; LA83: ; { isobjformat0 = copyString(((NimStringDesc*) &T839829468_638)); } LA79: ; memset((void*)LOC86, 0, sizeof(LOC86)); LOC86[0] = gentypeinfo_536941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_549247_839829468]).typ); appcg_533632_839829468((*p0).module, &orexpr0, isobjformat0, LOC86, 1); res_549524_839829468 += ((NI) 1); } LA74: ; } } { if (!(((NI) 1) < i0)) goto LA89; line_533695_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_620)); } LA89: ; memset((void*)LOC91, 0, sizeof(LOC91)); LOC91[0] = orexpr0; LOC92 = (NI)0; LOC92 = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_639), LOC91, 1); memset((void*)LOC93, 0, sizeof(LOC93)); LOC93[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_636), LOC93, 1); expr_540248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0); memset((void*)LOC94, 0, sizeof(LOC94)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_606), LOC94, 0); endblock_545060_839829468(p0); } LA58: ; i0 += ((NI) 1); } LA49: ; } (*p0).inexceptblock -= ((NI) 1); LOC95 = (Tnode293802*)0; LOC95 = pop_319246_1689653243((&(*p0).nestedtrystmts)); endblock_545060_839829468(p0); { NIM_BOOL LOC98; Ropeobj179006* LOC102; LOC98 = (NIM_BOOL)0; LOC98 = (i0 < length0); if (!(LOC98)) goto LA99; LOC98 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind293020) 107)); LA99: ; if (!LOC98) goto LA100; (*p0).finallysafepoints = (TY192350*) incrSeqV2(&((*p0).finallysafepoints)->Sup, sizeof(Ropeobj179006*)); asgnRefNoCycle((void**) (&(*p0).finallysafepoints->data[(*p0).finallysafepoints->Sup.len]), safepoint0); ++(*p0).finallysafepoints->Sup.len; gensimpleblock_545095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]); LOC102 = (Ropeobj179006*)0; LOC102 = pop_179530_1689653243((&(*p0).finallysafepoints)); } LA100: ; memset((void*)LOC103, 0, sizeof(LOC103)); LOC103[0] = safepoint0; linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_640), LOC103, 1); } N_NIMCALL(NimStringDesc*, getraisefrmt_547824_839829468)(Tcproc530021* p0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; result0 = copyString(((NimStringDesc*) &T839829468_641)); return result0; } N_NIMCALL(void, genraisestmt_547828_839829468)(Tcproc530021* p0, Tnode293802* t0) { { Tnode293802* finallyblock0; if (!(((NI) 0) < (*p0).inexceptblock)) goto LA3; finallyblock0 = lastson_296364_850551059((*p0).nestedtrystmts->data[(NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) 1))]); { if (!((*finallyblock0).kind == ((Tnodekind293020) 107))) goto LA7; gensimpleblock_545095_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]); } LA7: ; } LA3: ; { Tloc293816 a0; Ropeobj179006* e0; Ttype293840* typ0; NimStringDesc* LOC13; TY533811 LOC14; if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 1)))) goto LA11; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); e0 = rdloc_539188_839829468((&a0)); typ0 = skiptypes_297099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106247256320)); genlinedir_533823_839829468(p0, t0); LOC13 = (NimStringDesc*)0; LOC13 = getraisefrmt_547824_839829468(p0); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = e0; LOC14[1] = makecstring_192638_155036129((*(*(*typ0).sym).name).s); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), LOC13, LOC14, 2); } goto LA9; LA11: ; { genlinedir_533823_839829468(p0, t0); { NIM_BOOL LOC18; NIM_BOOL LOC19; TY534289 LOC24; Ropeobj179006* LOC25; LOC18 = (NIM_BOOL)0; LOC19 = (NIM_BOOL)0; LOC19 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC19) goto LA20; LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA20: ; LOC18 = LOC19; if (!(LOC18)) goto LA21; LOC18 = !(((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 31))&63U)))!=0)); LA21: ; if (!LOC18) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); LOC25 = (Ropeobj179006*)0; LOC25 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_623), LOC24, 0); line_533690_839829468(p0, ((Tcprocsection530011) 2), LOC25); } goto LA16; LA22: ; { TY534289 LOC27; memset((void*)LOC27, 0, sizeof(LOC27)); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_642), LOC27, 0); } LA16: ; } LA9: ; } N_NIMCALL(void, gentypesection_539184_839829468)(Tcgen530027* m0, Tnode293802* n0) { } N_NIMCALL(Tcfilesection530005, determinesection_549819_839829468)(Tnode293802* n0) { Tcfilesection530005 result0; result0 = (Tcfilesection530005)0; result0 = ((Tcfilesection530005) 7); { NIM_BOOL LOC3; NI LOC4; NimStringDesc* sec0; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = len_294081_850551059(n0); LOC3 = (((NI) 1) <= LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind >= ((Tnodekind293020) 20) && (*(*n0).kindU.S6.sons->data[((NI) 0)]).kind <= ((Tnodekind293020) 22)); LA5: ; if (!LOC3) goto LA6; sec0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S3.strval; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_643)); if (!LOC10) goto LA11; result0 = ((Tcfilesection530005) 3); } goto LA8; LA11: ; { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_644)); if (!LOC14) goto LA15; result0 = ((Tcfilesection530005) 9); } goto LA8; LA15: ; { NIM_BOOL LOC18; LOC18 = (NIM_BOOL)0; LOC18 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_645)); if (!LOC18) goto LA19; result0 = ((Tcfilesection530005) 1); } goto LA8; LA19: ; LA8: ; } LA6: ; return result0; } N_NIMCALL(void, genemit_549839_839829468)(Tcproc530021* p0, Tnode293802* t0) { Ropeobj179006* s0; s0 = genasmoremitstmt_549529_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], NIM_FALSE); { Tcfilesection530005 section0; Tnode293802* LOC5; if (!((*p0).prc == NIM_NIL)) goto LA3; LOC5 = (Tnode293802*)0; LOC5 = HEX5BHEX5D_294238_850551059(t0, ((NI) 1)); section0 = determinesection_549819_839829468(LOC5); genclinedir_533813_839829468(&(*(*p0).module).s[(section0)- 0], (*t0).info); add_179482_2381377266(&(*(*p0).module).s[(section0)- 0], s0); } goto LA1; LA3: ; { genlinedir_533823_839829468(p0, t0); line_533690_839829468(p0, ((Tcprocsection530011) 2), s0); } LA1: ; } N_NIMCALL(void, genbreakpoint_549862_839829468)(Tcproc530021* p0, Tnode293802* t0) { NimStringDesc* name0; name0 = (NimStringDesc*)0; { TY536238 LOC12; NI LOC13; NimStringDesc* LOC14; if (!(((*p0).options &(1U<<((NU)(((Toption170009) 17))&31U)))!=0)) goto LA3; { if (!((*t0).kind == ((Tnodekind293020) 34))) goto LA7; name0 = nsuNormalize((*(*t0).kindU.S6.sons->data[((NI) 1)]).kindU.S3.strval); } goto LA5; LA7: ; { NimStringDesc* LOC10; NimStringDesc* LOC11; breakpointid_549860_839829468 += ((NI) 1); LOC10 = (NimStringDesc*)0; LOC11 = (NimStringDesc*)0; LOC11 = nimIntToStr(breakpointid_549860_839829468); LOC10 = rawNewString(LOC11->Sup.len + 2); appendString(LOC10, ((NimStringDesc*) &T839829468_646)); appendString(LOC10, LOC11); name0 = LOC10; } LA5: ; genlinedir_533823_839829468(p0, t0); memset((void*)LOC12, 0, sizeof(LOC12)); LOC13 = (NI)0; LOC13 = tolinenumber_193415_155036129((*t0).info); LOC12[0] = rope_179401_2381377266(((NI64) (LOC13))); LOC14 = (NimStringDesc*)0; LOC14 = tofilename_193257_155036129((*t0).info.fileindex); LOC12[1] = makecstring_192638_155036129(LOC14); LOC12[2] = makecstring_192638_155036129(name0); appcg_533632_839829468((*p0).module, &gbreakpoints_549861_839829468, ((NimStringDesc*) &T839829468_647), LOC12, 3); } LA3: ; } N_NIMCALL(void, genwatchpoint_550016_839829468)(Tcproc530021* p0, Tnode293802* n0) { Tloc293816 a0; Ttype293840* typ0; TY536238 LOC5; NimStringDesc* LOC6; { { if (!!((((*p0).options &(1U<<((NU)(((Toption170009) 17))&31U)))!=0))) goto LA3; goto BeforeRet; } LA3: ; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); typ0 = skiptypes_297099_850551059((*(*n0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = addrloc_539204_839829468((&a0)); LOC6 = (NimStringDesc*)0; LOC6 = rendertree_312044_382274130((*n0).kindU.S6.sons->data[((NI) 1)], 0); LOC5[1] = makecstring_192638_155036129(LOC6); LOC5[2] = gentypeinfo_536941_839829468((*p0).module, typ0); linecg_533707_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_648), LOC5, 3); }BeforeRet: ; } N_NIMCALL(void, genpragma_550039_839829468)(Tcproc530021* p_550041_839829468, Tnode293802* n0) { { NI i_550054_839829468; NI HEX3Atmp_550073_839829468; NI LOC2; NI res_550076_839829468; i_550054_839829468 = (NI)0; HEX3Atmp_550073_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_296351_850551059(n0); HEX3Atmp_550073_839829468 = (NI)(LOC2 - ((NI) 1)); res_550076_839829468 = ((NI) 0); { while (1) { Tnode293802* it0; Tspecialword276003 LOC5; if (!(res_550076_839829468 <= HEX3Atmp_550073_839829468)) goto LA4; i_550054_839829468 = res_550076_839829468; it0 = (*n0).kindU.S6.sons->data[i_550054_839829468]; LOC5 = (Tspecialword276003)0; LOC5 = whichpragma_319911_2616423590(it0); switch (LOC5) { case ((Tspecialword276003) 191): { genemit_549839_839829468(p_550041_839829468, it0); } break; case ((Tspecialword276003) 131): { genbreakpoint_549862_839829468(p_550041_839829468, it0); } break; case ((Tspecialword276003) 176): { genwatchpoint_550016_839829468(p_550041_839829468, it0); } break; case ((Tspecialword276003) 183): { Tcproc530021* p0; Ropeobj179006** LOC10; p0 = newproc_530206_3723162438(NIM_NIL, (*p_550041_839829468).module); (*p0).options = ((*p0).options & ~ 98304); genstmts_540244_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)]); LOC10 = (Ropeobj179006**)0; LOC10 = s_530179_3723162438(p0, ((Tcprocsection530011) 2)); asgnRefNoCycle((void**) (&(*(*p0).module).injectstmt), (*LOC10)); } break; default: { } break; } res_550076_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, genparforstmt_547208_839829468)(Tcproc530021* p0, Tnode293802* t0) { NI oldbreakidx_547411_839829468; Tsym293834* forloopvar0; Tloc293816 rangea0; Tloc293816 rangeb0; Tnode293802* call0; TY536235 LOC1; NimStringDesc* LOC2; TY534289 LOC3; (*p0).withinloop += ((NI) 1); genlinedir_533823_839829468(p0, t0); oldbreakidx_547411_839829468 = (*p0).breakidx; forloopvar0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; memset((void*)(&rangea0), 0, sizeof(rangea0)); memset((void*)(&rangeb0), 0, sizeof(rangeb0)); assignlocalvar_539614_839829468(p0, forloopvar0); call0 = (*t0).kindU.S6.sons->data[((NI) 1)]; initlocexpr_540283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 1)], (&rangea0)); initlocexpr_540283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 2)], (&rangeb0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&(*forloopvar0).loc)); LOC1[1] = rdloc_539188_839829468((&rangea0)); LOC1[2] = rdloc_539188_839829468((&rangeb0)); LOC2 = (NimStringDesc*)0; LOC2 = getstr_298230_850551059((*call0).kindU.S6.sons->data[((NI) 3)]); LOC1[3] = rope_179277_2381377266(LOC2); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_649), LOC1, 4); memset((void*)LOC3, 0, sizeof(LOC3)); (*p0).breakidx = startblock_544978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC3, 0); (*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE; genstmts_540244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 2)]); endblock_545060_839829468(p0); (*p0).breakidx = oldbreakidx_547411_839829468; (*p0).withinloop -= ((NI) 1); } N_NIMCALL(void, genstate_545117_839829468)(Tcproc530021* p0, Tnode293802* n0) { NI64 idx0; TY179507 LOC9; { NIM_BOOL LOC3; NI LOC4; NimStringDesc* LOC8; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = len_294081_850551059(n0); LOC3 = (LOC4 == ((NI) 1)); if (!(LOC3)) goto LA5; LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 6)); LA5: ; if (!!(LOC3)) goto LA6; LOC8 = (NimStringDesc*)0; LOC8 = HEX24_197185_1689653243(T839829468_650); internalerror_197113_155036129(LOC8); } LA6: ; idx0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = rope_179401_2381377266(idx0); linefmt_533714_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_652), LOC9, 1); } N_NIMCALL(void, gengotostate_545144_839829468)(Tcproc530021* p0, Tnode293802* n0) { Tloc293816 a0; TY179507 LOC1; TY534289 LOC2; TY534289 LOC7; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_539188_839829468((&a0)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_603), LOC1, 1); (*p0).beforeretneeded = NIM_TRUE; memset((void*)LOC2, 0, sizeof(LOC2)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_653), LOC2, 0); { NI64 i_545214_839829468; NI64 HEX3Atmp_545223_839829468; NI64 res_545226_839829468; i_545214_839829468 = (NI64)0; HEX3Atmp_545223_839829468 = (NI64)0; HEX3Atmp_545223_839829468 = lastord_321004_3876443242((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ); res_545226_839829468 = IL64(0); { while (1) { TY179507 LOC6; if (!(res_545226_839829468 <= HEX3Atmp_545223_839829468)) goto LA5; i_545214_839829468 = res_545226_839829468; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_179401_2381377266(i_545214_839829468); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_654), LOC6, 1); res_545226_839829468 += ((NI) 1); } LA5: ; } } memset((void*)LOC7, 0, sizeof(LOC7)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_160), LOC7, 0); } N_NIMCALL(void, genbreakstate_545229_839829468)(Tcproc530021* p0, Tnode293802* n0) { Tloc293816 a0; memset((void*)(&a0), 0, sizeof(a0)); { TY179507 LOC5; if (!((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 155))) goto LA3; initlocexpr_540283_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_539188_839829468((&a0)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_655), LOC5, 1); } goto LA1; LA3: ; { TY179507 LOC7; initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_539188_839829468((&a0)); linef_533700_839829468(p0, ((Tcprocsection530011) 2), ((NimStringDesc*) &T839829468_656), LOC7, 1); } LA1: ; } N_NIMCALL(void, expr_540248_839829468)(Tcproc530021* p0, Tnode293802* n0, Tloc293816* d0) { switch ((*n0).kind) { case ((Tnodekind293020) 3): { Tsym293834* sym0; sym0 = (*n0).kindU.S4.sym; switch ((*sym0).kind) { case ((Tsymkind293435) 13): { { if (!!(((33554448 & (*sym0).flags) == 0))) goto LA5; fillprocloc_540201_839829468(sym0); genprocprototype_540254_839829468((*p0).module, sym0); } goto LA3; LA5: ; { genproc_533951_839829468((*p0).module, sym0); } LA3: ; putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind293435) 12): case ((Tsymkind293435) 15): case ((Tsymkind293435) 14): { { NimStringDesc* LOC13; if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 23))&31U)))!=0)) goto LA11; LOC13 = (NimStringDesc*)0; LOC13 = rawNewString((*(*sym0).name).s->Sup.len + 48); appendString(LOC13, ((NimStringDesc*) &T839829468_270)); appendString(LOC13, (*(*sym0).name).s); localerror_197085_155036129((*n0).info, LOC13); } LA11: ; genproc_533951_839829468((*p0).module, sym0); { NIM_BOOL LOC16; NimStringDesc* LOC20; LOC16 = (NIM_BOOL)0; LOC16 = ((*sym0).loc.r == NIM_NIL); if (LOC16) goto LA17; LOC16 = ((*sym0).loc.t == NIM_NIL); LA17: ; if (!LOC16) goto LA18; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString((*(*sym0).name).s->Sup.len + 20); appendString(LOC20, ((NimStringDesc*) &T839829468_271)); appendString(LOC20, (*(*sym0).name).s); internalerror_197100_155036129((*n0).info, LOC20); } LA18: ; putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind293435) 10): { { NIM_BOOL LOC24; Ropeobj179006* LOC27; LOC24 = (NIM_BOOL)0; LOC24 = issimpleconst_533311_839829468((*sym0).typ); if (!LOC24) goto LA25; LOC27 = (Ropeobj179006*)0; LOC27 = genliteral_550476_839829468(p0, (*sym0).ast, (*sym0).typ); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC27, ((Tstorageloc293812) 1)); } goto LA22; LA25: ; { gencomplexconst_559249_839829468(p0, sym0, d0); } LA22: ; } break; case ((Tsymkind293435) 19): { Ropeobj179006* LOC30; LOC30 = (Ropeobj179006*)0; LOC30 = rope_179401_2381377266(((NI64) ((*sym0).position))); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC30, ((Tstorageloc293812) 0)); } break; case ((Tsymkind293435) 8): case ((Tsymkind293435) 20): case ((Tsymkind293435) 11): case ((Tsymkind293435) 9): { { if (!!(((4194312 & (*sym0).flags) == 0))) goto LA34; genvarprototype_540236_839829468((*p0).module, sym0); } LA34: ; { NIM_BOOL LOC38; NimStringDesc* LOC42; NimStringDesc* LOC43; LOC38 = (NIM_BOOL)0; LOC38 = ((*sym0).loc.r == NIM_NIL); if (LOC38) goto LA39; LOC38 = ((*sym0).loc.t == NIM_NIL); LA39: ; if (!LOC38) goto LA40; LOC42 = (NimStringDesc*)0; LOC43 = (NimStringDesc*)0; LOC43 = nimIntToStr((*sym0).Sup.id); LOC42 = rawNewString((*(*sym0).name).s->Sup.len + LOC43->Sup.len + 20); appendString(LOC42, ((NimStringDesc*) &T839829468_285)); appendString(LOC42, (*(*sym0).name).s); appendString(LOC42, ((NimStringDesc*) &T839829468_12)); appendString(LOC42, LOC43); internalerror_197100_155036129((*n0).info, LOC42); } LA40: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag293184) 22))&31U)))!=0)) goto LA46; accessthreadlocalvar_533945_839829468(p0, sym0); { NIM_BOOL LOC50; Ropeobj179006* LOC53; LOC50 = (NIM_BOOL)0; LOC50 = emulatedthreadvars_533949_839829468(); if (!LOC50) goto LA51; LOC53 = (Ropeobj179006*)0; LOC53 = HEX26_179452_2381377266(((NimStringDesc*) &T839829468_288), (*sym0).loc.r); putintodest_551468_839829468(p0, d0, (*sym0).loc.t, LOC53, ((Tstorageloc293812) 0)); } goto LA48; LA51: ; { putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } LA48: ; } goto LA44; LA46: ; { putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } LA44: ; } break; case ((Tsymkind293435) 5): { { NIM_BOOL LOC59; NimStringDesc* LOC63; NimStringDesc* LOC64; LOC59 = (NIM_BOOL)0; LOC59 = ((*sym0).loc.r == NIM_NIL); if (LOC59) goto LA60; LOC59 = ((*sym0).loc.t == NIM_NIL); LA60: ; if (!LOC59) goto LA61; LOC63 = (NimStringDesc*)0; LOC64 = (NimStringDesc*)0; LOC64 = nimIntToStr((*sym0).Sup.id); LOC63 = rawNewString((*(*sym0).name).s->Sup.len + LOC64->Sup.len + 21); appendString(LOC63, ((NimStringDesc*) &T839829468_289)); appendString(LOC63, (*(*sym0).name).s); appendString(LOC63, ((NimStringDesc*) &T839829468_12)); appendString(LOC63, LOC64); internalerror_197100_155036129((*n0).info, LOC63); } LA61: ; putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind293435) 3): { { NIM_BOOL LOC68; NimStringDesc* LOC72; NimStringDesc* LOC73; LOC68 = (NIM_BOOL)0; LOC68 = ((*sym0).loc.r == NIM_NIL); if (LOC68) goto LA69; LOC68 = ((*sym0).loc.t == NIM_NIL); LA69: ; if (!LOC68) goto LA70; LOC72 = (NimStringDesc*)0; LOC73 = (NimStringDesc*)0; LOC73 = nimIntToStr((*sym0).Sup.id); LOC72 = rawNewString((*(*sym0).name).s->Sup.len + LOC73->Sup.len + 22); appendString(LOC72, ((NimStringDesc*) &T839829468_290)); appendString(LOC72, (*(*sym0).name).s); appendString(LOC72, ((NimStringDesc*) &T839829468_12)); appendString(LOC72, LOC73); internalerror_197100_155036129((*n0).info, LOC72); } LA70: ; putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } break; default: { NimStringDesc* LOC75; LOC75 = (NimStringDesc*)0; LOC75 = rawNewString(reprEnum((NI)(*sym0).kind, (&NTI293435))->Sup.len + 22); appendString(LOC75, ((NimStringDesc*) &T839829468_291)); appendString(LOC75, reprEnum((NI)(*sym0).kind, (&NTI293435))); appendString(LOC75, ((NimStringDesc*) &T839829468_292)); internalerror_197100_155036129((*n0).info, LOC75); } break; } } break; case ((Tnodekind293020) 23): { { NIM_BOOL LOC79; Ropeobj179006* LOC82; LOC79 = (NIM_BOOL)0; LOC79 = isemptytype_298441_850551059((*n0).typ); if (!!(LOC79)) goto LA80; LOC82 = (Ropeobj179006*)0; LOC82 = genliteral_540273_839829468(p0, n0); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC82, ((Tstorageloc293812) 0)); } LA80: ; } break; case ((Tnodekind293020) 20) ... ((Tnodekind293020) 22): { Ropeobj179006* LOC84; LOC84 = (Ropeobj179006*)0; LOC84 = genliteral_540273_839829468(p0, n0); putdataintodest_551436_839829468(p0, d0, (*n0).typ, LOC84); } break; case ((Tnodekind293020) 6) ... ((Tnodekind293020) 15): case ((Tnodekind293020) 16) ... ((Tnodekind293020) 19): case ((Tnodekind293020) 5): { Ropeobj179006* LOC86; LOC86 = (Ropeobj179006*)0; LOC86 = genliteral_540273_839829468(p0, n0); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC86, ((Tstorageloc293812) 0)); } break; case ((Tnodekind293020) 27): case ((Tnodekind293020) 32): case ((Tnodekind293020) 29): case ((Tnodekind293020) 30): case ((Tnodekind293020) 31): case ((Tnodekind293020) 26): case ((Tnodekind293020) 28): { Tnode293802* op0; genlinedir_533823_839829468(p0, n0); op0 = (*n0).kindU.S6.sons->data[((NI) 0)]; { Tloc293816 a0; if (!(*n0).typ == 0) goto LA90; memset((void*)(&a0), 0, sizeof(a0)); { NIM_BOOL LOC94; LOC94 = (NIM_BOOL)0; LOC94 = ((*op0).kind == ((Tnodekind293020) 3)); if (!(LOC94)) goto LA95; LOC94 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic293524) 0))); LA95: ; if (!LOC94) goto LA96; genmagicexpr_558033_839829468(p0, n0, (&a0), (*(*op0).kindU.S4.sym).magic); } goto LA92; LA96: ; { gencall_544632_839829468(p0, n0, (&a0)); } LA92: ; } goto LA88; LA90: ; { { NIM_BOOL LOC102; LOC102 = (NIM_BOOL)0; LOC102 = ((*op0).kind == ((Tnodekind293020) 3)); if (!(LOC102)) goto LA103; LOC102 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic293524) 0))); LA103: ; if (!LOC102) goto LA104; genmagicexpr_558033_839829468(p0, n0, d0, (*(*op0).kindU.S4.sym).magic); } goto LA100; LA104: ; { gencall_544632_839829468(p0, n0, d0); } LA100: ; } LA88: ; } break; case ((Tnodekind293020) 39): { { NIM_BOOL LOC110; NI LOC112; Ropeobj179006* LOC115; LOC110 = (NIM_BOOL)0; LOC110 = isdeepconstexpr_319566_2616423590(n0); if (!(LOC110)) goto LA111; LOC112 = (NI)0; LOC112 = len_294081_850551059(n0); LOC110 = !((LOC112 == ((NI) 0))); LA111: ; if (!LOC110) goto LA113; LOC115 = (Ropeobj179006*)0; LOC115 = gensetnode_550664_839829468(p0, n0); putintodest_551468_839829468(p0, d0, (*n0).typ, LOC115, ((Tstorageloc293812) 0)); } goto LA108; LA113: ; { gensetconstr_558496_839829468(p0, n0, d0); } LA108: ; } break; case ((Tnodekind293020) 41): { { NIM_BOOL LOC120; NI LOC122; LOC120 = (NIM_BOOL)0; LOC120 = isdeepconstexpr_319566_2616423590(n0); if (!(LOC120)) goto LA121; LOC122 = (NI)0; LOC122 = len_294081_850551059(n0); LOC120 = !((LOC122 == ((NI) 0))); LA121: ; if (!LOC120) goto LA123; exprcomplexconst_559684_839829468(p0, n0, d0); } goto LA118; LA123: ; { Ttype293840* LOC126; LOC126 = (Ttype293840*)0; LOC126 = skiptypes_297099_850551059((*n0).typ, IL64(211106242013440)); if (!((*LOC126).kind == ((Ttypekind293244) 24))) goto LA127; genseqconstr_556004_839829468(p0, n0, d0); } goto LA118; LA127: ; { genarrayconstr_559207_839829468(p0, n0, d0); } LA118: ; } break; case ((Tnodekind293020) 37): { { NIM_BOOL LOC133; NI LOC135; LOC133 = (NIM_BOOL)0; LOC133 = isdeepconstexpr_319566_2616423590(n0); if (!(LOC133)) goto LA134; LOC135 = (NI)0; LOC135 = len_294081_850551059(n0); LOC133 = !((LOC135 == ((NI) 0))); LA134: ; if (!LOC133) goto LA136; exprcomplexconst_559684_839829468(p0, n0, d0); } goto LA131; LA136: ; { gentupleconstr_558618_839829468(p0, n0, d0); } LA131: ; } break; case ((Tnodekind293020) 38): { genobjconstr_555903_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 61): { gencast_557538_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 58): case ((Tnodekind293020) 59): case ((Tnodekind293020) 60): { genconv_557633_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 64): case ((Tnodekind293020) 63): { genaddr_554051_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 42): { genbracketexpr_555277_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 47): case ((Tnodekind293020) 65): { genderef_544921_839829468(p0, n0, d0, NIM_FALSE); } break; case ((Tnodekind293020) 45): { genrecordfield_554448_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 46): { gencheckedrecordfield_555046_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 127): case ((Tnodekind293020) 112): { genblock_547083_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 126): { genstmtlistexpr_559402_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 115): { { NI i_560023_839829468; NI HEX3Atmp_560276_839829468; NI LOC151; NI res_560279_839829468; i_560023_839829468 = (NI)0; HEX3Atmp_560276_839829468 = (NI)0; LOC151 = (NI)0; LOC151 = sonslen_296351_850551059(n0); HEX3Atmp_560276_839829468 = (NI)(LOC151 - ((NI) 1)); res_560279_839829468 = ((NI) 0); { while (1) { if (!(res_560279_839829468 <= HEX3Atmp_560276_839829468)) goto LA153; i_560023_839829468 = res_560279_839829468; genstmts_540244_839829468(p0, (*n0).kindU.S6.sons->data[i_560023_839829468]); res_560279_839829468 += ((NI) 1); } LA153: ; } } } break; case ((Tnodekind293020) 48): case ((Tnodekind293020) 92): { genif_545982_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 93): { expr_540248_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[((NI) 0)], d0); } break; case ((Tnodekind293020) 66): { downconv_559581_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 67): { upconv_559431_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 68): { genrangechck_557591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_563)); } break; case ((Tnodekind293020) 69): { genrangechck_557591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_564)); } break; case ((Tnodekind293020) 70): { genrangechck_557591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_565)); } break; case ((Tnodekind293020) 71): { convstrtocstr_557643_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 72): { convcstrtostr_557655_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 51): case ((Tnodekind293020) 52): { Tsym293834* sym0; sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; genproc_533951_839829468((*p0).module, sym0); { NIM_BOOL LOC166; NimStringDesc* LOC170; LOC166 = (NIM_BOOL)0; LOC166 = ((*sym0).loc.r == NIM_NIL); if (LOC166) goto LA167; LOC166 = ((*sym0).loc.t == NIM_NIL); LA167: ; if (!LOC166) goto LA168; LOC170 = (NimStringDesc*)0; LOC170 = rawNewString((*(*sym0).name).s->Sup.len + 20); appendString(LOC170, ((NimStringDesc*) &T839829468_271)); appendString(LOC170, (*(*sym0).name).s); internalerror_197100_155036129((*n0).info, LOC170); } LA168: ; putlocintodest_540258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tnodekind293020) 155): { genclosure_558836_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 1): { } break; case ((Tnodekind293020) 96): { genwhilestmt_546985_839829468(p0, n0); } break; case ((Tnodekind293020) 99): case ((Tnodekind293020) 100): { genvarstmt_545854_839829468(p0, n0); } break; case ((Tnodekind293020) 101): { genconststmt_545909_839829468(p0, n0); } break; case ((Tnodekind293020) 94): { internalerror_197100_155036129((*n0).info, ((NimStringDesc*) &T839829468_594)); } break; case ((Tnodekind293020) 97): { gencase_548827_839829468(p0, n0, d0); } break; case ((Tnodekind293020) 109): { genreturnstmt_546617_839829468(p0, n0); } break; case ((Tnodekind293020) 110): { genbreakstmt_547444_839829468(p0, n0); } break; case ((Tnodekind293020) 73): { { if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag293427) 14))&15U)))!=0))) goto LA183; genasgn_550239_839829468(p0, n0, NIM_FALSE); } LA183: ; } break; case ((Tnodekind293020) 74): { { if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag293427) 14))&15U)))!=0))) goto LA188; genasgn_550239_839829468(p0, n0, !(((*p0).prc == NIM_NIL))); } LA188: ; } break; case ((Tnodekind293020) 114): { { Tloc293816 a0; if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind293020) 1)))) goto LA193; genlinedir_533823_839829468(p0, n0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_540283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA193: ; } break; case ((Tnodekind293020) 89): { genasmstmt_549659_839829468(p0, n0); } break; case ((Tnodekind293020) 106): { { NIM_BOOL LOC199; NIM_BOOL LOC200; LOC199 = (NIM_BOOL)0; LOC200 = (NIM_BOOL)0; LOC200 = (gcmd_170132_2607990831 == ((Tcommands170076) 2)); if (LOC200) goto LA201; LOC200 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA201: ; LOC199 = LOC200; if (!(LOC199)) goto LA202; LOC199 = !(((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 31))&63U)))!=0)); LA202: ; if (!LOC199) goto LA203; gentrycpp_548866_839829468(p0, n0, d0); } goto LA197; LA203: ; { gentry_549114_839829468(p0, n0, d0); } LA197: ; } break; case ((Tnodekind293020) 108): { genraisestmt_547828_839829468(p0, n0); } break; case ((Tnodekind293020) 98): { gentypesection_539184_839829468((*p0).module, n0); } break; case ((Tnodekind293020) 125): case ((Tnodekind293020) 84): case ((Tnodekind293020) 121): case ((Tnodekind293020) 116): case ((Tnodekind293020) 117): case ((Tnodekind293020) 118): case ((Tnodekind293020) 119): case ((Tnodekind293020) 120): case ((Tnodekind293020) 83): case ((Tnodekind293020) 82): { } break; case ((Tnodekind293020) 90): { genpragma_550039_839829468(p0, n0); } break; case ((Tnodekind293020) 91): { Tnode293802* LOC211; LOC211 = (Tnode293802*)0; LOC211 = lastson_296364_850551059(n0); expr_540248_839829468(p0, LOC211, d0); } break; case ((Tnodekind293020) 79): case ((Tnodekind293020) 80): case ((Tnodekind293020) 81): { { Tsym293834* prc0; if (!((*(*n0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind293020) 1))) goto LA215; prc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NIM_BOOL LOC219; Tsym293834* LOC220; LOC219 = (NIM_BOOL)0; LOC220 = (Tsym293834*)0; LOC220 = skipgenericowner_298280_850551059(prc0); LOC219 = ((*LOC220).kind == ((Tsymkind293435) 6)); if (!(LOC219)) goto LA221; LOC219 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 23))&31U)))!=0)); LA221: ; if (!LOC219) goto LA222; { NIM_BOOL LOC226; NIM_BOOL LOC227; NIM_BOOL LOC228; NIM_BOOL LOC229; Tsym293834* LOC231; NIM_BOOL LOC234; LOC226 = (NIM_BOOL)0; LOC227 = (NIM_BOOL)0; LOC228 = (NIM_BOOL)0; LOC229 = (NIM_BOOL)0; LOC229 = !(((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 2))&63U)))!=0)); if (!(LOC229)) goto LA230; LOC231 = (Tsym293834*)0; LOC231 = getmodule_300123_2984716966(prc0); LOC229 = !((((*LOC231).flags &(1U<<((NU)(((Tsymflag293184) 25))&31U)))!=0)); LA230: ; LOC228 = LOC229; if (LOC228) goto LA232; LOC228 = ((65600 & (*prc0).flags) == 64); LA232: ; LOC227 = LOC228; if (LOC227) goto LA233; LOC234 = (NIM_BOOL)0; LOC234 = (((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 6))&31U)))!=0); if (!(LOC234)) goto LA235; LOC234 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag293810) 5))&15U)))!=0); LA235: ; LOC227 = LOC234; LA233: ; LOC226 = LOC227; if (LOC226) goto LA236; LOC226 = ((*prc0).kind == ((Tsymkind293435) 13)); LA236: ; if (!LOC226) goto LA237; { NIM_BOOL LOC241; Tnode293802* LOC242; LOC241 = (NIM_BOOL)0; LOC242 = (Tnode293802*)0; LOC242 = getbody_336226_1724185294(prc0); LOC241 = !(((*LOC242).kind == ((Tnodekind293020) 1))); if (LOC241) goto LA243; LOC241 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag293810) 4))&15U)))!=0); LA243: ; if (!LOC241) goto LA244; genproc_533951_839829468((*p0).module, prc0); } LA244: ; } LA237: ; } LA222: ; } LA215: ; } break; case ((Tnodekind293020) 95): { genparforstmt_547208_839829468(p0, n0); } break; case ((Tnodekind293020) 157): { genstate_545117_839829468(p0, n0); } break; case ((Tnodekind293020) 156): { gengotostate_545144_839829468(p0, n0); } break; case ((Tnodekind293020) 158): { genbreakstate_545229_839829468(p0, n0); } break; default: { NimStringDesc* LOC251; LOC251 = (NimStringDesc*)0; LOC251 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI293020))->Sup.len + 25); appendString(LOC251, ((NimStringDesc*) &T839829468_291)); appendString(LOC251, reprEnum((NI)(*n0).kind, (&NTI293020))); appendString(LOC251, ((NimStringDesc*) &T839829468_657)); internalerror_197100_155036129((*n0).info, LOC251); } break; } } N_NIMCALL(void, genstmts_540244_839829468)(Tcproc530021* p0, Tnode293802* t0) { Tloc293816 a0; memset((void*)(&a0), 0, sizeof(a0)); expr_540248_839829468(p0, t0, (&a0)); { NimStringDesc* LOC5; if (!!(((7 &(1U<<((NU)(a0.k)&15U)))!=0))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_197185_1689653243(T839829468_658); internalerror_197113_155036129(LOC5); } LA3: ; } N_NIMCALL(Tnode293802*, myprocess_564402_839829468)(Tpasscontext342002* b0, Tnode293802* n0) { Tnode293802* result0; Tcgen530027* m0; { result0 = (Tnode293802*)0; result0 = n0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (b0 == NIM_NIL); if (LOC3) goto LA4; LOC3 = skipcodegen_342085_2355241294(n0); LA4: ; if (!LOC3) goto LA5; goto BeforeRet; } LA5: ; m0 = ((Tcgen530027*) (b0)); (*(*m0).initproc).options = initprocoptions_563635_839829468(m0); genstmts_540244_839829468((*m0).initproc, n0); }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj179006*, getsomeinitname_562904_839829468)(Tsym293834* m0, NimStringDesc* suffix0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { NimStringDesc* LOC5; if (!((12288 & (*m0).flags) == 0)) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = mangle_529847_2036603609((*(*(*m0).owner).name).s); result0 = rope_179277_2381377266(LOC5); add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_12)); } LA3: ; add_179487_2381377266(&result0, (*(*m0).name).s); add_179487_2381377266(&result0, suffix0); return result0; } N_NIMCALL(Ropeobj179006*, getinitname_563235_839829468)(Tsym293834* m0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = getsomeinitname_562904_839829468(m0, ((NimStringDesc*) &T839829468_659)); return result0; } N_NIMCALL(Ropeobj179006*, getdatinitname_563239_839829468)(Tsym293834* m0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = getsomeinitname_562904_839829468(m0, ((NimStringDesc*) &T839829468_660)); return result0; } N_NIMCALL(void, registermoduletomain_563243_839829468)(Tsym293834* m0) { Ropeobj179006* init0; Ropeobj179006* datinit0; TY179507 LOC1; TY179507 LOC2; init0 = getinitname_563235_839829468(m0); datinit0 = getdatinitname_563239_839829468(m0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = init0; addf_180205_2381377266(&mainmodprocs_530148_3723162438, ((NimStringDesc*) &T839829468_661), LOC1, 1); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = datinit0; addf_180205_2381377266(&mainmodprocs_530148_3723162438, ((NimStringDesc*) &T839829468_661), LOC2, 1); { TY179507 LOC7; Ropeobj179006* initcall0; TY179507 LOC8; if (!!((((*m0).flags &(1U<<((NU)(((Tsymflag293184) 13))&31U)))!=0))) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = datinit0; addf_180205_2381377266(&maindatinit_530151_3723162438, ((NimStringDesc*) &T839829468_662), LOC7, 1); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = init0; initcall0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_662), LOC8, 1); { if (!(((*m0).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0)) goto LA11; add_179482_2381377266(&mainmodinit_530149_3723162438, initcall0); } goto LA9; LA11: ; { add_179482_2381377266(&othermodsinit_530150_3723162438, initcall0); } LA9: ; } LA5: ; } N_NIMCALL(Ropeobj179006*, genfilenames_562688_839829468)(Tcgen530027* m0) { Ropeobj179006* result0; Ropeobj179006* LOC1; result0 = (Ropeobj179006*)0; LOC1 = (Ropeobj179006*)0; LOC1 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_673)); result0 = NIM_NIL; { NI i_562717_839829468; NI HEX3Atmp_562722_839829468; NI res_562725_839829468; i_562717_839829468 = (NI)0; HEX3Atmp_562722_839829468 = (NI)0; HEX3Atmp_562722_839829468 = ((fileinfos_192629_155036129 ? fileinfos_192629_155036129->Sup.len : 0) - 1); res_562725_839829468 = ((NI) 0); { while (1) { TY179507 LOC5; if (!(res_562725_839829468 <= HEX3Atmp_562722_839829468)) goto LA4; i_562717_839829468 = res_562725_839829468; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = makecstring_192638_155036129(fileinfos_192629_155036129->data[i_562717_839829468].projpath); addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_674), LOC5, 1); res_562725_839829468 += ((NI) 1); } LA4: ; } } return result0; } N_NIMCALL(void, genmainproc_562729_839829468)(Tcgen530027* m0) { NimStringDesc* nimmain0; NimStringDesc* othermain0; Ropeobj179006* initstackbottomcall0; TY537475 LOC38; TY536238 LOC47; nimmain0 = (NimStringDesc*)0; othermain0 = (NimStringDesc*)0; { NIM_BOOL LOC3; NIM_BOOL LOC12; LOC3 = (NIM_BOOL)0; LOC3 = (targetos_177629_4151366050 == ((Tsystemos177004) 2)); if (!(LOC3)) goto LA4; LOC3 = !(((gglobaloptions_170130_2607990831 & 1280) == 0)); LA4: ; if (!LOC3) goto LA5; { if (!((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 10))&63U)))!=0)) goto LA9; nimmain0 = copyString(((NimStringDesc*) &T839829468_663)); othermain0 = copyString(((NimStringDesc*) &T839829468_664)); } goto LA7; LA9: ; { nimmain0 = copyString(((NimStringDesc*) &T839829468_665)); othermain0 = copyString(((NimStringDesc*) &T839829468_666)); } LA7: ; LOC12 = (NIM_BOOL)0; LOC12 = includestr_147249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_667)); } goto LA1; LA5: ; { if (!((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 8))&63U)))!=0)) goto LA14; nimmain0 = copyString(((NimStringDesc*) &T839829468_665)); othermain0 = copyString(((NimStringDesc*) &T839829468_668)); } goto LA1; LA14: ; { if (!(targetos_177629_4151366050 == ((Tsystemos177004) 24))) goto LA17; nimmain0 = copyString(((NimStringDesc*) &T839829468_669)); othermain0 = copyString(((NimStringDesc*) &T839829468_670)); } goto LA1; LA17: ; { nimmain0 = copyString(((NimStringDesc*) &T839829468_669)); othermain0 = copyString(((NimStringDesc*) &T839829468_671)); } LA1: ; { Ropeobj179006* LOC24; if (!!((gbreakpoints_549861_839829468 == NIM_NIL))) goto LA22; LOC24 = (Ropeobj179006*)0; LOC24 = cgsym_533403_839829468(m0, ((NimStringDesc*) &T839829468_672)); } LA22: ; { Ropeobj179006* LOC29; if (!((goptions_170128_2607990831 &(1U<<((NU)(((Toption170009) 17))&31U)))!=0)) goto LA27; LOC29 = (Ropeobj179006*)0; LOC29 = genfilenames_562688_839829468(m0); add_179482_2381377266(&gbreakpoints_549861_839829468, LOC29); } LA27: ; { NIM_BOOL LOC32; LOC32 = (NIM_BOOL)0; LOC32 = (targetos_177629_4151366050 == ((Tsystemos177004) 24)); if (LOC32) goto LA33; LOC32 = (gselectedgc_170133_2607990831 == ((Tgcmode170080) 0)); LA33: ; if (!LOC32) goto LA34; initstackbottomcall0 = rope_179277_2381377266(((NimStringDesc*) &T839829468_490)); } goto LA30; LA34: ; { TY534289 LOC37; memset((void*)LOC37, 0, sizeof(LOC37)); initstackbottomcall0 = ropecg_533407_839829468(m0, ((NimStringDesc*) &T839829468_675), LOC37, 0); } LA30: ; (*m0).labels += ((NI) 1); memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = maindatinit_530151_3723162438; LOC38[1] = gbreakpoints_549861_839829468; LOC38[2] = othermodsinit_530150_3723162438; { NIM_BOOL LOC41; TY534289 LOC45; LOC41 = (NIM_BOOL)0; LOC41 = emulatedthreadvars_533949_839829468(); if (!(LOC41)) goto LA42; LOC41 = !((targetos_177629_4151366050 == ((Tsystemos177004) 24))); LA42: ; if (!LOC41) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC38[3] = ropecg_533407_839829468(m0, ((NimStringDesc*) &T839829468_677), LOC45, 0); } goto LA39; LA43: ; { LOC38[3] = rope_179277_2381377266(((NimStringDesc*) &T839829468_490)); } LA39: ; LOC38[4] = initstackbottomcall0; appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 10))- 0], ((NimStringDesc*) &T839829468_676), LOC38, 5); memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = mainmodinit_530149_3723162438; LOC47[1] = initstackbottomcall0; LOC47[2] = rope_179401_2381377266(((NI64) ((*m0).labels))); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 10))- 0], nimmain0, LOC47, 3); { TY534289 LOC52; if (!!(((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 20))&63U)))!=0))) goto LA50; memset((void*)LOC52, 0, sizeof(LOC52)); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 10))- 0], othermain0, LOC52, 0); } LA50: ; } N_NIMCALL(Tnode293802*, myclose_564830_839829468)(Tpasscontext342002* b0, Tnode293802* n0) { Tnode293802* result0; Tcgen530027* m0; { result0 = (Tnode293802*)0; result0 = n0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (b0 == NIM_NIL); if (LOC3) goto LA4; LOC3 = skipcodegen_342085_2355241294(n0); LA4: ; if (!LOC3) goto LA5; goto BeforeRet; } LA5: ; m0 = ((Tcgen530027*) (b0)); { if (!!((n0 == NIM_NIL))) goto LA9; (*(*m0).initproc).options = initprocoptions_563635_839829468(m0); genstmts_540244_839829468((*m0).initproc, n0); } LA9: ; registermoduletomain_563243_839829468((*m0).module); { Tnode293802* disp0; if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0)) goto LA13; (*m0).flags |= ((NU8)1)<<((((Codegenflag530025) 5))%(sizeof(NU8)*8)); disp0 = generatemethoddispatchers_433151_3853300031(); { NI i_564891_839829468; NI HEX3Atmp_564895_839829468; NI LOC16; NI res_564898_839829468; i_564891_839829468 = (NI)0; HEX3Atmp_564895_839829468 = (NI)0; LOC16 = (NI)0; LOC16 = sonslen_296351_850551059(disp0); HEX3Atmp_564895_839829468 = (NI)(LOC16 - ((NI) 1)); res_564898_839829468 = ((NI) 0); { while (1) { if (!(res_564898_839829468 <= HEX3Atmp_564895_839829468)) goto LA18; i_564891_839829468 = res_564898_839829468; genprocaux_561284_839829468(m0, (*(*disp0).kindU.S6.sons->data[i_564891_839829468]).kindU.S4.sym); res_564898_839829468 += ((NI) 1); } LA18: ; } } genmainproc_562729_839829468(m0); } LA13: ; }BeforeRet: ; return result0; } N_NIMCALL(void, finishmodule_564420_839829468)(Tcgen530027* m0) { NI i0; i0 = ((NI) 0); { while (1) { Tsym293834* prc0; if (!(i0 <= ((*m0).forwardedprocs ? ((*m0).forwardedprocs->Sup.len-1) : -1))) goto LA2; prc0 = (*m0).forwardedprocs->data[i0]; { NimStringDesc* LOC7; if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag293184) 4))&31U)))!=0)) goto LA5; LOC7 = (NimStringDesc*)0; LOC7 = rawNewString((*(*prc0).name).s->Sup.len + 17); appendString(LOC7, ((NimStringDesc*) &T839829468_678)); appendString(LOC7, (*(*prc0).name).s); internalerror_197100_155036129((*prc0).info, LOC7); } LA5: ; genprocnoforward_561906_839829468(m0, prc0); i0 += ((NI) 1); } LA2: ; } gforwardedprocscounter_530171_3723162438 -= i0; (*m0).forwardedprocs = (Tsymseq293804*) setLengthSeq(&((*m0).forwardedprocs)->Sup, sizeof(Tsym293834*), ((NI) 0)); } N_NIMCALL(void, geninitcode_563286_839829468)(Tcgen530027* m0) { Ropeobj179006* initname0; Ropeobj179006* prc0; TY179507 LOC1; Ropeobj179006* LOC12; Ropeobj179006* LOC13; Ropeobj179006** LOC14; Ropeobj179006** LOC15; Ropeobj179006** LOC16; Ropeobj179006* LOC17; Ropeobj179006* LOC33; Ropeobj179006** LOC34; Ropeobj179006** LOC35; Ropeobj179006** LOC36; Ropeobj179006* LOC37; Ropeobj179006* LOC38; Ropeobj179006** LOC39; Ropeobj179006** LOC40; Ropeobj179006** LOC41; Ropeobj179006* LOC42; Ropeobj179006* LOC50; TY534289 LOC51; TY179507 LOC52; TY534289 LOC58; initname0 = getinitname_563235_839829468((*m0).module); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = initname0; prc0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_679), LOC1, 1); { TY533811 LOC6; if (!(((NI) 0) < (*m0).typenodes)) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = (*m0).typenodesname; LOC6[1] = rope_179401_2381377266(((NI64) ((*m0).typenodes))); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 12))- 0], ((NimStringDesc*) &T839829468_680), LOC6, 2); } LA4: ; { TY533811 LOC11; if (!(((NI) 0) < (*m0).nimtypes)) goto LA9; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = (*m0).nimtypesname; LOC11[1] = rope_179401_2381377266(((NI64) ((*m0).nimtypes))); appcg_533632_839829468(m0, &(*m0).s[(((Tcfilesection530005) 12))- 0], ((NimStringDesc*) &T839829468_681), LOC11, 2); } LA9: ; LOC12 = (Ropeobj179006*)0; LOC12 = initgcframe_539435_839829468((*m0).initproc); add_179482_2381377266(&prc0, LOC12); LOC13 = (Ropeobj179006*)0; LOC13 = gensectionstart_531081_2760143328(((Tcprocsection530011) 0)); add_179482_2381377266(&prc0, LOC13); LOC14 = (Ropeobj179006**)0; LOC14 = s_530179_3723162438((*m0).preinitproc, ((Tcprocsection530011) 0)); add_179482_2381377266(&prc0, (*LOC14)); LOC15 = (Ropeobj179006**)0; LOC15 = s_530179_3723162438((*m0).initproc, ((Tcprocsection530011) 0)); add_179482_2381377266(&prc0, (*LOC15)); LOC16 = (Ropeobj179006**)0; LOC16 = s_530179_3723162438((*m0).postinitproc, ((Tcprocsection530011) 0)); add_179482_2381377266(&prc0, (*LOC16)); LOC17 = (Ropeobj179006*)0; LOC17 = gensectionend_531116_2760143328(((Tcprocsection530011) 0)); add_179482_2381377266(&prc0, LOC17); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption170009) 15))&31U)))!=0); if (!(LOC20)) goto LA21; LOC20 = !((((*m0).flags &(1U<<((NU)(((Codegenflag530025) 2))&7U)))!=0)); LA21: ; if (!LOC20) goto LA22; (*m0).flags |= ((NU8)1)<<((((Codegenflag530025) 2))%(sizeof(NU8)*8)); { Ropeobj179006* procname0; Ropeobj179006* LOC28; Ropeobj179006* LOC29; if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag530025) 0))&7U)))!=0))) goto LA26; procname0 = makecstring_192638_155036129((*(*(*m0).module).name).s); LOC28 = (Ropeobj179006*)0; LOC28 = quotedfilename_197818_155036129((*(*m0).module).info); LOC29 = (Ropeobj179006*)0; LOC29 = initframe_561140_839829468((*m0).initproc, procname0, LOC28); add_179482_2381377266(&prc0, LOC29); } goto LA24; LA26: ; { TY534289 LOC31; Ropeobj179006* LOC32; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj179006*)0; LOC32 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_682), LOC31, 0); add_179482_2381377266(&prc0, LOC32); } LA24: ; } LA22: ; LOC33 = (Ropeobj179006*)0; LOC33 = gensectionstart_531081_2760143328(((Tcprocsection530011) 1)); add_179482_2381377266(&prc0, LOC33); LOC34 = (Ropeobj179006**)0; LOC34 = s_530179_3723162438((*m0).preinitproc, ((Tcprocsection530011) 1)); add_179482_2381377266(&prc0, (*LOC34)); LOC35 = (Ropeobj179006**)0; LOC35 = s_530179_3723162438((*m0).initproc, ((Tcprocsection530011) 1)); add_179482_2381377266(&prc0, (*LOC35)); LOC36 = (Ropeobj179006**)0; LOC36 = s_530179_3723162438((*m0).postinitproc, ((Tcprocsection530011) 1)); add_179482_2381377266(&prc0, (*LOC36)); LOC37 = (Ropeobj179006*)0; LOC37 = gensectionend_531116_2760143328(((Tcprocsection530011) 1)); add_179482_2381377266(&prc0, LOC37); LOC38 = (Ropeobj179006*)0; LOC38 = gensectionstart_531081_2760143328(((Tcprocsection530011) 2)); add_179482_2381377266(&prc0, LOC38); LOC39 = (Ropeobj179006**)0; LOC39 = s_530179_3723162438((*m0).preinitproc, ((Tcprocsection530011) 2)); add_179482_2381377266(&prc0, (*LOC39)); LOC40 = (Ropeobj179006**)0; LOC40 = s_530179_3723162438((*m0).initproc, ((Tcprocsection530011) 2)); add_179482_2381377266(&prc0, (*LOC40)); LOC41 = (Ropeobj179006**)0; LOC41 = s_530179_3723162438((*m0).postinitproc, ((Tcprocsection530011) 2)); add_179482_2381377266(&prc0, (*LOC41)); LOC42 = (Ropeobj179006*)0; LOC42 = gensectionend_531116_2760143328(((Tcprocsection530011) 2)); add_179482_2381377266(&prc0, LOC42); { NIM_BOOL LOC45; Ropeobj179006* LOC49; LOC45 = (NIM_BOOL)0; LOC45 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption170009) 15))&31U)))!=0); if (!(LOC45)) goto LA46; LOC45 = !((((*m0).flags &(1U<<((NU)(((Codegenflag530025) 0))&7U)))!=0)); LA46: ; if (!LOC45) goto LA47; LOC49 = (Ropeobj179006*)0; LOC49 = deinitframe_561150_839829468((*m0).initproc); add_179482_2381377266(&prc0, LOC49); } LA47: ; LOC50 = (Ropeobj179006*)0; LOC50 = deinitgcframe_539441_839829468((*m0).initproc); add_179482_2381377266(&prc0, LOC50); memset((void*)LOC51, 0, sizeof(LOC51)); addf_180205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC51, 0); memset((void*)LOC52, 0, sizeof(LOC52)); LOC52[0] = getdatinitname_563239_839829468((*m0).module); addf_180205_2381377266(&prc0, ((NimStringDesc*) &T839829468_679), LOC52, 1); { Tcfilesection530005 i_563401_839829468; NI res_563482_839829468; i_563401_839829468 = (Tcfilesection530005)0; res_563482_839829468 = ((NI) 12); { while (1) { Ropeobj179006* LOC56; Ropeobj179006* LOC57; if (!(res_563482_839829468 <= ((NI) 16))) goto LA55; i_563401_839829468 = ((Tcfilesection530005) (res_563482_839829468)); LOC56 = (Ropeobj179006*)0; LOC56 = gensectionstart_531015_2760143328(i_563401_839829468); add_179482_2381377266(&prc0, LOC56); add_179482_2381377266(&prc0, (*m0).s[(i_563401_839829468)- 0]); LOC57 = (Ropeobj179006*)0; LOC57 = gensectionend_531050_2760143328(i_563401_839829468); add_179482_2381377266(&prc0, LOC57); res_563482_839829468 += ((NI) 1); } LA55: ; } } memset((void*)LOC58, 0, sizeof(LOC58)); addf_180205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC58, 0); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 11))- 0], prc0); { NIM_CHAR i_563442_839829468; Ropeobj179006* el_563443_839829468; TY530136 HEX3Atmp_563487_839829468; NIM_CHAR i_563490_839829468; i_563442_839829468 = (NIM_CHAR)0; el_563443_839829468 = (Ropeobj179006*)0; memset((void*)HEX3Atmp_563487_839829468, 0, sizeof(HEX3Atmp_563487_839829468)); memcpy((void*)HEX3Atmp_563487_839829468, (NIM_CONST void*)(*m0).extensionloaders, sizeof(HEX3Atmp_563487_839829468)); i_563490_839829468 = 48; { if (!((NU8)(((NIM_CHAR) (((NU8)(i_563490_839829468))))) <= (NU8)(57))) goto LA62; { while (1) { i_563442_839829468 = i_563490_839829468; el_563443_839829468 = HEX3Atmp_563487_839829468[(((NU8)(i_563490_839829468)))- 48]; { Ropeobj179006* ex0; TY533811 LOC70; if (!!((el_563443_839829468 == NIM_NIL))) goto LA68; memset((void*)LOC70, 0, sizeof(LOC70)); LOC70[0] = rope_179401_2381377266(((NI64) ((NI)(((NI) (((NU8)(i_563442_839829468)))) - ((NI) 48))))); LOC70[1] = el_563443_839829468; ex0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_684), LOC70, 2); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 11))- 0], ex0); } LA68: ; { if (!((NU8)(57) <= (NU8)(((NIM_CHAR) (((NU8)(i_563490_839829468))))))) goto LA73; goto LA64; } LA73: ; i_563490_839829468 += ((NI) 1); } } LA64: ; } LA62: ; } } N_NIMCALL(void, finishtypedescriptions_536842_839829468)(Tcgen530027* m0) { NI i0; i0 = ((NI) 0); { while (1) { Ropeobj179006* LOC3; if (!(i0 < ((*m0).typestack ? (*m0).typestack->Sup.len : 0))) goto LA2; LOC3 = (Ropeobj179006*)0; LOC3 = gettypedesc_536673_839829468(m0, (*m0).typestack->data[i0]); i0 += ((NI) 1); } LA2: ; } } N_NIMCALL(Ropeobj179006*, getcopyright_562665_839829468)(NimStringDesc* cfile0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; { TY179507 LOC5; if (!((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 4))&63U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_179277_2381377266(((NimStringDesc*) &T839829468_686)); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_685), LOC5, 1); } goto LA1; LA3: ; { TY537475 LOC7; NimStringDesc* LOC8; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rope_179277_2381377266(((NimStringDesc*) &T839829468_686)); LOC7[1] = rope_179277_2381377266(Os_177068_4151366050[(targetos_177629_4151366050)- 1].Field0); LOC7[2] = rope_179277_2381377266(Cpu_177496_4151366050[(targetcpu_177627_4151366050)- 1].Field0); LOC7[3] = rope_179277_2381377266(Cc_274413_2528170400[(ccompiler_274431_2528170400)- 1].Field0); LOC8 = (NimStringDesc*)0; LOC8 = getcompilecfilecmd_275284_2528170400(cfile0, NIM_FALSE); LOC7[4] = rope_179277_2381377266(LOC8); result0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_687), LOC7, 5); } LA1: ; return result0; } static N_INLINE(void, addinttypes_562659_839829468)(Ropeobj179006** result0) { NimStringDesc* LOC1; TY179507 LOC2; LOC1 = (NimStringDesc*)0; LOC1 = rawNewString(tnl_177644_4151366050->Sup.len + 22); appendString(LOC1, ((NimStringDesc*) &T839829468_688)); appendString(LOC1, tnl_177644_4151366050); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rope_179401_2381377266(((NI64) (Cpu_177496_4151366050[(targetcpu_177627_4151366050)- 1].Field1))); addf_180205_2381377266(result0, LOC1, LOC2, 1); } N_NIMCALL(Ropeobj179006*, getfileheader_562683_839829468)(NimStringDesc* cfile0) { Ropeobj179006* result0; result0 = (Ropeobj179006*)0; result0 = getcopyright_562665_839829468(cfile0); addinttypes_562659_839829468(&result0); return result0; } N_NIMCALL(void, generatethreadlocalstorage_539717_839829468)(Tcgen530027* m0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; TY179507 LOC13; LOC3 = (NIM_BOOL)0; LOC3 = !((nimtv_539656_839829468 == NIM_NIL)); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = (((*m0).flags &(1U<<((NU)(((Codegenflag530025) 1))&7U)))!=0); if (LOC5) goto LA6; LOC5 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; { Ttype293840* t_539761_839829468; NI i_539768_839829468; NI L_539770_839829468; t_539761_839829468 = (Ttype293840*)0; i_539768_839829468 = ((NI) 0); L_539770_839829468 = (nimtvdeps_539674_839829468 ? nimtvdeps_539674_839829468->Sup.len : 0); { while (1) { Ropeobj179006* LOC12; if (!(i_539768_839829468 < L_539770_839829468)) goto LA11; t_539761_839829468 = nimtvdeps_539674_839829468->data[i_539768_839829468]; LOC12 = (Ropeobj179006*)0; LOC12 = gettypedesc_536673_839829468(m0, t_539761_839829468); i_539768_839829468 += ((NI) 1); } LA11: ; } } memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = nimtv_539656_839829468; addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 4))- 0], ((NimStringDesc*) &T839829468_689), LOC13, 1); } LA7: ; } N_NIMCALL(void, generateheaders_561104_839829468)(Tcgen530027* m0) { NimStringDesc* LOC1; Tstrentry147009* it0; LOC1 = (NimStringDesc*)0; LOC1 = rawNewString(tnl_177644_4151366050->Sup.len + tnl_177644_4151366050->Sup.len + 20); appendString(LOC1, tnl_177644_4151366050); appendString(LOC1, ((NimStringDesc*) &T839829468_690)); appendString(LOC1, tnl_177644_4151366050); add_179487_2381377266(&(*m0).s[(((Tcfilesection530005) 1))- 0], LOC1); it0 = ((Tstrentry147009*) ((*m0).headerfiles.head)); { while (1) { if (!!((it0 == NIM_NIL))) goto LA3; { NimStringDesc* LOC8; NimStringDesc* LOC9; Ropeobj179006* LOC10; if (!((NU8)((*it0).data->data[((NI) 0)]) == (NU8)(35))) goto LA6; LOC8 = (NimStringDesc*)0; LOC9 = (NimStringDesc*)0; LOC9 = nsuReplaceChar((*it0).data, 96, 34); LOC8 = rawNewString(LOC9->Sup.len + tnl_177644_4151366050->Sup.len + 0); appendString(LOC8, LOC9); appendString(LOC8, tnl_177644_4151366050); LOC10 = (Ropeobj179006*)0; LOC10 = rope_179277_2381377266(LOC8); add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 1))- 0], LOC10); } goto LA4; LA6: ; { TY179507 LOC14; if (!!((((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(34)) || ((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(60))))) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_179277_2381377266((*it0).data); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 1))- 0], ((NimStringDesc*) &T839829468_691), LOC14, 1); } goto LA4; LA12: ; { TY179507 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rope_179277_2381377266((*it0).data); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 1))- 0], ((NimStringDesc*) &T839829468_692), LOC16, 1); } LA4: ; it0 = ((Tstrentry147009*) ((*it0).Sup.next)); } LA3: ; } } N_NIMCALL(Ropeobj179006*, genmodule_563491_839829468)(Tcgen530027* m0, NimStringDesc* cfile0) { Ropeobj179006* result0; Ropeobj179006* LOC1; result0 = (Ropeobj179006*)0; result0 = getfileheader_562683_839829468(cfile0); LOC1 = (Ropeobj179006*)0; LOC1 = genmergeinfo_531203_2760143328(m0); add_179482_2381377266(&result0, LOC1); generatethreadlocalstorage_539717_839829468(m0); generateheaders_561104_839829468(m0); { Tcfilesection530005 i_563614_839829468; NI res_563622_839829468; i_563614_839829468 = (Tcfilesection530005)0; res_563622_839829468 = ((NI) 1); { while (1) { Ropeobj179006* LOC5; Ropeobj179006* LOC6; if (!(res_563622_839829468 <= ((NI) 10))) goto LA4; i_563614_839829468 = ((Tcfilesection530005) (res_563622_839829468)); LOC5 = (Ropeobj179006*)0; LOC5 = gensectionstart_531015_2760143328(i_563614_839829468); add_179482_2381377266(&result0, LOC5); add_179482_2381377266(&result0, (*m0).s[(i_563614_839829468)- 0]); LOC6 = (Ropeobj179006*)0; LOC6 = gensectionend_531050_2760143328(i_563614_839829468); add_179482_2381377266(&result0, LOC6); res_563622_839829468 += ((NI) 1); } LA4: ; } } add_179482_2381377266(&result0, (*m0).s[(((Tcfilesection530005) 11))- 0]); return result0; } N_NIMCALL(void, updatecachedmodule_564813_839829468)(Tcgen530027* m0) { NimStringDesc* cfile0; NimStringDesc* cfilenoext0; cfile0 = getcfile_564201_839829468(m0); cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490)); { NIM_BOOL LOC3; Ropeobj179006* code0; LOC3 = (NIM_BOOL)0; LOC3 = mergerequired_531832_2760143328(m0); if (!(LOC3)) goto LA4; LOC3 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0)); LA4: ; if (!LOC3) goto LA5; mergefiles_532241_2760143328(cfile0, m0); geninitcode_563286_839829468(m0); finishtypedescriptions_536842_839829468(m0); code0 = genmodule_563491_839829468(m0, cfile0); writerope_179836_2381377266(code0, cfile0, NIM_FALSE); addfiletocompile_274863_2528170400(cfile0); } LA5: ; addfiletolink_274872_2528170400(cfilenoext0); } N_NIMCALL(void, generatethreadvarssize_539771_839829468)(Tcgen530027* m0) { { NimStringDesc* externc0; TY179507 LOC12; if (!!((nimtv_539656_839829468 == NIM_NIL))) goto LA3; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = !((gcmd_170132_2607990831 == ((Tcommands170076) 2))); if (!(LOC7)) goto LA8; LOC7 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; externc0 = copyString(((NimStringDesc*) &T839829468_693)); } goto LA5; LA9: ; { externc0 = copyString(((NimStringDesc*) &T839829468_490)); } LA5: ; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_179277_2381377266(externc0); addf_180205_2381377266(&(*m0).s[(((Tcfilesection530005) 10))- 0], ((NimStringDesc*) &T839829468_694), LOC12, 1); } LA3: ; } N_NIMCALL(NIM_BOOL, shouldrecompile_564621_839829468)(Ropeobj179006* code0, NimStringDesc* cfile0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; result0 = NIM_TRUE; { NimStringDesc* objfile0; if (!!(((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 1))&63U)))!=0))) goto LA3; objfile0 = toobjfile_274859_2528170400(cfile0); { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = writeropeifnotequal_180511_2381377266(code0, cfile0); if (!LOC7) goto LA8; goto BeforeRet; } LA8: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = nosexistsFile(objfile0); if (!(LOC12)) goto LA13; LOC12 = nosfileNewer(objfile0, cfile0); LA13: ; if (!LOC12) goto LA14; result0 = NIM_FALSE; } LA14: ; } goto LA1; LA3: ; { writerope_179836_2381377266(code0, cfile0, NIM_FALSE); } LA1: ; }BeforeRet: ; return result0; } N_NIMCALL(void, writemodule_564637_839829468)(Tcgen530027* m0, NIM_BOOL pending0) { NimStringDesc* cfile0; NimStringDesc* cfilenoext0; cfile0 = getcfile_564201_839829468(m0); cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490)); { NIM_BOOL LOC3; Ropeobj179006* code0; LOC3 = (NIM_BOOL)0; LOC3 = !((*m0).Sup.fromcache); if (LOC3) goto LA4; LOC3 = ((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 1))&63U)))!=0); LA4: ; if (!LOC3) goto LA5; geninitcode_563286_839829468(m0); finishtypedescriptions_536842_839829468(m0); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0)) goto LA9; add_179482_2381377266(&(*m0).s[(((Tcfilesection530005) 7))- 0], mainmodprocs_530148_3723162438); generatethreadvarssize_539771_839829468(m0); } LA9: ; code0 = genmodule_563491_839829468(m0, cfile0); { NIM_BOOL LOC13; LOC13 = (NIM_BOOL)0; LOC13 = shouldrecompile_564621_839829468(code0, cfile0); if (!LOC13) goto LA14; addfiletocompile_274863_2528170400(cfile0); } LA14: ; } goto LA1; LA5: ; { NIM_BOOL LOC17; NIM_BOOL LOC18; Ropeobj179006* code0; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = pending0; if (!(LOC18)) goto LA19; LOC18 = mergerequired_531832_2760143328(m0); LA19: ; LOC17 = LOC18; if (!(LOC17)) goto LA20; LOC17 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 12))&31U)))!=0)); LA20: ; if (!LOC17) goto LA21; mergefiles_532241_2760143328(cfile0, m0); geninitcode_563286_839829468(m0); finishtypedescriptions_536842_839829468(m0); code0 = genmodule_563491_839829468(m0, cfile0); writerope_179836_2381377266(code0, cfile0, NIM_FALSE); addfiletocompile_274863_2528170400(cfile0); } goto LA1; LA21: ; { NimStringDesc* LOC24; NIM_BOOL LOC25; LOC24 = (NimStringDesc*)0; LOC24 = toobjfile_274859_2528170400(cfilenoext0); LOC25 = (NIM_BOOL)0; LOC25 = nosexistsFile(LOC24); if (!!(LOC25)) goto LA26; addfiletocompile_274863_2528170400(cfile0); } goto LA1; LA26: ; LA1: ; addfiletolink_274872_2528170400(cfilenoext0); } N_NIMCALL(void, writeheader_564149_839829468)(Tcgen530027* m0) { Ropeobj179006* result0; Ropeobj179006* guard0; TY179507 LOC1; TY128506 LOC2; TY179507 LOC3; TY534289 LOC13; TY179507 LOC14; result0 = getcopyright_562665_839829468((*m0).filename); memset((void*)LOC1, 0, sizeof(LOC1)); memset((void*)(&LOC2), 0, sizeof(LOC2)); nossplitFile((*m0).filename, (&LOC2)); LOC1[0] = rope_179277_2381377266(LOC2.Field1); guard0 = HEX25_179905_2381377266(((NimStringDesc*) &T839829468_695), LOC1, 1); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = guard0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_696), LOC3, 1); addinttypes_562659_839829468(&result0); generateheaders_561104_839829468(m0); generatethreadlocalstorage_539717_839829468(m0); { Tcfilesection530005 i_564171_839829468; NI res_564197_839829468; i_564171_839829468 = (Tcfilesection530005)0; res_564197_839829468 = ((NI) 1); { while (1) { Ropeobj179006* LOC7; Ropeobj179006* LOC8; if (!(res_564197_839829468 <= ((NI) 10))) goto LA6; i_564171_839829468 = ((Tcfilesection530005) (res_564197_839829468)); LOC7 = (Ropeobj179006*)0; LOC7 = gensectionstart_531015_2760143328(i_564171_839829468); add_179482_2381377266(&result0, LOC7); add_179482_2381377266(&result0, (*m0).s[(i_564171_839829468)- 0]); LOC8 = (Ropeobj179006*)0; LOC8 = gensectionend_531050_2760143328(i_564171_839829468); add_179482_2381377266(&result0, LOC8); res_564197_839829468 += ((NI) 1); } LA6: ; } } add_179482_2381377266(&result0, (*m0).s[(((Tcfilesection530005) 11))- 0]); { if (!((gglobaloptions_170130_2607990831 &((NU64)1<<((NU)(((Tglobaloption170013) 8))&63U)))!=0)) goto LA11; add_179487_2381377266(&result0, ((NimStringDesc*) &T839829468_22)); } LA11: ; memset((void*)LOC13, 0, sizeof(LOC13)); addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_697), LOC13, 0); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = guard0; addf_180205_2381377266(&result0, ((NimStringDesc*) &T839829468_698), LOC14, 1); writerope_179836_2381377266(result0, (*m0).filename, NIM_FALSE); } N_NIMCALL(void, cgenwritemodules_564902_839829468)(void) { { if (!!((generatedheader_533201_839829468 == NIM_NIL))) goto LA3; finishmodule_564420_839829468(generatedheader_533201_839829468); } LA3: ; { while (1) { if (!(((NI) 0) < gforwardedprocscounter_530171_3723162438)) goto LA6; { Tcgen530027* m_564916_839829468; m_564916_839829468 = (Tcgen530027*)0; { NI i_564935_839829468; NI HEX3Atmp_564937_839829468; NI res_564939_839829468; i_564935_839829468 = (NI)0; HEX3Atmp_564937_839829468 = (NI)0; HEX3Atmp_564937_839829468 = (gmodules_530170_3723162438 ? (gmodules_530170_3723162438->Sup.len-1) : -1); res_564939_839829468 = ((NI) 0); { while (1) { if (!(res_564939_839829468 <= HEX3Atmp_564937_839829468)) goto LA10; i_564935_839829468 = res_564939_839829468; { if (!!((gmodules_530170_3723162438->data[i_564935_839829468] == NIM_NIL))) goto LA13; m_564916_839829468 = gmodules_530170_3723162438->data[i_564935_839829468]; { if (!!((*m_564916_839829468).Sup.fromcache)) goto LA17; finishmodule_564420_839829468(m_564916_839829468); } LA17: ; } LA13: ; res_564939_839829468 += ((NI) 1); } LA10: ; } } } } LA6: ; } { Tcgen530027* m_564917_839829468; m_564917_839829468 = (Tcgen530027*)0; { NI i_564946_839829468; NI HEX3Atmp_564948_839829468; NI res_564950_839829468; i_564946_839829468 = (NI)0; HEX3Atmp_564948_839829468 = (NI)0; HEX3Atmp_564948_839829468 = (gmodules_530170_3723162438 ? (gmodules_530170_3723162438->Sup.len-1) : -1); res_564950_839829468 = ((NI) 0); { while (1) { if (!(res_564950_839829468 <= HEX3Atmp_564948_839829468)) goto LA22; i_564946_839829468 = res_564950_839829468; { if (!!((gmodules_530170_3723162438->data[i_564946_839829468] == NIM_NIL))) goto LA25; m_564917_839829468 = gmodules_530170_3723162438->data[i_564946_839829468]; { if (!(*m_564917_839829468).Sup.fromcache) goto LA29; updatecachedmodule_564813_839829468(m_564917_839829468); } goto LA27; LA29: ; { writemodule_564637_839829468(m_564917_839829468, NIM_TRUE); } LA27: ; } LA25: ; res_564950_839829468 += ((NI) 1); } LA22: ; } } } writemapping_275789_2528170400(gmapping_530152_3723162438); { if (!!((generatedheader_533201_839829468 == NIM_NIL))) goto LA34; writeheader_564149_839829468(generatedheader_533201_839829468); } LA34: ; } N_NIMCALL(void, nullify_563833_839829468)(Ropeobj179006** arr0) { { Tcfilesection530005 i_563848_839829468; NI res_563853_839829468; i_563848_839829468 = (Tcfilesection530005)0; res_563853_839829468 = ((NI) 0); { while (1) { if (!(res_563853_839829468 <= ((NI) 17))) goto LA3; i_563848_839829468 = ((Tcfilesection530005) (res_563853_839829468)); unsureAsgnRef((void**) (&arr0[(i_563848_839829468)- 0]), NIM_NIL); res_563853_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, nullify_563858_839829468)(Ropeobj179006** arr0) { { NIM_CHAR i_564014_839829468; NI res_564019_839829468; i_564014_839829468 = (NIM_CHAR)0; res_564019_839829468 = ((NI) 48); { while (1) { if (!(res_564019_839829468 <= ((NI) 57))) goto LA3; i_564014_839829468 = ((NIM_CHAR) (res_564019_839829468)); unsureAsgnRef((void**) (&arr0[(((NU8)(i_564014_839829468)))- 48]), NIM_NIL); res_564019_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, resetmodule_563763_839829468)(Tcgen530027* m0) { initlinkedlist_147031_3771138726((&(*m0).headerfiles)); initintset_269885_2627731572((&(*m0).declaredprotos)); initidtable_297019_850551059((&(*m0).forwtypecache)); asgnRef((void**) (&(*m0).initproc), newproc_530206_3723162438(NIM_NIL, m0)); (*(*m0).initproc).options = initprocoptions_563635_839829468(m0); asgnRef((void**) (&(*m0).preinitproc), newpreinitproc_563625_839829468(m0)); asgnRef((void**) (&(*m0).postinitproc), newpostinitproc_563630_839829468(m0)); initnodetable_297085_850551059((&(*m0).datacache)); if ((*m0).typestack) nimGCunrefNoCycle((*m0).typestack); (*m0).typestack = (Ttypeseq293836*) newSeqRC1((&NTI293836), 0); if ((*m0).forwardedprocs) nimGCunrefNoCycle((*m0).forwardedprocs); (*m0).forwardedprocs = (Tsymseq293804*) newSeqRC1((&NTI293804), 0); asgnRefNoCycle((void**) (&(*m0).typenodesname), gettempname_534598_839829468(m0)); asgnRefNoCycle((void**) (&(*m0).nimtypesname), gettempname_534598_839829468(m0)); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag293184) 13))&31U)))!=0)) goto LA3; (*m0).flags |= ((NU8)1)<<((((Codegenflag530025) 0))%(sizeof(NU8)*8)); } goto LA1; LA3: ; { (*m0).flags &= ~(((NU8)1) << ((((Codegenflag530025) 0)) % (sizeof(NU8)*8))); } LA1: ; nullify_563833_839829468((*m0).s); (*m0).typenodes = ((NI) 0); (*m0).nimtypes = ((NI) 0); nullify_563858_839829468((*m0).extensionloaders); (*m0).Sup.fromcache = NIM_TRUE; } N_NIMCALL(void, resetcgenmodules_564024_839829468)(void) { { Tcgen530027* m_564026_839829468; m_564026_839829468 = (Tcgen530027*)0; { NI i_564031_839829468; NI HEX3Atmp_564033_839829468; NI res_564035_839829468; i_564031_839829468 = (NI)0; HEX3Atmp_564033_839829468 = (NI)0; HEX3Atmp_564033_839829468 = (gmodules_530170_3723162438 ? (gmodules_530170_3723162438->Sup.len-1) : -1); res_564035_839829468 = ((NI) 0); { while (1) { if (!(res_564035_839829468 <= HEX3Atmp_564033_839829468)) goto LA4; i_564031_839829468 = res_564035_839829468; { if (!!((gmodules_530170_3723162438->data[i_564031_839829468] == NIM_NIL))) goto LA7; m_564026_839829468 = gmodules_530170_3723162438->data[i_564031_839829468]; resetmodule_563763_839829468(m_564026_839829468); } LA7: ; res_564035_839829468 += ((NI) 1); } LA4: ; } } } } NIM_EXTERNC N_NOINLINE(void, compiler_cgenInit000)(void) { nimRegisterGlobalMarker(T839829468_2); nimRegisterGlobalMarker(T839829468_3); nimRegisterGlobalMarker(T839829468_5); nimRegisterGlobalMarker(T839829468_6); nimRegisterGlobalMarker(T839829468_7); nimRegisterGlobalMarker(T839829468_8); asgnRefNoCycle((void**) (&indent_533655_839829468), rope_179277_2381377266(((NimStringDesc*) &T839829468_4))); if (nimtvdeps_539674_839829468) nimGCunrefNoCycle(nimtvdeps_539674_839829468); nimtvdeps_539674_839829468 = (Ttypeseq293836*) newSeqRC1((&NTI293836), 0); chckNil((void*)(&nimtvdeclared_539675_839829468)); genericReset((void*)(&nimtvdeclared_539675_839829468), (&NTI269030)); initintset_269885_2627731572((&nimtvdeclared_539675_839829468)); breakpointid_549860_839829468 = ((NI) 0); } NIM_EXTERNC N_NOINLINE(void, compiler_cgenDatInit000)(void) { }
update_ops_control_single_target_single.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "constant.h" #include "update_ops.h" #include "utility.h" #ifdef _OPENMP #include <omp.h> #endif #ifdef _MSC_VER #include <intrin.h> #else #include <x86intrin.h> #endif //void single_qubit_control_single_qubit_dense_matrix_gate_single(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim); //void single_qubit_control_single_qubit_dense_matrix_gate_old_single(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim); //void single_qubit_control_single_qubit_dense_matrix_gate_old_parallel(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim); void single_qubit_control_single_qubit_dense_matrix_gate(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { //single_qubit_control_single_qubit_dense_matrix_gate_old_single(control_qubit_index, control_value, target_qubit_index,matrix,state, dim); //single_qubit_control_single_qubit_dense_matrix_gate_old_parallel(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); //single_qubit_control_single_qubit_dense_matrix_gate_single(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); //single_qubit_control_single_qubit_dense_matrix_gate_single_unroll(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); //single_qubit_control_single_qubit_dense_matrix_gate_single_simd(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); //single_qubit_control_single_qubit_dense_matrix_gate_parallel_simd(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); #ifdef _USE_SIMD #ifdef _OPENMP UINT threshold = 13; if (dim < (((ITYPE)1) << threshold)) { single_qubit_control_single_qubit_dense_matrix_gate_single_simd(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); } else { single_qubit_control_single_qubit_dense_matrix_gate_parallel_simd(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); } #else single_qubit_control_single_qubit_dense_matrix_gate_single_simd(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); #endif #else #ifdef _OPENMP UINT threshold = 13; if (dim < (((ITYPE)1) << threshold)) { single_qubit_control_single_qubit_dense_matrix_gate_single_unroll(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); } else { single_qubit_control_single_qubit_dense_matrix_gate_parallel_unroll(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); } #else single_qubit_control_single_qubit_dense_matrix_gate_single_unroll(control_qubit_index, control_value, target_qubit_index, matrix, state, dim); #endif #endif } void single_qubit_control_single_qubit_dense_matrix_gate_single_unroll(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { const ITYPE loop_dim = dim / 4; const ITYPE target_mask = 1ULL << target_qubit_index; const ITYPE control_mask = 1ULL << control_qubit_index; const UINT min_qubit_index = get_min_ui(control_qubit_index, target_qubit_index); const UINT max_qubit_index = get_max_ui(control_qubit_index, target_qubit_index); const ITYPE min_qubit_mask = 1ULL << min_qubit_index; const ITYPE max_qubit_mask = 1ULL << (max_qubit_index - 1); const ITYPE low_mask = min_qubit_mask - 1; const ITYPE mid_mask = (max_qubit_mask - 1) ^ low_mask; const ITYPE high_mask = ~(max_qubit_mask - 1); ITYPE state_index; if (target_qubit_index == 0) { for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_index = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; // fetch values CTYPE cval0 = state[basis_index]; CTYPE cval1 = state[basis_index+1]; // set values state[basis_index] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index+1] = matrix[2] * cval0 + matrix[3] * cval1; } } else if (control_qubit_index == 0) { for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_index_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_index_1 = basis_index_0 + target_mask; // fetch values CTYPE cval0 = state[basis_index_0]; CTYPE cval1 = state[basis_index_1]; // set values state[basis_index_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index_1] = matrix[2] * cval0 + matrix[3] * cval1; } }else { for (state_index = 0; state_index < loop_dim; state_index += 2) { ITYPE basis_index_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_index_1 = basis_index_0 + target_mask; // fetch values CTYPE cval0 = state[basis_index_0]; CTYPE cval1 = state[basis_index_1]; CTYPE cval2 = state[basis_index_0 + 1]; CTYPE cval3 = state[basis_index_1 + 1]; // set values state[basis_index_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index_1] = matrix[2] * cval0 + matrix[3] * cval1; state[basis_index_0 + 1] = matrix[0] * cval2 + matrix[1] * cval3; state[basis_index_1 + 1] = matrix[2] * cval2 + matrix[3] * cval3; } } } #ifdef _OPENMP void single_qubit_control_single_qubit_dense_matrix_gate_parallel_unroll(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { const ITYPE loop_dim = dim / 4; const ITYPE target_mask = 1ULL << target_qubit_index; const ITYPE control_mask = 1ULL << control_qubit_index; const UINT min_qubit_index = get_min_ui(control_qubit_index, target_qubit_index); const UINT max_qubit_index = get_max_ui(control_qubit_index, target_qubit_index); const ITYPE min_qubit_mask = 1ULL << min_qubit_index; const ITYPE max_qubit_mask = 1ULL << (max_qubit_index - 1); const ITYPE low_mask = min_qubit_mask - 1; const ITYPE mid_mask = (max_qubit_mask - 1) ^ low_mask; const ITYPE high_mask = ~(max_qubit_mask - 1); ITYPE state_index; if (target_qubit_index == 0) { #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_index = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; // fetch values CTYPE cval0 = state[basis_index]; CTYPE cval1 = state[basis_index + 1]; // set values state[basis_index] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index + 1] = matrix[2] * cval0 + matrix[3] * cval1; } } else if (control_qubit_index == 0) { #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_index_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_index_1 = basis_index_0 + target_mask; // fetch values CTYPE cval0 = state[basis_index_0]; CTYPE cval1 = state[basis_index_1]; // set values state[basis_index_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index_1] = matrix[2] * cval0 + matrix[3] * cval1; } } else { #pragma omp parallel for for (state_index = 0; state_index < loop_dim; state_index += 2) { ITYPE basis_index_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_index_1 = basis_index_0 + target_mask; // fetch values CTYPE cval0 = state[basis_index_0]; CTYPE cval1 = state[basis_index_1]; CTYPE cval2 = state[basis_index_0 + 1]; CTYPE cval3 = state[basis_index_1 + 1]; // set values state[basis_index_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index_1] = matrix[2] * cval0 + matrix[3] * cval1; state[basis_index_0 + 1] = matrix[0] * cval2 + matrix[1] * cval3; state[basis_index_1 + 1] = matrix[2] * cval2 + matrix[3] * cval3; } } } #endif #ifdef _USE_SIMD void single_qubit_control_single_qubit_dense_matrix_gate_single_simd(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { const ITYPE loop_dim = dim / 4; const ITYPE target_mask = 1ULL << target_qubit_index; const ITYPE control_mask = 1ULL << control_qubit_index; const UINT min_qubit_index = get_min_ui(control_qubit_index, target_qubit_index); const UINT max_qubit_index = get_max_ui(control_qubit_index, target_qubit_index); const ITYPE min_qubit_mask = 1ULL << min_qubit_index; const ITYPE max_qubit_mask = 1ULL << (max_qubit_index - 1); const ITYPE low_mask = min_qubit_mask - 1; const ITYPE mid_mask = (max_qubit_mask - 1) ^ low_mask; const ITYPE high_mask = ~(max_qubit_mask - 1); ITYPE state_index; if (target_qubit_index == 0) { __m256d mv00 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[0]), cimag(matrix[0])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[2]), cimag(matrix[2])); for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; double* ptr = (double*)(state + basis); __m256d data = _mm256_loadu_pd(ptr); __m256d data_u0 = _mm256_mul_pd(data, mv00); __m256d data_u1 = _mm256_mul_pd(data, mv01); __m256d data_u2 = _mm256_hadd_pd(data_u0, data_u1); data_u2 = _mm256_permute4x64_pd(data_u2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_d0 = _mm256_mul_pd(data, mv20); __m256d data_d1 = _mm256_mul_pd(data, mv21); __m256d data_d2 = _mm256_hadd_pd(data_d0, data_d1); data_d2 = _mm256_permute4x64_pd(data_d2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_r = _mm256_hadd_pd(data_u2, data_d2); data_r = _mm256_permute4x64_pd(data_r, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 _mm256_storeu_pd(ptr, data_r); } } else if (control_qubit_index == 0) { for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_index_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_index_1 = basis_index_0 + target_mask; // fetch values CTYPE cval0 = state[basis_index_0]; CTYPE cval1 = state[basis_index_1]; // set values state[basis_index_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index_1] = matrix[2] * cval0 + matrix[3] * cval1; } } else { __m256d mv00 = _mm256_set_pd(-cimag(matrix[0]), creal(matrix[0]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[0]), cimag(matrix[0]), creal(matrix[0]), cimag(matrix[0])); __m256d mv10 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[1]), creal(matrix[1])); __m256d mv11 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[1]), cimag(matrix[1])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[2]), creal(matrix[2]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[2]), cimag(matrix[2]), creal(matrix[2]), cimag(matrix[2])); __m256d mv30 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[3]), creal(matrix[3])); __m256d mv31 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[3]), cimag(matrix[3])); for (state_index = 0; state_index < loop_dim; state_index += 2) { ITYPE basis_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_1 = basis_0 + target_mask; double* ptr0 = (double*)(state + basis_0); double* ptr1 = (double*)(state + basis_1); __m256d data0 = _mm256_loadu_pd(ptr0); __m256d data1 = _mm256_loadu_pd(ptr1); __m256d data_u2 = _mm256_mul_pd(data0, mv00); __m256d data_u3 = _mm256_mul_pd(data1, mv10); __m256d data_u4 = _mm256_mul_pd(data0, mv01); __m256d data_u5 = _mm256_mul_pd(data1, mv11); __m256d data_u6 = _mm256_hadd_pd(data_u2, data_u4); __m256d data_u7 = _mm256_hadd_pd(data_u3, data_u5); __m256d data_d2 = _mm256_mul_pd(data0, mv20); __m256d data_d3 = _mm256_mul_pd(data1, mv30); __m256d data_d4 = _mm256_mul_pd(data0, mv21); __m256d data_d5 = _mm256_mul_pd(data1, mv31); __m256d data_d6 = _mm256_hadd_pd(data_d2, data_d4); __m256d data_d7 = _mm256_hadd_pd(data_d3, data_d5); __m256d data_r0 = _mm256_add_pd(data_u6, data_u7); __m256d data_r1 = _mm256_add_pd(data_d6, data_d7); _mm256_storeu_pd(ptr0, data_r0); _mm256_storeu_pd(ptr1, data_r1); } } } #ifdef _OPENMP void single_qubit_control_single_qubit_dense_matrix_gate_parallel_simd(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { const ITYPE loop_dim = dim / 4; const ITYPE target_mask = 1ULL << target_qubit_index; const ITYPE control_mask = 1ULL << control_qubit_index; const UINT min_qubit_index = get_min_ui(control_qubit_index, target_qubit_index); const UINT max_qubit_index = get_max_ui(control_qubit_index, target_qubit_index); const ITYPE min_qubit_mask = 1ULL << min_qubit_index; const ITYPE max_qubit_mask = 1ULL << (max_qubit_index - 1); const ITYPE low_mask = min_qubit_mask - 1; const ITYPE mid_mask = (max_qubit_mask - 1) ^ low_mask; const ITYPE high_mask = ~(max_qubit_mask - 1); ITYPE state_index; if (target_qubit_index == 0) { __m256d mv00 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[0]), cimag(matrix[0])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[2]), cimag(matrix[2])); #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; double* ptr = (double*)(state + basis); __m256d data = _mm256_loadu_pd(ptr); __m256d data_u0 = _mm256_mul_pd(data, mv00); __m256d data_u1 = _mm256_mul_pd(data, mv01); __m256d data_u2 = _mm256_hadd_pd(data_u0, data_u1); data_u2 = _mm256_permute4x64_pd(data_u2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_d0 = _mm256_mul_pd(data, mv20); __m256d data_d1 = _mm256_mul_pd(data, mv21); __m256d data_d2 = _mm256_hadd_pd(data_d0, data_d1); data_d2 = _mm256_permute4x64_pd(data_d2, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 __m256d data_r = _mm256_hadd_pd(data_u2, data_d2); data_r = _mm256_permute4x64_pd(data_r, 216); // (3210) -> (3120) : 1*0 + 4*2 + 16*1 + 64*3 = 216 _mm256_storeu_pd(ptr, data_r); } } else if (control_qubit_index == 0) { #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_index_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_index_1 = basis_index_0 + target_mask; // fetch values CTYPE cval0 = state[basis_index_0]; CTYPE cval1 = state[basis_index_1]; // set values state[basis_index_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index_1] = matrix[2] * cval0 + matrix[3] * cval1; } } else { __m256d mv00 = _mm256_set_pd(-cimag(matrix[0]), creal(matrix[0]), -cimag(matrix[0]), creal(matrix[0])); __m256d mv01 = _mm256_set_pd(creal(matrix[0]), cimag(matrix[0]), creal(matrix[0]), cimag(matrix[0])); __m256d mv10 = _mm256_set_pd(-cimag(matrix[1]), creal(matrix[1]), -cimag(matrix[1]), creal(matrix[1])); __m256d mv11 = _mm256_set_pd(creal(matrix[1]), cimag(matrix[1]), creal(matrix[1]), cimag(matrix[1])); __m256d mv20 = _mm256_set_pd(-cimag(matrix[2]), creal(matrix[2]), -cimag(matrix[2]), creal(matrix[2])); __m256d mv21 = _mm256_set_pd(creal(matrix[2]), cimag(matrix[2]), creal(matrix[2]), cimag(matrix[2])); __m256d mv30 = _mm256_set_pd(-cimag(matrix[3]), creal(matrix[3]), -cimag(matrix[3]), creal(matrix[3])); __m256d mv31 = _mm256_set_pd(creal(matrix[3]), cimag(matrix[3]), creal(matrix[3]), cimag(matrix[3])); #pragma omp parallel for for (state_index = 0; state_index < loop_dim; state_index += 2) { ITYPE basis_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_1 = basis_0 + target_mask; double* ptr0 = (double*)(state + basis_0); double* ptr1 = (double*)(state + basis_1); __m256d data0 = _mm256_loadu_pd(ptr0); __m256d data1 = _mm256_loadu_pd(ptr1); __m256d data_u2 = _mm256_mul_pd(data0, mv00); __m256d data_u3 = _mm256_mul_pd(data1, mv10); __m256d data_u4 = _mm256_mul_pd(data0, mv01); __m256d data_u5 = _mm256_mul_pd(data1, mv11); __m256d data_u6 = _mm256_hadd_pd(data_u2, data_u4); __m256d data_u7 = _mm256_hadd_pd(data_u3, data_u5); __m256d data_d2 = _mm256_mul_pd(data0, mv20); __m256d data_d3 = _mm256_mul_pd(data1, mv30); __m256d data_d4 = _mm256_mul_pd(data0, mv21); __m256d data_d5 = _mm256_mul_pd(data1, mv31); __m256d data_d6 = _mm256_hadd_pd(data_d2, data_d4); __m256d data_d7 = _mm256_hadd_pd(data_d3, data_d5); __m256d data_r0 = _mm256_add_pd(data_u6, data_u7); __m256d data_r1 = _mm256_add_pd(data_d6, data_d7); _mm256_storeu_pd(ptr0, data_r0); _mm256_storeu_pd(ptr1, data_r1); } } } #endif #endif /* void single_qubit_control_single_qubit_dense_matrix_gate_old_single(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { // loop varaibles const ITYPE loop_dim = dim >> 2; ITYPE state_index; // mask const ITYPE target_mask = 1ULL << target_qubit_index; const ITYPE control_mask = (1ULL << control_qubit_index) * control_value; // insert index const UINT min_qubit_index = get_min_ui(control_qubit_index, target_qubit_index); const UINT max_qubit_index = get_max_ui(control_qubit_index, target_qubit_index); const ITYPE min_qubit_mask = 1ULL << min_qubit_index; const ITYPE max_qubit_mask = 1ULL << max_qubit_index; for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_c_t0 = state_index; basis_c_t0 = insert_zero_to_basis_index(basis_c_t0, min_qubit_mask, min_qubit_index); basis_c_t0 = insert_zero_to_basis_index(basis_c_t0, max_qubit_mask, max_qubit_index); // flip control basis_c_t0 ^= control_mask; // gather index ITYPE basis_c_t1 = basis_c_t0 ^ target_mask; // fetch values CTYPE cval_c_t0 = state[basis_c_t0]; CTYPE cval_c_t1 = state[basis_c_t1]; // set values state[basis_c_t0] = matrix[0] * cval_c_t0 + matrix[1] * cval_c_t1; state[basis_c_t1] = matrix[2] * cval_c_t0 + matrix[3] * cval_c_t1; } } #ifdef _OPENMP void single_qubit_control_single_qubit_dense_matrix_gate_old_parallel(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { // loop varaibles const ITYPE loop_dim = dim >> 2; ITYPE state_index; // mask const ITYPE target_mask = 1ULL << target_qubit_index; const ITYPE control_mask = (1ULL << control_qubit_index) * control_value; // insert index const UINT min_qubit_index = get_min_ui(control_qubit_index, target_qubit_index); const UINT max_qubit_index = get_max_ui(control_qubit_index, target_qubit_index); const ITYPE min_qubit_mask = 1ULL << min_qubit_index; const ITYPE max_qubit_mask = 1ULL << max_qubit_index; #pragma omp parallel for for (state_index = 0; state_index < loop_dim; ++state_index) { // create base index ITYPE basis_c_t0 = state_index; basis_c_t0 = insert_zero_to_basis_index(basis_c_t0, min_qubit_mask, min_qubit_index); basis_c_t0 = insert_zero_to_basis_index(basis_c_t0, max_qubit_mask, max_qubit_index); // flip control basis_c_t0 ^= control_mask; // gather index ITYPE basis_c_t1 = basis_c_t0 ^ target_mask; // fetch values CTYPE cval_c_t0 = state[basis_c_t0]; CTYPE cval_c_t1 = state[basis_c_t1]; // set values state[basis_c_t0] = matrix[0] * cval_c_t0 + matrix[1] * cval_c_t1; state[basis_c_t1] = matrix[2] * cval_c_t0 + matrix[3] * cval_c_t1; } } #endif void single_qubit_control_single_qubit_dense_matrix_gate_single(UINT control_qubit_index, UINT control_value, UINT target_qubit_index, const CTYPE matrix[4], CTYPE *state, ITYPE dim) { const ITYPE loop_dim = dim / 4; const ITYPE target_mask = 1ULL << target_qubit_index; const ITYPE control_mask = 1ULL << control_qubit_index; const UINT min_qubit_index = get_min_ui(control_qubit_index, target_qubit_index); const UINT max_qubit_index = get_max_ui(control_qubit_index, target_qubit_index); const ITYPE min_qubit_mask = 1ULL << min_qubit_index; const ITYPE max_qubit_mask = 1ULL << (max_qubit_index - 1); const ITYPE low_mask = min_qubit_mask - 1; const ITYPE mid_mask = (max_qubit_mask - 1) ^ low_mask; const ITYPE high_mask = ~(max_qubit_mask - 1); ITYPE state_index; for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_index_0 = (state_index&low_mask) + ((state_index&mid_mask) << 1) + ((state_index&high_mask) << 2) + control_mask * control_value; ITYPE basis_index_1 = basis_index_0 + target_mask; // fetch values CTYPE cval0 = state[basis_index_0]; CTYPE cval1 = state[basis_index_1]; // set values state[basis_index_0] = matrix[0] * cval0 + matrix[1] * cval1; state[basis_index_1] = matrix[2] * cval0 + matrix[3] * cval1; } } */
test.c
#include <stdio.h> #pragma omp requires unified_shared_memory #include "../utilities/check.h" #define N 100 int main() { check_offloading(); int a[N], aa[N]; int i, error = 0; // initialize for(i=0; i<N; i++) aa[i] = a[i] = -1; // offload #pragma omp target map(tofrom: a[0:100]) { #pragma omp teams #pragma omp distribute simd for(int k=0; k<N; k++) a[k] = k; } // host for(i=0; i<N; i++) aa[i] = i; // check for(i=0; i<N; i++) { if (a[i] != aa[i]) printf("%d: a %d != %d (error %d)\n", i, a[i], aa[i], ++error); if (error > 10) { printf("abort\n"); return 0; } } // report printf("done with %d errors\n", error); return error; }
vptree_openmp.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <math.h> #include <omp.h> #include "../inc/vptree.h" // Threshold of points to switch to sequential execution #define POINT_THRESHOLD 10000 // Threshold of maximum live threads simultaneously for distance calculation #define THREADS_MAX 16 // Development flags to switch execution mode from serial to parallel for distance calculation and subtree creation #define PARALLELDIS true #define PARALLELSUB true // Function Prototypes vptree * buildvp(double *X, int n, int d); vptree * getInner(vptree * T); vptree * getOuter(vptree * T); double getMD(vptree * T); double * getVP(vptree * T); int getIDX(vptree * T); vptree * build_tree(double *points, int *ids, int n, int d); void euclidean(double *point, double *points, double *distances, int n, int d); void swap(double *a, double *b); int partition (double arr[], int low, int high); double quickselect_median(double arr[], int length); double quickselect(double arr[], int length, int idx); // Counter to keep track of live threads int threadCount = 0; // Thread-safe function to alter the live thread count void modThreadCount(int n){ #pragma omp atomic threadCount += n; } // Application entry point vptree * buildvp(double *X, int n, int d) { // Allocate space for the index array int *ids = calloc(n, sizeof(int)); // Build the initial ids array for (int i = 0; i < n; i++) ids[i] = i; // Call build_tree to get the pointer to the root of the tree return build_tree(X, ids, n, d); } // Function that recursively builds the binary tree and returns a pointer to its root vptree * build_tree(double *points, int *ids, int n, int d) { // Enable OpenMP Nested Parallelism omp_set_nested(true); // Create node to be returned vptree *node = calloc(1, sizeof(vptree)); // Check to end recursion: if points array is of size 0 - we are returning a leaf if (n == 1){ // Build node node->inner = NULL; node->outer = NULL; node->idx = ids[0]; node->md = 0; node->vp = calloc(d, sizeof(double)); memcpy(node->vp, points, sizeof(double) * d); // Free memory for ids and points arrays free(ids); free(points); // Return node return node; } // Choose the last point in X as the vantage point double *point = (points + (n-1)*d); int id = ids[n-1]; // Create array that holds euclidean distance of point from all other points double *distances = calloc(n-1, sizeof(double)); // Calculate distances in parallel if possible using work-construct, else do it sequentially (logic in euclidean()) euclidean(point, points, distances, n-1, d); // At this point distances[i] indicates the distance of point i in points from the vantage point // Find median by creating a copy of distances and passing it to QuickSelect double *distancesCopy = calloc(n-1, sizeof(double)); memcpy(distancesCopy, distances, sizeof(double) * (n-1)); double median = quickselect_median(distancesCopy, n-1); free(distancesCopy); // Sort points into two new arrays // Calculate array sizes for subtrees. Values up to and equal to the median go on the inner tree int innerLength = 0; for (int i = 0; i < n-1; i++) { if(distances[i] <= median) { innerLength++; } } int outerLength = n - 1 - innerLength; //TODO: Perhaps use distancesCopy to reduce the above linear scan to half // Pointers to keep track of inner and outer arrays content while sorting points int innerPointer = 0; int outerPointer = 0; // Create arrays for inner and outer points. Arrays contain the points and a list of ids (one for each point) double *innerPoints = calloc(innerLength * d, sizeof(double)); double *outerPoints = calloc(outerLength * d, sizeof(double)); int *innerIDs = calloc(innerLength, sizeof(int)); int *outerIDs = calloc(outerLength, sizeof(int)); // Sort points to inner and outer subtree for (int i = 0; i < n-1; i++){ if(distances[i] <= median){ memcpy(innerPoints + innerPointer * d, points + i*d, sizeof(double) * d); innerIDs[innerPointer] = ids[i]; innerPointer++; } else{ memcpy(outerPoints + outerPointer * d, points + i*d, sizeof(double) * d); outerIDs[outerPointer] = ids[i]; outerPointer++; } } // Set node fields // Copy the point into vp because we will call free(points) that will also free(point) node->vp = calloc(d, sizeof(double)); node->md = median; memcpy(node->vp, point, sizeof(double) * d); node->idx = id; // De-allocate unused memory free(points); free(distances); free(ids); // Build subtrees in parallel or sequentially if((PARALLELSUB == true) && (THREADS_MAX - threadCount >= 2)) { modThreadCount(2); #pragma omp parallel shared(node) { #pragma omp sections nowait { // Create threads #pragma omp section if(innerLength > 0) { node->inner = build_tree(innerPoints, innerIDs, innerLength, d); } #pragma omp section if(outerLength > 0) { node->outer = build_tree(outerPoints, outerIDs, outerLength, d); } } } modThreadCount(-2); } else { if(innerLength > 0) { node->inner = build_tree(innerPoints, innerIDs, innerLength, d); } if(outerLength > 0) { node->outer = build_tree(outerPoints, outerIDs, outerLength, d); } } if(innerLength < 1) { node->inner = NULL; } if(outerLength < 1) { node->outer= NULL; } return node; } // Return vantage-point subtree with points inside radius vptree * getInner(vptree * T) { return T->inner; } // Return vantage-point subtree with points outside radius vptree * getOuter(vptree * T) { return T->outer; } // Return median of distances to vantage point double getMD(vptree * T) { return T->md; } // Return the coordinates of the vantage point double * getVP(vptree * T) { return T->vp; } // Return the index of the vantage point int getIDX(vptree * T) { return T->idx; } // Calculates the distances of all points from point and writes them to an array. If possible use work-sharing to parallelize void euclidean(double *point, double *points, double *distances, int n, int d) { // Accumulator array for parallel execution double accumulator = 0; // Enable dynamic threads allocation omp_set_dynamic(1); // Decide if point calculation should happen in parallel or not if((n-1 > POINT_THRESHOLD) && (PARALLELDIS == true)) { #pragma omp parallel private(accumulator) { #pragma omp for schedule(auto) nowait for (int i = 0; i < n; i++) { accumulator = 0; for (int j = 0; j < d; j++) { accumulator += (point[j] - *(points + i * d + j)) * (point[j] - *(points + i * d + j)); } distances[i] = sqrt(accumulator); } } }else{ for (int i = 0; i < n; i++) { accumulator = 0; for (int j = 0; j < d; j++) { accumulator += (point[j] - *(points + i * d + j)) * (point[j] - *(points + i * d + j)); } distances[i] = sqrt(accumulator); } } return; } // A utility function to swap two elements void swap(double *a, double *b) { double t = *a; *a = *b; *b = t; } // QuickSort Partition function. low and high are the range of indexes in arr where partition should work int partition (double arr[], int low, int high) { // Select a pivot and initialize flag to position of smallest element before pivot double pivot = arr[high]; int i = (low - 1); // Go through the array examining each element for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot, increment i and swap it out with the one currently pointed by i if (arr[j] < pivot) { i++; swap(&arr[i], &arr[j]); } } // Finally place pivot in its correct position in the array and return the position as the middle point swap(&arr[i + 1], &arr[high]); return (i + 1); } // Returns the median using the QuickSelect algorithm double quickselect_median(double arr[], int length) { if (length % 2 == 1) { return quickselect(arr, length, (length+1)/2); } else { return 0.5 * (quickselect(arr, length, length/2) + quickselect(arr, length, length/2 + 1)); } } // Returns the idx-th element of arr when arr is sorted // idx is the index (starting from 1) of the point we want to find when the array is sorted. For the median idx should be the middle one (i.e (length+1)/2 for odd lengths etc) double quickselect(double arr[], int length, int idx) { // Check to end recursion if (length == 1) { return arr[0]; } // Select last array element as pivot double pivot = arr[length - 1]; // Get index of pivot after we partition the array int pivotIndex = partition(arr, 0, length - 1); // Create the higher and lower arrays that occur after partitioning in QuickSort fashion int lowerLength = pivotIndex; pivotIndex++; int higherLength = (length - (lowerLength + 1)); // At this point pivotIndex, lowerLength and higherLength all start from 1 not 0 double *lower = calloc(lowerLength, sizeof(double)); double *higher = calloc(higherLength, sizeof(double)); memcpy(lower, arr, sizeof(double) * lowerLength); memcpy(higher, arr + pivotIndex, sizeof(double) * higherLength); // Variable to store result of following recursive calls double result = 0; // This means that the point we're looking (median in our case) is in the lower partition if (idx <= lowerLength) { result = quickselect(lower, lowerLength, idx); } // This means that the median is our pivot point else if(idx == pivotIndex) { result = pivot; } // This means that the median is in the higher partition else { result = quickselect(higher, higherLength, idx - pivotIndex); } // Free memory allocated to lower and higher free(lower); free(higher); // Return result return result; }
GB_unaryop__identity_uint16_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_uint16_int64 // op(A') function: GB_tran__identity_uint16_int64 // C type: uint16_t // A type: int64_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint16_t z = (uint16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT16 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint16_int64 ( uint16_t *restrict Cx, const int64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_uint16_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 8; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,3);t1++) { lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6)); ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(0,ceild(3*t1,2)),ceild(24*t2-Nz+5,8)),3*t1-3*t2+1);t3<=min(min(min(floord(4*Nt+Ny-9,8),floord(12*t1+Ny+15,8)),floord(24*t2+Ny+11,8)),floord(24*t1-24*t2+Nz+Ny+13,8));t3++) { for (t4=max(max(max(max(0,ceild(3*t1-3*t2-6,8)),ceild(3*t1-14,16)),ceild(24*t2-Nz-51,64)),ceild(8*t3-Ny-51,64));t4<=min(min(min(min(floord(4*Nt+Nx-9,64),floord(12*t1+Nx+15,64)),floord(24*t2+Nx+11,64)),floord(8*t3+Nx-5,64)),floord(24*t1-24*t2+Nz+Nx+13,64));t4++) { for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(64*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),2*t3),Nt-1),3*t1+5),6*t2+4),16*t4+14);t5++) { for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(64*t4,4*t5+4); ubv=min(64*t4+63,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
HelloWorld_2.c
#include <omp.h> #include <stdio.h> int main() { int id_thread, num_threads; /* -id_thread: it must be private, that is, it must take on a different value for each thread that will execute the parallel piece of code. -num_threads: It can be left shared so it is left unique */ #pragma omp parallel private(id_thread), shared(num_threads) { id_thread = omp_get_thread_num(); num_threads = omp_get_num_threads(); printf("Hello from thread %d, nthread %d\n", id_thread, num_threads); } return 0; }
xgboost_regrank.h
#ifndef XGBOOST_REGRANK_H #define XGBOOST_REGRANK_H /*! * \file xgboost_regrank.h * \brief class for gradient boosted regression and ranking * \author Kailong Chen: chenkl198812@gmail.com, Tianqi Chen: tianqi.tchen@gmail.com */ #include <cmath> #include <cstdlib> #include <cstring> #include "xgboost_regrank_data.h" #include "xgboost_regrank_eval.h" #include "xgboost_regrank_obj.h" #include "../utils/xgboost_omp.h" #include "../booster/xgboost_gbmbase.h" #include "../utils/xgboost_utils.h" #include "../utils/xgboost_stream.h" namespace xgboost{ namespace regrank{ /*! \brief class for gradient boosted regression and ranking */ class RegRankBoostLearner{ public: /*! \brief constructor */ RegRankBoostLearner(void){ silent = 0; obj_ = NULL; name_obj_ = "reg:linear"; } /*! * \brief a regression booter associated with training and evaluating data * \param mats array of pointers to matrix whose prediction result need to be cached */ RegRankBoostLearner(const std::vector<const DMatrix *>& mats){ silent = 0; obj_ = NULL; name_obj_ = "reg:linear"; this->SetCacheData(mats); } /*! * \brief add internal cache space for mat, this can speedup prediction for matrix, * please cache prediction for training and eval data * warning: if the model is loaded from file from some previous training history * set cache data must be called with exactly SAME * data matrices to continue training otherwise it will cause error * \param mats array of pointers to matrix whose prediction result need to be cached */ inline void SetCacheData(const std::vector<const DMatrix *>& mats){ // estimate feature bound int num_feature = 0; // assign buffer index unsigned buffer_size = 0; utils::Assert( cache_.size() == 0, "can only call cache data once" ); for( size_t i = 0; i < mats.size(); ++i ){ bool dupilicate = false; for( size_t j = 0; j < i; ++ j ){ if( mats[i] == mats[j] ) dupilicate = true; } if( dupilicate ) continue; cache_.push_back( CacheEntry( mats[i], buffer_size ) ); buffer_size += static_cast<unsigned>(mats[i]->Size()); num_feature = std::max(num_feature, (int)(mats[i]->data.NumCol())); } char str_temp[25]; if (num_feature > mparam.num_feature){ mparam.num_feature = num_feature; sprintf(str_temp, "%d", num_feature); base_gbm.SetParam("bst:num_feature", str_temp); } sprintf(str_temp, "%u", buffer_size); base_gbm.SetParam("num_pbuffer", str_temp); if (!silent){ printf("buffer_size=%u\n", buffer_size); } } /*! * \brief set parameters from outside * \param name name of the parameter * \param val value of the parameter */ inline void SetParam(const char *name, const char *val){ if (!strcmp(name, "silent")) silent = atoi(val); if (!strcmp(name, "eval_metric")) evaluator_.AddEval(val); if (!strcmp(name, "objective") ) name_obj_ = val; if (!strcmp(name, "num_class") ) base_gbm.SetParam("num_booster_group", val ); mparam.SetParam(name, val); base_gbm.SetParam(name, val); cfg_.push_back( std::make_pair( std::string(name), std::string(val) ) ); } /*! * \brief initialize solver before training, called before training * this function is reserved for solver to allocate necessary space and do other preparation */ inline void InitTrainer(void){ if( mparam.num_class != 0 ){ if( name_obj_ != "multi:softmax" ){ name_obj_ = "multi:softmax"; printf("auto select objective=softmax to support multi-class classification\n" ); } } base_gbm.InitTrainer(); obj_ = CreateObjFunction( name_obj_.c_str() ); for( size_t i = 0; i < cfg_.size(); ++ i ){ obj_->SetParam( cfg_[i].first.c_str(), cfg_[i].second.c_str() ); } evaluator_.AddEval( obj_->DefaultEvalMetric() ); } /*! * \brief initialize the current data storage for model, if the model is used first time, call this function */ inline void InitModel(void){ base_gbm.InitModel(); mparam.AdjustBase(name_obj_.c_str()); } /*! * \brief load model from file * \param fname file name */ inline void LoadModel(const char *fname){ utils::FileStream fi(utils::FopenCheck(fname, "rb")); this->LoadModel(fi); fi.Close(); } /*! * \brief load model from stream * \param fi input stream */ inline void LoadModel(utils::IStream &fi){ base_gbm.LoadModel(fi); utils::Assert(fi.Read(&mparam, sizeof(ModelParam)) != 0); } /*! * \brief DumpModel * \param fo text file * \param fmap feature map that may help give interpretations of feature * \param with_stats whether print statistics as well */ inline void DumpModel(FILE *fo, const utils::FeatMap& fmap, bool with_stats){ base_gbm.DumpModel(fo, fmap, with_stats); } /*! * \brief Dump path of all trees * \param fo text file * \param data input data */ inline void DumpPath(FILE *fo, const DMatrix &data){ base_gbm.DumpPath(fo, data.data); } /*! * \brief save model to stream * \param fo output stream */ inline void SaveModel(utils::IStream &fo) const{ base_gbm.SaveModel(fo); fo.Write(&mparam, sizeof(ModelParam)); } /*! * \brief save model into file * \param fname file name */ inline void SaveModel(const char *fname) const{ utils::FileStream fo(utils::FopenCheck(fname, "wb")); this->SaveModel(fo); fo.Close(); } /*! * \brief update the model for one iteration */ inline void UpdateOneIter(const DMatrix &train){ this->PredictRaw(preds_, train); obj_->GetGradient(preds_, train.info, base_gbm.NumBoosters(), grad_, hess_); if( grad_.size() == train.Size() ){ base_gbm.DoBoost(grad_, hess_, train.data, train.info.root_index); }else{ int ngroup = base_gbm.NumBoosterGroup(); utils::Assert( grad_.size() == train.Size() * (size_t)ngroup, "BUG: UpdateOneIter: mclass" ); std::vector<float> tgrad( train.Size() ), thess( train.Size() ); for( int g = 0; g < ngroup; ++ g ){ memcpy( &tgrad[0], &grad_[g*tgrad.size()], sizeof(float)*tgrad.size() ); memcpy( &thess[0], &hess_[g*tgrad.size()], sizeof(float)*tgrad.size() ); base_gbm.DoBoost(tgrad, thess, train.data, train.info.root_index, g ); } } } /*! * \brief evaluate the model for specific iteration * \param iter iteration number * \param evals datas i want to evaluate * \param evname name of each dataset * \param fo file to output log */ inline void EvalOneIter(int iter, const std::vector<const DMatrix*> &evals, const std::vector<std::string> &evname, FILE *fo=stderr ){ fprintf(fo, "[%d]", iter); for (size_t i = 0; i < evals.size(); ++i){ this->PredictRaw(preds_, *evals[i]); obj_->PredTransform(preds_); evaluator_.Eval(fo, evname[i].c_str(), preds_, evals[i]->info); } fprintf(fo, "\n"); fflush(fo); } /*! * \brief get prediction * \param storage to store prediction * \param data input data * \param bst_group booster group we are in */ inline void Predict(std::vector<float> &preds, const DMatrix &data, int bst_group = -1){ this->PredictRaw( preds, data, bst_group ); obj_->PredTransform( preds ); } public: /*! * \brief interactive update * \param action action type * \parma train training data */ inline void UpdateInteract(std::string action, const DMatrix& train){ for(size_t i = 0; i < cache_.size(); ++i){ this->InteractPredict(preds_, *cache_[i].mat_); } if (action == "remove"){ base_gbm.DelteBooster(); return; } obj_->GetGradient(preds_, train.info, base_gbm.NumBoosters(), grad_, hess_); std::vector<unsigned> root_index; base_gbm.DoBoost(grad_, hess_, train.data, root_index); for(size_t i = 0; i < cache_.size(); ++i){ this->InteractRePredict(*cache_[i].mat_); } } private: /*! \brief get the transformed predictions, given data */ inline void InteractPredict(std::vector<float> &preds, const DMatrix &data){ int buffer_offset = this->FindBufferOffset(data); utils::Assert( buffer_offset >=0, "interact mode must cache training data" ); preds.resize(data.Size()); const unsigned ndata = static_cast<unsigned>(data.Size()); #pragma omp parallel for schedule( static ) for (unsigned j = 0; j < ndata; ++j){ preds[j] = mparam.base_score + base_gbm.InteractPredict(data.data, j, buffer_offset + j); } obj_->PredTransform( preds ); } /*! \brief repredict trial */ inline void InteractRePredict(const DMatrix &data){ int buffer_offset = this->FindBufferOffset(data); utils::Assert( buffer_offset >=0, "interact mode must cache training data" ); const unsigned ndata = static_cast<unsigned>(data.Size()); #pragma omp parallel for schedule( static ) for (unsigned j = 0; j < ndata; ++j){ base_gbm.InteractRePredict(data.data, j, buffer_offset + j); } } /*! \brief get un-transformed prediction*/ inline void PredictRaw(std::vector<float> &preds, const DMatrix &data, int bst_group = -1 ){ int buffer_offset = this->FindBufferOffset(data); if( bst_group < 0 ){ int ngroup = base_gbm.NumBoosterGroup(); preds.resize( data.Size() * ngroup ); for( int g = 0; g < ngroup; ++ g ){ this->PredictBuffer(&preds[ data.Size() * g ], data, buffer_offset, g ); } }else{ preds.resize( data.Size() ); this->PredictBuffer(&preds[0], data, buffer_offset, bst_group ); } } /*! \brief get the un-transformed predictions, given data */ inline void PredictBuffer(float *preds, const DMatrix &data, int buffer_offset, int bst_group ){ const unsigned ndata = static_cast<unsigned>(data.Size()); if( buffer_offset >= 0 ){ #pragma omp parallel for schedule( static ) for (unsigned j = 0; j < ndata; ++j){ preds[j] = mparam.base_score + base_gbm.Predict(data.data, j, buffer_offset + j, data.info.GetRoot(j), bst_group ); } }else #pragma omp parallel for schedule( static ) for (unsigned j = 0; j < ndata; ++j){ preds[j] = mparam.base_score + base_gbm.Predict(data.data, j, -1, data.info.GetRoot(j), bst_group ); }{ } } private: /*! \brief training parameter for regression */ struct ModelParam{ /* \brief global bias */ float base_score; /* \brief type of loss function */ int loss_type; /* \brief number of features */ int num_feature; /* \brief number of class, if it is multi-class classification */ int num_class; /*! \brief reserved field */ int reserved[15]; /*! \brief constructor */ ModelParam(void){ base_score = 0.5f; loss_type = -1; num_feature = 0; num_class = 0; memset(reserved, 0, sizeof(reserved)); } /*! * \brief set parameters from outside * \param name name of the parameter * \param val value of the parameter */ inline void SetParam(const char *name, const char *val){ if (!strcmp("base_score", name)) base_score = (float)atof(val); if (!strcmp("num_class", name)) num_class = atoi(val); if (!strcmp("loss_type", name)) loss_type = atoi(val); if (!strcmp("bst:num_feature", name)) num_feature = atoi(val); } /*! * \brief adjust base_score based on loss type and objective function */ inline void AdjustBase(const char *obj){ // some tweaks for loss type if( loss_type == -1 ){ loss_type = 1; if( !strcmp("reg:linear", obj ) ) loss_type = 0; } if (loss_type == 1 || loss_type == 2|| loss_type == 3){ utils::Assert(base_score > 0.0f && base_score < 1.0f, "sigmoid range constrain"); base_score = -logf(1.0f / base_score - 1.0f); } } }; private: struct CacheEntry{ const DMatrix *mat_; int buffer_offset_; CacheEntry(const DMatrix *mat, int buffer_offset) :mat_(mat), buffer_offset_(buffer_offset){} }; /*! \brief the entries indicates that we have internal prediction cache */ std::vector<CacheEntry> cache_; private: // find internal bufer offset for certain matrix, if not exist, return -1 inline int FindBufferOffset(const DMatrix &mat){ for(size_t i = 0; i < cache_.size(); ++i){ if( cache_[i].mat_ == &mat ) return cache_[i].buffer_offset_; } return -1; } protected: int silent; EvalSet evaluator_; booster::GBMBase base_gbm; ModelParam mparam; // objective fnction IObjFunction *obj_; // name of objective function std::string name_obj_; std::vector< std::pair<std::string, std::string> > cfg_; protected: std::vector<float> grad_, hess_, preds_; }; } }; #endif
GB_unop__identity_int64_int8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int64_int8) // op(A') function: GB (_unop_tran__identity_int64_int8) // C type: int64_t // A type: int8_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int64_t z = (int64_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = (int64_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_INT64 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int64_int8) ( int64_t *Cx, // Cx and Ax may be aliased const int8_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; int64_t z = (int64_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int8_t aij = Ax [p] ; int64_t z = (int64_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_int64_int8) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
reduction-clauseModificado7.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; omp_set_num_threads(n); #pragma omp parallel { #pragma omp critical suma+=a[omp_get_thread_num()]; } printf("Tras 'parallel' suma=%d\n",suma); }
msgmerge.c
/* GNU gettext - internationalization aids Copyright (C) 1995-1998, 2000-2010, 2012 Free Software Foundation, Inc. This file was written by Peter Miller <millerp@canb.auug.org.au> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <alloca.h> #include <getopt.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include "closeout.h" #include "dir-list.h" #include "error.h" #include "error-progname.h" #include "progname.h" #include "relocatable.h" #include "basename.h" #include "message.h" #include "read-catalog.h" #include "read-po.h" #include "read-properties.h" #include "read-stringtable.h" #include "write-catalog.h" #include "write-po.h" #include "write-properties.h" #include "write-stringtable.h" #include "color.h" #include "format.h" #include "xalloc.h" #include "xmalloca.h" #include "obstack.h" #include "c-strstr.h" #include "c-strcase.h" #include "po-charset.h" #include "msgl-iconv.h" #include "msgl-equal.h" #include "msgl-fsearch.h" #include "glthread/lock.h" #include "lang-table.h" #include "plural-exp.h" #include "plural-count.h" #include "msgl-check.h" #include "po-xerror.h" #include "backupfile.h" #include "copy-file.h" #include "propername.h" #include "gettext.h" #define _(str) gettext (str) #define obstack_chunk_alloc xmalloc #define obstack_chunk_free free /* If true do not print unneeded messages. */ static bool quiet; /* Verbosity level. */ static int verbosity_level; /* Force output of PO file even if empty. */ static int force_po; /* Apply the .pot file to each of the domains in the PO file. */ static bool multi_domain_mode = false; /* Determines whether to use fuzzy matching. */ static bool use_fuzzy_matching = true; /* Determines whether to keep old msgids as previous msgids. */ static bool keep_previous = false; /* Language (ISO-639 code) and optional territory (ISO-3166 code). */ static const char *catalogname = NULL; /* List of user-specified compendiums. */ static message_list_list_ty *compendiums; /* List of corresponding filenames. */ static string_list_ty *compendium_filenames; /* Update mode. */ static bool update_mode = false; static const char *version_control_string; static const char *backup_suffix_string; /* Long options. */ static const struct option long_options[] = { { "add-location", no_argument, &line_comment, 1 }, { "backup", required_argument, NULL, CHAR_MAX + 1 }, { "color", optional_argument, NULL, CHAR_MAX + 9 }, { "compendium", required_argument, NULL, 'C', }, { "directory", required_argument, NULL, 'D' }, { "escape", no_argument, NULL, 'E' }, { "force-po", no_argument, &force_po, 1 }, { "help", no_argument, NULL, 'h' }, { "indent", no_argument, NULL, 'i' }, { "lang", required_argument, NULL, CHAR_MAX + 8 }, { "multi-domain", no_argument, NULL, 'm' }, { "no-escape", no_argument, NULL, 'e' }, { "no-fuzzy-matching", no_argument, NULL, 'N' }, { "no-location", no_argument, &line_comment, 0 }, { "no-wrap", no_argument, NULL, CHAR_MAX + 4 }, { "output-file", required_argument, NULL, 'o' }, { "previous", no_argument, NULL, CHAR_MAX + 7 }, { "properties-input", no_argument, NULL, 'P' }, { "properties-output", no_argument, NULL, 'p' }, { "quiet", no_argument, NULL, 'q' }, { "sort-by-file", no_argument, NULL, 'F' }, { "sort-output", no_argument, NULL, 's' }, { "silent", no_argument, NULL, 'q' }, { "strict", no_argument, NULL, CHAR_MAX + 2 }, { "stringtable-input", no_argument, NULL, CHAR_MAX + 5 }, { "stringtable-output", no_argument, NULL, CHAR_MAX + 6 }, { "style", required_argument, NULL, CHAR_MAX + 10 }, { "suffix", required_argument, NULL, CHAR_MAX + 3 }, { "update", no_argument, NULL, 'U' }, { "verbose", no_argument, NULL, 'v' }, { "version", no_argument, NULL, 'V' }, { "width", required_argument, NULL, 'w', }, { NULL, 0, NULL, 0 } }; struct statistics { size_t merged; size_t fuzzied; size_t missing; size_t obsolete; }; /* Forward declaration of local functions. */ static void usage (int status) #if defined __GNUC__ && ((__GNUC__ == 2 && __GNUC_MINOR__ >= 5) || __GNUC__ > 2) __attribute__ ((noreturn)) #endif ; static void compendium (const char *filename); static void msgdomain_list_stablesort_by_obsolete (msgdomain_list_ty *mdlp); static msgdomain_list_ty *merge (const char *fn1, const char *fn2, catalog_input_format_ty input_syntax, msgdomain_list_ty **defp); int main (int argc, char **argv) { int opt; bool do_help; bool do_version; char *output_file; msgdomain_list_ty *def; msgdomain_list_ty *result; catalog_input_format_ty input_syntax = &input_format_po; catalog_output_format_ty output_syntax = &output_format_po; bool sort_by_filepos = false; bool sort_by_msgid = false; /* Set program name for messages. */ set_program_name (argv[0]); error_print_progname = maybe_print_progname; verbosity_level = 0; quiet = false; gram_max_allowed_errors = UINT_MAX; #ifdef HAVE_SETLOCALE /* Set locale via LC_ALL. */ setlocale (LC_ALL, ""); #endif /* Set the text message domain. */ bindtextdomain (PACKAGE, relocate (LOCALEDIR)); bindtextdomain ("bison-runtime", relocate (BISON_LOCALEDIR)); textdomain (PACKAGE); /* Ensure that write errors on stdout are detected. */ atexit (close_stdout); /* Set default values for variables. */ do_help = false; do_version = false; output_file = NULL; while ((opt = getopt_long (argc, argv, "C:D:eEFhimNo:pPqsUvVw:", long_options, NULL)) != EOF) switch (opt) { case '\0': /* Long option. */ break; case 'C': compendium (optarg); break; case 'D': dir_list_append (optarg); break; case 'e': message_print_style_escape (false); break; case 'E': message_print_style_escape (true); break; case 'F': sort_by_filepos = true; break; case 'h': do_help = true; break; case 'i': message_print_style_indent (); break; case 'm': multi_domain_mode = true; break; case 'N': use_fuzzy_matching = false; break; case 'o': output_file = optarg; break; case 'p': output_syntax = &output_format_properties; break; case 'P': input_syntax = &input_format_properties; break; case 'q': quiet = true; break; case 's': sort_by_msgid = true; break; case 'U': update_mode = true; break; case 'v': ++verbosity_level; break; case 'V': do_version = true; break; case 'w': { int value; char *endp; value = strtol (optarg, &endp, 10); if (endp != optarg) message_page_width_set (value); } break; case CHAR_MAX + 1: /* --backup */ version_control_string = optarg; break; case CHAR_MAX + 2: /* --strict */ message_print_style_uniforum (); break; case CHAR_MAX + 3: /* --suffix */ backup_suffix_string = optarg; break; case CHAR_MAX + 4: /* --no-wrap */ message_page_width_ignore (); break; case CHAR_MAX + 5: /* --stringtable-input */ input_syntax = &input_format_stringtable; break; case CHAR_MAX + 6: /* --stringtable-output */ output_syntax = &output_format_stringtable; break; case CHAR_MAX + 7: /* --previous */ keep_previous = true; break; case CHAR_MAX + 8: /* --lang */ catalogname = optarg; break; case CHAR_MAX + 9: /* --color */ if (handle_color_option (optarg) || color_test_mode) usage (EXIT_FAILURE); break; case CHAR_MAX + 10: /* --style */ handle_style_option (optarg); break; default: usage (EXIT_FAILURE); break; } /* Version information is requested. */ if (do_version) { printf ("%s (GNU %s) %s\n", basename (program_name), PACKAGE, VERSION); /* xgettext: no-wrap */ printf (_("Copyright (C) %s Free Software Foundation, Inc.\n\ License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n\ This is free software: you are free to change and redistribute it.\n\ There is NO WARRANTY, to the extent permitted by law.\n\ "), "1995-1998, 2000-2010"); printf (_("Written by %s.\n"), proper_name ("Peter Miller")); exit (EXIT_SUCCESS); } /* Help is requested. */ if (do_help) usage (EXIT_SUCCESS); /* Test whether we have an .po file name as argument. */ if (optind >= argc) { error (EXIT_SUCCESS, 0, _("no input files given")); usage (EXIT_FAILURE); } if (optind + 2 != argc) { error (EXIT_SUCCESS, 0, _("exactly 2 input files required")); usage (EXIT_FAILURE); } /* Verify selected options. */ if (update_mode) { if (output_file != NULL) { error (EXIT_FAILURE, 0, _("%s and %s are mutually exclusive"), "--update", "--output-file"); } } else { if (version_control_string != NULL) { error (EXIT_SUCCESS, 0, _("%s is only valid with %s"), "--backup", "--update"); usage (EXIT_FAILURE); } if (backup_suffix_string != NULL) { error (EXIT_SUCCESS, 0, _("%s is only valid with %s"), "--suffix", "--update"); usage (EXIT_FAILURE); } } if (!line_comment && sort_by_filepos) error (EXIT_FAILURE, 0, _("%s and %s are mutually exclusive"), "--no-location", "--sort-by-file"); if (sort_by_msgid && sort_by_filepos) error (EXIT_FAILURE, 0, _("%s and %s are mutually exclusive"), "--sort-output", "--sort-by-file"); /* In update mode, --properties-input implies --properties-output. */ if (update_mode && input_syntax == &input_format_properties) output_syntax = &output_format_properties; /* In update mode, --stringtable-input implies --stringtable-output. */ if (update_mode && input_syntax == &input_format_stringtable) output_syntax = &output_format_stringtable; /* Merge the two files. */ result = merge (argv[optind], argv[optind + 1], input_syntax, &def); /* Sort the results. */ if (sort_by_filepos) msgdomain_list_sort_by_filepos (result); else if (sort_by_msgid) msgdomain_list_sort_by_msgid (result); if (update_mode) { /* Before comparing result with def, sort the result into the same order as would be done implicitly by output_syntax->print. */ if (output_syntax->sorts_obsoletes_to_end) msgdomain_list_stablesort_by_obsolete (result); /* Do nothing if the original file and the result are equal. Also do nothing if the original file and the result differ only by the POT-Creation-Date in the header entry; this is needed for projects which don't put the .pot file under CVS. */ if (!msgdomain_list_equal (def, result, true)) { /* Back up def.po. */ enum backup_type backup_type; char *backup_file; output_file = argv[optind]; if (backup_suffix_string == NULL) { backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX"); if (backup_suffix_string != NULL && backup_suffix_string[0] == '\0') backup_suffix_string = NULL; } if (backup_suffix_string != NULL) simple_backup_suffix = backup_suffix_string; backup_type = xget_version (_("backup type"), version_control_string); if (backup_type != none) { backup_file = find_backup_file_name (output_file, backup_type); copy_file_preserving (output_file, backup_file); } /* Write the merged message list out. */ msgdomain_list_print (result, output_file, output_syntax, true, false); } } else { /* Write the merged message list out. */ msgdomain_list_print (result, output_file, output_syntax, force_po, false); } exit (EXIT_SUCCESS); } /* Display usage information and exit. */ static void usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try '%s --help' for more information.\n"), program_name); else { printf (_("\ Usage: %s [OPTION] def.po ref.pot\n\ "), program_name); printf ("\n"); /* xgettext: no-wrap */ printf (_("\ Merges two Uniforum style .po files together. The def.po file is an\n\ existing PO file with translations which will be taken over to the newly\n\ created file as long as they still match; comments will be preserved,\n\ but extracted comments and file positions will be discarded. The ref.pot\n\ file is the last created PO file with up-to-date source references but\n\ old translations, or a PO Template file (generally created by xgettext);\n\ any translations or comments in the file will be discarded, however dot\n\ comments and file positions will be preserved. Where an exact match\n\ cannot be found, fuzzy matching is used to produce better results.\n\ ")); printf ("\n"); printf (_("\ Mandatory arguments to long options are mandatory for short options too.\n")); printf ("\n"); printf (_("\ Input file location:\n")); printf (_("\ def.po translations referring to old sources\n")); printf (_("\ ref.pot references to new sources\n")); printf (_("\ -D, --directory=DIRECTORY add DIRECTORY to list for input files search\n")); printf (_("\ -C, --compendium=FILE additional library of message translations,\n\ may be specified more than once\n")); printf ("\n"); printf (_("\ Operation mode:\n")); printf (_("\ -U, --update update def.po,\n\ do nothing if def.po already up to date\n")); printf ("\n"); printf (_("\ Output file location:\n")); printf (_("\ -o, --output-file=FILE write output to specified file\n")); printf (_("\ The results are written to standard output if no output file is specified\n\ or if it is -.\n")); printf ("\n"); printf (_("\ Output file location in update mode:\n")); printf (_("\ The result is written back to def.po.\n")); printf (_("\ --backup=CONTROL make a backup of def.po\n")); printf (_("\ --suffix=SUFFIX override the usual backup suffix\n")); printf (_("\ The version control method may be selected via the --backup option or through\n\ the VERSION_CONTROL environment variable. Here are the values:\n\ none, off never make backups (even if --backup is given)\n\ numbered, t make numbered backups\n\ existing, nil numbered if numbered backups exist, simple otherwise\n\ simple, never always make simple backups\n")); printf (_("\ The backup suffix is '~', unless set with --suffix or the SIMPLE_BACKUP_SUFFIX\n\ environment variable.\n\ ")); printf ("\n"); printf (_("\ Operation modifiers:\n")); printf (_("\ -m, --multi-domain apply ref.pot to each of the domains in def.po\n")); printf (_("\ -N, --no-fuzzy-matching do not use fuzzy matching\n")); printf (_("\ --previous keep previous msgids of translated messages\n")); printf ("\n"); printf (_("\ Input file syntax:\n")); printf (_("\ -P, --properties-input input files are in Java .properties syntax\n")); printf (_("\ --stringtable-input input files are in NeXTstep/GNUstep .strings\n\ syntax\n")); printf ("\n"); printf (_("\ Output details:\n")); printf (_("\ --lang=CATALOGNAME set 'Language' field in the header entry\n")); printf (_("\ --color use colors and other text attributes always\n\ --color=WHEN use colors and other text attributes if WHEN.\n\ WHEN may be 'always', 'never', 'auto', or 'html'.\n")); printf (_("\ --style=STYLEFILE specify CSS style rule file for --color\n")); printf (_("\ -e, --no-escape do not use C escapes in output (default)\n")); printf (_("\ -E, --escape use C escapes in output, no extended chars\n")); printf (_("\ --force-po write PO file even if empty\n")); printf (_("\ -i, --indent indented output style\n")); printf (_("\ --no-location suppress '#: filename:line' lines\n")); printf (_("\ --add-location preserve '#: filename:line' lines (default)\n")); printf (_("\ --strict strict Uniforum output style\n")); printf (_("\ -p, --properties-output write out a Java .properties file\n")); printf (_("\ --stringtable-output write out a NeXTstep/GNUstep .strings file\n")); printf (_("\ -w, --width=NUMBER set output page width\n")); printf (_("\ --no-wrap do not break long message lines, longer than\n\ the output page width, into several lines\n")); printf (_("\ -s, --sort-output generate sorted output\n")); printf (_("\ -F, --sort-by-file sort output by file location\n")); printf ("\n"); printf (_("\ Informative output:\n")); printf (_("\ -h, --help display this help and exit\n")); printf (_("\ -V, --version output version information and exit\n")); printf (_("\ -v, --verbose increase verbosity level\n")); printf (_("\ -q, --quiet, --silent suppress progress indicators\n")); printf ("\n"); /* TRANSLATORS: The placeholder indicates the bug-reporting address for this package. Please add _another line_ saying "Report translation bugs to <...>\n" with the address for translation bugs (typically your translation team's web or email address). */ fputs (_("Report bugs to <bug-gnu-gettext@gnu.org>.\n"), stdout); } exit (status); } static void compendium (const char *filename) { msgdomain_list_ty *mdlp; size_t k; mdlp = read_catalog_file (filename, &input_format_po); if (compendiums == NULL) { compendiums = message_list_list_alloc (); compendium_filenames = string_list_alloc (); } for (k = 0; k < mdlp->nitems; k++) { message_list_list_append (compendiums, mdlp->item[k]->messages); string_list_append (compendium_filenames, filename); } } /* Sorts obsolete messages to the end, for every domain. */ static void msgdomain_list_stablesort_by_obsolete (msgdomain_list_ty *mdlp) { size_t k; for (k = 0; k < mdlp->nitems; k++) { message_list_ty *mlp = mdlp->item[k]->messages; /* Sort obsolete messages to the end. */ if (mlp->nitems > 0) { message_ty **l1 = XNMALLOC (mlp->nitems, message_ty *); size_t n1; message_ty **l2 = XNMALLOC (mlp->nitems, message_ty *); size_t n2; size_t j; /* Sort the non-obsolete messages into l1 and the obsolete messages into l2. */ n1 = 0; n2 = 0; for (j = 0; j < mlp->nitems; j++) { message_ty *mp = mlp->item[j]; if (mp->obsolete) l2[n2++] = mp; else l1[n1++] = mp; } if (n1 > 0 && n2 > 0) { memcpy (mlp->item, l1, n1 * sizeof (message_ty *)); memcpy (mlp->item + n1, l2, n2 * sizeof (message_ty *)); } free (l2); free (l1); } } } /* Data structure representing the messages with known translations. They are composed of - A message list from def.po, - The compendiums. The data structure is optimized for exact and fuzzy searches. */ typedef struct definitions_ty definitions_ty; struct definitions_ty { /* A list of message lists. The first comes from def.po, the other ones from the compendiums. Each message list has a built-in hash table, for speed when doing the exact searches. */ message_list_list_ty *lists; /* A fuzzy index of the current list of non-compendium messages, for speed when doing fuzzy searches. Used only if use_fuzzy_matching is true. */ message_fuzzy_index_ty *curr_findex; /* A once-only execution guard for the initialization of the fuzzy index. Needed for OpenMP. */ gl_lock_define(, curr_findex_init_lock) /* A fuzzy index of the compendiums, for speed when doing fuzzy searches. Used only if use_fuzzy_matching is true and compendiums != NULL. */ message_fuzzy_index_ty *comp_findex; /* A once-only execution guard for the initialization of the fuzzy index. Needed for OpenMP. */ gl_lock_define(, comp_findex_init_lock) /* The canonical encoding of the definitions and the compendiums. Only used for fuzzy matching. */ const char *canon_charset; }; static inline void definitions_init (definitions_ty *definitions, const char *canon_charset) { definitions->lists = message_list_list_alloc (); message_list_list_append (definitions->lists, NULL); if (compendiums != NULL) message_list_list_append_list (definitions->lists, compendiums); definitions->curr_findex = NULL; gl_lock_init (definitions->curr_findex_init_lock); definitions->comp_findex = NULL; gl_lock_init (definitions->comp_findex_init_lock); definitions->canon_charset = canon_charset; } /* Return the current list of non-compendium messages. */ static inline message_list_ty * definitions_current_list (const definitions_ty *definitions) { return definitions->lists->item[0]; } /* Set the current list of non-compendium messages. */ static inline void definitions_set_current_list (definitions_ty *definitions, message_list_ty *mlp) { definitions->lists->item[0] = mlp; if (definitions->curr_findex != NULL) { message_fuzzy_index_free (definitions->curr_findex); definitions->curr_findex = NULL; } } /* Create the fuzzy index for the current list of non-compendium messages. Used only if use_fuzzy_matching is true. */ static inline void definitions_init_curr_findex (definitions_ty *definitions) { /* Protect against concurrent execution. */ gl_lock_lock (definitions->curr_findex_init_lock); if (definitions->curr_findex == NULL) definitions->curr_findex = message_fuzzy_index_alloc (definitions_current_list (definitions), definitions->canon_charset); gl_lock_unlock (definitions->curr_findex_init_lock); } /* Create the fuzzy index for the compendium messages. Used only if use_fuzzy_matching is true and compendiums != NULL. */ static inline void definitions_init_comp_findex (definitions_ty *definitions) { /* Protect against concurrent execution. */ gl_lock_lock (definitions->comp_findex_init_lock); if (definitions->comp_findex == NULL) { /* Combine all the compendium message lists into a single one. Don't bother checking for duplicates. */ message_list_ty *all_compendium; size_t i; all_compendium = message_list_alloc (false); for (i = 0; i < compendiums->nitems; i++) { message_list_ty *mlp = compendiums->item[i]; size_t j; for (j = 0; j < mlp->nitems; j++) message_list_append (all_compendium, mlp->item[j]); } /* Create the fuzzy index from it. */ definitions->comp_findex = message_fuzzy_index_alloc (all_compendium, definitions->canon_charset); } gl_lock_unlock (definitions->comp_findex_init_lock); } /* Exact search. */ static inline message_ty * definitions_search (const definitions_ty *definitions, const char *msgctxt, const char *msgid) { return message_list_list_search (definitions->lists, msgctxt, msgid); } /* Fuzzy search. Used only if use_fuzzy_matching is true. */ static inline message_ty * definitions_search_fuzzy (definitions_ty *definitions, const char *msgctxt, const char *msgid) { message_ty *mp1; if (false) { /* Old, slow code. */ mp1 = message_list_search_fuzzy (definitions_current_list (definitions), msgctxt, msgid); } else { /* Speedup through early abort in fstrcmp(), combined with pre-sorting of the messages through a hashed index. */ /* Create the fuzzy index lazily. */ if (definitions->curr_findex == NULL) definitions_init_curr_findex (definitions); mp1 = message_fuzzy_index_search (definitions->curr_findex, msgctxt, msgid, FUZZY_THRESHOLD, false); } if (compendiums != NULL) { double lower_bound_for_mp2; message_ty *mp2; lower_bound_for_mp2 = (mp1 != NULL ? fuzzy_search_goal_function (mp1, msgctxt, msgid, 0.0) : FUZZY_THRESHOLD); /* This lower bound must be >= FUZZY_THRESHOLD. */ if (!(lower_bound_for_mp2 >= FUZZY_THRESHOLD)) abort (); /* Create the fuzzy index lazily. */ if (definitions->comp_findex == NULL) definitions_init_comp_findex (definitions); mp2 = message_fuzzy_index_search (definitions->comp_findex, msgctxt, msgid, lower_bound_for_mp2, true); /* Choose the best among mp1, mp2. */ if (mp1 == NULL || (mp2 != NULL && (fuzzy_search_goal_function (mp2, msgctxt, msgid, lower_bound_for_mp2) > lower_bound_for_mp2))) mp1 = mp2; } return mp1; } static inline void definitions_destroy (definitions_ty *definitions) { message_list_list_free (definitions->lists, 2); if (definitions->curr_findex != NULL) message_fuzzy_index_free (definitions->curr_findex); if (definitions->comp_findex != NULL) message_fuzzy_index_free (definitions->comp_findex); } /* A silent error logger. We are only interested in knowing whether errors occurred at all. */ static void silent_error_logger (const char *format, ...) __attribute__ ((__format__ (__printf__, 1, 2))); static void silent_error_logger (const char *format, ...) { } /* Another silent error logger. */ static void silent_xerror (int severity, const struct message_ty *message, const char *filename, size_t lineno, size_t column, int multiline_p, const char *message_text) { } static message_ty * message_merge (message_ty *def, message_ty *ref, bool force_fuzzy, const struct plural_distribution *distribution) { const char *msgstr; size_t msgstr_len; const char *prev_msgctxt; const char *prev_msgid; const char *prev_msgid_plural; message_ty *result; size_t j, i; /* Take the msgid from the reference. When fuzzy matches are made, the definition will not be unique, but the reference will be - usually because it has only been slightly changed. */ /* Take the msgstr from the definition. The msgstr of the reference is usually empty, as it was generated by xgettext. If we currently process the header entry we have to merge the msgstr by using the Report-Msgid-Bugs-To and POT-Creation-Date fields from the reference. */ if (is_header (ref)) { /* Oh, oh. The header entry and we have something to fill in. */ static const struct { const char *name; size_t len; } known_fields[] = { { "Project-Id-Version:", sizeof ("Project-Id-Version:") - 1 }, #define PROJECT_ID 0 { "Report-Msgid-Bugs-To:", sizeof ("Report-Msgid-Bugs-To:") - 1 }, #define REPORT_MSGID_BUGS_TO 1 { "POT-Creation-Date:", sizeof ("POT-Creation-Date:") - 1 }, #define POT_CREATION_DATE 2 { "PO-Revision-Date:", sizeof ("PO-Revision-Date:") - 1 }, #define PO_REVISION_DATE 3 { "Last-Translator:", sizeof ("Last-Translator:") - 1 }, #define LAST_TRANSLATOR 4 { "Language-Team:", sizeof ("Language-Team:") - 1 }, #define LANGUAGE_TEAM 5 { "Language:", sizeof ("Language:") - 1 }, #define LANGUAGE 6 { "MIME-Version:", sizeof ("MIME-Version:") - 1 }, #define MIME_VERSION 7 { "Content-Type:", sizeof ("Content-Type:") - 1 }, #define CONTENT_TYPE 8 { "Content-Transfer-Encoding:", sizeof ("Content-Transfer-Encoding:") - 1 } #define CONTENT_TRANSFER 9 }; #define UNKNOWN 10 struct { const char *string; size_t len; } header_fields[UNKNOWN + 1]; struct obstack pool; const char *cp; char *newp; size_t len, cnt; /* Clear all fields. */ memset (header_fields, '\0', sizeof (header_fields)); /* Prepare a temporary memory pool. */ obstack_init (&pool); cp = def->msgstr; while (*cp != '\0') { const char *endp = strchr (cp, '\n'); int terminated = endp != NULL; if (!terminated) { /* Add a trailing newline. */ char *copy; endp = strchr (cp, '\0'); len = endp - cp + 1; copy = (char *) obstack_alloc (&pool, len + 1); stpcpy (stpcpy (copy, cp), "\n"); cp = copy; } else { len = (endp - cp) + 1; ++endp; } /* Compare with any of the known fields. */ for (cnt = 0; cnt < sizeof (known_fields) / sizeof (known_fields[0]); ++cnt) if (c_strncasecmp (cp, known_fields[cnt].name, known_fields[cnt].len) == 0) break; if (cnt < sizeof (known_fields) / sizeof (known_fields[0])) { header_fields[cnt].string = &cp[known_fields[cnt].len]; header_fields[cnt].len = len - known_fields[cnt].len; } else { /* It's an unknown field. Append content to what is already known. */ char *extended = (char *) obstack_alloc (&pool, header_fields[UNKNOWN].len + len + 1); memcpy (extended, header_fields[UNKNOWN].string, header_fields[UNKNOWN].len); memcpy (&extended[header_fields[UNKNOWN].len], cp, len); extended[header_fields[UNKNOWN].len + len] = '\0'; header_fields[UNKNOWN].string = extended; header_fields[UNKNOWN].len += len; } cp = endp; } /* Set the Language field if specified on the command line. */ if (catalogname != NULL) { /* Prepend a space and append a newline. */ size_t len = strlen (catalogname); char *copy = (char *) obstack_alloc (&pool, 1 + len + 1 + 1); stpcpy (stpcpy (stpcpy (copy, " "), catalogname), "\n"); header_fields[LANGUAGE].string = copy; header_fields[LANGUAGE].len = strlen (header_fields[LANGUAGE].string); } /* Add a Language field to PO files that don't have one. The Language field was introduced in gettext-0.18. */ else if (header_fields[LANGUAGE].string == NULL) { const char *language_team_ptr = header_fields[LANGUAGE_TEAM].string; if (language_team_ptr != NULL) { size_t language_team_len = header_fields[LANGUAGE_TEAM].len; /* Trim leading blanks. */ while (language_team_len > 0 && (*language_team_ptr == ' ' || *language_team_ptr == '\t')) { language_team_ptr++; language_team_len--; } /* Trim trailing blanks. */ while (language_team_len > 0 && (language_team_ptr[language_team_len - 1] == ' ' || language_team_ptr[language_team_len - 1] == '\t')) language_team_len--; /* Trim last word, if it looks like an URL or email address. */ { size_t i; for (i = language_team_len; i > 0; i--) if (language_team_ptr[i - 1] == ' ' || language_team_ptr[i - 1] == '\t') break; /* The last word: language_team_ptr[i..language_team_len-1]. */ if (i < language_team_len && (language_team_ptr[i] == '<' || language_team_ptr[language_team_len - 1] == '>' || memchr (language_team_ptr, '@', language_team_len) != NULL || memchr (language_team_ptr, '/', language_team_len) != NULL)) { /* Trim last word and blanks before it. */ while (i > 0 && (language_team_ptr[i - 1] == ' ' || language_team_ptr[i - 1] == '\t')) i--; language_team_len = i; } } /* The rest of the Language-Team field should be the english name of the languge. Convert to ISO 639 and ISO 3166 syntax. */ { size_t i; for (i = 0; i < language_variant_table_size; i++) if (strlen (language_variant_table[i].english) == language_team_len && memcmp (language_variant_table[i].english, language_team_ptr, language_team_len) == 0) { header_fields[LANGUAGE].string = language_variant_table[i].code; break; } } if (header_fields[LANGUAGE].string == NULL) { size_t i; for (i = 0; i < language_table_size; i++) if (strlen (language_table[i].english) == language_team_len && memcmp (language_table[i].english, language_team_ptr, language_team_len) == 0) { header_fields[LANGUAGE].string = language_table[i].code; break; } } if (header_fields[LANGUAGE].string != NULL) { /* Prepend a space and append a newline. */ const char *str = header_fields[LANGUAGE].string; size_t len = strlen (str); char *copy = (char *) obstack_alloc (&pool, 1 + len + 1 + 1); stpcpy (stpcpy (stpcpy (copy, " "), str), "\n"); header_fields[LANGUAGE].string = copy; } else header_fields[LANGUAGE].string = " \n"; header_fields[LANGUAGE].len = strlen (header_fields[LANGUAGE].string); } } { const char *msgid_bugs_ptr; msgid_bugs_ptr = c_strstr (ref->msgstr, "Report-Msgid-Bugs-To:"); if (msgid_bugs_ptr != NULL) { size_t msgid_bugs_len; const char *endp; msgid_bugs_ptr += sizeof ("Report-Msgid-Bugs-To:") - 1; endp = strchr (msgid_bugs_ptr, '\n'); if (endp == NULL) { /* Add a trailing newline. */ char *extended; endp = strchr (msgid_bugs_ptr, '\0'); msgid_bugs_len = (endp - msgid_bugs_ptr) + 1; extended = (char *) obstack_alloc (&pool, msgid_bugs_len + 1); stpcpy (stpcpy (extended, msgid_bugs_ptr), "\n"); msgid_bugs_ptr = extended; } else msgid_bugs_len = (endp - msgid_bugs_ptr) + 1; header_fields[REPORT_MSGID_BUGS_TO].string = msgid_bugs_ptr; header_fields[REPORT_MSGID_BUGS_TO].len = msgid_bugs_len; } } { const char *pot_date_ptr; pot_date_ptr = c_strstr (ref->msgstr, "POT-Creation-Date:"); if (pot_date_ptr != NULL) { size_t pot_date_len; const char *endp; pot_date_ptr += sizeof ("POT-Creation-Date:") - 1; endp = strchr (pot_date_ptr, '\n'); if (endp == NULL) { /* Add a trailing newline. */ char *extended; endp = strchr (pot_date_ptr, '\0'); pot_date_len = (endp - pot_date_ptr) + 1; extended = (char *) obstack_alloc (&pool, pot_date_len + 1); stpcpy (stpcpy (extended, pot_date_ptr), "\n"); pot_date_ptr = extended; } else pot_date_len = (endp - pot_date_ptr) + 1; header_fields[POT_CREATION_DATE].string = pot_date_ptr; header_fields[POT_CREATION_DATE].len = pot_date_len; } } /* Concatenate all the various fields. */ len = 0; for (cnt = 0; cnt < UNKNOWN; ++cnt) if (header_fields[cnt].string != NULL) len += known_fields[cnt].len + header_fields[cnt].len; len += header_fields[UNKNOWN].len; cp = newp = XNMALLOC (len + 1, char); newp[len] = '\0'; #define IF_FILLED(idx) \ if (header_fields[idx].string) \ newp = stpncpy (stpcpy (newp, known_fields[idx].name), \ header_fields[idx].string, header_fields[idx].len) IF_FILLED (PROJECT_ID); IF_FILLED (REPORT_MSGID_BUGS_TO); IF_FILLED (POT_CREATION_DATE); IF_FILLED (PO_REVISION_DATE); IF_FILLED (LAST_TRANSLATOR); IF_FILLED (LANGUAGE_TEAM); IF_FILLED (LANGUAGE); IF_FILLED (MIME_VERSION); IF_FILLED (CONTENT_TYPE); IF_FILLED (CONTENT_TRANSFER); if (header_fields[UNKNOWN].string != NULL) stpcpy (newp, header_fields[UNKNOWN].string); #undef IF_FILLED /* Free the temporary memory pool. */ obstack_free (&pool, NULL); msgstr = cp; msgstr_len = strlen (cp) + 1; prev_msgctxt = NULL; prev_msgid = NULL; prev_msgid_plural = NULL; } else { msgstr = def->msgstr; msgstr_len = def->msgstr_len; if (def->is_fuzzy) { prev_msgctxt = def->prev_msgctxt; prev_msgid = def->prev_msgid; prev_msgid_plural = def->prev_msgid_plural; } else { prev_msgctxt = def->msgctxt; prev_msgid = def->msgid; prev_msgid_plural = def->msgid_plural; } } result = message_alloc (ref->msgctxt != NULL ? xstrdup (ref->msgctxt) : NULL, xstrdup (ref->msgid), ref->msgid_plural, msgstr, msgstr_len, &def->pos); /* Take the comments from the definition file. There will be none at all in the reference file, as it was generated by xgettext. */ if (def->comment) for (j = 0; j < def->comment->nitems; ++j) message_comment_append (result, def->comment->item[j]); /* Take the dot comments from the reference file, as they are generated by xgettext. Any in the definition file are old ones collected by previous runs of xgettext and msgmerge. */ if (ref->comment_dot) for (j = 0; j < ref->comment_dot->nitems; ++j) message_comment_dot_append (result, ref->comment_dot->item[j]); /* The flags are mixed in a special way. Some informations come from the reference message (such as format/no-format), others come from the definition file (fuzzy or not). */ result->is_fuzzy = def->is_fuzzy | force_fuzzy; /* If ref and def have the same msgid but different msgid_plural, it's a reason to mark the result fuzzy. */ if (!result->is_fuzzy && (ref->msgid_plural != NULL ? def->msgid_plural == NULL || strcmp (ref->msgid_plural, def->msgid_plural) != 0 : def->msgid_plural != NULL)) result->is_fuzzy = true; for (i = 0; i < NFORMATS; i++) { result->is_format[i] = ref->is_format[i]; /* If the reference message is marked as being a format specifier, but the definition message is not, we check if the resulting message would pass "msgfmt -c". If yes, then all is fine. If not, we add a fuzzy marker, because 1. the message needs the translator's attention, 2. msgmerge must not transform a PO file which passes "msgfmt -c" into a PO file which doesn't. */ if (!result->is_fuzzy && possible_format_p (ref->is_format[i]) && !possible_format_p (def->is_format[i]) && check_msgid_msgstr_format_i (ref->msgid, ref->msgid_plural, msgstr, msgstr_len, i, ref->range, distribution, silent_error_logger) > 0) result->is_fuzzy = true; } result->range = ref->range; /* If the definition message was assuming a certain range, but the reference message does not specify a range any more or specifies a range that is not the same or a subset, we add a fuzzy marker, because 1. the message needs the translator's attention, 2. msgmerge must not transform a PO file which passes "msgfmt -c" into a PO file which doesn't. */ if (!result->is_fuzzy && has_range_p (def->range) && !(has_range_p (ref->range) && ref->range.min >= def->range.min && ref->range.max <= def->range.max)) result->is_fuzzy = true; result->do_wrap = ref->do_wrap; /* Insert previous msgid, commented out with "#|". Do so only when --previous is specified, for backward compatibility. Since the "previous msgid" represents the original msgid that led to the current msgstr, - we can omit it if the resulting message is not fuzzy or is untranslated (but do this in a later pass, since result->is_fuzzy is not finalized at this point), - otherwise, if the corresponding message from the definition file was translated (not fuzzy), we use that message's msgid, - otherwise, we use that message's prev_msgid. */ if (keep_previous) { result->prev_msgctxt = prev_msgctxt; result->prev_msgid = prev_msgid; result->prev_msgid_plural = prev_msgid_plural; } /* If the reference message was obsolete, make the resulting message obsolete. This case doesn't occur for POT files, but users sometimes use PO files that are themselves the result of msgmerge instead of POT files. */ result->obsolete = ref->obsolete; /* Take the file position comments from the reference file, as they are generated by xgettext. Any in the definition file are old ones collected by previous runs of xgettext and msgmerge. */ for (j = 0; j < ref->filepos_count; ++j) { lex_pos_ty *pp = &ref->filepos[j]; message_comment_filepos (result, pp->file_name, pp->line_number); } /* Special postprocessing is needed if the reference message is a plural form and the definition message isn't, or vice versa. */ if (ref->msgid_plural != NULL) { if (def->msgid_plural == NULL) result->used = 1; } else { if (def->msgid_plural != NULL) result->used = 2; } /* All done, return the merged message to the caller. */ return result; } #define DOT_FREQUENCY 10 static void match_domain (const char *fn1, const char *fn2, definitions_ty *definitions, message_list_ty *refmlp, message_list_ty *resultmlp, struct statistics *stats, unsigned int *processed) { message_ty *header_entry; unsigned long int nplurals; const struct expression *plural_expr; char *untranslated_plural_msgstr; struct plural_distribution distribution; struct search_result { message_ty *found; bool fuzzy; } *search_results; size_t j; header_entry = message_list_search (definitions_current_list (definitions), NULL, ""); extract_plural_expression (header_entry ? header_entry->msgstr : NULL, &plural_expr, &nplurals); untranslated_plural_msgstr = XNMALLOC (nplurals, char); memset (untranslated_plural_msgstr, '\0', nplurals); /* Determine the plural distribution of the plural_expr formula. */ { /* Disable error output temporarily. */ void (*old_po_xerror) (int, const struct message_ty *, const char *, size_t, size_t, int, const char *) = po_xerror; po_xerror = silent_xerror; if (check_plural_eval (plural_expr, nplurals, header_entry, &distribution) > 0) { distribution.expr = NULL; distribution.often = NULL; distribution.often_length = 0; distribution.histogram = NULL; } po_xerror = old_po_xerror; } /* Most of the time is spent in definitions_search_fuzzy. Perform it in a separate loop that can be parallelized by an OpenMP capable compiler. */ search_results = XNMALLOC (refmlp->nitems, struct search_result); { long int nn = refmlp->nitems; long int jj; /* Tell the OpenMP capable compiler to distribute this loop across several threads. The schedule is dynamic, because for some messages the loop body can be executed very quickly, whereas for others it takes a long time. Note: The Sun Workshop 6.2 C compiler does not allow a space between '#' and 'pragma'. */ #ifdef _OPENMP #pragma omp parallel for schedule(dynamic) #endif for (jj = 0; jj < nn; jj++) { message_ty *refmsg = refmlp->item[jj]; message_ty *defmsg; /* Because merging can take a while we print something to signal we are not dead. */ if (!quiet && verbosity_level <= 1 && *processed % DOT_FREQUENCY == 0) fputc ('.', stderr); #ifdef _OPENMP #pragma omp atomic #endif (*processed)++; /* See if it is in the other file. */ defmsg = definitions_search (definitions, refmsg->msgctxt, refmsg->msgid); if (defmsg != NULL) { search_results[jj].found = defmsg; search_results[jj].fuzzy = false; } else if (!is_header (refmsg) /* If the message was not defined at all, try to find a very similar message, it could be a typo, or the suggestion may help. */ && use_fuzzy_matching && ((defmsg = definitions_search_fuzzy (definitions, refmsg->msgctxt, refmsg->msgid)) != NULL)) { search_results[jj].found = defmsg; search_results[jj].fuzzy = true; } else search_results[jj].found = NULL; } } for (j = 0; j < refmlp->nitems; j++) { message_ty *refmsg = refmlp->item[j]; /* See if it is in the other file. This used definitions_search. */ if (search_results[j].found != NULL && !search_results[j].fuzzy) { message_ty *defmsg = search_results[j].found; /* Merge the reference with the definition: take the #. and #: comments from the reference, take the # comments from the definition, take the msgstr from the definition. Add this merged entry to the output message list. */ message_ty *mp = message_merge (defmsg, refmsg, false, &distribution); message_list_append (resultmlp, mp); /* Remember that this message has been used, when we scan later to see if anything was omitted. */ defmsg->used = 1; stats->merged++; } else if (!is_header (refmsg)) { /* If the message was not defined at all, try to find a very similar message, it could be a typo, or the suggestion may help. This search assumed use_fuzzy_matching and used definitions_search_fuzzy. */ if (search_results[j].found != NULL && search_results[j].fuzzy) { message_ty *defmsg = search_results[j].found; message_ty *mp; if (verbosity_level > 1) { po_gram_error_at_line (&refmsg->pos, _("\ this message is used but not defined...")); error_message_count--; po_gram_error_at_line (&defmsg->pos, _("\ ...but this definition is similar")); } /* Merge the reference with the definition: take the #. and #: comments from the reference, take the # comments from the definition, take the msgstr from the definition. Add this merged entry to the output message list. */ mp = message_merge (defmsg, refmsg, true, &distribution); message_list_append (resultmlp, mp); /* Remember that this message has been used, when we scan later to see if anything was omitted. */ defmsg->used = 1; stats->fuzzied++; if (!quiet && verbosity_level <= 1) /* Always print a dot if we handled a fuzzy match. */ fputc ('.', stderr); } else { message_ty *mp; bool is_untranslated; const char *p; const char *pend; if (verbosity_level > 1) po_gram_error_at_line (&refmsg->pos, _("\ this message is used but not defined in %s"), fn1); mp = message_copy (refmsg); if (mp->msgid_plural != NULL) { /* Test if mp is untranslated. (It most likely is.) */ is_untranslated = true; for (p = mp->msgstr, pend = p + mp->msgstr_len; p < pend; p++) if (*p != '\0') { is_untranslated = false; break; } if (is_untranslated) { /* Change mp->msgstr_len consecutive empty strings into nplurals consecutive empty strings. */ if (nplurals > mp->msgstr_len) mp->msgstr = untranslated_plural_msgstr; mp->msgstr_len = nplurals; } } message_list_append (resultmlp, mp); stats->missing++; } } } free (search_results); /* Now postprocess the problematic merges. This is needed because we want the result to pass the "msgfmt -c -v" check. */ { /* message_merge sets mp->used to 1 or 2, depending on the problem. Compute the bitwise OR of all these. */ int problematic = 0; for (j = 0; j < resultmlp->nitems; j++) problematic |= resultmlp->item[j]->used; if (problematic) { unsigned long int nplurals = 0; if (problematic & 1) { /* Need to know nplurals of the result domain. */ message_ty *header_entry = message_list_search (resultmlp, NULL, ""); nplurals = get_plural_count (header_entry ? header_entry->msgstr : NULL); } for (j = 0; j < resultmlp->nitems; j++) { message_ty *mp = resultmlp->item[j]; if ((mp->used & 1) && (nplurals > 0)) { /* ref->msgid_plural != NULL but def->msgid_plural == NULL. Use a copy of def->msgstr for each possible plural form. */ size_t new_msgstr_len; char *new_msgstr; char *p; unsigned long i; if (verbosity_level > 1) { po_gram_error_at_line (&mp->pos, _("\ this message should define plural forms")); } new_msgstr_len = nplurals * mp->msgstr_len; new_msgstr = XNMALLOC (new_msgstr_len, char); for (i = 0, p = new_msgstr; i < nplurals; i++) { memcpy (p, mp->msgstr, mp->msgstr_len); p += mp->msgstr_len; } mp->msgstr = new_msgstr; mp->msgstr_len = new_msgstr_len; mp->is_fuzzy = true; } if ((mp->used & 2) && (mp->msgstr_len > strlen (mp->msgstr) + 1)) { /* ref->msgid_plural == NULL but def->msgid_plural != NULL. Use only the first among the plural forms. */ if (verbosity_level > 1) { po_gram_error_at_line (&mp->pos, _("\ this message should not define plural forms")); } mp->msgstr_len = strlen (mp->msgstr) + 1; mp->is_fuzzy = true; } /* Postprocessing of this message is done. */ mp->used = 0; } } } /* Now that mp->is_fuzzy is finalized for all messages, remove the "previous msgid" information from all messages that are not fuzzy or are untranslated. */ for (j = 0; j < resultmlp->nitems; j++) { message_ty *mp = resultmlp->item[j]; if (!mp->is_fuzzy || mp->msgstr[0] == '\0') { mp->prev_msgctxt = NULL; mp->prev_msgid = NULL; mp->prev_msgid_plural = NULL; } } } static msgdomain_list_ty * merge (const char *fn1, const char *fn2, catalog_input_format_ty input_syntax, msgdomain_list_ty **defp) { msgdomain_list_ty *def; msgdomain_list_ty *ref; size_t j, k; unsigned int processed; struct statistics stats; msgdomain_list_ty *result; const char *def_canon_charset; definitions_ty definitions; message_list_ty *empty_list; stats.merged = stats.fuzzied = stats.missing = stats.obsolete = 0; /* This is the definitions file, created by a human. */ def = read_catalog_file (fn1, input_syntax); /* This is the references file, created by groping the sources with the xgettext program. */ ref = read_catalog_file (fn2, input_syntax); /* Add a dummy header entry, if the references file contains none. */ for (k = 0; k < ref->nitems; k++) if (message_list_search (ref->item[k]->messages, NULL, "") == NULL) { static lex_pos_ty pos = { __FILE__, __LINE__ }; message_ty *refheader = message_alloc (NULL, "", NULL, "", 1, &pos); message_list_prepend (ref->item[k]->messages, refheader); } /* The references file can be either in ASCII or in UTF-8. If it is in UTF-8, we have to convert the definitions and the compendiums to UTF-8 as well. */ { bool was_utf8 = false; for (k = 0; k < ref->nitems; k++) { message_list_ty *mlp = ref->item[k]->messages; for (j = 0; j < mlp->nitems; j++) if (is_header (mlp->item[j]) && !mlp->item[j]->obsolete) { const char *header = mlp->item[j]->msgstr; if (header != NULL) { const char *charsetstr = c_strstr (header, "charset="); if (charsetstr != NULL) { size_t len; charsetstr += strlen ("charset="); len = strcspn (charsetstr, " \t\n"); if (len == strlen ("UTF-8") && c_strncasecmp (charsetstr, "UTF-8", len) == 0) was_utf8 = true; } } } } if (was_utf8) { def = iconv_msgdomain_list (def, "UTF-8", true, fn1); if (compendiums != NULL) for (k = 0; k < compendiums->nitems; k++) iconv_message_list (compendiums->item[k], NULL, po_charset_utf8, compendium_filenames->item[k]); } else if (compendiums != NULL && compendiums->nitems > 0) { /* Ensure that the definitions and the compendiums are in the same encoding. Prefer the encoding of the definitions file, if possible; otherwise, if the definitions file is empty and the compendiums are all in the same encoding, use that encoding; otherwise, use UTF-8. */ bool conversion_done = false; { char *charset = NULL; /* Get the encoding of the definitions file. */ for (k = 0; k < def->nitems; k++) { message_list_ty *mlp = def->item[k]->messages; for (j = 0; j < mlp->nitems; j++) if (is_header (mlp->item[j]) && !mlp->item[j]->obsolete) { const char *header = mlp->item[j]->msgstr; if (header != NULL) { const char *charsetstr = c_strstr (header, "charset="); if (charsetstr != NULL) { size_t len; charsetstr += strlen ("charset="); len = strcspn (charsetstr, " \t\n"); charset = (char *) xmalloca (len + 1); memcpy (charset, charsetstr, len); charset[len] = '\0'; break; } } } if (charset != NULL) break; } if (charset != NULL) { const char *canon_charset = po_charset_canonicalize (charset); if (canon_charset != NULL) { bool all_compendiums_iconvable = true; if (compendiums != NULL) for (k = 0; k < compendiums->nitems; k++) if (!is_message_list_iconvable (compendiums->item[k], NULL, canon_charset)) { all_compendiums_iconvable = false; break; } if (all_compendiums_iconvable) { /* Convert the compendiums to def's encoding. */ if (compendiums != NULL) for (k = 0; k < compendiums->nitems; k++) iconv_message_list (compendiums->item[k], NULL, canon_charset, compendium_filenames->item[k]); conversion_done = true; } } freea (charset); } } if (!conversion_done) { if (def->nitems == 0 || (def->nitems == 1 && def->item[0]->messages->nitems == 0)) { /* The definitions file is empty. Compare the encodings of the compendiums. */ const char *common_canon_charset = NULL; for (k = 0; k < compendiums->nitems; k++) { message_list_ty *mlp = compendiums->item[k]; char *charset = NULL; const char *canon_charset = NULL; for (j = 0; j < mlp->nitems; j++) if (is_header (mlp->item[j]) && !mlp->item[j]->obsolete) { const char *header = mlp->item[j]->msgstr; if (header != NULL) { const char *charsetstr = c_strstr (header, "charset="); if (charsetstr != NULL) { size_t len; charsetstr += strlen ("charset="); len = strcspn (charsetstr, " \t\n"); charset = (char *) xmalloca (len + 1); memcpy (charset, charsetstr, len); charset[len] = '\0'; break; } } } if (charset != NULL) { canon_charset = po_charset_canonicalize (charset); freea (charset); } /* If no charset declaration was found in this file, or if it is not a valid encoding name, or if it differs from the common charset found so far, we have no common charset. */ if (canon_charset == NULL || (common_canon_charset != NULL && canon_charset != common_canon_charset)) { common_canon_charset = NULL; break; } common_canon_charset = canon_charset; } if (common_canon_charset != NULL) /* No conversion needed in this case. */ conversion_done = true; } if (!conversion_done) { /* It's too hairy to find out what would be the optimal target encoding. So, convert everything to UTF-8. */ def = iconv_msgdomain_list (def, "UTF-8", true, fn1); if (compendiums != NULL) for (k = 0; k < compendiums->nitems; k++) iconv_message_list (compendiums->item[k], NULL, po_charset_utf8, compendium_filenames->item[k]); } } } } /* Determine canonicalized encoding name of the definitions now, after conversion. Only used for fuzzy matching. */ if (use_fuzzy_matching) { def_canon_charset = def->encoding; if (def_canon_charset == NULL) { char *charset = NULL; /* Get the encoding of the definitions file. */ for (k = 0; k < def->nitems; k++) { message_list_ty *mlp = def->item[k]->messages; for (j = 0; j < mlp->nitems; j++) if (is_header (mlp->item[j]) && !mlp->item[j]->obsolete) { const char *header = mlp->item[j]->msgstr; if (header != NULL) { const char *charsetstr = c_strstr (header, "charset="); if (charsetstr != NULL) { size_t len; charsetstr += strlen ("charset="); len = strcspn (charsetstr, " \t\n"); charset = (char *) xmalloca (len + 1); memcpy (charset, charsetstr, len); charset[len] = '\0'; break; } } } if (charset != NULL) break; } if (charset != NULL) def_canon_charset = po_charset_canonicalize (charset); if (def_canon_charset == NULL) /* Unspecified encoding. Assume unibyte encoding. */ def_canon_charset = po_charset_ascii; } } else def_canon_charset = NULL; /* Initialize and preprocess the total set of message definitions. */ definitions_init (&definitions, def_canon_charset); empty_list = message_list_alloc (false); result = msgdomain_list_alloc (false); processed = 0; /* Every reference must be matched with its definition. */ if (!multi_domain_mode) for (k = 0; k < ref->nitems; k++) { const char *domain = ref->item[k]->domain; message_list_ty *refmlp = ref->item[k]->messages; message_list_ty *resultmlp = msgdomain_list_sublist (result, domain, true); message_list_ty *defmlp; defmlp = msgdomain_list_sublist (def, domain, false); if (defmlp == NULL) defmlp = empty_list; definitions_set_current_list (&definitions, defmlp); match_domain (fn1, fn2, &definitions, refmlp, resultmlp, &stats, &processed); } else { /* Apply the references messages in the default domain to each of the definition domains. */ message_list_ty *refmlp = ref->item[0]->messages; for (k = 0; k < def->nitems; k++) { const char *domain = def->item[k]->domain; message_list_ty *defmlp = def->item[k]->messages; /* Ignore the default message domain if it has no messages. */ if (k > 0 || defmlp->nitems > 0) { message_list_ty *resultmlp = msgdomain_list_sublist (result, domain, true); definitions_set_current_list (&definitions, defmlp); match_domain (fn1, fn2, &definitions, refmlp, resultmlp, &stats, &processed); } } } definitions_destroy (&definitions); /* Look for messages in the definition file, which are not present in the reference file, indicating messages which defined but not used in the program. Don't scan the compendium(s). */ for (k = 0; k < def->nitems; ++k) { const char *domain = def->item[k]->domain; message_list_ty *defmlp = def->item[k]->messages; for (j = 0; j < defmlp->nitems; j++) { message_ty *defmsg = defmlp->item[j]; if (!defmsg->used) { /* Remember the old translation although it is not used anymore. But we mark it as obsolete. */ message_ty *mp; mp = message_copy (defmsg); /* Clear the extracted comments. */ if (mp->comment_dot != NULL) { string_list_free (mp->comment_dot); mp->comment_dot = NULL; } /* Clear the file position comments. */ if (mp->filepos != NULL) { size_t i; for (i = 0; i < mp->filepos_count; i++) free ((char *) mp->filepos[i].file_name); mp->filepos_count = 0; free (mp->filepos); mp->filepos = NULL; } /* Mark as obsolete. */ mp->obsolete = true; message_list_append (msgdomain_list_sublist (result, domain, true), mp); stats.obsolete++; } } } /* Determine the known a-priori encoding, if any. */ if (def->encoding == ref->encoding) result->encoding = def->encoding; /* Report some statistics. */ if (verbosity_level > 0) fprintf (stderr, _("%s\ Read %ld old + %ld reference, \ merged %ld, fuzzied %ld, missing %ld, obsolete %ld.\n"), !quiet && verbosity_level <= 1 ? "\n" : "", (long) def->nitems, (long) ref->nitems, (long) stats.merged, (long) stats.fuzzied, (long) stats.missing, (long) stats.obsolete); else if (!quiet) fputs (_(" done.\n"), stderr); /* Return results. */ *defp = def; return result; }
nh_p_grad.h
#ifndef NH_P_GRAD_H #define NH_P_GRAD_H void nh_p_grad(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage3D& rdx, const Storage3D& rdy, const Storage3D& gz, const Storage3D& pp, const Storage3D& pk3, const Storage3D& wk1, Storage3D& wk, Storage3D& du, Storage3D& dv, const ElementType dt) { for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size + 1; ++i) { for (int64_t j = 0; j < domain_size + 1; ++j) { wk(i, j, k) = (pk3(i, j, k + 1) - pk3(i, j, k)); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { du(i, j, k) = ((dt / (wk(i, j, k) + wk(i + 1, j, k))) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pk3(i + 1, j, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pk3(i, j, k + 1) - pk3(i + 1, j, k))))); uout(i, j, k) = (((uin(i, j, k) + du(i, j, k)) + ((dt / (wk1(i, j, k) + wk1(i + 1, j, k))) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pp(i + 1, j, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pp(i, j, k + 1) - pp(i + 1, j, k)))))) * rdx(i, j, k)); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { dv(i, j, k) = ((dt / (wk(i, j, k) + wk(i, j + 1, k))) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pk3(i, j + 1, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pk3(i, j, k + 1) - pk3(i, j + 1, k))))); vout(i, j, k) = (((vin(i, j, k) + dv(i, j, k)) + ((dt / (wk1(i, j, k) + wk1(i, j + 1, k))) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pp(i, j + 1, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pp(i, j, k + 1) - pp(i, j + 1, k)))))) * rdy(i, j, k)); } } } } void nh_p_grad_fullfusion(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage3D& rdx, const Storage3D& rdy, const Storage3D& gz, const Storage3D& pp, const Storage3D& pk3, const Storage3D& wk1, Storage3D& wk, Storage3D& du, Storage3D& dv, const ElementType dt) { for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto wk_ijk = (pk3(i, j, k + 1) - pk3(i, j, k)); auto wk_i1jk = (pk3(i + 1, j, k + 1) - pk3(i + 1, j, k)); auto wk_ij1k = (pk3(i, j + 1, k + 1) - pk3(i, j + 1, k)); auto _du = ((dt / (wk_ijk + wk_i1jk)) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pk3(i + 1, j, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pk3(i, j, k + 1) - pk3(i + 1, j, k))))); uout(i, j, k) = (((uin(i, j, k) + _du) + ((dt / (wk1(i, j, k) + wk1(i + 1, j, k))) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pp(i + 1, j, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pp(i, j, k + 1) - pp(i + 1, j, k)))))) * rdx(i, j, k)); auto _dv = ((dt / (wk_ijk + wk_ij1k)) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pk3(i, j + 1, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pk3(i, j, k + 1) - pk3(i, j + 1, k))))); vout(i, j, k) = (((vin(i, j, k) + _dv) + ((dt / (wk1(i, j, k) + wk1(i, j + 1, k))) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pp(i, j + 1, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pp(i, j, k + 1) - pp(i, j + 1, k)))))) * rdy(i, j, k)); } } } } void nh_p_grad_partialfusion(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage3D& rdx, const Storage3D& rdy, const Storage3D& gz, const Storage3D& pp, const Storage3D& pk3, const Storage3D& wk1, Storage3D& wk, Storage3D& du, Storage3D& dv, const ElementType dt) { for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto wk_ijk = (pk3(i, j, k + 1) - pk3(i, j, k)); auto wk_i1jk = (pk3(i + 1, j, k + 1) - pk3(i + 1, j, k)); auto _du = ((dt / (wk_ijk + wk_i1jk)) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pk3(i + 1, j, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pk3(i, j, k + 1) - pk3(i + 1, j, k))))); uout(i, j, k) = (((uin(i, j, k) + _du) + ((dt / (wk1(i, j, k) + wk1(i + 1, j, k))) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pp(i + 1, j, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pp(i, j, k + 1) - pp(i + 1, j, k)))))) * rdx(i, j, k)); } } } for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto wk_ijk = (pk3(i, j, k + 1) - pk3(i, j, k)); auto wk_ij1k = (pk3(i, j + 1, k + 1) - pk3(i, j + 1, k)); auto _dv = ((dt / (wk_ijk + wk_ij1k)) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pk3(i, j + 1, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pk3(i, j, k + 1) - pk3(i, j + 1, k))))); vout(i, j, k) = (((vin(i, j, k) + _dv) + ((dt / (wk1(i, j, k) + wk1(i, j + 1, k))) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pp(i, j + 1, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pp(i, j, k + 1) - pp(i, j + 1, k)))))) * rdy(i, j, k)); } } } } void nh_p_grad_openmp(Storage3D& uout, Storage3D& vout, const Storage3D& uin, const Storage3D& vin, const Storage3D& rdx, const Storage3D& rdy, const Storage3D& gz, const Storage3D& pp, const Storage3D& pk3, const Storage3D& wk1, Storage3D& wk, Storage3D& du, Storage3D& dv, const ElementType dt) { #pragma omp parallel for for (int64_t k = 0; k < domain_height; ++k) { for (int64_t i = 0; i < domain_size; ++i) { for (int64_t j = 0; j < domain_size; ++j) { auto wk_ijk = (pk3(i, j, k + 1) - pk3(i, j, k)); auto wk_i1jk = (pk3(i + 1, j, k + 1) - pk3(i + 1, j, k)); auto wk_ij1k = (pk3(i, j + 1, k + 1) - pk3(i, j + 1, k)); auto _du = ((dt / (wk_ijk + wk_i1jk)) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pk3(i + 1, j, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pk3(i, j, k + 1) - pk3(i + 1, j, k))))); uout(i, j, k) = (((uin(i, j, k) + _du) + ((dt / (wk1(i, j, k) + wk1(i + 1, j, k))) * (((gz(i, j, k + 1) - gz(i + 1, j, k)) * (pp(i + 1, j, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i + 1, j, k + 1)) * (pp(i, j, k + 1) - pp(i + 1, j, k)))))) * rdx(i, j, k)); auto _dv = ((dt / (wk_ijk + wk_ij1k)) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pk3(i, j + 1, k + 1) - pk3(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pk3(i, j, k + 1) - pk3(i, j + 1, k))))); vout(i, j, k) = (((vin(i, j, k) + _dv) + ((dt / (wk1(i, j, k) + wk1(i, j + 1, k))) * (((gz(i, j, k + 1) - gz(i, j + 1, k)) * (pp(i, j + 1, k + 1) - pp(i, j, k))) + ((gz(i, j, k) - gz(i, j + 1, k + 1)) * (pp(i, j, k + 1) - pp(i, j + 1, k)))))) * rdy(i, j, k)); } } } } #endif // NH_P_GRAD_H
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 32; tile_size[1] = 32; tile_size[2] = 24; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
Vanka.h
#define TOKENPASTE(x, y, z) x ## y ##_## z #define TOKENPASTE1(x, y) x ## y #define computeResidualAtIdx(T,S) TOKENPASTE(computeResidualAtIdx_, T, S) void computeResidualAtIdx(ValName,IndName)(spIndType *rowptr , spValType *valA ,spIndType *colA, spValType *b, spValType *x,long long* Idxs, spValType *local_r, spIndType blockSize){ spIndType i,tt; for (i = 0 ; i < blockSize ; ++i){ local_r[i] = b[Idxs[i]-1]; } for (i = 0 ; i < blockSize ; ++i){ for (tt = rowptr[Idxs[i]-1]; tt <= rowptr[Idxs[i]]-1 ; ++tt){ local_r[i] -= conj(valA[tt-1])*x[colA[tt-1]-1]; } } } #define computeATvAndAddAtIdx(T,S) TOKENPASTE(computeATvAndAddAtIdx_, T, S) void computeATvAndAddAtIdx(ValName,IndName)(spIndType *rowptr , spValType *valA ,spIndType *colA, spValType *local_v, spValType *x, long long* Idxs, spIndType blockSize){ spIndType i,tt; for (i = 0 ; i < blockSize ; ++i){ for (tt = rowptr[Idxs[i]-1]; tt <= rowptr[Idxs[i]]-1 ; ++tt){ x[colA[tt-1]-1] += valA[tt-1]*local_v[i]; } } } #define updateSolution(T) TOKENPASTE1(updateSolution_, T) void updateSolution(ValName)(vankaPrecType *mat, spValType *x, spValType *r, int n,long long* Idxs){ // x[Idxs] = x[Idxs] + (reshape(D[:,i],blockSize,blockSize)'*r); int i,j,offset; spValType t; for (i=0 ; i<n; ++i){ t = 0.0; offset = i*n; for (j=0 ; j<n; ++j){ t += conj(mat[offset + j])*r[j]; } x[Idxs[i]-1] += t; } } // # [ D y ][a0] = [b0] // # [ x' z ][a1] = [b1] // # D*a0 + y*a1 = b0 // # x'*a0 + z*a1 = b1 // # 1) a1 = (b1 - x'*D\b0) / (z-x'*D\y) // # 2) a0 = D\(b0 - y*a1) = D\b0 - a1*D\y // # with w: // # 1) a1 = w*((b1 - x'*D\b0) / (z-x'*D\y)) // # 2) a0 = w*(D\(b0 - y*a1)) = w*(D\b0 - a1*D\y) // # which is: // # 1) a1 = ((b1 - x'*D\b0) / ((z-x'*D\y)/w)) // # 2) a0 = w*(D\(b0 - (y/w)*a1)) = w*(D\b0 - a1*w*D\y) // # We can save: gamma = w/(z-x'*D\y); beta = D\x; alpha = y/w; // # a1 = (b1 - beta'*b0)*gamma // # a0 = w*invD.*(b0 - a1*alpha) #define updateSolutionEconomic(T) TOKENPASTE1(updateSolutionEconomic_, T) void updateSolutionEconomic(ValName)(vankaPrecType *mat, spValType *x, spValType *r, int n,long long* Idxs){ // n is blockSize // mat is [beta ; invd ; alpha] as above, each of size n-1. int i,j,offset1,offset2; // setting last element: spValType t = r[n-1]; for (i=0 ; i<n-1 ; ++i){ t -= mat[i]*r[i]; } t *= mat[n-1]; // multiplying schur complement offset1 = n; offset2 = 2*n-1; x[Idxs[n-1]-1] += t; for (i=0 ; i<n-1 ; ++i){ x[Idxs[i]-1] += mat[i+offset1]*(r[i] - mat[i+offset2]*t); } } #define updateSolutionLocal(T) TOKENPASTE1(updateSolutionLocal_, T) void updateSolutionLocal(ValName)(vankaPrecType *mat, spValType *x, spValType *r, int n){ int i,j; spValType t; for (i=0 ; i<n; ++i){ t = 0.0; for (j=0 ; j<n; ++j){ t += conj(mat[i*n + j])*r[j]; } x[i] = t; } } #define applyVankaFacesColor(T,S) TOKENPASTE(applyVankaFacesColor_, T, S) void applyVankaFacesColor(ValName,IndName)(spIndType *rowptr , spValType *valA ,spIndType *colA,long long *n,long long *nf,long long dim, spValType *x, spValType *b, vankaPrecType *D,long long numit,long long includePressure, spIndType blockSize, spIndType num_cells, long long VankaType){ // long long lengthVecs = (dim==2) ? (nf[0]*nf[1]*(includePressure ? n[0]*n[1] : 1)) : (nf[0]*nf[1]*nf[2]*(includePressure ? n[0]*n[1]*n[2] : 1)); //spValType* y = NULL; //spValType* y = (spValType*)malloc(lengthVecs*sizeof(spValType)); #pragma omp parallel shared(x,rowptr,valA,colA,n,nf,dim,b,D,numit)//,y) { int color; spIndType k,i,cellSizeInD; cellSizeInD = (VankaType == FULL_VANKA) ? blockSize*blockSize : (3*(blockSize-1)+1); long long *Idxs = (long long*)malloc(blockSize*sizeof(long long)); long long *i_vec = (long long*)malloc(dim*sizeof(long long)); spValType* local_r = (spValType*)malloc(blockSize*sizeof(spValType)); for (k=0 ; k < numit ; ++k){ //for (color=1 ; color <= numColors ; ++color){ // this is an old code that applied multicolor. for (color=1 ; color <= 2 ; ++color){ //#pragma omp single // if we wish to make the code identical for parallel and serial, the residual has to be computed with a copy of x. //{ // memcpy(y,x,lengthVecs*sizeof(spValType)); //} #pragma omp for for (i=1 ; i <= num_cells ; ++i){ cs2loc(i,n,dim,i_vec); if (cellColor(i_vec,dim)==color){ getVankaVariablesOfCell(i_vec,n,nf,Idxs,includePressure,dim); computeResidualAtIdx(ValName,IndName)(rowptr,valA,colA,b,x,Idxs,local_r,blockSize); if (VankaType == FULL_VANKA){ updateSolution(ValName)(D + (i-1)*cellSizeInD , x, local_r, blockSize,Idxs); }else{ updateSolutionEconomic(ValName)(D + (i-1)*cellSizeInD , x, local_r, blockSize,Idxs); } } } } } free(Idxs); free(i_vec); free(local_r); } return; } #define RelaxVankaFacesColor(T,S) TOKENPASTE(RelaxVankaFacesColor_, T, S) void RelaxVankaFacesColor(ValName,IndName)(spIndType *rowptr , spValType *valA ,spIndType *colA,long long *n,long long *nf,long long dim, spValType *x, spValType *b, vankaPrecType *D,long long numit,long long includePressure, long long VankaType, long long numCores){ //int numColors; spIndType num_cells,blockSize; if (dim==2){ blockSize = includePressure ? 5 : 4; //numColors = 4; num_cells = n[0]*n[1]; }else{ blockSize = includePressure ? 7 : 6; //numColors = 8; num_cells = n[0]*n[1]*n[2]; } omp_set_num_threads(numCores); switch( VankaType ) { case FULL_VANKA: case ECON_VANKA: applyVankaFacesColor(ValName,IndName)(rowptr , valA ,colA,n,nf,dim, x, b, D,numit,includePressure, blockSize, num_cells,VankaType); break; default: printf("ERROR Vanka.h: Unknown VankaType"); break; } return; } // double computeNorm(spValType* x, int len){ // double norm = 0.0; // for (int i = 0 ; i < len ; ++i){ // norm += creal(conj(x[i])*x[i]); // norm += creal(x[i])*creal(x[i]) + cimag(x[i])*cimag(x[i]); // } // return norm; // } #define applyHybridCellWiseKaczmarz(T,S) TOKENPASTE(applyHybridCellWiseKaczmarz_, T, S) void applyHybridCellWiseKaczmarz(ValName,IndName)(spIndType *rowptr , spValType *valA ,spIndType *colA,long long *n,long long *nf,long long dim, spValType *x, spValType *b, vankaPrecType *D,long long numit,long long includePressure, long long numCores, unsigned int *ArrIdxs,long long numDomains, long long domainLength){ spIndType N,blockSize; if (dim==2){ blockSize = includePressure ? 5 : 4; N = n[0]*n[1]; }else{ blockSize = includePressure ? 7 : 6; N = n[0]*n[1]*n[2]; } omp_set_num_threads(numCores); #pragma omp parallel shared(x,rowptr,valA,colA,n,nf,dim,b,D,numit) { spIndType k,i; long long cell,domain; long long *Idxs = (long long*)malloc(blockSize*sizeof(long long)); long long *cell_vec = (long long*)malloc(dim*sizeof(long long)); spValType* local_r = (spValType*)malloc(blockSize*sizeof(spValType)); spValType* local_x = (spValType*)malloc(blockSize*sizeof(spValType)); for (k=0 ; k < numit ; ++k){ #pragma omp for for (domain=0 ; domain < numDomains ; ++domain){ for (i=0 ; i < domainLength ; ++i){ cell = (long long)ArrIdxs[domain*domainLength + i]; if (cell > 0){ cs2loc(cell,n,dim,cell_vec); getVankaVariablesOfCell(cell_vec,n,nf,Idxs,includePressure,dim); // printf("Cell #%ld::",cell); computeResidualAtIdx(ValName,IndName)(rowptr,valA,colA,b,x,Idxs,local_r,blockSize); // printf("rnorm %6.3e, ",computeNorm(local_r,blockSize)); updateSolutionLocal(ValName)(D + (cell-1)*blockSize*blockSize , local_x, local_r, blockSize); // printf("xnorm %6.3e, ",computeNorm(local_x,blockSize)); // printf("Dnorm %6.3e",computeNorm(D,blockSize*blockSize)); computeATvAndAddAtIdx(ValName,IndName)(rowptr,valA,colA,local_x,x,Idxs,blockSize); // printf("\n"); } } // if (includePressure){ // double complex inner; // double complex invD; // spIndType row; // spIndType gIdx; // for (i=0 ; i < domainLength ; ++i){ // cell = (long long)ArrIdxs[domain*domainLength + i]; // if (cell > 0){ // invD = 0.0; // cs2loc(cell,n,dim,cell_vec); // getVankaVariablesOfCell(cell_vec,n,nf,Idxs,includePressure,dim); // row = Idxs[blockSize-1]; // inner = b[row-1]; // for (gIdx = rowptr[row-1]-1; gIdx < rowptr[row]-1; ++gIdx){ // // gIdx is in C indices here... // inner -= conj(valA[gIdx])*x[colA[gIdx]-1]; // invD += creal(conj(valA[gIdx])*valA[gIdx]); // } // inner*=(1.0/invD); // for (gIdx = rowptr[row-1]-1; gIdx < rowptr[row]-1; ++gIdx){ // // gIdx is in C indices here... // x[colA[gIdx]-1] += inner*valA[gIdx]; // } // } // } // } } } free(Idxs); free(cell_vec); free(local_r); free(local_x); } return; }
loop-4.c
/* { dg-do run } */ extern void abort (void); int main (void) { int e = 0; #pragma omp parallel num_threads (4) reduction(+:e) { long i; #pragma omp for schedule(dynamic,1) for (i = __LONG_MAX__ - 30001; i <= __LONG_MAX__ - 10001; i += 10000) if (i != __LONG_MAX__ - 30001 && i != __LONG_MAX__ - 20001 && i != __LONG_MAX__ - 10001) e = 1; #pragma omp for schedule(dynamic,1) for (i = -__LONG_MAX__ + 30000; i >= -__LONG_MAX__ + 10000; i -= 10000) if (i != -__LONG_MAX__ + 30000 && i != -__LONG_MAX__ + 20000 && i != -__LONG_MAX__ + 10000) e = 1; } if (e) abort (); return 0; }
local_parametrization.h
#ifndef LOCAL_PARAMETRIZATION #define LOCAL_PARAMETRIZATION #include "defines.h" ///fitting //#include <vcg/space/fitting3.h> #include <vcg/math/matrix33.h> #include <vcg/space/triangle2.h> #include "texcoord_optimization.h" #include "mesh_operators.h" //#include <vcg/complex/algorithms/point_sampling.h> //#define samples_area 80 template <class MeshType> void ParametrizeExternal(MeshType &to_parametrize) { typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; std::vector<VertexType*> vertices; ///find first border vertex VertexType* Start=NULL; typename MeshType::VertexIterator Vi=to_parametrize.vert.begin(); while ((Start==NULL)&&(Vi<to_parametrize.vert.end())) { if (((*Vi).IsB())&&(!(*Vi).IsD())) Start=&(*Vi); Vi++; } if (Vi==to_parametrize.vert.end()) { assert(0); } ///get sorted border vertices FindSortedBorderVertices<MeshType>(to_parametrize,Start,vertices); //assert(vertices.size()>=4); ///find perimeter ScalarType perimeter=0; int size=vertices.size(); for (int i=0;i<size;i++) perimeter+=(vertices[i]->P()-vertices[(i+1)%size]->P()).Norm(); ///find scaling factor /*ScalarType Sperimeter=(2.0*M_PI)/perimeter;*/ ///set default texCoords for (Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { (*Vi).T().U()=-2; (*Vi).T().V()=-2; } ///set border vertices typename std::vector<VertexType*>::iterator iteV; /*ScalarType curr_perim=0;*/ ScalarType curr_angle=0; vertices[0]->T().U()=cos(curr_angle); vertices[0]->T().V()=sin(curr_angle); //for (int i=1;i<vertices.size();i++) //{ // curr_perim+=(vertices[i]->P()-vertices[(i-1)]->P()).Norm(); // //curr_perim+=perimeter/(ScalarType)size; // curr_angle=curr_perim*Sperimeter; // vertices[i]->T().U()=cos(curr_angle); // vertices[i]->T().V()=sin(curr_angle); // assert((vertices[i]->T().U()>=-1)&&(vertices[i]->T().U()<=1)); // assert((vertices[i]->T().V()>=-1)&&(vertices[i]->T().V()<=1)); //} ScalarType anglediv=(2.0*M_PI)/(ScalarType)(vertices.size()); curr_angle=0; for (unsigned int i=1;i<vertices.size();i++) { curr_angle+=anglediv; vertices[i]->T().U()=cos(curr_angle); vertices[i]->T().V()=sin(curr_angle); assert((vertices[i]->T().U()>=-1)&&(vertices[i]->T().U()<=1)); assert((vertices[i]->T().V()>=-1)&&(vertices[i]->T().V()<=1)); } } template <class MeshType> void ParametrizeInternal(MeshType &to_parametrize) { typedef typename MeshType::ScalarType ScalarType; const ScalarType Eps=(ScalarType)0.0001; ///set internal vertices for (typename MeshType::VertexIterator Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { //assert(!Vi->IsD()); if ((!Vi->IsB())&&(!Vi->IsD())) { ///find kernel std::vector<typename MeshType::VertexType*> star; getVertexStar<MeshType>(&(*Vi),star); ScalarType kernel=0; for (unsigned int k=0;k<star.size();k++) if (star[k]->IsB()) { ScalarType dist=((*Vi).P()-star[k]->P()).Norm(); if (dist<Eps) dist=Eps; //ScalarType peso=1.0/(dist); ScalarType peso=(dist)/star.size(); kernel+=(peso);//*dist); } assert(kernel>0); ///then find factor kernel=1.0/kernel; (*Vi).T().U()=0; (*Vi).T().V()=0; int num=0; ///find weighted media for (unsigned int k=0;k<star.size();k++) if (star[k]->IsB()) { ScalarType dist=((*Vi).P()-star[k]->P()).Norm(); if (dist<Eps) dist=Eps; //ScalarType peso=1.0/(dist); ScalarType peso=(dist)/star.size(); ScalarType kval=(peso)*kernel; assert(kval>0); (*Vi).T().U()+=kval*star[k]->T().U(); (*Vi).T().V()+=kval*star[k]->T().V(); num++; } ////on border case 2 neighbors ///go next to the center /*if (num==2) { (*Vi).T().U()/=2.0; (*Vi).T().V()/=2.0; }*/ /*ScalarType u=(*Vi).T().U(); ScalarType v=(*Vi).T().V();*/ assert(((*Vi).T().U()>=-1)&&((*Vi).T().U()<=1)); assert(((*Vi).T().V()>=-1)&&((*Vi).T().V()<=1)); } } ///smoothing of txcoords InitDampRestUV(to_parametrize); for (typename MeshType::VertexIterator Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { if ((!Vi->IsB())&&(!Vi->IsD())) { std::vector<typename MeshType::VertexType*> star; getVertexStar<MeshType>(&(*Vi),star); vcg::Point2<ScalarType> UV=vcg::Point2<ScalarType>(0,0); for (unsigned int k=0;k<star.size();k++) UV+=star[k]->RestUV; UV/=(ScalarType)star.size(); (*Vi).T().P()=UV; } } } template <class FaceType> typename FaceType::CoordType InterpolatePos (FaceType* f, const typename FaceType::CoordType &bary) {return (f->V(0)->P()*bary.X()+f->V(1)->P()*bary.Y()+f->V(2)->P()*bary.Z());} template <class FaceType> typename FaceType::CoordType InterpolateRPos (FaceType* f,const typename FaceType::CoordType &bary) { return (f->V(0)->RPos*bary.X()+f->V(1)->RPos*bary.Y()+f->V(2)->RPos*bary.Z()); } template <class FaceType> typename FaceType::CoordType InterpolateNorm (FaceType* f, const typename FaceType::CoordType &bary) { typedef typename FaceType::CoordType CoordType; CoordType n0=f->V(0)->N(); CoordType n1=f->V(1)->N(); CoordType n2=f->V(2)->N(); return (n0*bary.X()+n1*bary.Y()+n2*bary.Z()); } template <class ScalarType> int Approx(const ScalarType &value) { ScalarType val0=floor(value); ScalarType val1=ceil(value); if (fabs(val0-value)<fabs(val1-value)) return ((int)val0); else return ((int)val1); } template <class FaceType> vcg::Point3i InterpolateColor (FaceType* f,const typename FaceType::CoordType &bary) { typedef typename FaceType::ScalarType ScalarType; vcg::Color4b c0=f->V(0)->C(); vcg::Color4b c1=f->V(1)->C(); vcg::Color4b c2=f->V(2)->C(); double R=(ScalarType)c0.X()*bary.X()+(ScalarType)c1.X()*bary.Y()+(ScalarType)c2.X()*bary.Z(); double G=(ScalarType)c0.Y()*bary.X()+(ScalarType)c1.Y()*bary.Y()+(ScalarType)c2.Y()*bary.Z(); double B=(ScalarType)c0.Z()*bary.X()+(ScalarType)c1.Z()*bary.Y()+(ScalarType)c2.Z()*bary.Z(); vcg::Point3i p=vcg::Point3i(Approx(R),Approx(G),Approx(B)); assert(p.X()<=255); assert(p.Y()<=255); assert(p.Z()<=255); return (p); } template <class VertexType> typename VertexType::CoordType ProjectPos(const VertexType &v) { typedef typename VertexType::FaceType FaceType; typedef typename VertexType::CoordType CoordType; FaceType *f=v.father; CoordType b=v.Bary; return (InterpolatePos<FaceType>(f,b)); } template <class VertexType> typename VertexType::CoordType Warp(const VertexType* v) { typename VertexType::FaceType * father=v->father; typename VertexType::CoordType proj=father->P(0)*v->Bary.X()+father->P(1)*v->Bary.Y()+father->P(2)*v->Bary.Z(); return proj; } template <class VertexType> typename VertexType::CoordType WarpRpos(const VertexType* v) { typename VertexType::FaceType * father=v->father; typename VertexType::CoordType proj=father->V(0)->RPos*v->Bary.X()+father->V(1)->RPos*v->Bary.Y()+father->V(2)->RPos*v->Bary.Z(); return proj; } template <class MeshType> typename MeshType::ScalarType EstimateLenghtByParam (const typename MeshType::VertexType* v0, const typename MeshType::VertexType* v1, typename MeshType::FaceType* on_edge[2]) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::ScalarType ScalarType; // assert((on_edge.size()==0)||(on_edge.size()==1)); ScalarType estimated[2]={0,0}; size_t num[2]={0,0}; for (int i=0;i<2;i++) { FaceType *test_face=on_edge[i]; int edge_index=EdgeIndex(test_face,v0,v1); FaceType *Fopp=test_face->FFp(edge_index); if (test_face->vertices_bary.size()<2) { ScalarType dist=Distance(v0->RPos,v1->RPos); //#pragma omp atomic estimated[i]+=dist; num[i]=0; continue; } ///collect vertices std::vector<VertexType*> vertices; vertices.reserve(test_face->vertices_bary.size()); for (unsigned int k=0;k<test_face->vertices_bary.size();k++) vertices.push_back(test_face->vertices_bary[k].first); ///collect faces std::vector<FaceType*> faces; getSharedFace<MeshType>(vertices,faces); ///get border edges std::vector<std::pair<VertexType*,VertexType*> > edges; for (unsigned int j=0;j<faces.size();j++) { FaceType*f=faces[j]; ///find if there is an on-edge edge bool found=false; int k=0; while ((k<3)&&(!found)) { if ((f->V0(k)->father==test_face)&& (f->V1(k)->father==test_face)&& (f->V2(k)->father==Fopp)) { edges.push_back(std::pair<VertexType*,VertexType*>(f->V0(k),f->V1(k))); found=true; } k++; } } ///find if there's ant edge return inital lenght if (edges.size()==0) { estimated[i]+=(Distance(v0->RPos,v1->RPos)); num[i]=0; continue; } else { //get edge direction ///store the two nearest for each vertex /*VertexType *n0=edges[0].first; VertexType *n1=edges[0].second; ScalarType d0=(Warp(n0)-v0->P()).Norm(); ScalarType d1=(Warp(n1)-v1->P()).Norm();*/ //CoordType edgedir=v0->cP()-v1->cP(); CoordType edgedir=v0->RPos-v1->RPos; edgedir.Normalize(); num[i]=edges.size(); for (unsigned int e=0;e<edges.size();e++) { VertexType *vH0=edges[e].first; VertexType *vH1=edges[e].second; ///project points over the plane /*CoordType proj0=Warp(vH0); CoordType proj1=Warp(vH1);*/ CoordType proj0=WarpRpos(vH0); CoordType proj1=WarpRpos(vH1); CoordType dirproj=proj0-proj1; dirproj.Normalize(); //estimated[i]+=fabs(dirproj*edgedir)*((vH0->P()-vH1->P()).Norm()); //#pragma omp atomic estimated[i]+=fabs(dirproj*edgedir)*((vH0->RPos-vH1->RPos).Norm()); } } } ///media of estimated values ScalarType alpha0,alpha1; ScalarType max_num=abstraction_num; if (num[0]>=max_num) alpha0=1; else alpha0=num[0]/max_num; if (num[1]>=max_num) alpha1=1; else alpha1=num[1]/max_num; estimated[0]= (ScalarType)(alpha0*estimated[0]+(1.0-alpha0)*(Distance(v0->RPos,v1->RPos))); estimated[1]= (ScalarType)(alpha1*estimated[1]+(1.0-alpha1)*(Distance(v0->RPos,v1->RPos))); return(ScalarType)((estimated[0]+estimated[1])/2.0); } template <class MeshType> void MeanVal(const std::vector<vcg::Point2<typename MeshType::ScalarType> > &Points, std::vector<typename MeshType::ScalarType> &Lamda, typename MeshType::CoordType &p) { typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; int size=Points.size(); Lamda.resize(size); ScalarType sum=0; for (int i=0;i<size;i++) { int size=Points.size()-1; vcg::Point2<ScalarType> Pcurr=Points[i]; vcg::Point2<ScalarType> Pprev=Points[(i+(size-1))%size]; vcg::Point2<ScalarType> Pnext=Points[(i+1)%size]; CoordType v0=Pprev-p; CoordType v1=Pcurr-p; CoordType v2=Pnext-p; ScalarType l=v1.Norm(); v0.Normalize(); v1.Normalize(); v2.Normalize(); ScalarType Alpha0=acos(v0*v1); ScalarType Alpha1=acos(v1*v2); Lamda[i]=(tan(Alpha0/2.0)+tan(Alpha1/2.0))/l; sum+=Lamda[i]; } ///normalization for (int i=0;i<size;i++) Lamda[i]/=sum; } template <class FaceType> typename FaceType::ScalarType EstimateAreaByParam(const FaceType* f) { typedef typename FaceType::VertexType VertexType; typedef typename FaceType::ScalarType ScalarType; int num=0; ScalarType estimated=0; for (unsigned int k=0;k<f->vertices_bary.size();k++) { VertexType *HresVert=f->vertices_bary[k].first; estimated+=HresVert->area; num++; } ///media of estimated values ScalarType alpha; ScalarType max_num=abstraction_num; if (num>=max_num) alpha=1; else alpha=num/max_num; ScalarType Rarea= (ScalarType)(((f->cV(1)->RPos-f->cV(0)->RPos)^(f->cV(2)->RPos-f->cV(0)->RPos)).Norm()/2.0); estimated=(ScalarType)(alpha*estimated+(1.0-alpha)*Rarea); return(estimated); } template <class MeshType> typename MeshType::ScalarType EstimateAreaByParam (const typename MeshType::VertexType* v0, const typename MeshType::VertexType* v1, typename MeshType::FaceType* on_edge[2]) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::ScalarType ScalarType; //MeshType::PerVertexAttributeHandle<AuxiliaryVertData> handle = vcg::tri::Allocator<MeshType>::GetPerVertexAttribute<AuxiliaryVertData>(mesh,"AuxiliaryVertData"); ScalarType estimated[2]={0,0}; int num[2]={0,0}; VertexType *v2[2]; for (int i=0;i<2;i++) { FaceType *test_face=on_edge[i]; for (int k=0;k<3;k++) if ((test_face->V(k)!=v0)&&(test_face->V(k)!=v1)) v2[i]=test_face->V(k); for (unsigned int k=0;k<test_face->vertices_bary.size();k++) { VertexType *brother=test_face->vertices_bary[k].first; estimated[i]+=brother->area; //estimated[i]+=handle[brother].area; num[i]++; } } ///media of estimated values ScalarType alpha0,alpha1; ScalarType max_num=abstraction_num;//20 if (num[0]>=max_num) alpha0=1; else alpha0=num[0]/max_num; if (num[1]>=max_num) alpha1=1; else alpha1=num[1]/max_num; ScalarType Rarea0= (ScalarType)(((on_edge[0]->V(1)->RPos-on_edge[0]->V(0)->RPos)^(on_edge[0]->V(2)->RPos-on_edge[0]->V(0)->RPos)).Norm()/2.0); ScalarType Rarea1= (ScalarType)(((on_edge[1]->V(1)->RPos-on_edge[1]->V(0)->RPos)^(on_edge[1]->V(2)->RPos-on_edge[1]->V(0)->RPos)).Norm()/2.0); estimated[0]= (ScalarType)(alpha0*estimated[0]+(1.0-alpha0)*Rarea0); estimated[1]= (ScalarType)(alpha1*estimated[1]+(1.0-alpha1)*Rarea1); return(ScalarType)((estimated[0]+estimated[1])/2.0); } ///template class used to sample surface template <class FaceType> class VertexSampler{ typedef typename FaceType::CoordType CoordType; public: std::vector<CoordType> points; void AddFace(const FaceType &f,const CoordType & bary) {points.push_back(f.P(0)*bary.X()+f.P(1)*bary.Y()+f.P(2)*bary.Z());} }; ///sample 3d vertex possible's position ///using area criterion //template <class MeshType> //void SamplingPoints(MeshType &mesh, // std::vector<typename MeshType::CoordType> &pos) //{ // typedef typename MeshType::CoordType CoordType; // typedef VertexSampler<MeshType::FaceType> Sampler; // pos.reserve(samples_area); // Sampler ps; // ps.points.reserve(samples_area); // // vcg::tri::SurfaceSampling<MeshType,Sampler>::Montecarlo(mesh,ps,samples_area); // pos=std::vector<CoordType>(ps.points.begin(),ps.points.end()); //} template <class MeshType> void InitDampRestUV(MeshType &m) { for (unsigned int i=0;i<m.vert.size();i++) m.vert[i].RestUV=m.vert[i].T().P(); } template <class MeshType> void RestoreRestUV(MeshType &m) { for (unsigned int i=0;i<m.vert.size();i++) m.vert[i].T().P()=m.vert[i].RestUV; } #ifndef IMPLICIT ///parametrize a submesh from trinagles that are incident on vertices template <class MeshType> void ParametrizeLocally(MeshType &parametrized, bool fix_boundary=true, bool init_border=true) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; //const ScalarType epsilon=(ScalarType)0.0001; ///save old positions std::vector<CoordType> positions; positions.resize(parametrized.vert.size()); ///set rest position for (unsigned int i=0;i<parametrized.vert.size();i++) { positions[i]=parametrized.vert[i].P(); parametrized.vert[i].P()=parametrized.vert[i].RPos; } UpdateTopologies(&parametrized); if (init_border) ParametrizeExternal(parametrized); ParametrizeInternal(parametrized); //for (int i=0;i<parametrized.vert.size();i++) // parametrized.vert[i].RPos=parametrized.vert[i].P(); vcg::tri::MeanValueTexCoordOptimization<MeshType> opt(parametrized); vcg::tri::AreaPreservingTexCoordOptimization<MeshType> opt1(parametrized); opt.SetSpeed((ScalarType)0.0005); InitDampRestUV(parametrized); if (fix_boundary) { opt.TargetEquilateralGeometry(); //opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.IterateUntilConvergence((ScalarType)0.000001,100); /*opt.Iterate(); opt.Iterate();*/ } else { opt1.TargetCurrentGeometry(); //opt1.SetBorderAsFixed(); opt1.IterateUntilConvergence((ScalarType)0.000001,200); } ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); #ifndef NDEBUG ScalarType area=(tex1-tex0)^(tex2-tex0); assert(area>0); #endif } ///restore position for (unsigned int i=0;i<parametrized.vert.size();i++) parametrized.vert[i].P()=positions[i]; } #else ///parametrize a submesh keeping fixed the borders template <class MeshType> void ParametrizeLocally(MeshType &parametrized, bool fix_boundary=true, bool init_border=true) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; ///save old positions std::vector<CoordType> positions; positions.resize(parametrized.vert.size()); ///set rest position for (unsigned int i=0;i<parametrized.vert.size();i++) { positions[i]=parametrized.vert[i].P(); parametrized.vert[i].P()=parametrized.vert[i].RPos; } UpdateTopologies(&parametrized); if (init_border) ParametrizeExternal(parametrized); ParametrizeInternal(parametrized); //for (int i=0;i<parametrized.vert.size();i++) // parametrized.vert[i].RPos=parametrized.vert[i].P(); vcg::tri::MeanValueTexCoordOptimization<MeshType> opt(parametrized); vcg::tri::AreaPreservingTexCoordOptimization<MeshType> opt1(parametrized); opt.SetSpeed((ScalarType)0.0005); InitDampRestUV(parametrized); if (fix_boundary) { opt.TargetEquilateralGeometry(); //opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.IterateUntilConvergence((ScalarType)0.000001,100); /*opt.Iterate(); opt.Iterate();*/ } else { opt1.TargetCurrentGeometry(); //opt1.SetBorderAsFixed(); opt1.IterateUntilConvergence((ScalarType)0.000001,200); } ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Triangle2<typename MeshType::ScalarType> t2d=vcg::Triangle2<typename MeshType::ScalarType>(tex0,tex1,tex2); #ifndef NDEBUG ScalarType area=(tex1-tex0)^(tex2-tex0); assert(area>0); #endif } ///restore position for (unsigned int i=0;i<parametrized.vert.size();i++) parametrized.vert[i].P()=positions[i]; } #endif template <class MeshType> void ForceInParam(vcg::Point2<typename MeshType::ScalarType> &UV,MeshType &domain) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; ScalarType minDist=(ScalarType)1000.0; vcg::Point2<ScalarType> closest; vcg::Point2<ScalarType> center=vcg::Point2<ScalarType>(0,0); for (unsigned int i=0;i<domain.face.size();i++) { FaceType *f=&domain.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); center+=tex0; center+=tex1; center+=tex2; vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType dist; vcg::Point2<ScalarType> temp; t2d.PointDistance(UV,dist,temp); if (dist<minDist) { minDist=dist; closest=temp; } } center/=(ScalarType)(domain.face.size()*3); UV=closest*(ScalarType)0.95+center*(ScalarType)0.05; } template <class VertexType> bool testParamCoords(VertexType *v) { typedef typename VertexType::ScalarType ScalarType; ScalarType eps=(ScalarType)0.00001; if (!(((v->T().P().X()>=-1-eps)&&(v->T().P().X()<=1+eps)&& (v->T().P().Y()>=-1-eps)&&(v->T().P().Y()<=1+eps)))) return (false); return true; } template <class MeshType> bool testParamCoords(MeshType &domain) { for (unsigned int i=0;i<domain.vert.size();i++) { typename MeshType::VertexType *v=&domain.vert[i]; bool b=testParamCoords<typename MeshType::VertexType>(v); if (!b) { #ifndef _MESHLAB printf("\n position %lf,%lf \n",v->T().U(),v->T().V()); #endif return false; } } return true; } template <class CoordType> bool testBaryCoords(CoordType &bary) { typedef typename CoordType::ScalarType ScalarType; ///test float eps=(ScalarType)0.0001; if(!(fabs(bary.X()+bary.Y()+bary.Z()-1.0)<eps)) return false; if(!((bary.X()<=1.0)&&(bary.X()>=-eps)&&(bary.Y()<=1.0)&&(bary.Y()>=-eps)&&(bary.Z()<=1.0)&&(bary.Z()>=-eps))) return false; return true; } template <class CoordType> bool NormalizeBaryCoords(CoordType &bary) { typedef typename CoordType::ScalarType ScalarType; ScalarType EPS=(ScalarType)0.00000001; bool isOK=testBaryCoords(bary); if (!isOK) return false; typedef typename CoordType::ScalarType ScalarType; ///test <0 if (bary.X()<0) bary.X()=EPS; if (bary.Y()<0) bary.Y()=EPS; if (bary.Z()<0) bary.Z()=EPS; ///test >1 if (bary.X()>1.0) bary.X()=1.0-EPS; if (bary.Y()>1.0) bary.Y()=1.0-EPS; if (bary.Z()>1.0) bary.Z()=1.0-EPS; ///test sum ScalarType diff=bary.X()+bary.Y()+bary.Z()-1.0; bary.X()-=(diff+EPS); if (bary.X()<0) bary.X()=EPS; return true; } template <class MeshType> void AssingFather(typename MeshType::VertexType &v, typename MeshType::FaceType *father, typename MeshType::CoordType &bary, MeshType & domain) { #ifdef _DEBUG const typename MeshType::ScalarType eps=(typename MeshType::ScalarType)0.00001; assert(vcg::tri::IsValidPointer(domain,father)); assert(!(father->IsD())); assert(!(father==NULL)); assert((bary.X()>=0)&&(bary.X()<=1)&& (bary.Y()>=0)&&(bary.Y()<=1)&& (bary.Z()>=0)&&(bary.Z()<=1)&& ((bary.X()+bary.Y()+bary.Z())<=1+eps)&& ((bary.X()+bary.Y()+bary.Z())>=1-eps)); #endif v.father=father; v.Bary=bary; } template <class MeshType> bool testParametrization(MeshType &domain, MeshType &Hlev) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::VertexType VertexType; bool is_good=true; int num_del=0; int num_null=0; int fath_son=0; int wrong_address=0; for (unsigned int i=0;i<Hlev.vert.size();i++) { VertexType *v=&Hlev.vert[i]; bool isGoodAddr=true; if ((v->father-&(*domain.face.begin()))>=(int)domain.face.size()) { // printf("\n ADDRESS EXCEEDS OF %d \n",v->father-&(*domain.face.begin())); wrong_address++; is_good=false; isGoodAddr=false; } if ((isGoodAddr)&&(v->father==NULL)) { //printf("\n PAR ERROR : father NULL\n"); num_null++; is_good=false; } if ((isGoodAddr)&&(v->father->IsD())) { //printf("\n PAR ERROR : father DELETED \n"); num_del++; is_good=false; } if ((isGoodAddr)&&(!(((v->Bary.X()>=0)&&(v->Bary.X()<=1))&& ((v->Bary.Y()>=0)&&(v->Bary.Y()<=1))&& ((v->Bary.Z()>=0)&&(v->Bary.Z()<=1))))) { printf("\n PAR ERROR 0: bary coords exceeds: %f,%f,%f \n",v->Bary.X(),v->Bary.Y(),v->Bary.Z()); /*system("pause");*/ NormalizeBaryCoords(v->Bary); is_good=false; } } for (unsigned int i=0;i<domain.face.size();i++) { FaceType *face=&domain.face[i]; if (!face->IsD()) { for (unsigned int j=0;j<face->vertices_bary.size();j++) { VertexType *v=face->vertices_bary[j].first; if (v->father!=face) { //printf("\n PAR ERROR : Father<->son \n"); fath_son++; v->father=face; is_good=false; } } } } if (num_del>0) printf("\n PAR ERROR %d Father isDel \n",num_del); if (num_null>0) printf("\n PAR ERROR %d Father isNull \n",num_null); if (fath_son>0) printf("\n PAR ERROR %d Father<->son \n",fath_son); if (wrong_address>0) { printf("\n PAR ERROR %d Wrong Address Num Faces %d\n",wrong_address,domain.fn); /*system("pause");*/ } return (is_good); } template <class MeshType> bool NonFolded(MeshType &parametrized) { //const ScalarType epsilon=0.00001; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; if (!((f->V(0)->IsB())&&(f->V(1)->IsB())&&(f->V(2)->IsB()))) { vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); ScalarType area=(tex1-tex0)^(tex2-tex0); if (area<=0) return false; } } return true; } template <class MeshType> bool NonFolded(MeshType &parametrized,std::vector<typename MeshType::FaceType*> &folded) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; const ScalarType epsilon=(ScalarType)0.00001; folded.resize(0); ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; if (!((f->V(0)->IsB())&&(f->V(1)->IsB())&&(f->V(2)->IsB()))) { vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); ScalarType area=(tex1-tex0)^(tex2-tex0); if (area<=epsilon) folded.push_back(f); } } return (folded.size()==0); } //getFoldedFaces(std::vector) ///parametrize a submesh from trinagles that are incident on vertices with equi-area subdivision template <class MeshType> void ParametrizeStarEquilateral(MeshType &parametrized, const typename MeshType::ScalarType &radius=1) { typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; UpdateTopologies(&parametrized); //set borders ///find first border & non border vertex std::vector<VertexType*> non_border; VertexType* Start=NULL; for (unsigned int i=0;i<parametrized.vert.size();i++) { VertexType* vert=&parametrized.vert[i]; if ((Start==NULL)&&(vert->IsB())) Start=vert; if (!vert->IsB()) non_border.push_back(vert); } assert(non_border.size()!=0); ///get sorted border vertices std::vector<VertexType*> vertices; FindSortedBorderVertices<MeshType>(parametrized,Start,vertices); ///set border vertices int num=vertices.size(); typename std::vector<VertexType*>::iterator iteV; ScalarType curr_angle=0; vertices[0]->T().U()=cos(curr_angle)*radius; vertices[0]->T().V()=sin(curr_angle)*radius; ScalarType division=(2*M_PI)/(ScalarType)num; ///set border for (unsigned int i=1;i<vertices.size();i++) { curr_angle+=division; vertices[i]->T().U()=radius*cos(curr_angle); vertices[i]->T().V()=radius*sin(curr_angle); } if (non_border.size()==1) { ///if non-border vertex is one then set it to zero otherwise ///set it to the average of neighbors non_border[0]->T().P()=vcg::Point2<ScalarType>(0,0); } else { ///set media of star vertices assert(non_border.size()==2); for (unsigned int i=0;i<non_border.size();i++) { VertexType *v=non_border[i]; v->T().P()=vcg::Point2<ScalarType>(0,0); int ariety_vert=0; std::vector<VertexType*> star; getVertexStar<MeshType>(v,star); for (unsigned int k=0;k<star.size();k++) { if ((!star[k]->IsD())&&(star[k]->IsB())) { v->T().P()+=star[k]->T().P(); ariety_vert++; } } v->T().P()/=(ScalarType)ariety_vert; } ///test particular cases if (!NonFolded(parametrized)) { std::vector<VertexType*> shared; getSharedVertexStar<MeshType>(non_border[0],non_border[1],shared); assert(shared.size()==2); assert(shared[0]->IsB()); assert(shared[1]->IsB()); assert(shared[0]!=shared[1]); //ScalarType epsilon=(ScalarType)0.001; ///then get the media of two shared vertices vcg::Point2<ScalarType> uvAve=shared[0]->T().P()+shared[1]->T().P(); assert(uvAve.Norm()>(ScalarType)0.001); uvAve.Normalize(); vcg::Point2<ScalarType> p0=uvAve*(ScalarType)0.3; vcg::Point2<ScalarType> p1=uvAve*(ScalarType)(-0.3); ///then test and set right assignement non_border[0]->T().P()=p0; non_border[1]->T().P()=p1; if (!NonFolded(parametrized)){ non_border[0]->T().P()=p1; non_border[1]->T().P()=p0; } } } ///final assert parametrization assert(NonFolded(parametrized)); } ///given the mesh and the two edges (same) seen from face[0] and face[1] of the mesh construct ///a diamond parametrization using equilateral triangles of edge edge_len template <class MeshType> void ParametrizeDiamondEquilateral(MeshType &parametrized, const int &edge0,const int &edge1, const typename MeshType::ScalarType &edge_len=1) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::VertexType VertexType; ScalarType h=(sqrt(3.0)/2.0)*edge_len; FaceType *fd0=&parametrized.face[0]; #ifndef NDEBUG FaceType *fd1=&parametrized.face[1]; #endif assert(fd0->FFp(edge0)==fd1); assert(fd1->FFp(edge1)==fd0); ///get 2 vertex on the edge VertexType *v0=fd0->V(edge0); VertexType *v1=fd0->V((edge0+1)%3); #ifndef NDEBUG VertexType *vtest0=fd1->V(edge1); VertexType *vtest1=fd1->V((edge1+1)%3); assert(v0!=v1); assert(vtest0!=vtest1); assert(((v0==vtest0)&&(v1==vtest1))||((v1==vtest0)&&(v0==vtest1))); #endif ///other 2 vertex VertexType *v2=parametrized.face[0].V((edge0+2)%3); VertexType *v3=parametrized.face[1].V((edge1+2)%3); assert((v2!=v3)&&(v0!=v2)&&(v0!=v3)&&(v1!=v2)&&(v1!=v3)); ///assing texcoords v0->T().P()=vcg::Point2<ScalarType>(0,-edge_len/2.0); v1->T().P()=vcg::Point2<ScalarType>(0,edge_len/2.0); v2->T().P()=vcg::Point2<ScalarType>(-h,0); v3->T().P()=vcg::Point2<ScalarType>(h,0); ///test assert(NonFolded(parametrized)); } ///given the mesh and the two edges (same) seen from face[0] and face[1] of the mesh construct ///a diamond parametrization using equilateral triangles of edge edge_len template <class MeshType> void ParametrizeFaceEquilateral(MeshType &parametrized, const typename MeshType::ScalarType &edge_len=1) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::ScalarType ScalarType; ScalarType h=(sqrt(3.0)/2.0)*edge_len; FaceType *f_param=&(parametrized.face[0]); f_param->V(0)->T().P()=vcg::Point2<ScalarType>(edge_len/2.0,0); f_param->V(1)->T().P()=vcg::Point2<ScalarType>(0,h); f_param->V(2)->T().P()=vcg::Point2<ScalarType>(-edge_len/2.0,0); } ///parametrize and create a submesh from trinagles that are incident on /// vertices .... seturn a vetor of original faces template <class MeshType> void ParametrizeLocally(MeshType &parametrized, const std::vector<typename MeshType::VertexType*> &subset, std::vector<typename MeshType::FaceType*> &orderedFaces, std::vector<typename MeshType::VertexType*> &orderedVertex) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::VertexType VertexType; orderedFaces.clear(); std::vector<VertexType*> vertices; ///get faces referenced by vertices getSharedFace<MeshType>(subset,orderedFaces); ///do a first copy of the mesh ///and parametrize it ///NB: order of faces is mantained CopyMeshFromFaces<MeshType>(orderedFaces,orderedVertex,parametrized); //CreateMeshVertexStar(subset,orderedFaces,parametrized); ParametrizeLocally(parametrized); } template <class MeshType> void InterpolateUV(const typename MeshType::FaceType* f, const typename MeshType::CoordType &bary, typename MeshType::ScalarType &U, typename MeshType::ScalarType &V) { U=bary.X()*f->cV(0)->T().U()+bary.Y()*f->cV(1)->T().U()+bary.Z()*f->cV(2)->T().U(); V=bary.X()*f->cV(0)->T().V()+bary.Y()*f->cV(1)->T().V()+bary.Z()*f->cV(2)->T().V(); /*if ((!((U>=-1)&&(U<=1)))||(!((V>=-1)&&(V<=1)))) { printf("Bary:%f,%f,%f \n",bary.X(),bary.Y(),bary.Z()); printf("texCoord:%f,%f \n",U,V); assert(0); }*/ //assert ((U>=-1)&&(U<=1)); //assert ((V>=-1)&&(V<=1)); } template <class MeshType> bool GetBaryFaceFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, typename MeshType::CoordType &bary, int &index) { typedef typename MeshType::ScalarType ScalarType; const ScalarType _EPSILON = ScalarType(0.0000001); /*assert ((U>=-1)&&(U<=1)); assert ((V>=-1)&&(V<=1));*/ for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->cV(0)->T().U(),f->cV(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->cV(1)->T().U(),f->cV(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->cV(2)->T().U(),f->cV(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); //assert(area>-_EPSILON); ///then find if the point 2d falls inside if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { index=i; ///approximation errors ScalarType sum=0; for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; sum+=bary[x]; } if (sum==0) printf("error SUM %f \n",sum); bary/=sum; return true; } } return (false); } template <class FaceType> bool GetBaryFaceFromUV(std::vector<FaceType*> faces, const typename FaceType::ScalarType &U, const typename FaceType::ScalarType &V, typename FaceType::CoordType &bary, int &index) { typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::ScalarType ScalarType; const ScalarType _EPSILON = ScalarType(0.0000001); /*assert ((U>=-1)&&(U<=1)); assert ((V>=-1)&&(V<=1));*/ for (unsigned int i=0;i<faces.size();i++) { FaceType *f=faces[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=fabs((tex1-tex0)^(tex2-tex0)); //assert(area>-_EPSILON); ///then find if the point 2d falls inside if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { index=i; ///approximation errors ScalarType sum=0; for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; sum+=fabs(bary[x]); } if (sum==0) printf("error SUM %f \n",sum); bary/=sum; /*if (!((bary.X()>=0)&& (bary.X()<=1))) printf("error %f \n",bary.X());*/ /*ScalarType diff=(1.0-bary.X()-bary.Y()-bary.Z()); bary.X()+=diff;*/ return true; } } return (false); } template <class MeshType> bool GetBaryFaceFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, const std::vector<typename MeshType::FaceType*> &orderedFaces, typename MeshType::CoordType &bary, typename MeshType::FaceType* &chosen) { int index; bool found=GetBaryFaceFromUV(m,U,V,bary,index); if(!found) { chosen=0; return false; } chosen=orderedFaces[index]; return true; } template <class MeshType> bool GetCoordFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, typename MeshType::CoordType &val, bool rpos=false) { typedef typename MeshType::ScalarType ScalarType; const ScalarType _EPSILON = (ScalarType)0.00001; for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->cV(0)->T().U(),f->cV(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->cV(1)->T().U(),f->cV(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->cV(2)->T().U(),f->cV(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); ///then find if the point 2d falls inside typename MeshType::CoordType bary; if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { ///approximation errors for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; } ScalarType diff= (ScalarType)(1.0-bary.X()-bary.Y()-bary.Z()); bary.X()+=diff; if (!rpos) val=f->cP(0)*bary.X()+f->cP(1)*bary.Y()+f->cP(0)*bary.Z(); else val=f->cV(0)->RPos*bary.X()+f->cV(1)->RPos*bary.Y()+f->cV(2)->RPos*bary.Z(); return true; } } return false; } template <class MeshType> typename MeshType::ScalarType GetSmallestUVEdgeSize(const MeshType &m) { typedef typename MeshType::ScalarType ScalarType; ScalarType smallest=100.f; assert(m.fn>0); for (int i=0;i<m.face.size();i++) { ///approximation errors for (int j=0;j<3;j++) { vcg::Point2<ScalarType> uv0=m.face[i].V(j)->T().P(); vcg::Point2<ScalarType> uv1=m.face[i].V((j+1)%3)->T().P(); ScalarType test=(uv0-uv1).Norm(); if (test<smallest) smallest=test; } } return smallest; } template <class MeshType> typename MeshType::ScalarType GetSmallestUVHeight(const MeshType &m) { typedef typename MeshType::ScalarType ScalarType; ScalarType smallest=(ScalarType)100.0; ScalarType eps=(ScalarType)0.0001; assert(m.fn>0); for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; ///approximation errors for (int j=0;j<3;j++) { vcg::Point2<ScalarType> uv0=f->cV(j)->cT().P(); vcg::Point2<ScalarType> uv1=f->cV1(j)->cT().P(); vcg::Point2<ScalarType> uv2=f->cV2(j)->cT().P(); ScalarType area=fabs((uv1-uv0)^(uv2-uv0)); ScalarType base=(uv1-uv2).Norm(); ScalarType h_test=area/base; if (h_test<smallest) smallest=h_test; } } if (smallest<eps) smallest=(ScalarType)eps; if (smallest>(ScalarType)0.05) smallest=(ScalarType)0.05; return smallest; } template <class MeshType> void ParametrizeStarEquilateral(typename MeshType::VertexType *center, bool /*subvertices=true*/) { ///initialize domain typedef typename MeshType::VertexType VertexType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; MeshType parametrized; std::vector<VertexType*> vertices,ordVert; std::vector<VertexType*> HresVert; std::vector<FaceType*> faces; vertices.push_back(center); getSharedFace<MeshType>(vertices,faces); CopyMeshFromFaces<MeshType>(faces,ordVert,parametrized); ///parametrize and then copy back ParametrizeStarEquilateral<MeshType>(parametrized); for (unsigned int i=0;i<ordVert.size();i++) ordVert[i]->T().P()=parametrized.vert[i].T().P(); ///initialize sub-vertices getHresVertex<FaceType>(faces,HresVert); for (unsigned int i=0;i<HresVert.size();i++) { FaceType *father=HresVert[i]->father; CoordType Bary=HresVert[i]->Bary; InterpolateUV<MeshType>(father,Bary,HresVert[i]->T().U(),HresVert[i]->T().V()); } } #endif
par_strength.c
/*BHEADER********************************************************************** * Copyright (c) 2017, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * Written by Ulrike Yang (yang11@llnl.gov) et al. CODE-LLNL-738-322. * This file is part of AMG. See files README and COPYRIGHT for details. * * AMG is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTIBILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of the * GNU General Public License for more details. * ***********************************************************************EHEADER*/ /****************************************************************************** * *****************************************************************************/ /* following should be in a header file */ #include "_hypre_parcsr_ls.h" #include "hypre_hopscotch_hash.h" /*==========================================================================*/ /*==========================================================================*/ /** Generates strength matrix Notes: \begin{itemize} \item The underlying matrix storage scheme is a hypre_ParCSR matrix. \item The routine returns the following: \begin{itemize} \item S - a ParCSR matrix representing the "strength matrix". This is used in the coarsening and interpolation routines. \end{itemize} \item The graph of the "strength matrix" for A is a subgraph of the graph of A, but requires nonsymmetric storage even if A is symmetric. This is because of the directional nature of the "strengh of dependence" notion (see below). Since we are using nonsymmetric storage for A right now, this is not a problem. If we ever add the ability to store A symmetrically, then we could store the strength graph as floats instead of doubles to save space. \item This routine currently "compresses" the strength matrix. We should consider the possibility of defining this matrix to have the same "nonzero structure" as A. To do this, we could use the same A\_i and A\_j arrays, and would need only define the S\_data array. There are several pros and cons to discuss. \end{itemize} Terminology: \begin{itemize} \item Ruge's terminology: A point is "strongly connected to" $j$, or "strongly depends on" $j$, if $-a_ij >= \theta max_{l != j} \{-a_il\}$. \item Here, we retain some of this terminology, but with a more generalized notion of "strength". We also retain the "natural" graph notation for representing the directed graph of a matrix. That is, the nonzero entry $a_ij$ is represented as: i --> j. In the strength matrix, S, the entry $s_ij$ is also graphically denoted as above, and means both of the following: \begin{itemize} \item $i$ "depends on" $j$ with "strength" $s_ij$ \item $j$ "influences" $i$ with "strength" $s_ij$ \end{itemize} \end{itemize} {\bf Input files:} _hypre_parcsr_ls.h @return Error code. @param A [IN] coefficient matrix @param strength_threshold [IN] threshold parameter used to define strength @param max_row_sum [IN] parameter used to modify definition of strength for diagonal dominant matrices @param S_ptr [OUT] strength matrix @see */ /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateS(hypre_ParCSRMatrix *A, HYPRE_Real strength_threshold, HYPRE_Real max_row_sum, HYPRE_Int num_functions, HYPRE_Int *dof_func, hypre_ParCSRMatrix **S_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATES] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = NULL; HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd = 0; HYPRE_Int num_cols_offd = 0; hypre_ParCSRMatrix *S; hypre_CSRMatrix *S_diag; HYPRE_Int *S_diag_i; HYPRE_Int *S_diag_j; /* HYPRE_Real *S_diag_data; */ hypre_CSRMatrix *S_offd; HYPRE_Int *S_offd_i = NULL; HYPRE_Int *S_offd_j = NULL; /* HYPRE_Real *S_offd_data; */ HYPRE_Real diag, row_scale, row_sum; HYPRE_Int i, jA, jS; HYPRE_Int ierr = 0; HYPRE_Int *dof_func_offd; HYPRE_Int num_sends; HYPRE_Int *int_buf_data; HYPRE_Int index, start, j; HYPRE_Int *prefix_sum_workspace; /*-------------------------------------------------------------- * Compute a ParCSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = 1, else S_ij = 0. * * NOTE: the entries are negative initially, corresponding * to "unaccounted-for" dependence. *----------------------------------------------------------------*/ num_nonzeros_diag = A_diag_i[num_variables]; num_cols_offd = hypre_CSRMatrixNumCols(A_offd); A_offd_i = hypre_CSRMatrixI(A_offd); num_nonzeros_offd = A_offd_i[num_variables]; S = hypre_ParCSRMatrixCreate(comm, global_num_vars, global_num_vars, row_starts, row_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); /* row_starts is owned by A, col_starts = row_starts */ hypre_ParCSRMatrixSetRowStartsOwner(S,0); S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrixI(S_diag) = hypre_CTAlloc(HYPRE_Int, num_variables+1); hypre_CSRMatrixJ(S_diag) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_diag); S_offd = hypre_ParCSRMatrixOffd(S); hypre_CSRMatrixI(S_offd) = hypre_CTAlloc(HYPRE_Int, num_variables+1); S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_temp_diag_j = hypre_CSRMatrixJ(S_diag); S_offd_i = hypre_CSRMatrixI(S_offd); S_diag_j = hypre_TAlloc(HYPRE_Int, num_nonzeros_diag); HYPRE_Int *S_temp_offd_j = NULL; dof_func_offd = NULL; if (num_cols_offd) { A_offd_data = hypre_CSRMatrixData(A_offd); hypre_CSRMatrixJ(S_offd) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd); S_temp_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *col_map_offd_S = hypre_TAlloc(HYPRE_Int, num_cols_offd); hypre_ParCSRMatrixColMapOffd(S) = col_map_offd_S; if (num_functions > 1) dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); S_offd_j = hypre_TAlloc(HYPRE_Int, num_nonzeros_offd); HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols_offd; i++) col_map_offd_S[i] = col_map_offd_A[i]; } /*------------------------------------------------------------------- * Get the dof_func data for the off-processor columns *-------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_functions > 1) { int_buf_data = hypre_CTAlloc(HYPRE_Int,hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data); } /*HYPRE_Int prefix_sum_workspace[2*(hypre_NumThreads() + 1)];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2*(hypre_NumThreads() + 1)); /* give S same nonzero structure as A */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,diag,row_scale,row_sum,jA,jS) #endif { HYPRE_Int start, stop; hypre_GetSimpleThreadPartition(&start, &stop, num_variables); HYPRE_Int jS_diag = 0, jS_offd = 0; for (i = start; i < stop; i++) { S_diag_i[i] = jS_diag; if (num_cols_offd) { S_offd_i[i] = jS_offd; } diag = A_diag_data[A_diag_i[i]]; /* compute scaling factor and row sum */ row_scale = 0.0; row_sum = diag; if (num_functions > 1) { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_max(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_max(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_min(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_min(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } } /* diag >= 0 */ } /* num_functions > 1 */ else { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_max(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_max(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_min(row_scale, A_diag_data[jA]); row_sum += A_diag_data[jA]; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_min(row_scale, A_offd_data[jA]); row_sum += A_offd_data[jA]; } } /* diag >= 0*/ } /* num_functions <= 1 */ jS_diag += A_diag_i[i + 1] - A_diag_i[i] - 1; jS_offd += A_offd_i[i + 1] - A_offd_i[i]; /* compute row entries of S */ S_temp_diag_j[A_diag_i[i]] = -1; if ((fabs(row_sum) > fabs(diag)*max_row_sum) && (max_row_sum < 1.0)) { /* make all dependencies weak */ for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { S_temp_diag_j[jA] = -1; } jS_diag -= A_diag_i[i + 1] - (A_diag_i[i] + 1); for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { S_temp_offd_j[jA] = -1; } jS_offd -= A_offd_i[i + 1] - A_offd_i[i]; } else { if (num_functions > 1) { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] <= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] <= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] >= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] >= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } /* diag >= 0 */ } /* num_functions > 1 */ else { if (diag < 0) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] <= strength_threshold * row_scale) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] <= strength_threshold * row_scale) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (A_diag_data[jA] >= strength_threshold * row_scale) { S_temp_diag_j[jA] = -1; --jS_diag; } else { S_temp_diag_j[jA] = A_diag_j[jA]; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (A_offd_data[jA] >= strength_threshold * row_scale) { S_temp_offd_j[jA] = -1; --jS_offd; } else { S_temp_offd_j[jA] = A_offd_j[jA]; } } } /* diag >= 0 */ } /* num_functions <= 1 */ } /* !((row_sum > max_row_sum) && (max_row_sum < 1.0)) */ } /* for each variable */ hypre_prefix_sum_pair(&jS_diag, S_diag_i + num_variables, &jS_offd, S_offd_i + num_variables, prefix_sum_workspace); /*-------------------------------------------------------------- * "Compress" the strength matrix. * * NOTE: S has *NO DIAGONAL ELEMENT* on any row. Caveat Emptor! * * NOTE: This "compression" section of code may be removed, and * coarsening will still be done correctly. However, the routine * that builds interpolation would have to be modified first. *----------------------------------------------------------------*/ for (i = start; i < stop; i++) { S_diag_i[i] += jS_diag; S_offd_i[i] += jS_offd; jS = S_diag_i[i]; for (jA = A_diag_i[i]; jA < A_diag_i[i+1]; jA++) { if (S_temp_diag_j[jA] > -1) { S_diag_j[jS] = S_temp_diag_j[jA]; jS++; } } jS = S_offd_i[i]; for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (S_temp_offd_j[jA] > -1) { S_offd_j[jS] = S_temp_offd_j[jA]; jS++; } } } /* for each variable */ } /* omp parallel */ hypre_CSRMatrixNumNonzeros(S_diag) = S_diag_i[num_variables]; hypre_CSRMatrixNumNonzeros(S_offd) = S_offd_i[num_variables]; hypre_CSRMatrixJ(S_diag) = S_diag_j; hypre_CSRMatrixJ(S_offd) = S_offd_j; hypre_ParCSRMatrixCommPkg(S) = NULL; *S_ptr = S; hypre_TFree(prefix_sum_workspace); hypre_TFree(dof_func_offd); hypre_TFree(S_temp_diag_j); hypre_TFree(S_temp_offd_j); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATES] += hypre_MPI_Wtime(); #endif return (ierr); } /*==========================================================================*/ /*==========================================================================*/ /** Generates strength matrix Notes: \begin{itemize} \item The underlying matrix storage scheme is a hypre_ParCSR matrix. \item The routine returns the following: \begin{itemize} \item S - a ParCSR matrix representing the "strength matrix". This is used in the coarsening and interpolation routines. \end{itemize} \item The graph of the "strength matrix" for A is a subgraph of the graph of A, but requires nonsymmetric storage even if A is symmetric. This is because of the directional nature of the "strengh of dependence" notion (see below). Since we are using nonsymmetric storage for A right now, this is not a problem. If we ever add the ability to store A symmetrically, then we could store the strength graph as floats instead of doubles to save space. \item This routine currently "compresses" the strength matrix. We should consider the possibility of defining this matrix to have the same "nonzero structure" as A. To do this, we could use the same A\_i and A\_j arrays, and would need only define the S\_data array. There are several pros and cons to discuss. \end{itemize} Terminology: \begin{itemize} \item Ruge's terminology: A point is "strongly connected to" $j$, or "strongly depends on" $j$, if $|a_ij| >= \theta max_{l != j} |a_il|}$. \item Here, we retain some of this terminology, but with a more generalized notion of "strength". We also retain the "natural" graph notation for representing the directed graph of a matrix. That is, the nonzero entry $a_ij$ is represented as: i --> j. In the strength matrix, S, the entry $s_ij$ is also graphically denoted as above, and means both of the following: \begin{itemize} \item $i$ "depends on" $j$ with "strength" $s_ij$ \item $j$ "influences" $i$ with "strength" $s_ij$ \end{itemize} \end{itemize} {\bf Input files:} _hypre_parcsr_ls.h @return Error code. @param A [IN] coefficient matrix @param strength_threshold [IN] threshold parameter used to define strength @param max_row_sum [IN] parameter used to modify definition of strength for diagonal dominant matrices @param S_ptr [OUT] strength matrix @see */ /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateSabs(hypre_ParCSRMatrix *A, HYPRE_Real strength_threshold, HYPRE_Real max_row_sum, HYPRE_Int num_functions, HYPRE_Int *dof_func, hypre_ParCSRMatrix **S_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = NULL; HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *row_starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int global_num_vars = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int num_nonzeros_diag; HYPRE_Int num_nonzeros_offd = 0; HYPRE_Int num_cols_offd = 0; hypre_ParCSRMatrix *S; hypre_CSRMatrix *S_diag; HYPRE_Int *S_diag_i; HYPRE_Int *S_diag_j; /* HYPRE_Real *S_diag_data; */ hypre_CSRMatrix *S_offd; HYPRE_Int *S_offd_i = NULL; HYPRE_Int *S_offd_j = NULL; /* HYPRE_Real *S_offd_data; */ HYPRE_Real diag, row_scale, row_sum; HYPRE_Int i, jA, jS; HYPRE_Int ierr = 0; HYPRE_Int *dof_func_offd; HYPRE_Int num_sends; HYPRE_Int *int_buf_data; HYPRE_Int index, start, j; /*-------------------------------------------------------------- * Compute a ParCSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = 1, else S_ij = 0. * * NOTE: the entries are negative initially, corresponding * to "unaccounted-for" dependence. *----------------------------------------------------------------*/ num_nonzeros_diag = A_diag_i[num_variables]; num_cols_offd = hypre_CSRMatrixNumCols(A_offd); A_offd_i = hypre_CSRMatrixI(A_offd); num_nonzeros_offd = A_offd_i[num_variables]; S = hypre_ParCSRMatrixCreate(comm, global_num_vars, global_num_vars, row_starts, row_starts, num_cols_offd, num_nonzeros_diag, num_nonzeros_offd); /* row_starts is owned by A, col_starts = row_starts */ hypre_ParCSRMatrixSetRowStartsOwner(S,0); S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrixI(S_diag) = hypre_CTAlloc(HYPRE_Int, num_variables+1); hypre_CSRMatrixJ(S_diag) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_diag); S_offd = hypre_ParCSRMatrixOffd(S); hypre_CSRMatrixI(S_offd) = hypre_CTAlloc(HYPRE_Int, num_variables+1); S_diag_i = hypre_CSRMatrixI(S_diag); S_diag_j = hypre_CSRMatrixJ(S_diag); S_offd_i = hypre_CSRMatrixI(S_offd); dof_func_offd = NULL; if (num_cols_offd) { A_offd_data = hypre_CSRMatrixData(A_offd); hypre_CSRMatrixJ(S_offd) = hypre_CTAlloc(HYPRE_Int, num_nonzeros_offd); S_offd_j = hypre_CSRMatrixJ(S_offd); hypre_ParCSRMatrixColMapOffd(S) = hypre_CTAlloc(HYPRE_Int, num_cols_offd); if (num_functions > 1) dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd); } /*------------------------------------------------------------------- * Get the dof_func data for the off-processor columns *-------------------------------------------------------------------*/ if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_functions > 1) { int_buf_data = hypre_CTAlloc(HYPRE_Int,hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends)); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data); } /* give S same nonzero structure as A */ hypre_ParCSRMatrixCopy(A,S,0); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,diag,row_scale,row_sum,jA) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_variables; i++) { diag = A_diag_data[A_diag_i[i]]; /* compute scaling factor and row sum */ row_scale = 0.0; row_sum = diag; if (num_functions > 1) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (dof_func[i] == dof_func[A_diag_j[jA]]) { row_scale = hypre_max(row_scale, fabs(A_diag_data[jA])); row_sum += fabs(A_diag_data[jA]); } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (dof_func[i] == dof_func_offd[A_offd_j[jA]]) { row_scale = hypre_max(row_scale, fabs(A_offd_data[jA])); row_sum += fabs(A_offd_data[jA]); } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { row_scale = hypre_max(row_scale, fabs(A_diag_data[jA])); row_sum += fabs(A_diag_data[jA]); } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { row_scale = hypre_max(row_scale, fabs(A_offd_data[jA])); row_sum += fabs(A_offd_data[jA]); } } /* compute row entries of S */ S_diag_j[A_diag_i[i]] = -1; if ((fabs(row_sum) > fabs(diag)*max_row_sum) && (max_row_sum < 1.0)) { /* make all dependencies weak */ for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { S_diag_j[jA] = -1; } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { S_offd_j[jA] = -1; } } else { if (num_functions > 1) { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (fabs(A_diag_data[jA]) <= strength_threshold * row_scale || dof_func[i] != dof_func[A_diag_j[jA]]) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (fabs(A_offd_data[jA]) <= strength_threshold * row_scale || dof_func[i] != dof_func_offd[A_offd_j[jA]]) { S_offd_j[jA] = -1; } } } else { for (jA = A_diag_i[i]+1; jA < A_diag_i[i+1]; jA++) { if (fabs(A_diag_data[jA]) <= strength_threshold * row_scale) { S_diag_j[jA] = -1; } } for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (fabs(A_offd_data[jA]) <= strength_threshold * row_scale) { S_offd_j[jA] = -1; } } } } } /*-------------------------------------------------------------- * "Compress" the strength matrix. * * NOTE: S has *NO DIAGONAL ELEMENT* on any row. Caveat Emptor! * * NOTE: This "compression" section of code may be removed, and * coarsening will still be done correctly. However, the routine * that builds interpolation would have to be modified first. *----------------------------------------------------------------*/ /* RDF: not sure if able to thread this loop */ jS = 0; for (i = 0; i < num_variables; i++) { S_diag_i[i] = jS; for (jA = A_diag_i[i]; jA < A_diag_i[i+1]; jA++) { if (S_diag_j[jA] > -1) { S_diag_j[jS] = S_diag_j[jA]; jS++; } } } S_diag_i[num_variables] = jS; hypre_CSRMatrixNumNonzeros(S_diag) = jS; /* RDF: not sure if able to thread this loop */ jS = 0; for (i = 0; i < num_variables; i++) { S_offd_i[i] = jS; for (jA = A_offd_i[i]; jA < A_offd_i[i+1]; jA++) { if (S_offd_j[jA] > -1) { S_offd_j[jS] = S_offd_j[jA]; jS++; } } } S_offd_i[num_variables] = jS; hypre_CSRMatrixNumNonzeros(S_offd) = jS; hypre_ParCSRMatrixCommPkg(S) = NULL; *S_ptr = S; hypre_TFree(dof_func_offd); return (ierr); } /*--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateSCommPkg(hypre_ParCSRMatrix *A, hypre_ParCSRMatrix *S, HYPRE_Int **col_offd_S_to_A_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_MPI_Status *status; hypre_MPI_Request *requests; hypre_ParCSRCommPkg *comm_pkg_A = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommPkg *comm_pkg_S; hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *col_map_offd_S = hypre_ParCSRMatrixColMapOffd(S); HYPRE_Int *recv_procs_A = hypre_ParCSRCommPkgRecvProcs(comm_pkg_A); HYPRE_Int *recv_vec_starts_A = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_A); HYPRE_Int *send_procs_A = hypre_ParCSRCommPkgSendProcs(comm_pkg_A); HYPRE_Int *send_map_starts_A = hypre_ParCSRCommPkgSendMapStarts(comm_pkg_A); HYPRE_Int *recv_procs_S; HYPRE_Int *recv_vec_starts_S; HYPRE_Int *send_procs_S; HYPRE_Int *send_map_starts_S; HYPRE_Int *send_map_elmts_S; HYPRE_Int *col_offd_S_to_A; HYPRE_Int *S_marker; HYPRE_Int *send_change; HYPRE_Int *recv_change; HYPRE_Int num_variables = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int num_cols_offd_A = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int num_cols_offd_S; HYPRE_Int i, j, jcol; HYPRE_Int proc, cnt, proc_cnt, total_nz; HYPRE_Int first_row; HYPRE_Int ierr = 0; HYPRE_Int num_sends_A = hypre_ParCSRCommPkgNumSends(comm_pkg_A); HYPRE_Int num_recvs_A = hypre_ParCSRCommPkgNumRecvs(comm_pkg_A); HYPRE_Int num_sends_S; HYPRE_Int num_recvs_S; HYPRE_Int num_nonzeros; num_nonzeros = S_offd_i[num_variables]; S_marker = NULL; if (num_cols_offd_A) S_marker = hypre_CTAlloc(HYPRE_Int,num_cols_offd_A); for (i=0; i < num_cols_offd_A; i++) S_marker[i] = -1; for (i=0; i < num_nonzeros; i++) { jcol = S_offd_j[i]; S_marker[jcol] = 0; } proc = 0; proc_cnt = 0; cnt = 0; num_recvs_S = 0; for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++) { if (!S_marker[j]) { S_marker[j] = cnt; cnt++; proc = 1; } } if (proc) {num_recvs_S++; proc = 0;} } num_cols_offd_S = cnt; recv_change = NULL; recv_procs_S = NULL; send_change = NULL; if (col_map_offd_S) hypre_TFree(col_map_offd_S); col_map_offd_S = NULL; col_offd_S_to_A = NULL; if (num_recvs_A) recv_change = hypre_CTAlloc(HYPRE_Int, num_recvs_A); if (num_sends_A) send_change = hypre_CTAlloc(HYPRE_Int, num_sends_A); if (num_recvs_S) recv_procs_S = hypre_CTAlloc(HYPRE_Int, num_recvs_S); recv_vec_starts_S = hypre_CTAlloc(HYPRE_Int, num_recvs_S+1); if (num_cols_offd_S) { col_map_offd_S = hypre_CTAlloc(HYPRE_Int,num_cols_offd_S); col_offd_S_to_A = hypre_CTAlloc(HYPRE_Int,num_cols_offd_S); } if (num_cols_offd_S < num_cols_offd_A) { for (i=0; i < num_nonzeros; i++) { jcol = S_offd_j[i]; S_offd_j[i] = S_marker[jcol]; } proc = 0; proc_cnt = 0; cnt = 0; recv_vec_starts_S[0] = 0; for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++) { if (S_marker[j] != -1) { col_map_offd_S[cnt] = col_map_offd_A[j]; col_offd_S_to_A[cnt++] = j; proc = 1; } } recv_change[i] = j-cnt-recv_vec_starts_A[i] +recv_vec_starts_S[proc_cnt]; if (proc) { recv_procs_S[proc_cnt++] = recv_procs_A[i]; recv_vec_starts_S[proc_cnt] = cnt; proc = 0; } } } else { for (i=0; i < num_recvs_A; i++) { for (j=recv_vec_starts_A[i]; j < recv_vec_starts_A[i+1]; j++) { col_map_offd_S[j] = col_map_offd_A[j]; col_offd_S_to_A[j] = j; } recv_procs_S[i] = recv_procs_A[i]; recv_vec_starts_S[i] = recv_vec_starts_A[i]; } recv_vec_starts_S[num_recvs_A] = recv_vec_starts_A[num_recvs_A]; } requests = hypre_CTAlloc(hypre_MPI_Request,num_sends_A+num_recvs_A); j=0; for (i=0; i < num_sends_A; i++) hypre_MPI_Irecv(&send_change[i],1,HYPRE_MPI_INT,send_procs_A[i], 0,comm,&requests[j++]); for (i=0; i < num_recvs_A; i++) hypre_MPI_Isend(&recv_change[i],1,HYPRE_MPI_INT,recv_procs_A[i], 0,comm,&requests[j++]); status = hypre_CTAlloc(hypre_MPI_Status,j); hypre_MPI_Waitall(j,requests,status); hypre_TFree(status); hypre_TFree(requests); num_sends_S = 0; total_nz = send_map_starts_A[num_sends_A]; for (i=0; i < num_sends_A; i++) { if (send_change[i]) { if ((send_map_starts_A[i+1]-send_map_starts_A[i]) > send_change[i]) num_sends_S++; } else num_sends_S++; total_nz -= send_change[i]; } send_procs_S = NULL; if (num_sends_S) send_procs_S = hypre_CTAlloc(HYPRE_Int,num_sends_S); send_map_starts_S = hypre_CTAlloc(HYPRE_Int,num_sends_S+1); send_map_elmts_S = NULL; if (total_nz) send_map_elmts_S = hypre_CTAlloc(HYPRE_Int,total_nz); proc = 0; proc_cnt = 0; for (i=0; i < num_sends_A; i++) { cnt = send_map_starts_A[i+1]-send_map_starts_A[i]-send_change[i]; if (cnt) { send_procs_S[proc_cnt++] = send_procs_A[i]; send_map_starts_S[proc_cnt] = send_map_starts_S[proc_cnt-1]+cnt; } } comm_pkg_S = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(comm_pkg_S) = comm; hypre_ParCSRCommPkgNumRecvs(comm_pkg_S) = num_recvs_S; hypre_ParCSRCommPkgRecvProcs(comm_pkg_S) = recv_procs_S; hypre_ParCSRCommPkgRecvVecStarts(comm_pkg_S) = recv_vec_starts_S; hypre_ParCSRCommPkgNumSends(comm_pkg_S) = num_sends_S; hypre_ParCSRCommPkgSendProcs(comm_pkg_S) = send_procs_S; hypre_ParCSRCommPkgSendMapStarts(comm_pkg_S) = send_map_starts_S; comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg_S, col_map_offd_S, send_map_elmts_S); hypre_ParCSRCommHandleDestroy(comm_handle); first_row = hypre_ParCSRMatrixFirstRowIndex(A); if (first_row) for (i=0; i < send_map_starts_S[num_sends_S]; i++) send_map_elmts_S[i] -= first_row; hypre_ParCSRCommPkgSendMapElmts(comm_pkg_S) = send_map_elmts_S; hypre_ParCSRMatrixCommPkg(S) = comm_pkg_S; hypre_ParCSRMatrixColMapOffd(S) = col_map_offd_S; hypre_CSRMatrixNumCols(S_offd) = num_cols_offd_S; hypre_TFree(S_marker); hypre_TFree(send_change); hypre_TFree(recv_change); *col_offd_S_to_A_ptr = col_offd_S_to_A; return ierr; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGCreate2ndS : creates strength matrix on coarse points * for second coarsening pass in aggressive coarsening (S*S+2S) *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreate2ndS( hypre_ParCSRMatrix *S, HYPRE_Int *CF_marker, HYPRE_Int num_paths, HYPRE_Int *coarse_row_starts, hypre_ParCSRMatrix **C_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATE_2NDS] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S); hypre_ParCSRCommPkg *tmp_comm_pkg; hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int num_cols_diag_S = hypre_CSRMatrixNumCols(S_diag); HYPRE_Int num_cols_offd_S = hypre_CSRMatrixNumCols(S_offd); hypre_ParCSRMatrix *S2; HYPRE_Int *col_map_offd_C = NULL; hypre_CSRMatrix *C_diag; /*HYPRE_Int *C_diag_data = NULL;*/ HYPRE_Int *C_diag_i; HYPRE_Int *C_diag_j = NULL; hypre_CSRMatrix *C_offd; /*HYPRE_Int *C_offd_data=NULL;*/ HYPRE_Int *C_offd_i; HYPRE_Int *C_offd_j=NULL; HYPRE_Int num_cols_offd_C = 0; HYPRE_Int *S_ext_diag_i = NULL; HYPRE_Int *S_ext_diag_j = NULL; HYPRE_Int S_ext_diag_size = 0; HYPRE_Int *S_ext_offd_i = NULL; HYPRE_Int *S_ext_offd_j = NULL; HYPRE_Int S_ext_offd_size = 0; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *S_marker = NULL; HYPRE_Int *S_marker_offd = NULL; HYPRE_Int *temp = NULL; HYPRE_Int *fine_to_coarse = NULL; HYPRE_Int *fine_to_coarse_offd = NULL; HYPRE_Int *map_S_to_C = NULL; HYPRE_Int num_sends = 0; HYPRE_Int num_recvs = 0; HYPRE_Int *send_map_starts; HYPRE_Int *tmp_send_map_starts = NULL; HYPRE_Int *send_map_elmts; HYPRE_Int *recv_vec_starts; HYPRE_Int *tmp_recv_vec_starts = NULL; HYPRE_Int *int_buf_data = NULL; HYPRE_Int i, j, k; HYPRE_Int i1, i2, i3; HYPRE_Int jj1, jj2, jrow, j_cnt; /*HYPRE_Int cnt, cnt_offd, cnt_diag;*/ HYPRE_Int num_procs, my_id; HYPRE_Int index; /*HYPRE_Int value;*/ HYPRE_Int num_coarse; HYPRE_Int num_nonzeros; HYPRE_Int global_num_coarse; HYPRE_Int my_first_cpt, my_last_cpt; HYPRE_Int *S_int_i = NULL; HYPRE_Int *S_int_j = NULL; HYPRE_Int *S_ext_i = NULL; HYPRE_Int *S_ext_j = NULL; /*HYPRE_Int prefix_sum_workspace[2*(hypre_NumThreads() + 1)];*/ HYPRE_Int *prefix_sum_workspace; HYPRE_Int *num_coarse_prefix_sum; prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2*(hypre_NumThreads() + 1)); num_coarse_prefix_sum = hypre_TAlloc(HYPRE_Int, hypre_NumThreads() + 1); /*----------------------------------------------------------------------- * Extract S_ext, i.e. portion of B that is stored on neighbor procs * and needed locally for matrix matrix product *-----------------------------------------------------------------------*/ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); #ifdef HYPRE_NO_GLOBAL_PARTITION my_first_cpt = coarse_row_starts[0]; my_last_cpt = coarse_row_starts[1]-1; if (my_id == (num_procs -1)) global_num_coarse = coarse_row_starts[1]; hypre_MPI_Bcast(&global_num_coarse, 1, HYPRE_MPI_INT, num_procs-1, comm); #else my_first_cpt = coarse_row_starts[my_id]; my_last_cpt = coarse_row_starts[my_id+1]-1; global_num_coarse = coarse_row_starts[num_procs]; #endif if (num_cols_offd_S) { CF_marker_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_S); fine_to_coarse_offd = hypre_TAlloc(HYPRE_Int, num_cols_offd_S); } HYPRE_Int *coarse_to_fine = NULL; if (num_cols_diag_S) { fine_to_coarse = hypre_TAlloc(HYPRE_Int, num_cols_diag_S); coarse_to_fine = hypre_TAlloc(HYPRE_Int, num_cols_diag_S); } /*HYPRE_Int num_coarse_prefix_sum[hypre_NumThreads() + 1];*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i) #endif { HYPRE_Int num_coarse_private = 0; HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_diag_S); for (i = i_begin; i < i_end; i++) { if (CF_marker[i] > 0) num_coarse_private++; } hypre_prefix_sum(&num_coarse_private, &num_coarse, num_coarse_prefix_sum); for (i = i_begin; i < i_end; i++) { if (CF_marker[i] > 0) { fine_to_coarse[i] = num_coarse_private; coarse_to_fine[num_coarse_private] = i; num_coarse_private++; } else { fine_to_coarse[i] = -1; } } } /* omp parallel */ if (num_procs > 1) { if (!comm_pkg) { hypre_MatvecCommPkgCreate(S); comm_pkg = hypre_ParCSRMatrixCommPkg(S); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); send_map_starts = hypre_ParCSRCommPkgSendMapStarts(comm_pkg); send_map_elmts = hypre_ParCSRCommPkgSendMapElmts(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); recv_vec_starts = hypre_ParCSRCommPkgRecvVecStarts(comm_pkg); HYPRE_Int begin = send_map_starts[0]; HYPRE_Int end = send_map_starts[num_sends]; int_buf_data = hypre_TAlloc(HYPRE_Int, end); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (index = begin; index < end; index++) { int_buf_data[index - begin] = fine_to_coarse[send_map_elmts[index]] + my_first_cpt; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, fine_to_coarse_offd); hypre_ParCSRCommHandleDestroy(comm_handle); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (index = begin; index < end; index++) { int_buf_data[index - begin] = CF_marker[send_map_elmts[index]]; } comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data); S_int_i = hypre_TAlloc(HYPRE_Int, end+1); S_ext_i = hypre_CTAlloc(HYPRE_Int, recv_vec_starts[num_recvs]+1); /*-------------------------------------------------------------------------- * generate S_int_i through adding number of coarse row-elements of offd and diag * for corresponding rows. S_int_i[j+1] contains the number of coarse elements of * a row j (which is determined through send_map_elmts) *--------------------------------------------------------------------------*/ S_int_i[0] = 0; num_nonzeros = 0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j,k) reduction(+:num_nonzeros) HYPRE_SMP_SCHEDULE #endif for (j = begin; j < end; j++) { HYPRE_Int jrow = send_map_elmts[j]; HYPRE_Int index = 0; for (k = S_diag_i[jrow]; k < S_diag_i[jrow+1]; k++) { if (CF_marker[S_diag_j[k]] > 0) index++; } for (k = S_offd_i[jrow]; k < S_offd_i[jrow+1]; k++) { if (CF_marker_offd[S_offd_j[k]] > 0) index++; } S_int_i[j - begin + 1] = index; num_nonzeros += S_int_i[j - begin + 1]; } /*-------------------------------------------------------------------------- * initialize communication *--------------------------------------------------------------------------*/ if (num_procs > 1) comm_handle = hypre_ParCSRCommHandleCreate(11,comm_pkg,&S_int_i[1],&S_ext_i[1]); if (num_nonzeros) S_int_j = hypre_TAlloc(HYPRE_Int, num_nonzeros); tmp_send_map_starts = hypre_CTAlloc(HYPRE_Int, num_sends+1); tmp_recv_vec_starts = hypre_CTAlloc(HYPRE_Int, num_recvs+1); tmp_send_map_starts[0] = 0; j_cnt = 0; for (i=0; i < num_sends; i++) { for (j = send_map_starts[i]; j < send_map_starts[i+1]; j++) { jrow = send_map_elmts[j]; for (k=S_diag_i[jrow]; k < S_diag_i[jrow+1]; k++) { if (CF_marker[S_diag_j[k]] > 0) S_int_j[j_cnt++] = fine_to_coarse[S_diag_j[k]]+my_first_cpt; } for (k=S_offd_i[jrow]; k < S_offd_i[jrow+1]; k++) { if (CF_marker_offd[S_offd_j[k]] > 0) S_int_j[j_cnt++] = fine_to_coarse_offd[S_offd_j[k]]; } } tmp_send_map_starts[i+1] = j_cnt; } tmp_comm_pkg = hypre_CTAlloc(hypre_ParCSRCommPkg,1); hypre_ParCSRCommPkgComm(tmp_comm_pkg) = comm; hypre_ParCSRCommPkgNumSends(tmp_comm_pkg) = num_sends; hypre_ParCSRCommPkgNumRecvs(tmp_comm_pkg) = num_recvs; hypre_ParCSRCommPkgSendProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgSendProcs(comm_pkg); hypre_ParCSRCommPkgRecvProcs(tmp_comm_pkg) = hypre_ParCSRCommPkgRecvProcs(comm_pkg); hypre_ParCSRCommPkgSendMapStarts(tmp_comm_pkg) = tmp_send_map_starts; hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; /*-------------------------------------------------------------------------- * after communication exchange S_ext_i[j+1] contains the number of coarse elements * of a row j ! * evaluate S_ext_i and compute num_nonzeros for S_ext *--------------------------------------------------------------------------*/ for (i=0; i < recv_vec_starts[num_recvs]; i++) S_ext_i[i+1] += S_ext_i[i]; num_nonzeros = S_ext_i[recv_vec_starts[num_recvs]]; if (num_nonzeros) S_ext_j = hypre_TAlloc(HYPRE_Int, num_nonzeros); tmp_recv_vec_starts[0] = 0; for (i=0; i < num_recvs; i++) tmp_recv_vec_starts[i+1] = S_ext_i[recv_vec_starts[i+1]]; hypre_ParCSRCommPkgRecvVecStarts(tmp_comm_pkg) = tmp_recv_vec_starts; comm_handle = hypre_ParCSRCommHandleCreate(11,tmp_comm_pkg,S_int_j,S_ext_j); hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; hypre_TFree(tmp_send_map_starts); hypre_TFree(tmp_recv_vec_starts); hypre_TFree(tmp_comm_pkg); hypre_TFree(S_int_i); hypre_TFree(S_int_j); #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] -= hypre_MPI_Wtime(); #endif #ifdef HYPRE_CONCURRENT_HOPSCOTCH S_ext_diag_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_S+1); S_ext_diag_i[0] = 0; S_ext_offd_i = hypre_TAlloc(HYPRE_Int, num_cols_offd_S+1); S_ext_offd_i[0] = 0; /*HYPRE_Int temp_size = 0;*/ hypre_UnorderedIntSet found_set; hypre_UnorderedIntSetCreate(&found_set, S_ext_i[num_cols_offd_S] + num_cols_offd_S, 16*hypre_NumThreads()); #pragma omp parallel private(i,j) { HYPRE_Int S_ext_offd_size_private = 0; HYPRE_Int S_ext_diag_size_private = 0; HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_S); for (i = i_begin; i < i_end; i++) { if (CF_marker_offd[i] > 0) { hypre_UnorderedIntSetPut(&found_set, fine_to_coarse_offd[i]); } for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { HYPRE_Int i1 = S_ext_j[j]; if (i1 < my_first_cpt || i1 > my_last_cpt) { S_ext_offd_size_private++; hypre_UnorderedIntSetPut(&found_set, i1); } else S_ext_diag_size_private++; } } hypre_prefix_sum_pair( &S_ext_diag_size_private, &S_ext_diag_size, &S_ext_offd_size_private, &S_ext_offd_size, prefix_sum_workspace); #pragma omp master { if (S_ext_diag_size) S_ext_diag_j = hypre_TAlloc(HYPRE_Int, S_ext_diag_size); if (S_ext_offd_size) S_ext_offd_j = hypre_TAlloc(HYPRE_Int, S_ext_offd_size); } #pragma omp barrier for (i = i_begin; i < i_end; i++) { for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { HYPRE_Int i1 = S_ext_j[j]; if (i1 < my_first_cpt || i1 > my_last_cpt) S_ext_offd_j[S_ext_offd_size_private++] = i1; else S_ext_diag_j[S_ext_diag_size_private++] = i1 - my_first_cpt; } S_ext_diag_i[i + 1] = S_ext_diag_size_private; S_ext_offd_i[i + 1] = S_ext_offd_size_private; } } // omp parallel temp = hypre_UnorderedIntSetCopyToArray(&found_set, &num_cols_offd_C); hypre_UnorderedIntSetDestroy( &found_set); hypre_TFree(S_ext_i); hypre_TFree(S_ext_j); hypre_UnorderedIntMap col_map_offd_C_inverse; hypre_sort_and_create_inverse_map(temp, num_cols_offd_C, &col_map_offd_C, &col_map_offd_C_inverse); #pragma omp parallel for HYPRE_SMP_SCHEDULE for (i=0 ; i < S_ext_offd_size; i++) S_ext_offd_j[i] = hypre_UnorderedIntMapGet(&col_map_offd_C_inverse, S_ext_offd_j[i]); if (num_cols_offd_C) hypre_UnorderedIntMapDestroy(&col_map_offd_C_inverse); #else /* !HYPRE_CONCURRENT_HOPSCOTCH */ HYPRE_Int cnt_offd, cnt_diag, cnt, value; S_ext_diag_size = 0; S_ext_offd_size = 0; for (i=0; i < num_cols_offd_S; i++) { for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { if (S_ext_j[j] < my_first_cpt || S_ext_j[j] > my_last_cpt) S_ext_offd_size++; else S_ext_diag_size++; } } S_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S+1); S_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_cols_offd_S+1); if (S_ext_diag_size) { S_ext_diag_j = hypre_CTAlloc(HYPRE_Int, S_ext_diag_size); } if (S_ext_offd_size) { S_ext_offd_j = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size); } cnt_offd = 0; cnt_diag = 0; cnt = 0; HYPRE_Int num_coarse_offd = 0; for (i=0; i < num_cols_offd_S; i++) { if (CF_marker_offd[i] > 0) num_coarse_offd++; for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { i1 = S_ext_j[j]; if (i1 < my_first_cpt || i1 > my_last_cpt) S_ext_offd_j[cnt_offd++] = i1; else S_ext_diag_j[cnt_diag++] = i1 - my_first_cpt; } S_ext_diag_i[++cnt] = cnt_diag; S_ext_offd_i[cnt] = cnt_offd; } hypre_TFree(S_ext_i); hypre_TFree(S_ext_j); cnt = 0; if (S_ext_offd_size || num_coarse_offd) { temp = hypre_CTAlloc(HYPRE_Int, S_ext_offd_size+num_coarse_offd); for (i=0; i < S_ext_offd_size; i++) temp[i] = S_ext_offd_j[i]; cnt = S_ext_offd_size; for (i=0; i < num_cols_offd_S; i++) if (CF_marker_offd[i] > 0) temp[cnt++] = fine_to_coarse_offd[i]; } if (cnt) { hypre_qsort0(temp, 0, cnt-1); num_cols_offd_C = 1; value = temp[0]; for (i=1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) col_map_offd_C = hypre_CTAlloc(HYPRE_Int,num_cols_offd_C); for (i=0; i < num_cols_offd_C; i++) col_map_offd_C[i] = temp[i]; if (S_ext_offd_size || num_coarse_offd) hypre_TFree(temp); for (i=0 ; i < S_ext_offd_size; i++) S_ext_offd_j[i] = hypre_BinarySearch(col_map_offd_C, S_ext_offd_j[i], num_cols_offd_C); #endif /* !HYPRE_CONCURRENT_HOPSCOTCH */ if (num_cols_offd_S) { map_S_to_C = hypre_TAlloc(HYPRE_Int,num_cols_offd_S); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i) #endif { HYPRE_Int i_begin, i_end; hypre_GetSimpleThreadPartition(&i_begin, &i_end, num_cols_offd_S); HYPRE_Int cnt = 0; for (i = i_begin; i < i_end; i++) { if (CF_marker_offd[i] > 0) { cnt = hypre_LowerBound(col_map_offd_C + cnt, col_map_offd_C + num_cols_offd_C, fine_to_coarse_offd[i]) - col_map_offd_C; map_S_to_C[i] = cnt++; } else map_S_to_C[i] = -1; } } /* omp parallel */ } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RENUMBER_COLIDX] += hypre_MPI_Wtime(); #endif } /* num_procs > 1 */ /*----------------------------------------------------------------------- * Allocate and initialize some stuff. *-----------------------------------------------------------------------*/ HYPRE_Int *S_marker_array = NULL, *S_marker_offd_array = NULL; if (num_coarse) S_marker_array = hypre_TAlloc(HYPRE_Int, num_coarse*hypre_NumThreads()); if (num_cols_offd_C) S_marker_offd_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_C*hypre_NumThreads()); HYPRE_Int *C_temp_offd_j_array = NULL; HYPRE_Int *C_temp_diag_j_array = NULL; HYPRE_Int *C_temp_offd_data_array = NULL; HYPRE_Int *C_temp_diag_data_array = NULL; if (num_paths > 1) { C_temp_diag_j_array = hypre_TAlloc(HYPRE_Int, num_coarse*hypre_NumThreads()); C_temp_offd_j_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_C*hypre_NumThreads()); C_temp_diag_data_array = hypre_TAlloc(HYPRE_Int, num_coarse*hypre_NumThreads()); C_temp_offd_data_array = hypre_TAlloc(HYPRE_Int, num_cols_offd_C*hypre_NumThreads()); } C_diag_i = hypre_CTAlloc(HYPRE_Int, num_coarse+1); C_offd_i = hypre_CTAlloc(HYPRE_Int, num_coarse+1); /*----------------------------------------------------------------------- * Loop over rows of S *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i1,i2,i3,jj1,jj2,index) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int i1_begin, i1_end; hypre_GetSimpleThreadPartition(&i1_begin, &i1_end, num_cols_diag_S); HYPRE_Int *C_temp_diag_j = NULL, *C_temp_offd_j = NULL; HYPRE_Int *C_temp_diag_data = NULL, *C_temp_offd_data = NULL; if (num_paths > 1) { C_temp_diag_j = C_temp_diag_j_array + num_coarse*my_thread_num; C_temp_offd_j = C_temp_offd_j_array + num_cols_offd_C*my_thread_num; C_temp_diag_data = C_temp_diag_data_array + num_coarse*my_thread_num; C_temp_offd_data = C_temp_offd_data_array + num_cols_offd_C*my_thread_num; } HYPRE_Int *S_marker = NULL, *S_marker_offd = NULL; if (num_coarse) S_marker = S_marker_array + num_coarse*my_thread_num; if (num_cols_offd_C) S_marker_offd = S_marker_offd_array + num_cols_offd_C*my_thread_num; for (i1 = 0; i1 < num_coarse; i1++) { S_marker[i1] = -1; } for (i1 = 0; i1 < num_cols_offd_C; i1++) { S_marker_offd[i1] = -1; } // These two counters are for before filtering by num_paths HYPRE_Int jj_count_diag = 0; HYPRE_Int jj_count_offd = 0; // These two counters are for after filtering by num_paths HYPRE_Int num_nonzeros_diag = 0; HYPRE_Int num_nonzeros_offd = 0; HYPRE_Int ic_begin = num_coarse_prefix_sum[my_thread_num]; HYPRE_Int ic_end = num_coarse_prefix_sum[my_thread_num + 1]; HYPRE_Int ic; if (num_paths == 1) { for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = num_nonzeros_diag; HYPRE_Int jj_row_begin_offd = num_nonzeros_offd; C_diag_i[ic] = num_nonzeros_diag; if (num_cols_offd_C) { C_offd_i[ic] = num_nonzeros_offd; } for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; num_nonzeros_diag++; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0) { index = fine_to_coarse[i3]; if (index != ic && S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; num_nonzeros_diag++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; num_nonzeros_offd++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; num_nonzeros_offd++; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic && S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = num_nonzeros_diag; num_nonzeros_diag++; } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = num_nonzeros_offd; num_nonzeros_offd++; } } } } /* for each row */ } /* num_paths == 1 */ else { for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = jj_count_diag; HYPRE_Int jj_row_begin_offd = jj_count_offd; C_diag_i[ic] = num_nonzeros_diag; if (num_cols_offd_C) { C_offd_i[ic] = num_nonzeros_offd; } for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 2; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag] += 2; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0 && fine_to_coarse[i3] != ic) { index = fine_to_coarse[i3]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag]++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd]++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 2; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd] += 2; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic) { if (S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = jj_count_diag; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[i3] - jj_row_begin_diag]++; } } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = jj_count_offd; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[i3] - jj_row_begin_offd]++; } } } for (jj1 = jj_row_begin_diag; jj1 < jj_count_diag; jj1++) { if (C_temp_diag_data[jj1 - jj_row_begin_diag] >= num_paths) { ++num_nonzeros_diag; } C_temp_diag_data[jj1 - jj_row_begin_diag] = 0; } for (jj1 = jj_row_begin_offd; jj1 < jj_count_offd; jj1++) { if (C_temp_offd_data[jj1 - jj_row_begin_offd] >= num_paths) { ++num_nonzeros_offd; } C_temp_offd_data[jj1 - jj_row_begin_offd] = 0; } } /* for each row */ } /* num_paths > 1 */ hypre_prefix_sum_pair( &num_nonzeros_diag, &C_diag_i[num_coarse], &num_nonzeros_offd, &C_offd_i[num_coarse], prefix_sum_workspace); for (i1 = 0; i1 < num_coarse; i1++) { S_marker[i1] = -1; } for (i1 = 0; i1 < num_cols_offd_C; i1++) { S_marker_offd[i1] = -1; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #pragma omp master #endif { if (C_diag_i[num_coarse]) { C_diag_j = hypre_TAlloc(HYPRE_Int, C_diag_i[num_coarse]); } if (C_offd_i[num_coarse]) { C_offd_j = hypre_TAlloc(HYPRE_Int, C_offd_i[num_coarse]); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (ic = ic_begin; ic < ic_end - 1; ic++) { if (C_diag_i[ic+1] == C_diag_i[ic] && C_offd_i[ic+1] == C_offd_i[ic]) CF_marker[coarse_to_fine[ic]] = 2; C_diag_i[ic] += num_nonzeros_diag; C_offd_i[ic] += num_nonzeros_offd; } if (ic_begin < ic_end) { C_diag_i[ic] += num_nonzeros_diag; C_offd_i[ic] += num_nonzeros_offd; HYPRE_Int next_C_diag_i = prefix_sum_workspace[2*(my_thread_num + 1)]; HYPRE_Int next_C_offd_i = prefix_sum_workspace[2*(my_thread_num + 1) + 1]; if (next_C_diag_i == C_diag_i[ic] && next_C_offd_i == C_offd_i[ic]) CF_marker[coarse_to_fine[ic]] = 2; } if (num_paths == 1) { for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = num_nonzeros_diag; HYPRE_Int jj_row_begin_offd = num_nonzeros_offd; for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; C_diag_j[num_nonzeros_diag] = index; num_nonzeros_diag++; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0) { index = fine_to_coarse[i3]; if (index != ic && S_marker[index] < jj_row_begin_diag) { S_marker[index] = num_nonzeros_diag; C_diag_j[num_nonzeros_diag] = index; num_nonzeros_diag++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; C_offd_j[num_nonzeros_offd] = index; num_nonzeros_offd++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = num_nonzeros_offd; C_offd_j[num_nonzeros_offd] = index; num_nonzeros_offd++; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic && S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = num_nonzeros_diag; C_diag_j[num_nonzeros_diag] = i3; num_nonzeros_diag++; } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = num_nonzeros_offd; C_offd_j[num_nonzeros_offd] = i3; num_nonzeros_offd++; } } } } /* for each row */ } /* num_paths == 1 */ else { jj_count_diag = num_nonzeros_diag; jj_count_offd = num_nonzeros_offd; for (ic = ic_begin; ic < ic_end; ic++) { /*-------------------------------------------------------------------- * Set marker for diagonal entry, C_{i1,i1} (for square matrices). *--------------------------------------------------------------------*/ HYPRE_Int i1 = coarse_to_fine[ic]; HYPRE_Int jj_row_begin_diag = jj_count_diag; HYPRE_Int jj_row_begin_offd = jj_count_offd; for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1+1]; jj1++) { i2 = S_diag_j[jj1]; if (CF_marker[i2] > 0) { index = fine_to_coarse[i2]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_j[jj_count_diag - jj_row_begin_diag] = index; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 2; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag] += 2; } } for (jj2 = S_diag_i[i2]; jj2 < S_diag_i[i2+1]; jj2++) { i3 = S_diag_j[jj2]; if (CF_marker[i3] > 0 && fine_to_coarse[i3] != ic) { index = fine_to_coarse[i3]; if (S_marker[index] < jj_row_begin_diag) { S_marker[index] = jj_count_diag; C_temp_diag_j[jj_count_diag - jj_row_begin_diag] = index; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[index] - jj_row_begin_diag]++; } } } for (jj2 = S_offd_i[i2]; jj2 < S_offd_i[i2+1]; jj2++) { i3 = S_offd_j[jj2]; if (CF_marker_offd[i3] > 0) { index = map_S_to_C[i3]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_j[jj_count_offd - jj_row_begin_offd] = index; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd]++; } } } } for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1+1]; jj1++) { i2 = S_offd_j[jj1]; if (CF_marker_offd[i2] > 0) { index = map_S_to_C[i2]; if (S_marker_offd[index] < jj_row_begin_offd) { S_marker_offd[index] = jj_count_offd; C_temp_offd_j[jj_count_offd - jj_row_begin_offd] = index; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 2; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[index] - jj_row_begin_offd] += 2; } } for (jj2 = S_ext_diag_i[i2]; jj2 < S_ext_diag_i[i2+1]; jj2++) { i3 = S_ext_diag_j[jj2]; if (i3 != ic) { if (S_marker[i3] < jj_row_begin_diag) { S_marker[i3] = jj_count_diag; C_temp_diag_j[jj_count_diag - jj_row_begin_diag] = i3; C_temp_diag_data[jj_count_diag - jj_row_begin_diag] = 1; jj_count_diag++; } else { C_temp_diag_data[S_marker[i3] - jj_row_begin_diag]++; } } } for (jj2 = S_ext_offd_i[i2]; jj2 < S_ext_offd_i[i2+1]; jj2++) { i3 = S_ext_offd_j[jj2]; if (S_marker_offd[i3] < jj_row_begin_offd) { S_marker_offd[i3] = jj_count_offd; C_temp_offd_j[jj_count_offd - jj_row_begin_offd] = i3; C_temp_offd_data[jj_count_offd - jj_row_begin_offd] = 1; jj_count_offd++; } else { C_temp_offd_data[S_marker_offd[i3] - jj_row_begin_offd]++; } } } for (jj1 = jj_row_begin_diag; jj1 < jj_count_diag; jj1++) { if (C_temp_diag_data[jj1 - jj_row_begin_diag] >= num_paths) { C_diag_j[num_nonzeros_diag++] = C_temp_diag_j[jj1 - jj_row_begin_diag]; } C_temp_diag_data[jj1 - jj_row_begin_diag] = 0; } for (jj1 = jj_row_begin_offd; jj1 < jj_count_offd; jj1++) { if (C_temp_offd_data[jj1 - jj_row_begin_offd] >= num_paths) { C_offd_j[num_nonzeros_offd++] = C_temp_offd_j[jj1 - jj_row_begin_offd]; } C_temp_offd_data[jj1 - jj_row_begin_offd] = 0; } } /* for each row */ } /* num_paths > 1 */ } /* omp parallel */ S2 = hypre_ParCSRMatrixCreate(comm, global_num_coarse, global_num_coarse, coarse_row_starts, coarse_row_starts, num_cols_offd_C, C_diag_i[num_coarse], C_offd_i[num_coarse]); hypre_ParCSRMatrixOwnsRowStarts(S2) = 0; C_diag = hypre_ParCSRMatrixDiag(S2); hypre_CSRMatrixI(C_diag) = C_diag_i; if (C_diag_i[num_coarse]) hypre_CSRMatrixJ(C_diag) = C_diag_j; C_offd = hypre_ParCSRMatrixOffd(S2); hypre_CSRMatrixI(C_offd) = C_offd_i; hypre_ParCSRMatrixOffd(S2) = C_offd; if (num_cols_offd_C) { if (C_offd_i[num_coarse]) hypre_CSRMatrixJ(C_offd) = C_offd_j; hypre_ParCSRMatrixColMapOffd(S2) = col_map_offd_C; } /*----------------------------------------------------------------------- * Free various arrays *-----------------------------------------------------------------------*/ hypre_TFree(C_temp_diag_j_array); hypre_TFree(C_temp_diag_data_array); hypre_TFree(C_temp_offd_j_array); hypre_TFree(C_temp_offd_data_array); hypre_TFree(S_marker_array); hypre_TFree(S_marker_offd_array); hypre_TFree(S_marker); hypre_TFree(S_marker_offd); hypre_TFree(S_ext_diag_i); hypre_TFree(fine_to_coarse); hypre_TFree(coarse_to_fine); if (S_ext_diag_size) { hypre_TFree(S_ext_diag_j); } hypre_TFree(S_ext_offd_i); if (S_ext_offd_size) { hypre_TFree(S_ext_offd_j); } if (num_cols_offd_S) { hypre_TFree(map_S_to_C); hypre_TFree(CF_marker_offd); hypre_TFree(fine_to_coarse_offd); } *C_ptr = S2; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_CREATE_2NDS] += hypre_MPI_Wtime(); #endif hypre_TFree(prefix_sum_workspace); hypre_TFree(num_coarse_prefix_sum); return 0; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGCorrectCFMarker : corrects CF_marker after aggr. coarsening *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCorrectCFMarker(HYPRE_Int *CF_marker, HYPRE_Int num_var, HYPRE_Int *new_CF_marker) { HYPRE_Int i, cnt; cnt = 0; for (i=0; i < num_var; i++) { if (CF_marker[i] > 0 ) { if (CF_marker[i] == 1) CF_marker[i] = new_CF_marker[cnt++]; else { CF_marker[i] = 1; cnt++;} } } return 0; } /*-------------------------------------------------------------------------- * hypre_BoomerAMGCorrectCFMarker2 : corrects CF_marker after aggr. coarsening, * but marks new F-points (previous C-points) as -2 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCorrectCFMarker2(HYPRE_Int *CF_marker, HYPRE_Int num_var, HYPRE_Int *new_CF_marker) { HYPRE_Int i, cnt; cnt = 0; for (i=0; i < num_var; i++) { if (CF_marker[i] > 0 ) { if (new_CF_marker[cnt] == -1) CF_marker[i] = -2; else CF_marker[i] = 1; cnt++; } } return 0; }
effect.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % EEEEE FFFFF FFFFF EEEEE CCCC TTTTT % % E F F E C T % % EEE FFF FFF EEE C T % % E F F E C T % % EEEEE F F EEEEE CCCC T % % % % % % MagickCore Image Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % 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 "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/distort.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/matrix.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/morphology.h" #include "magick/morphology-private.h" #include "magick/opencl-private.h" #include "magick/paint.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resample.h" #include "magick/resample-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/transform.h" #include "magick/threshold.h" #ifdef MAGICKCORE_CLPERFMARKER #include "CLPerfMarker.h" #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveBlurImage() adaptively blurs the image by blurring less % intensely near image edges and more intensely far from edges. We blur the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveBlurImage() selects a suitable radius for you. % % The format of the AdaptiveBlurImage method is: % % Image *AdaptiveBlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *AdaptiveBlurImageChannel(const Image *image, % const ChannelType channel,double radius,const double sigma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *blur_image; blur_image=AdaptiveBlurImageChannel(image,DefaultChannels,radius,sigma, exception); return(blur_image); } MagickExport Image *AdaptiveBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { #define AdaptiveBlurImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *blur_view, *edge_view, *image_view; double **kernel, normalize; Image *blur_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; register ssize_t i; size_t width; ssize_t j, k, u, v, y; 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); blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) <= MagickEpsilon) return(blur_image); if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } /* Edge detect the image brighness channel, level, blur, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { blur_image=DestroyImage(blur_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, sizeof(*kernel))); if (kernel == (double **) NULL) { edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (double *) NULL) break; normalize=0.0; j=(ssize_t) (width-i-1)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(double) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(k-1)/2]+=(1.0-normalize); if (sigma < MagickEpsilon) kernel[i][(k-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively blur image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,blur_image->rows,1) #endif for (y=0; y < (ssize_t) blur_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict blur_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((r == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) blur_image->columns; x++) { double alpha, gamma; DoublePixelPacket pixel; register const double *magick_restrict k; register ssize_t i, u, v; gamma=0.0; i=(ssize_t) ceil((double) width*QuantumScale* GetPixelIntensity(edge_image,r)-0.5); if (i < 0) i=0; else if (i > (ssize_t) width) i=(ssize_t) width; if ((i & 0x01) != 0) i--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-i)/2L),y- (ssize_t) ((width-i)/2L),width-i,width-i,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; k=kernel[i]; for (v=0; v < (ssize_t) (width-i); v++) { for (u=0; u < (ssize_t) (width-i); u++) { alpha=1.0; if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p)); if ((channel & RedChannel) != 0) pixel.red+=(*k)*alpha*GetPixelRed(p); if ((channel & GreenChannel) != 0) pixel.green+=(*k)*alpha*GetPixelGreen(p); if ((channel & BlueChannel) != 0) pixel.blue+=(*k)*alpha*GetPixelBlue(p); if ((channel & OpacityChannel) != 0) pixel.opacity+=(*k)*GetPixelOpacity(p); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+(width-i)*v+u); gamma+=(*k)*alpha; k++; p++; } } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index)); q++; r++; } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveBlurImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveSharpenImage() adaptively sharpens the image by sharpening more % intensely near image edges and less intensely far from edges. We sharpen the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and AdaptiveSharpenImage() selects a suitable radius for you. % % The format of the AdaptiveSharpenImage method is: % % Image *AdaptiveSharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *AdaptiveSharpenImageChannel(const Image *image, % const ChannelType channel,double radius,const double sigma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveSharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *sharp_image; sharp_image=AdaptiveSharpenImageChannel(image,DefaultChannels,radius,sigma, exception); return(sharp_image); } MagickExport Image *AdaptiveSharpenImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { #define AdaptiveSharpenImageTag "Convolve/Image" #define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma) CacheView *sharp_view, *edge_view, *image_view; double **kernel, normalize; Image *sharp_image, *edge_image, *gaussian_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; register ssize_t i; size_t width; ssize_t j, k, u, v, y; 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); sharp_image=CloneImage(image,0,0,MagickTrue,exception); if (sharp_image == (Image *) NULL) return((Image *) NULL); if (fabs(sigma) <= MagickEpsilon) return(sharp_image); if (SetImageStorageClass(sharp_image,DirectClass) == MagickFalse) { InheritException(exception,&sharp_image->exception); sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } /* Edge detect the image brighness channel, level, sharp, and level again. */ edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) { sharp_image=DestroyImage(sharp_image); return((Image *) NULL); } (void) AutoLevelImage(edge_image); gaussian_image=BlurImage(edge_image,radius,sigma,exception); if (gaussian_image != (Image *) NULL) { edge_image=DestroyImage(edge_image); edge_image=gaussian_image; } (void) AutoLevelImage(edge_image); /* Create a set of kernels from maximum (radius,sigma) to minimum. */ width=GetOptimalKernelWidth2D(radius,sigma); kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, sizeof(*kernel))); if (kernel == (double **) NULL) { edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } (void) memset(kernel,0,(size_t) width*sizeof(*kernel)); for (i=0; i < (ssize_t) width; i+=2) { kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) (width-i),(width-i)*sizeof(**kernel))); if (kernel[i] == (double *) NULL) break; normalize=0.0; j=(ssize_t) (width-i-1)/2; k=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel[i][k]=(double) (-exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel[i][k]; k++; } } kernel[i][(k-1)/2]=(double) ((-2.0)*normalize); if (sigma < MagickEpsilon) kernel[i][(k-1)/2]=1.0; } if (i < (ssize_t) width) { for (i-=2; i >= 0; i-=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); edge_image=DestroyImage(edge_image); sharp_image=DestroyImage(sharp_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Adaptively sharpen image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); edge_view=AcquireVirtualCacheView(edge_image,exception); sharp_view=AcquireAuthenticCacheView(sharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,sharp_image,sharp_image->rows,1) #endif for (y=0; y < (ssize_t) sharp_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict sharp_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(sharp_view,0,y,sharp_image->columns,1, exception); if ((r == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } sharp_indexes=GetCacheViewAuthenticIndexQueue(sharp_view); for (x=0; x < (ssize_t) sharp_image->columns; x++) { double alpha, gamma; DoublePixelPacket pixel; register const double *magick_restrict k; register ssize_t i, u, v; gamma=0.0; i=(ssize_t) ceil((double) width*(1.0-QuantumScale* GetPixelIntensity(edge_image,r))-0.5); if (i < 0) i=0; else if (i > (ssize_t) width) i=(ssize_t) width; if ((i & 0x01) != 0) i--; p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-i)/2L),y- (ssize_t) ((width-i)/2L),width-i,width-i,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); k=kernel[i]; pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; for (v=0; v < (ssize_t) (width-i); v++) { for (u=0; u < (ssize_t) (width-i); u++) { alpha=1.0; if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p)); if ((channel & RedChannel) != 0) pixel.red+=(*k)*alpha*GetPixelRed(p); if ((channel & GreenChannel) != 0) pixel.green+=(*k)*alpha*GetPixelGreen(p); if ((channel & BlueChannel) != 0) pixel.blue+=(*k)*alpha*GetPixelBlue(p); if ((channel & OpacityChannel) != 0) pixel.opacity+=(*k)*GetPixelOpacity(p); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+(width-i)*v+u); gamma+=(*k)*alpha; k++; p++; } } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(sharp_indexes+x,ClampToQuantum(gamma*pixel.index)); q++; r++; } if (SyncCacheViewAuthenticPixels(sharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AdaptiveSharpenImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sharp_image->type=image->type; sharp_view=DestroyCacheView(sharp_view); edge_view=DestroyCacheView(edge_view); image_view=DestroyCacheView(image_view); edge_image=DestroyImage(edge_image); for (i=0; i < (ssize_t) width; i+=2) kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]); kernel=(double **) RelinquishAlignedMemory(kernel); if (status == MagickFalse) sharp_image=DestroyImage(sharp_image); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlurImage() blurs an image. We convolve the image with a Gaussian operator % of the given radius and standard deviation (sigma). For reasonable results, % the radius should be larger than sigma. Use a radius of 0 and BlurImage() % selects a suitable radius for you. % % The format of the BlurImage method is: % % Image *BlurImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *BlurImageChannel(const Image *image,const ChannelType channel, % const double radius,const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *blur_image; blur_image=BlurImageChannel(image,DefaultChannels,radius,sigma,exception); return(blur_image); } MagickExport Image *BlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { char geometry[MaxTextExtent]; KernelInfo *kernel_info; Image *blur_image = NULL; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) blur_image=AccelerateBlurImage(image,channel,radius,sigma,exception); if (blur_image != (Image *) NULL) return(blur_image); #endif (void) FormatLocaleString(geometry,MaxTextExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o n v o l v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConvolveImage() applies a custom convolution kernel to the image. % % The format of the ConvolveImage method is: % % Image *ConvolveImage(const Image *image,const size_t order, % const double *kernel,ExceptionInfo *exception) % Image *ConvolveImageChannel(const Image *image,const ChannelType channel, % const size_t order,const double *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o order: the number of columns and rows in the filter kernel. % % o kernel: An array of double representing the convolution kernel. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ConvolveImage(const Image *image,const size_t order, const double *kernel,ExceptionInfo *exception) { Image *convolve_image; #ifdef MAGICKCORE_CLPERFMARKER clBeginPerfMarkerAMD(__FUNCTION__,""); #endif convolve_image=ConvolveImageChannel(image,DefaultChannels,order,kernel, exception); #ifdef MAGICKCORE_CLPERFMARKER clEndPerfMarkerAMD(); #endif return(convolve_image); } MagickExport Image *ConvolveImageChannel(const Image *image, const ChannelType channel,const size_t order,const double *kernel, ExceptionInfo *exception) { Image *convolve_image; KernelInfo *kernel_info; register ssize_t i; kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); kernel_info->width=order; kernel_info->height=order; kernel_info->x=(ssize_t) (order-1)/2; kernel_info->y=(ssize_t) (order-1)/2; kernel_info->signature=MagickCoreSignature; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->width*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (order*order); i++) kernel_info->values[i]=kernel[i]; convolve_image=(Image *) NULL; #if defined(MAGICKCORE_OPENCL_SUPPORT) convolve_image=AccelerateConvolveImageChannel(image,channel,kernel_info, exception); #endif if (convolve_image == (Image *) NULL) convolve_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(convolve_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s p e c k l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DespeckleImage() reduces the speckle noise in an image while perserving the % edges of the original image. A speckle removing filter uses a complementary % hulling technique (raising pixels that are darker than their surrounding % neighbors, then complementarily lowering pixels that are brighter than their % surrounding neighbors) to reduce the speckle index of that image (reference % Crimmins speckle removal). % % The format of the DespeckleImage method is: % % Image *DespeckleImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static void Hull(const Image *image,const ssize_t x_offset, const ssize_t y_offset,const size_t columns,const size_t rows, const int polarity,Quantum *magick_restrict f,Quantum *magick_restrict g) { register Quantum *p, *q, *r, *s; ssize_t y; assert(f != (Quantum *) NULL); assert(g != (Quantum *) NULL); p=f+(columns+2); q=g+(columns+2); r=p+(y_offset*((ssize_t) columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { register ssize_t i, x; SignedQuantum v; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) p[i]; if ((SignedQuantum) r[i] >= (v+ScaleCharToQuantum(2))) v+=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) p[i]; if ((SignedQuantum) r[i] <= (v-ScaleCharToQuantum(2))) v-=ScaleCharToQuantum(1); q[i]=(Quantum) v; i++; } } p=f+(columns+2); q=g+(columns+2); r=q+(y_offset*((ssize_t) columns+2)+x_offset); s=q-(y_offset*((ssize_t) columns+2)+x_offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { register ssize_t i, x; SignedQuantum v; i=(2*y+1)+y*columns; if (polarity > 0) for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) q[i]; if (((SignedQuantum) s[i] >= (v+ScaleCharToQuantum(2))) && ((SignedQuantum) r[i] > v)) v+=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } else for (x=0; x < (ssize_t) columns; x++) { v=(SignedQuantum) q[i]; if (((SignedQuantum) s[i] <= (v-ScaleCharToQuantum(2))) && ((SignedQuantum) r[i] < v)) v-=ScaleCharToQuantum(1); p[i]=(Quantum) v; i++; } } } MagickExport Image *DespeckleImage(const Image *image,ExceptionInfo *exception) { #define DespeckleImageTag "Despeckle/Image" CacheView *despeckle_view, *image_view; Image *despeckle_image; MagickBooleanType status; MemoryInfo *buffer_info, *pixel_info; register ssize_t i; Quantum *magick_restrict buffer, *magick_restrict pixels; size_t length, number_channels; static const ssize_t X[4] = {0, 1, 1,-1}, Y[4] = {1, 0, 1, 1}; /* Allocate despeckled 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 defined(MAGICKCORE_OPENCL_SUPPORT) despeckle_image=AccelerateDespeckleImage(image, exception); if (despeckle_image != (Image *) NULL) return(despeckle_image); #endif despeckle_image=CloneImage(image,0,0,MagickTrue,exception); if (despeckle_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(despeckle_image,DirectClass) == MagickFalse) { InheritException(exception,&despeckle_image->exception); despeckle_image=DestroyImage(despeckle_image); return((Image *) NULL); } /* Allocate image buffer. */ length=(size_t) ((image->columns+2)*(image->rows+2)); pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); buffer_info=AcquireVirtualMemory(length,sizeof(*buffer)); if ((pixel_info == (MemoryInfo *) NULL) || (buffer_info == (MemoryInfo *) NULL)) { if (buffer_info != (MemoryInfo *) NULL) buffer_info=RelinquishVirtualMemory(buffer_info); if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image=DestroyImage(despeckle_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(Quantum *) GetVirtualMemoryBlob(pixel_info); buffer=(Quantum *) GetVirtualMemoryBlob(buffer_info); /* Reduce speckle in the image. */ status=MagickTrue; number_channels=(size_t) (image->colorspace == CMYKColorspace ? 5 : 4); image_view=AcquireVirtualCacheView(image,exception); despeckle_view=AcquireAuthenticCacheView(despeckle_image,exception); for (i=0; i < (ssize_t) number_channels; i++) { register ssize_t k, x; ssize_t j, y; if (status == MagickFalse) continue; if ((image->matte == MagickFalse) && (i == 3)) continue; (void) memset(pixels,0,length*sizeof(*pixels)); j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); j++; for (x=0; x < (ssize_t) image->columns; x++) { switch (i) { case 0: pixels[j]=GetPixelRed(p); break; case 1: pixels[j]=GetPixelGreen(p); break; case 2: pixels[j]=GetPixelBlue(p); break; case 3: pixels[j]=GetPixelOpacity(p); break; case 4: pixels[j]=GetPixelBlack(indexes+x); break; default: break; } p++; j++; } j++; } (void) memset(buffer,0,length*sizeof(*buffer)); for (k=0; k < 4; k++) { Hull(image,X[k],Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,1,pixels,buffer); Hull(image,-X[k],-Y[k],image->columns,image->rows,-1,pixels,buffer); Hull(image,X[k],Y[k],image->columns,image->rows,-1,pixels,buffer); } j=(ssize_t) image->columns+2; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; q=GetCacheViewAuthenticPixels(despeckle_view,0,y,despeckle_image->columns, 1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(despeckle_view); j++; for (x=0; x < (ssize_t) image->columns; x++) { switch (i) { case 0: SetPixelRed(q,pixels[j]); break; case 1: SetPixelGreen(q,pixels[j]); break; case 2: SetPixelBlue(q,pixels[j]); break; case 3: SetPixelOpacity(q,pixels[j]); break; case 4: SetPixelIndex(indexes+x,pixels[j]); break; default: break; } q++; j++; } sync=SyncCacheViewAuthenticPixels(despeckle_view,exception); if (sync == MagickFalse) { status=MagickFalse; break; } j++; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DespeckleImageTag,(MagickOffsetType) i, number_channels); if (proceed == MagickFalse) status=MagickFalse; } } despeckle_view=DestroyCacheView(despeckle_view); image_view=DestroyCacheView(image_view); buffer_info=RelinquishVirtualMemory(buffer_info); pixel_info=RelinquishVirtualMemory(pixel_info); despeckle_image->type=image->type; if (status == MagickFalse) despeckle_image=DestroyImage(despeckle_image); return(despeckle_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EdgeImage() finds edges in an image. Radius defines the radius of the % convolution filter. Use a radius of 0 and EdgeImage() selects a suitable % radius for you. % % The format of the EdgeImage method is: % % Image *EdgeImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EdgeImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *edge_image; KernelInfo *kernel_info; register ssize_t i; size_t width; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth1D(radius,0.5); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (kernel_info->width-1)/2; kernel_info->y=(ssize_t) (kernel_info->height-1)/2; kernel_info->signature=MagickCoreSignature; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->height*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]=(-1.0); kernel_info->values[i/2]=(double) kernel_info->width*kernel_info->height-1.0; edge_image=(Image *) NULL; #if defined(MAGICKCORE_OPENCL_SUPPORT) edge_image=AccelerateConvolveImageChannel(image,DefaultChannels,kernel_info, exception); #endif if (edge_image == (Image *) NULL) edge_image=MorphologyImageChannel(image,DefaultChannels,ConvolveMorphology, 1,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E m b o s s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EmbossImage() returns a grayscale image with a three-dimensional effect. % We convolve the image with a Gaussian operator of the given radius and % standard deviation (sigma). For reasonable results, radius should be % larger than sigma. Use a radius of 0 and Emboss() selects a suitable % radius for you. % % The format of the EmbossImage method is: % % Image *EmbossImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *EmbossImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { double gamma, normalize; Image *emboss_image; KernelInfo *kernel_info; register ssize_t i; size_t width; ssize_t j, k, u, v; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth1D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->width*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } j=(ssize_t) (kernel_info->width-1)/2; k=j; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(double) (((u < 0) || (v < 0) ? -8.0 : 8.0)*exp(-((double) u*u+v*v)/(2.0*MagickSigma*MagickSigma))/ (2.0*MagickPI*MagickSigma*MagickSigma)); if (u != k) kernel_info->values[i]=0.0; i++; } k--; } normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; emboss_image=(Image *) NULL; #if defined(MAGICKCORE_OPENCL_SUPPORT) emboss_image=AccelerateConvolveImageChannel(image,DefaultChannels,kernel_info, exception); #endif if (emboss_image == (Image *) NULL) emboss_image=MorphologyImageChannel(image,DefaultChannels, ConvolveMorphology,1,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (emboss_image != (Image *) NULL) (void) EqualizeImageChannel(emboss_image,(ChannelType) (AllChannels &~ SyncChannels)); return(emboss_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F i l t e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FilterImage() applies a custom convolution kernel to the image. % % The format of the FilterImage method is: % % Image *FilterImage(const Image *image,const KernelInfo *kernel, % ExceptionInfo *exception) % Image *FilterImageChannel(const Image *image,const ChannelType channel, % const KernelInfo *kernel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o kernel: the filtering kernel. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *FilterImage(const Image *image,const KernelInfo *kernel, ExceptionInfo *exception) { Image *filter_image; filter_image=FilterImageChannel(image,DefaultChannels,kernel,exception); return(filter_image); } MagickExport Image *FilterImageChannel(const Image *image, const ChannelType channel,const KernelInfo *kernel,ExceptionInfo *exception) { #define FilterImageTag "Filter/Image" CacheView *filter_view, *image_view; Image *filter_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; MagickRealType *filter_kernel; register ssize_t i; ssize_t y; #ifdef MAGICKCORE_CLPERFMARKER clBeginPerfMarkerAMD(__FUNCTION__,""); #endif /* Initialize filter image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((kernel->width % 2) == 0) ThrowImageException(OptionError,"KernelWidthMustBeAnOddNumber"); if (image->debug != MagickFalse) { char format[MaxTextExtent], *message; register const double *k; ssize_t u, v; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " FilterImage with %.20gx%.20g kernel:",(double) kernel->width,(double) kernel->height); message=AcquireString(""); k=kernel->values; for (v=0; v < (ssize_t) kernel->height; v++) { *message='\0'; (void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < (ssize_t) kernel->width; u++) { (void) FormatLocaleString(format,MaxTextExtent,"%g ",*k++); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } #if defined(MAGICKCORE_OPENCL_SUPPORT) filter_image=AccelerateConvolveImageChannel(image,channel,kernel,exception); if (filter_image != (Image *) NULL) { #ifdef MAGICKCORE_CLPERFMARKER clEndPerfMarkerAMD(); #endif return(filter_image); } #endif filter_image=CloneImage(image,0,0,MagickTrue,exception); if (filter_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(filter_image,DirectClass) == MagickFalse) { InheritException(exception,&filter_image->exception); filter_image=DestroyImage(filter_image); return((Image *) NULL); } /* Normalize kernel. */ filter_kernel=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory( kernel->width,kernel->height*sizeof(*filter_kernel))); if (filter_kernel == (MagickRealType *) NULL) { filter_image=DestroyImage(filter_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++) filter_kernel[i]=(MagickRealType) kernel->values[i]; /* Filter image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); filter_view=AcquireAuthenticCacheView(filter_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,filter_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict filter_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (kernel->width-1)/2L),y- (ssize_t) ((kernel->height-1)/2L),image->columns+kernel->width, kernel->height,exception); q=GetCacheViewAuthenticPixels(filter_view,0,y,filter_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); filter_indexes=GetCacheViewAuthenticIndexQueue(filter_view); for (x=0; x < (ssize_t) image->columns; x++) { DoublePixelPacket pixel; register const MagickRealType *magick_restrict k; register const PixelPacket *magick_restrict kernel_pixels; register ssize_t u; ssize_t v; pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; k=filter_kernel; kernel_pixels=p; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.red+=(*k)*kernel_pixels[u].red; pixel.green+=(*k)*kernel_pixels[u].green; pixel.blue+=(*k)*kernel_pixels[u].blue; k++; } kernel_pixels+=image->columns+kernel->width; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) { k=filter_kernel; kernel_pixels=p; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.opacity+=(*k)*kernel_pixels[u].opacity; k++; } kernel_pixels+=image->columns+kernel->width; } SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { register const IndexPacket *magick_restrict kernel_indexes; k=filter_kernel; kernel_indexes=indexes; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.index+=(*k)*GetPixelIndex(kernel_indexes+u); k++; } kernel_indexes+=image->columns+kernel->width; } SetPixelIndex(filter_indexes+x,ClampToQuantum(pixel.index)); } } else { double alpha, gamma; gamma=0.0; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { alpha=(MagickRealType) (QuantumScale*(QuantumRange- GetPixelOpacity(kernel_pixels+u))); pixel.red+=(*k)*alpha*GetPixelRed(kernel_pixels+u); pixel.green+=(*k)*alpha*GetPixelGreen(kernel_pixels+u); pixel.blue+=(*k)*alpha*GetPixelBlue(kernel_pixels+u); gamma+=(*k)*alpha; k++; } kernel_pixels+=image->columns+kernel->width; } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); if ((channel & OpacityChannel) != 0) { k=filter_kernel; kernel_pixels=p; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { pixel.opacity+=(*k)*GetPixelOpacity(kernel_pixels+u); k++; } kernel_pixels+=image->columns+kernel->width; } SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { register const IndexPacket *magick_restrict kernel_indexes; k=filter_kernel; kernel_pixels=p; kernel_indexes=indexes; for (v=0; v < (ssize_t) kernel->width; v++) { for (u=0; u < (ssize_t) kernel->height; u++) { alpha=(MagickRealType) (QuantumScale*(QuantumRange- kernel_pixels[u].opacity)); pixel.index+=(*k)*alpha*GetPixelIndex(kernel_indexes+u); k++; } kernel_pixels+=image->columns+kernel->width; kernel_indexes+=image->columns+kernel->width; } SetPixelIndex(filter_indexes+x,ClampToQuantum(gamma*pixel.index)); } } indexes++; p++; q++; } sync=SyncCacheViewAuthenticPixels(filter_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,FilterImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } filter_image->type=image->type; filter_view=DestroyCacheView(filter_view); image_view=DestroyCacheView(image_view); filter_kernel=(MagickRealType *) RelinquishAlignedMemory(filter_kernel); if (status == MagickFalse) filter_image=DestroyImage(filter_image); #ifdef MAGICKCORE_CLPERFMARKER clEndPerfMarkerAMD(); #endif return(filter_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G a u s s i a n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GaussianBlurImage() blurs an image. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, the radius should be larger than sigma. Use a % radius of 0 and GaussianBlurImage() selects a suitable radius for you % % The format of the GaussianBlurImage method is: % % Image *GaussianBlurImage(const Image *image,onst double radius, % const double sigma,ExceptionInfo *exception) % Image *GaussianBlurImageChannel(const Image *image, % const ChannelType channel,const double radius,const double sigma, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GaussianBlurImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *blur_image; blur_image=GaussianBlurImageChannel(image,DefaultChannels,radius,sigma, exception); return(blur_image); } MagickExport Image *GaussianBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { char geometry[MaxTextExtent]; KernelInfo *kernel_info; Image *blur_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); (void) FormatLocaleString(geometry,MaxTextExtent,"gaussian:%.20gx%.20g", radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); blur_image=(Image *) NULL; #if defined(MAGICKCORE_OPENCL_SUPPORT) blur_image=AccelerateConvolveImageChannel(image,channel,kernel_info, exception); #endif if (blur_image == (Image *) NULL) blur_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o t i o n B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MotionBlurImage() simulates motion blur. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). % For reasonable results, radius should be larger than sigma. Use a % radius of 0 and MotionBlurImage() selects a suitable radius for you. % Angle gives the angle of the blurring motion. % % Andrew Protano contributed this effect. % % The format of the MotionBlurImage method is: % % Image *MotionBlurImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % Image *MotionBlurImageChannel(const Image *image,const ChannelType channel, % const double radius,const double sigma,const double angle, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: Apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ static double *GetMotionBlurKernel(const size_t width,const double sigma) { double *kernel, normalize; register ssize_t i; /* Generate a 1-D convolution kernel. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); kernel=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, sizeof(*kernel))); if (kernel == (double *) NULL) return(kernel); normalize=0.0; for (i=0; i < (ssize_t) width; i++) { kernel[i]=(double) (exp((-((double) i*i)/(double) (2.0*MagickSigma* MagickSigma)))/(MagickSQ2PI*MagickSigma)); normalize+=kernel[i]; } for (i=0; i < (ssize_t) width; i++) kernel[i]/=normalize; return(kernel); } MagickExport Image *MotionBlurImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { Image *motion_blur; motion_blur=MotionBlurImageChannel(image,DefaultChannels,radius,sigma,angle, exception); return(motion_blur); } MagickExport Image *MotionBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double angle,ExceptionInfo *exception) { #define BlurImageTag "Blur/Image" CacheView *blur_view, *image_view; double *kernel; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; OffsetInfo *offset; PointInfo point; register ssize_t i; size_t width; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); width=GetOptimalKernelWidth1D(radius,sigma); kernel=GetMotionBlurKernel(width,sigma); if (kernel == (double *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); offset=(OffsetInfo *) AcquireQuantumMemory(width,sizeof(*offset)); if (offset == (OffsetInfo *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } point.x=(double) width*sin(DegreesToRadians(angle)); point.y=(double) width*cos(DegreesToRadians(angle)); for (i=0; i < (ssize_t) width; i++) { offset[i].x=(ssize_t) ceil((double) (i*point.y)/hypot(point.x,point.y)-0.5); offset[i].y=(ssize_t) ceil((double) (i*point.x)/hypot(point.x,point.y)-0.5); } /* Motion blur image. */ #if defined(MAGICKCORE_OPENCL_SUPPORT) blur_image=AccelerateMotionBlurImage(image,channel,kernel,width,offset, exception); if (blur_image != (Image *) NULL) return blur_image; #endif blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); return((Image *) NULL); } if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { kernel=(double *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); image_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict blur_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket qixel; PixelPacket pixel; register const IndexPacket *magick_restrict indexes; register double *magick_restrict k; register ssize_t i; k=kernel; qixel=bias; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (i=0; i < (ssize_t) width; i++) { (void) GetOneCacheViewVirtualPixel(image_view,x+offset[i].x,y+ offset[i].y,&pixel,exception); qixel.red+=(*k)*pixel.red; qixel.green+=(*k)*pixel.green; qixel.blue+=(*k)*pixel.blue; qixel.opacity+=(*k)*pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=(*k)*(*indexes); } k++; } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(qixel.index)); } else { double alpha, gamma; alpha=0.0; gamma=0.0; for (i=0; i < (ssize_t) width; i++) { (void) GetOneCacheViewVirtualPixel(image_view,x+offset[i].x,y+ offset[i].y,&pixel,exception); alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(&pixel)); qixel.red+=(*k)*alpha*pixel.red; qixel.green+=(*k)*alpha*pixel.green; qixel.blue+=(*k)*alpha*pixel.blue; qixel.opacity+=(*k)*pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=(*k)*alpha*GetPixelIndex(indexes); } gamma+=(*k)*alpha; k++; } gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*qixel.index)); } q++; } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BlurImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); image_view=DestroyCacheView(image_view); kernel=(double *) RelinquishAlignedMemory(kernel); offset=(OffsetInfo *) RelinquishMagickMemory(offset); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % K u w a h a r a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % KuwaharaImage() is an edge preserving noise reduction filter. % % The format of the KuwaharaImage method is: % % Image *KuwaharaImage(const Image *image,const double width, % const double sigma,ExceptionInfo *exception) % Image *KuwaharaImageChannel(const Image *image,const ChannelType channel, % const double width,const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the square window radius. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *KuwaharaImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *kuwahara_image; kuwahara_image=KuwaharaImageChannel(image,DefaultChannels,radius,sigma, exception); return(kuwahara_image); } MagickExport Image *KuwaharaImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { #define KuwaharaImageTag "Kiwahara/Image" CacheView *image_view, *kuwahara_view; Image *gaussian_image, *kuwahara_image; MagickBooleanType status; MagickOffsetType progress; size_t width; ssize_t y; /* Initialize Kuwahara image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); (void) channel; width=(size_t) radius+1; gaussian_image=BlurImage(image,radius,sigma,exception); if (gaussian_image == (Image *) NULL) return((Image *) NULL); kuwahara_image=CloneImage(image,0,0,MagickTrue,exception); if (kuwahara_image == (Image *) NULL) { gaussian_image=DestroyImage(gaussian_image); return((Image *) NULL); } if (SetImageStorageClass(kuwahara_image,DirectClass) == MagickFalse) { InheritException(exception,&kuwahara_image->exception); gaussian_image=DestroyImage(gaussian_image); kuwahara_image=DestroyImage(kuwahara_image); return((Image *) NULL); } /* Edge preserving noise reduction filter. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(gaussian_image,exception); kuwahara_view=AcquireAuthenticCacheView(kuwahara_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,kuwahara_image,kuwahara_image->rows,1) #endif for (y=0; y < (ssize_t) kuwahara_image->rows; y++) { register IndexPacket *magick_restrict kuwahara_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(kuwahara_view,0,y,kuwahara_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } kuwahara_indexes=GetCacheViewAuthenticIndexQueue(kuwahara_view); for (x=0; x < (ssize_t) kuwahara_image->columns; x++) { double min_variance; MagickPixelPacket pixel; RectangleInfo quadrant, target; register ssize_t i; min_variance=MagickMaximumValue; SetGeometry(gaussian_image,&target); quadrant.width=width; quadrant.height=width; for (i=0; i < 4; i++) { const PixelPacket *magick_restrict p; double variance; MagickPixelPacket mean; register const PixelPacket *magick_restrict k; register ssize_t n; quadrant.x=x; quadrant.y=y; switch (i) { case 0: { quadrant.x=x-(ssize_t) (width-1); quadrant.y=y-(ssize_t) (width-1); break; } case 1: { quadrant.y=y-(ssize_t) (width-1); break; } case 2: { quadrant.x=x-(ssize_t) (width-1); break; } default: break; } p=GetCacheViewVirtualPixels(image_view,quadrant.x,quadrant.y, quadrant.width,quadrant.height,exception); if (p == (const PixelPacket *) NULL) break; GetMagickPixelPacket(image,&mean); k=p; for (n=0; n < (ssize_t) (width*width); n++) { mean.red+=(double) k->red; mean.green+=(double) k->green; mean.blue+=(double) k->blue; k++; } mean.red/=(double) (width*width); mean.green/=(double) (width*width); mean.blue/=(double) (width*width); k=p; variance=0.0; for (n=0; n < (ssize_t) (width*width); n++) { double luma; luma=GetPixelLuma(image,k); variance+=(luma-MagickPixelLuma(&mean))*(luma-MagickPixelLuma(&mean)); k++; } if (variance < min_variance) { min_variance=variance; target=quadrant; } } if (i < 4) { status=MagickFalse; break; } status=InterpolateMagickPixelPacket(gaussian_image,image_view, UndefinedInterpolatePixel,(double) target.x+target.width/2.0, (double) target.y+target.height/2.0,&pixel,exception); if (status == MagickFalse) break; SetPixelPacket(kuwahara_image,&pixel,q,kuwahara_indexes+x); q++; } if (SyncCacheViewAuthenticPixels(kuwahara_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,KuwaharaImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } kuwahara_view=DestroyCacheView(kuwahara_view); image_view=DestroyCacheView(image_view); gaussian_image=DestroyImage(gaussian_image); if (status == MagickFalse) kuwahara_image=DestroyImage(kuwahara_image); return(kuwahara_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L o c a l C o n t r a s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LocalContrastImage() attempts to increase the appearance of large-scale % light-dark transitions. Local contrast enhancement works similarly to % sharpening with an unsharp mask, however the mask is instead created using % an image with a greater blur distance. % % The format of the LocalContrastImage method is: % % Image *LocalContrastImage(const Image *image, const double radius, % const double strength, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian blur, in percentage with 100% % resulting in a blur radius of 20% of largest dimension. % % o strength: the strength of the blur mask in percentage. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *LocalContrastImage(const Image *image,const double radius, const double strength,ExceptionInfo *exception) { #define LocalContrastImageTag "LocalContrast/Image" CacheView *image_view, *contrast_view; float *interImage, *scanline, totalWeight; Image *contrast_image; MagickBooleanType status; MemoryInfo *interImage_info, *scanline_info; ssize_t scanLineSize, width; /* Initialize contrast image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) contrast_image=AccelerateLocalContrastImage(image,radius,strength,exception); if (contrast_image != (Image *) NULL) return(contrast_image); #endif contrast_image=CloneImage(image,0,0,MagickTrue,exception); if (contrast_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(contrast_image,DirectClass) == MagickFalse) { InheritException(exception,&contrast_image->exception); contrast_image=DestroyImage(contrast_image); return((Image *) NULL); } image_view=AcquireVirtualCacheView(image,exception); contrast_view=AcquireAuthenticCacheView(contrast_image,exception); scanLineSize=(ssize_t) MagickMax(image->columns,image->rows); width=(ssize_t) scanLineSize*0.002f*fabs(radius); scanLineSize+=(2*width); scanline_info=AcquireVirtualMemory(GetOpenMPMaximumThreads()* scanLineSize,sizeof(*scanline)); if (scanline_info == (MemoryInfo *) NULL) { contrast_view=DestroyCacheView(contrast_view); image_view=DestroyCacheView(image_view); contrast_image=DestroyImage(contrast_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } scanline=(float *) GetVirtualMemoryBlob(scanline_info); /* Create intermediate buffer. */ interImage_info=AcquireVirtualMemory(image->rows*(image->columns+(2*width)), sizeof(*interImage)); if (interImage_info == (MemoryInfo *) NULL) { scanline_info=RelinquishVirtualMemory(scanline_info); contrast_view=DestroyCacheView(contrast_view); image_view=DestroyCacheView(image_view); contrast_image=DestroyImage(contrast_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } interImage=(float *) GetVirtualMemoryBlob(interImage_info); totalWeight=(width+1)*(width+1); /* Vertical pass. */ status=MagickTrue; { ssize_t x; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict p; float *out, *pix, *pixels; register ssize_t y; ssize_t i; if (status == MagickFalse) continue; pixels=scanline; pixels+=id*scanLineSize; pix=pixels; p=GetCacheViewVirtualPixels(image_view,x,-width,1,image->rows+(2*width), exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } for (y=0; y < (ssize_t) image->rows+(2*width); y++) { *pix++=(float)GetPixelLuma(image,p); p++; } out=interImage+x+width; for (y=0; y < (ssize_t) image->rows; y++) { float sum, weight; weight=1.0f; sum=0; pix=pixels+y; for (i=0; i < width; i++) { sum+=weight*(*pix++); weight+=1.0f; } for (i=width+1; i < (2*width); i++) { sum+=weight*(*pix++); weight-=1.0f; } /* write to output */ *out=sum/totalWeight; /* mirror into padding */ if (x <= width && x != 0) *(out-(x*2))=*out; if ((x > (ssize_t) image->columns-width-2) && (x != (ssize_t) image->columns-1)) *(out+((image->columns-x-1)*2))=*out; out+=image->columns+(width*2); } } } /* Horizontal pass. */ { ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict p; float *pix, *pixels; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t i; if (status == MagickFalse) continue; pixels=scanline; pixels+=id*scanLineSize; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); q=GetCacheViewAuthenticPixels(contrast_view,0,y,image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } memcpy(pixels,interImage+(y*(image->columns+(2*width))),(image->columns+ (2*width))*sizeof(float)); for (x=0; x < (ssize_t) image->columns; x++) { float mult, srcVal, sum, weight; weight=1.0f; sum=0; pix=pixels+x; for (i=0; i < width; i++) { sum+=weight*(*pix++); weight+=1.0f; } for (i=width+1; i < (2*width); i++) { sum+=weight*(*pix++); weight-=1.0f; } /* Apply and write */ srcVal=(float) GetPixelLuma(image,p); mult=(srcVal-(sum/totalWeight))*(strength/100.0f); mult=(srcVal+mult)/srcVal; SetPixelRed(q,ClampToQuantum((MagickRealType) GetPixelRed(p)*mult)); SetPixelGreen(q,ClampToQuantum((MagickRealType) GetPixelGreen(p)*mult)); SetPixelBlue(q,ClampToQuantum((MagickRealType) GetPixelBlue(p)*mult)); p++; q++; } if (SyncCacheViewAuthenticPixels(contrast_view,exception) == MagickFalse) status=MagickFalse; } } scanline_info=RelinquishVirtualMemory(scanline_info); interImage_info=RelinquishVirtualMemory(interImage_info); contrast_view=DestroyCacheView(contrast_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) contrast_image=DestroyImage(contrast_image); return(contrast_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r e v i e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PreviewImage() tiles 9 thumbnails of the specified image with an image % processing operation applied with varying parameters. This may be helpful % pin-pointing an appropriate parameter for a particular image processing % operation. % % The format of the PreviewImages method is: % % Image *PreviewImages(const Image *image,const PreviewType preview, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o preview: the image processing operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PreviewImage(const Image *image,const PreviewType preview, ExceptionInfo *exception) { #define NumberTiles 9 #define PreviewImageTag "Preview/Image" #define DefaultPreviewGeometry "204x204+10+10" char factor[MaxTextExtent], label[MaxTextExtent]; double degrees, gamma, percentage, radius, sigma, threshold; Image *images, *montage_image, *preview_image, *thumbnail; ImageInfo *preview_info; MagickBooleanType proceed; MontageInfo *montage_info; QuantizeInfo quantize_info; RectangleInfo geometry; register ssize_t i, x; size_t colors; ssize_t y; /* Open output image file. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); colors=2; degrees=0.0; gamma=(-0.2f); preview_info=AcquireImageInfo(); SetGeometry(image,&geometry); (void) ParseMetaGeometry(DefaultPreviewGeometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); images=NewImageList(); percentage=12.5; GetQuantizeInfo(&quantize_info); radius=0.0; sigma=1.0; threshold=0.0; x=0; y=0; for (i=0; i < NumberTiles; i++) { thumbnail=ThumbnailImage(image,geometry.width,geometry.height,exception); if (thumbnail == (Image *) NULL) break; (void) SetImageProgressMonitor(thumbnail,(MagickProgressMonitor) NULL, (void *) NULL); (void) SetImageProperty(thumbnail,"label",DefaultTileLabel); if (i == (NumberTiles/2)) { (void) QueryColorDatabase("#dfdfdf",&thumbnail->matte_color,exception); AppendImageToList(&images,thumbnail); continue; } switch (preview) { case RotatePreview: { degrees+=45.0; preview_image=RotateImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"rotate %g",degrees); break; } case ShearPreview: { degrees+=5.0; preview_image=ShearImage(thumbnail,degrees,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"shear %gx%g", degrees,2.0*degrees); break; } case RollPreview: { x=(ssize_t) ((i+1)*thumbnail->columns)/NumberTiles; y=(ssize_t) ((i+1)*thumbnail->rows)/NumberTiles; preview_image=RollImage(thumbnail,x,y,exception); (void) FormatLocaleString(label,MaxTextExtent,"roll %+.20gx%+.20g", (double) x,(double) y); break; } case HuePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"100,100,%g", 2.0*percentage); (void) ModulateImage(preview_image,factor); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case SaturationPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"100,%g",2.0*percentage); (void) ModulateImage(preview_image,factor); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case BrightnessPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(factor,MaxTextExtent,"%g",2.0*percentage); (void) ModulateImage(preview_image,factor); (void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor); break; } case GammaPreview: default: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; gamma+=0.4f; (void) GammaImageChannel(preview_image,DefaultChannels,gamma); (void) FormatLocaleString(label,MaxTextExtent,"gamma %g",gamma); break; } case SpiffPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image != (Image *) NULL) for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickTrue); (void) FormatLocaleString(label,MaxTextExtent,"contrast (%.20g)", (double) i+1); break; } case DullPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; for (x=0; x < i; x++) (void) ContrastImage(preview_image,MagickFalse); (void) FormatLocaleString(label,MaxTextExtent,"+contrast (%.20g)", (double) i+1); break; } case GrayscalePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; quantize_info.colorspace=GRAYColorspace; (void) QuantizeImage(&quantize_info,preview_image); (void) FormatLocaleString(label,MaxTextExtent, "-colorspace gray -colors %.20g",(double) colors); break; } case QuantizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; colors<<=1; quantize_info.number_colors=colors; (void) QuantizeImage(&quantize_info,preview_image); (void) FormatLocaleString(label,MaxTextExtent,"colors %.20g",(double) colors); break; } case DespecklePreview: { for (x=0; x < (i-1); x++) { preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; thumbnail=DestroyImage(thumbnail); thumbnail=preview_image; } preview_image=DespeckleImage(thumbnail,exception); if (preview_image == (Image *) NULL) break; (void) FormatLocaleString(label,MaxTextExtent,"despeckle (%.20g)", (double) i+1); break; } case ReduceNoisePreview: { preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) radius, (size_t) radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"noise %g",radius); break; } case AddNoisePreview: { switch ((int) i) { case 0: { (void) CopyMagickString(factor,"uniform",MaxTextExtent); break; } case 1: { (void) CopyMagickString(factor,"gaussian",MaxTextExtent); break; } case 2: { (void) CopyMagickString(factor,"multiplicative",MaxTextExtent); break; } case 3: { (void) CopyMagickString(factor,"impulse",MaxTextExtent); break; } case 5: { (void) CopyMagickString(factor,"laplacian",MaxTextExtent); break; } case 6: { (void) CopyMagickString(factor,"poisson",MaxTextExtent); break; } default: { (void) CopyMagickString(thumbnail->magick,"NULL",MaxTextExtent); break; } } preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) i, (size_t) i,exception); (void) FormatLocaleString(label,MaxTextExtent,"+noise %s",factor); break; } case SharpenPreview: { preview_image=SharpenImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MaxTextExtent,"sharpen %gx%g", radius,sigma); break; } case BlurPreview: { preview_image=BlurImage(thumbnail,radius,sigma,exception); (void) FormatLocaleString(label,MaxTextExtent,"blur %gx%g",radius, sigma); break; } case ThresholdPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) BilevelImage(thumbnail, (double) (percentage*((MagickRealType) QuantumRange+1.0))/100.0); (void) FormatLocaleString(label,MaxTextExtent,"threshold %g", (double) (percentage*((MagickRealType) QuantumRange+1.0))/100.0); break; } case EdgeDetectPreview: { preview_image=EdgeImage(thumbnail,radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"edge %g",radius); break; } case SpreadPreview: { preview_image=SpreadImage(thumbnail,radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"spread %g", radius+0.5); break; } case SolarizePreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; (void) SolarizeImage(preview_image,(double) QuantumRange* percentage/100.0); (void) FormatLocaleString(label,MaxTextExtent,"solarize %g", (QuantumRange*percentage)/100.0); break; } case ShadePreview: { degrees+=10.0; preview_image=ShadeImage(thumbnail,MagickTrue,degrees,degrees, exception); (void) FormatLocaleString(label,MaxTextExtent,"shade %gx%g", degrees,degrees); break; } case RaisePreview: { RectangleInfo raise; preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; raise.width=(size_t) (2*i+2); raise.height=(size_t) (2*i+2); raise.x=(i-1)/2; raise.y=(i-1)/2; (void) RaiseImage(preview_image,&raise,MagickTrue); (void) FormatLocaleString(label,MaxTextExtent, "raise %.20gx%.20g%+.20g%+.20g",(double) raise.width,(double) raise.height,(double) raise.x,(double) raise.y); break; } case SegmentPreview: { preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; threshold+=0.4f; (void) SegmentImage(preview_image,sRGBColorspace,MagickFalse,threshold, threshold); (void) FormatLocaleString(label,MaxTextExtent,"segment %gx%g", threshold,threshold); break; } case SwirlPreview: { preview_image=SwirlImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"swirl %g",degrees); degrees+=45.0; break; } case ImplodePreview: { degrees+=0.1f; preview_image=ImplodeImage(thumbnail,degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"implode %g",degrees); break; } case WavePreview: { degrees+=5.0f; preview_image=WaveImage(thumbnail,0.5*degrees,2.0*degrees,exception); (void) FormatLocaleString(label,MaxTextExtent,"wave %gx%g", 0.5*degrees,2.0*degrees); break; } case OilPaintPreview: { preview_image=OilPaintImage(thumbnail,(double) radius,exception); (void) FormatLocaleString(label,MaxTextExtent,"paint %g",radius); break; } case CharcoalDrawingPreview: { preview_image=CharcoalImage(thumbnail,(double) radius,(double) sigma, exception); (void) FormatLocaleString(label,MaxTextExtent,"charcoal %gx%g", radius,sigma); break; } case JPEGPreview: { char filename[MaxTextExtent]; int file; MagickBooleanType status; preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception); if (preview_image == (Image *) NULL) break; preview_info->quality=(size_t) percentage; (void) FormatLocaleString(factor,MaxTextExtent,"%.20g",(double) preview_info->quality); file=AcquireUniqueFileResource(filename); if (file != -1) file=close(file)-1; (void) FormatLocaleString(preview_image->filename,MaxTextExtent, "jpeg:%s",filename); status=WriteImage(preview_info,preview_image); if (status != MagickFalse) { Image *quality_image; (void) CopyMagickString(preview_info->filename, preview_image->filename,MaxTextExtent); quality_image=ReadImage(preview_info,exception); if (quality_image != (Image *) NULL) { preview_image=DestroyImage(preview_image); preview_image=quality_image; } } (void) RelinquishUniqueFileResource(preview_image->filename); if ((GetBlobSize(preview_image)/1024) >= 1024) (void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%gmb ", factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/ 1024.0/1024.0); else if (GetBlobSize(preview_image) >= 1024) (void) FormatLocaleString(label,MaxTextExtent, "quality %s\n%gkb ",factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/1024.0); else (void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%.20gb ", factor,(double) ((MagickOffsetType) GetBlobSize(thumbnail))); break; } } thumbnail=DestroyImage(thumbnail); percentage+=12.5; radius+=0.5; sigma+=0.25; if (preview_image == (Image *) NULL) break; (void) DeleteImageProperty(preview_image,"label"); (void) SetImageProperty(preview_image,"label",label); AppendImageToList(&images,preview_image); proceed=SetImageProgress(image,PreviewImageTag,(MagickOffsetType) i, NumberTiles); if (proceed == MagickFalse) break; } if (images == (Image *) NULL) { preview_info=DestroyImageInfo(preview_info); return((Image *) NULL); } /* Create the montage. */ montage_info=CloneMontageInfo(preview_info,(MontageInfo *) NULL); (void) CopyMagickString(montage_info->filename,image->filename,MaxTextExtent); montage_info->shadow=MagickTrue; (void) CloneString(&montage_info->tile,"3x3"); (void) CloneString(&montage_info->geometry,DefaultPreviewGeometry); (void) CloneString(&montage_info->frame,DefaultTileFrame); montage_image=MontageImages(images,montage_info,exception); montage_info=DestroyMontageInfo(montage_info); images=DestroyImageList(images); if (montage_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (montage_image->montage != (char *) NULL) { /* Free image directory. */ montage_image->montage=(char *) RelinquishMagickMemory( montage_image->montage); if (image->directory != (char *) NULL) montage_image->directory=(char *) RelinquishMagickMemory( montage_image->directory); } preview_info=DestroyImageInfo(preview_info); return(montage_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o t a t i o n a l B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RotationalBlurImage() applies a rotational blur to the image. % % Andrew Protano contributed this effect. % % The format of the RotationalBlurImage method is: % % Image *RotationalBlurImage(const Image *image,const double angle, % ExceptionInfo *exception) % Image *RotationalBlurImageChannel(const Image *image, % const ChannelType channel,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o angle: the angle of the rotational blur. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *RotationalBlurImage(const Image *image,const double angle, ExceptionInfo *exception) { Image *blur_image; blur_image=RotationalBlurImageChannel(image,DefaultChannels,angle,exception); return(blur_image); } MagickExport Image *RotationalBlurImageChannel(const Image *image, const ChannelType channel,const double angle,ExceptionInfo *exception) { CacheView *blur_view, *image_view; Image *blur_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; MagickRealType blur_radius, *cos_theta, offset, *sin_theta, theta; PointInfo blur_center; register ssize_t i; size_t n; ssize_t y; /* Allocate blur image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) blur_image=AccelerateRadialBlurImage(image,channel,angle,exception); if (blur_image != (Image *) NULL) return(blur_image); #endif blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } blur_center.x=(double) (image->columns-1)/2.0; blur_center.y=(double) (image->rows-1)/2.0; blur_radius=hypot(blur_center.x,blur_center.y); n=(size_t) fabs(4.0*DegreesToRadians(angle)*sqrt((double) blur_radius)+2UL); theta=DegreesToRadians(angle)/(MagickRealType) (n-1); cos_theta=(MagickRealType *) AcquireQuantumMemory((size_t) n, sizeof(*cos_theta)); sin_theta=(MagickRealType *) AcquireQuantumMemory((size_t) n, sizeof(*sin_theta)); if ((cos_theta == (MagickRealType *) NULL) || (sin_theta == (MagickRealType *) NULL)) { if (cos_theta != (MagickRealType *) NULL) cos_theta=(MagickRealType *) RelinquishMagickMemory(cos_theta); if (sin_theta != (MagickRealType *) NULL) sin_theta=(MagickRealType *) RelinquishMagickMemory(sin_theta); blur_image=DestroyImage(blur_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } offset=theta*(MagickRealType) (n-1)/2.0; for (i=0; i < (ssize_t) n; i++) { cos_theta[i]=cos((double) (theta*i-offset)); sin_theta[i]=sin((double) (theta*i-offset)); } /* Radial blur image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); image_view=AcquireVirtualCacheView(image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,blur_image->rows,1) #endif for (y=0; y < (ssize_t) blur_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register IndexPacket *magick_restrict blur_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) blur_image->columns; x++) { MagickPixelPacket qixel; MagickRealType normalize, radius; PixelPacket pixel; PointInfo center; register ssize_t i; size_t step; center.x=(double) x-blur_center.x; center.y=(double) y-blur_center.y; radius=hypot((double) center.x,center.y); if (radius == 0) step=1; else { step=(size_t) (blur_radius/radius); if (step == 0) step=1; else if (step >= n) step=n-1; } normalize=0.0; qixel=bias; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (i=0; i < (ssize_t) n; i+=(ssize_t) step) { (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) (blur_center.x+center.x*cos_theta[i]-center.y*sin_theta[i]+0.5), (ssize_t) (blur_center.y+center.x*sin_theta[i]+center.y* cos_theta[i]+0.5),&pixel,exception); qixel.red+=pixel.red; qixel.green+=pixel.green; qixel.blue+=pixel.blue; qixel.opacity+=pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=(*indexes); } normalize+=1.0; } normalize=PerceptibleReciprocal(normalize); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(normalize*qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(normalize*qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(normalize*qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(normalize*qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(normalize*qixel.index)); } else { double alpha, gamma; alpha=1.0; gamma=0.0; for (i=0; i < (ssize_t) n; i+=(ssize_t) step) { (void) GetOneCacheViewVirtualPixel(image_view,(ssize_t) (blur_center.x+center.x*cos_theta[i]-center.y*sin_theta[i]+0.5), (ssize_t) (blur_center.y+center.x*sin_theta[i]+center.y* cos_theta[i]+0.5),&pixel,exception); alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(&pixel)); qixel.red+=alpha*pixel.red; qixel.green+=alpha*pixel.green; qixel.blue+=alpha*pixel.blue; qixel.opacity+=pixel.opacity; if (image->colorspace == CMYKColorspace) { indexes=GetCacheViewVirtualIndexQueue(image_view); qixel.index+=alpha*(*indexes); } gamma+=alpha; normalize+=1.0; } gamma=PerceptibleReciprocal(gamma); normalize=PerceptibleReciprocal(normalize); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*qixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*qixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*qixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(normalize*qixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*qixel.index)); } q++; } if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BlurImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_view=DestroyCacheView(blur_view); image_view=DestroyCacheView(image_view); cos_theta=(MagickRealType *) RelinquishMagickMemory(cos_theta); sin_theta=(MagickRealType *) RelinquishMagickMemory(sin_theta); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e l e c t i v e B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SelectiveBlurImage() selectively blur pixels within a contrast threshold. % It is similar to the unsharpen mask that sharpens everything with contrast % above a certain threshold. % % The format of the SelectiveBlurImage method is: % % Image *SelectiveBlurImage(const Image *image,const double radius, % const double sigma,const double threshold,ExceptionInfo *exception) % Image *SelectiveBlurImageChannel(const Image *image, % const ChannelType channel,const double radius,const double sigma, % const double threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o threshold: only pixels within this contrast threshold are included % in the blur operation. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SelectiveBlurImage(const Image *image,const double radius, const double sigma,const double threshold,ExceptionInfo *exception) { Image *blur_image; blur_image=SelectiveBlurImageChannel(image,DefaultChannels,radius,sigma, threshold,exception); return(blur_image); } MagickExport Image *SelectiveBlurImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double threshold,ExceptionInfo *exception) { #define SelectiveBlurImageTag "SelectiveBlur/Image" CacheView *blur_view, *image_view, *luminance_view; double *kernel; Image *blur_image, *luminance_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; register ssize_t i; size_t width; ssize_t center, j, u, v, y; /* Initialize blur image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth1D(radius,sigma); kernel=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width, width*sizeof(*kernel))); if (kernel == (double *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); j=(ssize_t) (width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) kernel[i++]=(double) (exp(-((double) u*u+v*v)/(2.0*MagickSigma* MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); } if (image->debug != MagickFalse) { char format[MaxTextExtent], *message; register const double *k; ssize_t u, v; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " SelectiveBlurImage with %.20gx%.20g kernel:",(double) width,(double) width); message=AcquireString(""); k=kernel; for (v=0; v < (ssize_t) width; v++) { *message='\0'; (void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < (ssize_t) width; u++) { (void) FormatLocaleString(format,MaxTextExtent,"%+f ",*k++); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } blur_image=CloneImage(image,0,0,MagickTrue,exception); if (blur_image == (Image *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); return((Image *) NULL); } if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse) { kernel=(double *) RelinquishAlignedMemory(kernel); InheritException(exception,&blur_image->exception); blur_image=DestroyImage(blur_image); return((Image *) NULL); } luminance_image=CloneImage(image,0,0,MagickTrue,exception); if (luminance_image == (Image *) NULL) { kernel=(double *) RelinquishAlignedMemory(kernel); blur_image=DestroyImage(blur_image); return((Image *) NULL); } status=TransformImageColorspace(luminance_image,GRAYColorspace); if (status == MagickFalse) { InheritException(exception,&luminance_image->exception); kernel=(double *) RelinquishAlignedMemory(kernel); blur_image=DestroyImage(blur_image); luminance_image=DestroyImage(luminance_image); return((Image *) NULL); } /* Threshold blur image. */ status=MagickTrue; progress=0; center=(ssize_t) ((image->columns+width)*((width-1)/2L)+((width-1)/2L)); GetMagickPixelPacket(image,&bias); SetMagickPixelPacketBias(image,&bias); image_view=AcquireVirtualCacheView(image,exception); luminance_view=AcquireVirtualCacheView(luminance_image,exception); blur_view=AcquireAuthenticCacheView(blur_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,blur_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double gamma; MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict l, *magick_restrict p; register IndexPacket *magick_restrict blur_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (width-1)/2L),y-(ssize_t) ((width-1)/2L),image->columns+width,width,exception); l=GetCacheViewVirtualPixels(luminance_view,-((ssize_t) (width-1)/2L),y- (ssize_t) ((width-1)/2L),luminance_image->columns+width,width,exception); q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (l == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view); for (x=0; x < (ssize_t) image->columns; x++) { double contrast; DoublePixelPacket pixel; MagickRealType intensity; register const double *magick_restrict k; register ssize_t u; ssize_t j, v; pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; k=kernel; intensity=GetPixelIntensity(image,p+center); gamma=0.0; j=0; if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse)) { for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { pixel.red+=(*k)*GetPixelRed(p+u+j); pixel.green+=(*k)*GetPixelGreen(p+u+j); pixel.blue+=(*k)*GetPixelBlue(p+u+j); gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } if (gamma != 0.0) { gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); } if ((channel & OpacityChannel) != 0) { gamma=0.0; j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { pixel.opacity+=(*k)*(p+u+j)->opacity; gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } gamma=PerceptibleReciprocal(gamma); SetPixelOpacity(q,ClampToQuantum(gamma*pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { gamma=0.0; j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { pixel.index+=(*k)*GetPixelIndex(indexes+x+u+j); gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } gamma=PerceptibleReciprocal(gamma); SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index)); } } else { MagickRealType alpha; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p+u+j)); pixel.red+=(*k)*alpha*GetPixelRed(p+u+j); pixel.green+=(*k)*alpha*GetPixelGreen(p+u+j); pixel.blue+=(*k)*alpha*GetPixelBlue(p+u+j); pixel.opacity+=(*k)*GetPixelOpacity(p+u+j); gamma+=(*k)*alpha; } k++; } j+=(ssize_t) (image->columns+width); } if (gamma != 0.0) { gamma=PerceptibleReciprocal(gamma); if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(gamma*pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(gamma*pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue)); } if ((channel & OpacityChannel) != 0) { j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) pixel.opacity+=(*k)*GetPixelOpacity(p+u+j); k++; } j+=(ssize_t) (image->columns+width); } SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { gamma=0.0; j=0; for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity; if (fabs(contrast) < threshold) { alpha=(MagickRealType) (QuantumScale* GetPixelAlpha(p+u+j)); pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+u+j); gamma+=(*k); } k++; } j+=(ssize_t) (image->columns+width); } gamma=PerceptibleReciprocal(gamma); SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index)); } } p++; l++; q++; } sync=SyncCacheViewAuthenticPixels(blur_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,SelectiveBlurImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } blur_image->type=image->type; blur_view=DestroyCacheView(blur_view); luminance_view=DestroyCacheView(luminance_view); image_view=DestroyCacheView(image_view); luminance_image=DestroyImage(luminance_image); kernel=(double *) RelinquishAlignedMemory(kernel); if (status == MagickFalse) blur_image=DestroyImage(blur_image); return(blur_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadeImage() shines a distant light on an image to create a % three-dimensional effect. You control the positioning of the light with % azimuth and elevation; azimuth is measured in degrees off the x axis % and elevation is measured in pixels above the Z axis. % % The format of the ShadeImage method is: % % Image *ShadeImage(const Image *image,const MagickBooleanType gray, % const double azimuth,const double elevation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o gray: A value other than zero shades the intensity of each pixel. % % o azimuth, elevation: Define the light source direction. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadeImage(const Image *image,const MagickBooleanType gray, const double azimuth,const double elevation,ExceptionInfo *exception) { #define GetShadeIntensity(image,pixel) \ ClampPixel(GetPixelIntensity((image),(pixel))) #define ShadeImageTag "Shade/Image" CacheView *image_view, *shade_view; Image *linear_image, *shade_image; MagickBooleanType status; MagickOffsetType progress; PrimaryInfo light; ssize_t y; /* Initialize shaded image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); linear_image=CloneImage(image,0,0,MagickTrue,exception); shade_image=CloneImage(image,0,0,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (shade_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (shade_image != (Image *) NULL) shade_image=DestroyImage(shade_image); return((Image *) NULL); } if (SetImageStorageClass(shade_image,DirectClass) == MagickFalse) { InheritException(exception,&shade_image->exception); linear_image=DestroyImage(linear_image); shade_image=DestroyImage(shade_image); return((Image *) NULL); } /* Compute the light vector. */ light.x=(double) QuantumRange*cos(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.y=(double) QuantumRange*sin(DegreesToRadians(azimuth))* cos(DegreesToRadians(elevation)); light.z=(double) QuantumRange*sin(DegreesToRadians(elevation)); /* Shade image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(linear_image,exception); shade_view=AcquireAuthenticCacheView(shade_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(linear_image,shade_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { MagickRealType distance, normal_distance, shade; PrimaryInfo normal; register const PixelPacket *magick_restrict p, *magick_restrict s0, *magick_restrict s1, *magick_restrict s2; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-1,y-1,linear_image->columns+2,3, exception); q=QueueCacheViewAuthenticPixels(shade_view,0,y,shade_image->columns,1, exception); if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } /* Shade this row of pixels. */ normal.z=2.0*(double) QuantumRange; /* constant Z of surface normal */ for (x=0; x < (ssize_t) linear_image->columns; x++) { /* Determine the surface normal and compute shading. */ s0=p+1; s1=s0+image->columns+2; s2=s1+image->columns+2; normal.x=(double) (GetShadeIntensity(linear_image,s0-1)+ GetShadeIntensity(linear_image,s1-1)+ GetShadeIntensity(linear_image,s2-1)- GetShadeIntensity(linear_image,s0+1)- GetShadeIntensity(linear_image,s1+1)- GetShadeIntensity(linear_image,s2+1)); normal.y=(double) (GetShadeIntensity(linear_image,s2-1)+ GetShadeIntensity(linear_image,s2)+ GetShadeIntensity(linear_image,s2+1)- GetShadeIntensity(linear_image,s0-1)- GetShadeIntensity(linear_image,s0)- GetShadeIntensity(linear_image,s0+1)); if ((fabs(normal.x) <= MagickEpsilon) && (fabs(normal.y) <= MagickEpsilon)) shade=light.z; else { shade=0.0; distance=normal.x*light.x+normal.y*light.y+normal.z*light.z; if (distance > MagickEpsilon) { normal_distance=normal.x*normal.x+normal.y*normal.y+normal.z* normal.z; if (normal_distance > (MagickEpsilon*MagickEpsilon)) shade=distance/sqrt((double) normal_distance); } } if (gray != MagickFalse) { SetPixelRed(q,shade); SetPixelGreen(q,shade); SetPixelBlue(q,shade); } else { SetPixelRed(q,ClampToQuantum(QuantumScale*shade*GetPixelRed(s1))); SetPixelGreen(q,ClampToQuantum(QuantumScale*shade*GetPixelGreen(s1))); SetPixelBlue(q,ClampToQuantum(QuantumScale*shade*GetPixelBlue(s1))); } q->opacity=s1->opacity; p++; q++; } if (SyncCacheViewAuthenticPixels(shade_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ShadeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } shade_view=DestroyCacheView(shade_view); image_view=DestroyCacheView(image_view); linear_image=DestroyImage(linear_image); if (status == MagickFalse) shade_image=DestroyImage(shade_image); return(shade_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a r p e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SharpenImage() sharpens the image. We convolve the image with a Gaussian % operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SharpenImage() selects a suitable radius for you. % % Using a separable kernel would be faster, but the negative weights cancel % out on the corners of the kernel producing often undesirable ringing in the % filtered result; this can be avoided by using a 2D gaussian shaped image % sharpening kernel instead. % % The format of the SharpenImage method is: % % Image *SharpenImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % Image *SharpenImageChannel(const Image *image,const ChannelType channel, % const double radius,const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Laplacian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SharpenImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *sharp_image; sharp_image=SharpenImageChannel(image,DefaultChannels,radius,sigma,exception); return(sharp_image); } MagickExport Image *SharpenImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, ExceptionInfo *exception) { double gamma, normalize; Image *sharp_image; KernelInfo *kernel_info; register ssize_t i; size_t width; ssize_t j, u, v; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth2D(radius,sigma); kernel_info=AcquireKernelInfo((const char *) NULL); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(kernel_info,0,sizeof(*kernel_info)); kernel_info->width=width; kernel_info->height=width; kernel_info->x=(ssize_t) (width-1)/2; kernel_info->y=(ssize_t) (width-1)/2; kernel_info->signature=MagickCoreSignature; kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory( kernel_info->width,kernel_info->height*sizeof(*kernel_info->values))); if (kernel_info->values == (double *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } normalize=0.0; j=(ssize_t) (kernel_info->width-1)/2; i=0; for (v=(-j); v <= j; v++) { for (u=(-j); u <= j; u++) { kernel_info->values[i]=(double) (-exp(-((double) u*u+v*v)/(2.0* MagickSigma*MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma)); normalize+=kernel_info->values[i]; i++; } } kernel_info->values[i/2]=(double) ((-2.0)*normalize); normalize=0.0; for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) normalize+=kernel_info->values[i]; gamma=PerceptibleReciprocal(normalize); for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++) kernel_info->values[i]*=gamma; sharp_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); return(sharp_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p r e a d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpreadImage() is a special effects method that randomly displaces each % pixel in a block defined by the radius parameter. % % The format of the SpreadImage method is: % % Image *SpreadImage(const Image *image,const double radius, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: Choose a random pixel in a neighborhood of this extent. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpreadImage(const Image *image,const double radius, ExceptionInfo *exception) { #define SpreadImageTag "Spread/Image" CacheView *image_view, *spread_view; Image *spread_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; RandomInfo **magick_restrict random_info; size_t width; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize spread image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); spread_image=CloneImage(image,0,0,MagickTrue,exception); if (spread_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(spread_image,DirectClass) == MagickFalse) { InheritException(exception,&spread_image->exception); spread_image=DestroyImage(spread_image); return((Image *) NULL); } /* Spread image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(spread_image,&bias); width=GetOptimalKernelWidth1D(radius,0.5); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); spread_view=AcquireAuthenticCacheView(spread_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,spread_image,spread_image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) spread_image->rows; y++) { const int id = GetOpenMPThreadId(); MagickPixelPacket pixel; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(spread_view,0,y,spread_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(spread_view); pixel=bias; for (x=0; x < (ssize_t) spread_image->columns; x++) { PointInfo point; point.x=GetPseudoRandomValue(random_info[id]); point.y=GetPseudoRandomValue(random_info[id]); status=InterpolateMagickPixelPacket(image,image_view,image->interpolate, (double) x+width*(point.x-0.5),(double) y+width*(point.y-0.5),&pixel, exception); if (status == MagickFalse) break; SetPixelPacket(spread_image,&pixel,q,indexes+x); q++; } if (SyncCacheViewAuthenticPixels(spread_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SpreadImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } spread_view=DestroyCacheView(spread_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) spread_image=DestroyImage(spread_image); return(spread_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n s h a r p M a s k I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnsharpMaskImage() sharpens one or more image channels. We convolve the % image with a Gaussian operator of the given radius and standard deviation % (sigma). For reasonable results, radius should be larger than sigma. Use a % radius of 0 and UnsharpMaskImage() selects a suitable radius for you. % % The format of the UnsharpMaskImage method is: % % Image *UnsharpMaskImage(const Image *image,const double radius, % const double sigma,const double amount,const double threshold, % ExceptionInfo *exception) % Image *UnsharpMaskImageChannel(const Image *image, % const ChannelType channel,const double radius,const double sigma, % const double gain,const double threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o radius: the radius of the Gaussian, in pixels, not counting the center % pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o gain: the percentage of the difference between the original and the % blur image that is added back into the original. % % o threshold: the threshold in pixels needed to apply the diffence gain. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *UnsharpMaskImage(const Image *image,const double radius, const double sigma,const double gain,const double threshold, ExceptionInfo *exception) { Image *sharp_image; sharp_image=UnsharpMaskImageChannel(image,DefaultChannels,radius,sigma,gain, threshold,exception); return(sharp_image); } MagickExport Image *UnsharpMaskImageChannel(const Image *image, const ChannelType channel,const double radius,const double sigma, const double gain,const double threshold,ExceptionInfo *exception) { #define SharpenImageTag "Sharpen/Image" CacheView *image_view, *unsharp_view; Image *unsharp_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket bias; MagickRealType quantum_threshold; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); /* This kernel appears to be broken. #if defined(MAGICKCORE_OPENCL_SUPPORT) unsharp_image=AccelerateUnsharpMaskImage(image,channel,radius,sigma,gain, threshold,exception); if (unsharp_image != (Image *) NULL) return(unsharp_image); #endif */ unsharp_image=BlurImageChannel(image,(ChannelType) (channel &~ SyncChannels), radius,sigma,exception); if (unsharp_image == (Image *) NULL) return((Image *) NULL); quantum_threshold=(MagickRealType) QuantumRange*threshold; /* Unsharp-mask image. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&bias); image_view=AcquireVirtualCacheView(image,exception); unsharp_view=AcquireAuthenticCacheView(unsharp_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,unsharp_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { DoublePixelPacket pixel; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict unsharp_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(unsharp_view,0,y,unsharp_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); unsharp_indexes=GetCacheViewAuthenticIndexQueue(unsharp_view); pixel.red=bias.red; pixel.green=bias.green; pixel.blue=bias.blue; pixel.opacity=bias.opacity; pixel.index=bias.index; for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { pixel.red=GetPixelRed(p)-(MagickRealType) GetPixelRed(q); if (fabs(2.0*pixel.red) < quantum_threshold) pixel.red=(MagickRealType) GetPixelRed(p); else pixel.red=(MagickRealType) GetPixelRed(p)+(pixel.red*gain); SetPixelRed(q,ClampToQuantum(pixel.red)); } if ((channel & GreenChannel) != 0) { pixel.green=GetPixelGreen(p)-(MagickRealType) q->green; if (fabs(2.0*pixel.green) < quantum_threshold) pixel.green=(MagickRealType) GetPixelGreen(p); else pixel.green=(MagickRealType) GetPixelGreen(p)+(pixel.green*gain); SetPixelGreen(q,ClampToQuantum(pixel.green)); } if ((channel & BlueChannel) != 0) { pixel.blue=GetPixelBlue(p)-(MagickRealType) q->blue; if (fabs(2.0*pixel.blue) < quantum_threshold) pixel.blue=(MagickRealType) GetPixelBlue(p); else pixel.blue=(MagickRealType) GetPixelBlue(p)+(pixel.blue*gain); SetPixelBlue(q,ClampToQuantum(pixel.blue)); } if ((channel & OpacityChannel) != 0) { pixel.opacity=GetPixelOpacity(p)-(MagickRealType) q->opacity; if (fabs(2.0*pixel.opacity) < quantum_threshold) pixel.opacity=(MagickRealType) GetPixelOpacity(p); else pixel.opacity=GetPixelOpacity(p)+(pixel.opacity*gain); SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { pixel.index=GetPixelIndex(indexes+x)-(MagickRealType) GetPixelIndex(unsharp_indexes+x); if (fabs(2.0*pixel.index) < quantum_threshold) pixel.index=(MagickRealType) GetPixelIndex(indexes+x); else pixel.index=(MagickRealType) GetPixelIndex(indexes+x)+ (pixel.index*gain); SetPixelIndex(unsharp_indexes+x,ClampToQuantum(pixel.index)); } p++; q++; } if (SyncCacheViewAuthenticPixels(unsharp_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SharpenImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } unsharp_image->type=image->type; unsharp_view=DestroyCacheView(unsharp_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) unsharp_image=DestroyImage(unsharp_image); return(unsharp_image); }
DeclOpenMP.h
//===- DeclOpenMP.h - Classes for representing OpenMP directives -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file defines OpenMP nodes for declarative directives. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_OPENMP_H #define LLVM_CLANG_AST_OPENMP_H #include "clang/AST/DeclBase.h" #include "llvm/ADT/ArrayRef.h" namespace clang { /// \brief This represents '#pragma omp threadprivate ...' directive. /// For example, in the following, both 'a' and 'A::b' are threadprivate: /// /// \code /// int a; /// #pragma omp threadprivate(a) /// struct A { /// static int b; /// #pragma omp threadprivate(b) /// }; /// \endcode /// class OMPThreadPrivateDecl : public Decl { friend class ASTDeclReader; unsigned NumVars; virtual void anchor(); OMPThreadPrivateDecl(Kind DK, DeclContext *DC, SourceLocation L) : Decl(DK, DC, L), NumVars(0) { } ArrayRef<const Expr *> getVars() const { return ArrayRef<const Expr *>( reinterpret_cast<const Expr * const *>(this + 1), NumVars); } llvm::MutableArrayRef<Expr *> getVars() { return llvm::MutableArrayRef<Expr *>( reinterpret_cast<Expr **>(this + 1), NumVars); } void setVars(ArrayRef<Expr *> VL); public: static OMPThreadPrivateDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, ArrayRef<Expr *> VL); static OMPThreadPrivateDecl *CreateDeserialized(ASTContext &C, unsigned ID, unsigned N); typedef llvm::MutableArrayRef<Expr *>::iterator varlist_iterator; typedef ArrayRef<const Expr *>::iterator varlist_const_iterator; unsigned varlist_size() const { return NumVars; } bool varlist_empty() const { return NumVars == 0; } varlist_iterator varlist_begin() { return getVars().begin(); } varlist_iterator varlist_end() { return getVars().end(); } varlist_const_iterator varlist_begin() const { return getVars().begin(); } varlist_const_iterator varlist_end() const { return getVars().end(); } static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classofKind(Kind K) { return K == OMPThreadPrivate; } }; } // end namespace clang #endif
pi.c
/* OpenMP example program that computes the value of Pi using the trapeziod rule. Compile with gcc -fopenmp -O3 omp_pi.c -o omp_pi */ // Online source: http://users.abo.fi/mats/PP2012/examples/OpenMP/omp_pi.c // // permission obtained #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <math.h> void print_usage(char *s) { printf("Usage: %s -i <nr of intervals>\n", s); exit(0); } /* This is the function to integrate */ double f(double x) { return (4.0 / (1.0 + x*x)); } int main (int argc, char *argv[]) { const double PI24 = 3.141592653589793238462643; int nthreads, tid; double d, x, sum=0.0, pi; double starttime, stoptime; int n=100, i; // MATT CHANGED 1000 to 100 to SCALE DOWN char c; /* Check if we have at least one argument */ // if (argc <=1 ) { // print_usage(argv[0]); // } // else { // /* Parse the arguments for a -h or -i flag */ // while ((c=getopt(argc, argv, "hi:")) != EOF) { // switch (c) { // case 'h': // print_usage(argv[0]); // case 'i': // n = atoi(optarg); /* Get number of intervals */ // break; // default: // print_usage(argv[0]); // } // } // } /* Compute the size of intervals */ d = 1.0/(double) n; /* Start the threads */ #pragma omp parallel default(shared) private(nthreads, tid, x) { /* Get the thread number */ tid = omp_get_thread_num(); /* The master thread checks how many there are */ #pragma omp master { nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); starttime = omp_get_wtime(); /* Measure the execution time */ } /* This loop is executed in parallel by the threads */ #pragma omp for reduction(+:sum) for (i=0; i<n; i++) { x = d*(double)i; sum += f(x) + f(x+d); } } /* The parallel section ends here */ /* The multiplication by d and division by 2 is moved out of the loop */ pi = d*sum*0.5; stoptime = omp_get_wtime(); printf("The computed value of Pi is %2.24f\n", pi); printf("The \"exact\" value of Pi is %2.24f\n", PI24); printf("The difference is %e\n", fabs(PI24-pi)); printf("Time: %2.4f seconds \n", stoptime-starttime); exit(0); }
GxB_Matrix_Option_get.c
//------------------------------------------------------------------------------ // GxB_Matrix_Option_get: get an option in a matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #include "GB.h" GrB_Info GxB_Matrix_Option_get // gets the current option of a matrix ( GrB_Matrix A, // matrix to query GxB_Option_Field field, // option to query ... // return value of the matrix option ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE1 ("GxB_Matrix_Option_get (A, field, &value)") ; GB_RETURN_IF_NULL_OR_FAULTY (A) ; ASSERT_MATRIX_OK (A, "A to get option", GB0) ; //-------------------------------------------------------------------------- // get the option //-------------------------------------------------------------------------- va_list ap ; switch (field) { case GxB_HYPER_SWITCH : { va_start (ap, field) ; double *hyper_switch = va_arg (ap, double *) ; va_end (ap) ; GB_RETURN_IF_NULL (hyper_switch) ; (*hyper_switch) = (double) A->hyper_switch ; } break ; case GxB_BITMAP_SWITCH : { va_start (ap, field) ; double *bitmap_switch = va_arg (ap, double *) ; va_end (ap) ; GB_RETURN_IF_NULL (bitmap_switch) ; (*bitmap_switch) = (double) A->bitmap_switch ; } break ; case GxB_SPARSITY_CONTROL : { va_start (ap, field) ; int *sparsity_control = va_arg (ap, int *) ; va_end (ap) ; GB_RETURN_IF_NULL (sparsity_control) ; (*sparsity_control) = A->sparsity_control ; } break ; case GxB_SPARSITY_STATUS : { va_start (ap, field) ; int *sparsity = va_arg (ap, int *) ; va_end (ap) ; GB_RETURN_IF_NULL (sparsity) ; (*sparsity) = GB_sparsity (A) ; } break ; case GxB_FORMAT : { va_start (ap, field) ; GxB_Format_Value *format = va_arg (ap, GxB_Format_Value *) ; va_end (ap) ; GB_RETURN_IF_NULL (format) ; (*format) = (A->is_csc) ? GxB_BY_COL : GxB_BY_ROW ; } break ; case GxB_IS_HYPER : // historical; use GxB_SPARSITY_STATUS instead { va_start (ap, field) ; bool *A_is_hyper = va_arg (ap, bool *) ; va_end (ap) ; GB_RETURN_IF_NULL (A_is_hyper) ; (*A_is_hyper) = (GB_sparsity (A) == GxB_HYPERSPARSE) ; } break ; default : return (GrB_INVALID_VALUE) ; } #pragma omp flush return (GrB_SUCCESS) ; }
prime.c
#include <stdio.h> // Gives us printf #include <stdbool.h> // Gives us the bool type #include <stdlib.h> // Gives us dynamic memory functions #include <math.h> // Gives us math functions like sqrt static int* primeList; // Pointer variable accessible to anything in this file // Factor test by trial division using the 6k +- 1 optimisation, this // means that factors of factors will not be displayed, i.e. if the test // number is a factor of 2, it will not show 4, 6, 8 etc. // static bool findFactors(const int testNum, bool verbose) { int const testLimit = (int) floor(sqrt((double) testNum)); // Local constant variable bool isPrime = true; if (testNum <= 3) { isPrime = (testNum > 1); if (verbose) printf("Special case %d", testNum); // %d means print an integer } else { for (int i = 2; i <= 3; i++) // Test for divisibility by 2 and 3 { if ((testNum % i) == 0) { isPrime = false; if (verbose) printf("divides by %d", i); } } } for (int divisor = 5; divisor <= testLimit; divisor += 6) // Loop from divisor = 5 to testLimit (inclusive), increment by 6 { if ((testNum % divisor) == 0) // Test if it divides by the divisor (i.e. 6k - 1) { if (verbose) printf("divides by %d", divisor); isPrime = false; } if ((testNum % (divisor + 2)) == 0) // Test if it divides by the divisor + 2 (i.e. 6k + 1) { if (verbose) printf("divides by %d", divisor + 2); isPrime = false; } } return isPrime; } // Helper function for calculating all prime numbers up to maxNumber // static int primeListTest(const int maxNumber) { int numPrimes = 0; primeList = calloc(maxNumber, sizeof(int)); // Dynamic memory allocation & initialize to 0 #pragma omp parallel for schedule(guided) // Uses OpenMP to create multiple threads to run this loop in parallel for (int i = 1; i <= maxNumber; i++) // Loop from i = 1 to maxNumber (inclusive), increment by 1 { if (findFactors(i, false) == true) // Is this number (i) prime? { primeList[i - 1] = i; // Arrays start at 0 in C } } for (int i = 0; i < maxNumber; i++) // This loop essentially removes the blanks and bunches all the primes up next to eachother in primeList { if (primeList[i] != 0) { primeList[numPrimes] = primeList[i]; numPrimes++; // Count up the number of primes we found } } return numPrimes; } // main is the default name for the starting point of a program in C // int main(int argc, char *argv[]) { int maxNumber, numPrimes; // local variables only visible to this function maxNumber = atoi(argv[1]); // atoi = Ascii TO Integer, argv[0] will be the name of the executable, the first argument is argv[1] numPrimes = primeListTest(maxNumber); // Calculates all prime numbers up to maxNumber printf("Generated %d primes, Largest was: %d \n", numPrimes, primeList[numPrimes - 1]); free(primeList); }
stat_ops.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "stat_ops.h" #include "utility.h" #include "constant.h" double expectation_value_X_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_Y_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_Z_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_multi_qubit_Pauli_operator_XZ_mask(ITYPE bit_flip_mask, ITYPE phase_flip_mask, UINT global_phase_90rot_count,UINT pivot_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_multi_qubit_Pauli_operator_Z_mask(ITYPE phase_flip_mask, const CTYPE* state, ITYPE dim); CTYPE transition_amplitude_multi_qubit_Pauli_operator_XZ_mask(ITYPE bit_flip_mask, ITYPE phase_flip_mask, UINT global_phase_90rot_count, UINT pivot_qubit_index, const CTYPE* state_bra, const CTYPE* state_ket, ITYPE dim); CTYPE transition_amplitude_multi_qubit_Pauli_operator_Z_mask(ITYPE phase_flip_mask, const CTYPE* state_bra, const CTYPE* state_ket, ITYPE dim); // calculate norm double state_norm(const CTYPE *state, ITYPE dim) { ITYPE index; double norm = 0; #ifdef _OPENMP #pragma omp parallel for reduction(+:norm) #endif for (index = 0; index < dim; ++index){ norm += pow(cabs(state[index]), 2); } return norm; } // calculate entropy of probability distribution of Z-basis measurements double measurement_distribution_entropy(const CTYPE *state, ITYPE dim){ ITYPE index; double ent=0; const double eps = 1e-15; #ifdef _OPENMP #pragma omp parallel for reduction(+:ent) #endif for(index = 0; index < dim; ++index){ double prob = pow(cabs(state[index]),2); if(prob > eps){ ent += -1.0*prob*log(prob); } } return ent; } // calculate inner product of two state vector CTYPE state_inner_product(const CTYPE *state_bra, const CTYPE *state_ket, ITYPE dim) { #ifndef _MSC_VER CTYPE value = 0; ITYPE index; #ifdef _OPENMP #pragma omp parallel for reduction(+:value) #endif for(index = 0; index < dim; ++index){ value += conj(state_bra[index]) * state_ket[index]; } return value; #else double real_sum = 0.; double imag_sum = 0.; ITYPE index; #ifdef _OPENMP #pragma omp parallel for reduction(+:real_sum,imag_sum) #endif for (index = 0; index < dim; ++index) { CTYPE value; value += conj(state_bra[index]) * state_ket[index]; real_sum += creal(value); imag_sum += cimag(value); } return real_sum + 1.i * imag_sum; #endif } // calculate probability with which we obtain 0 at target qubit double M0_prob(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE mask = 1ULL << target_qubit_index; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_0 = insert_zero_to_basis_index(state_index,mask,target_qubit_index); sum += pow(cabs(state[basis_0]),2); } return sum; } // calculate probability with which we obtain 1 at target qubit double M1_prob(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE mask = 1ULL << target_qubit_index; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_1 = insert_zero_to_basis_index(state_index,mask,target_qubit_index) ^ mask; sum += pow(cabs(state[basis_1]),2); } return sum; } // calculate merginal probability with which we obtain the set of values measured_value_list at sorted_target_qubit_index_list // warning: sorted_target_qubit_index_list must be sorted. double marginal_prob(const UINT* sorted_target_qubit_index_list, const UINT* measured_value_list, UINT target_qubit_index_count, const CTYPE* state, ITYPE dim){ ITYPE loop_dim = dim >> target_qubit_index_count; ITYPE state_index; double sum=0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index = 0;state_index < loop_dim; ++state_index){ ITYPE basis = state_index; for(UINT cursor=0; cursor < target_qubit_index_count ; cursor++){ UINT insert_index = sorted_target_qubit_index_list[cursor]; ITYPE mask = 1ULL << insert_index; basis = insert_zero_to_basis_index(basis, mask , insert_index ); basis ^= mask * measured_value_list[cursor]; } sum += pow(cabs(state[basis]),2); } return sum; } // calculate expectation value of X on target qubit double expectation_value_X_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE mask = 1ULL << target_qubit_index; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_0 = insert_zero_to_basis_index(state_index,mask,target_qubit_index); ITYPE basis_1 = basis_0 ^ mask; sum += creal( conj(state[basis_0]) * state[basis_1] ) * 2; } return sum; } // calculate expectation value of Y on target qubit double expectation_value_Y_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE mask = 1ULL << target_qubit_index; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_0 = insert_zero_to_basis_index(state_index,mask,target_qubit_index); ITYPE basis_1 = basis_0 ^ mask; sum += cimag( conj(state[basis_0]) * state[basis_1] ) * 2; } return sum; } // calculate expectation value of Z on target qubit double expectation_value_Z_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ int sign = 1 - 2 * ((state_index >> target_qubit_index)%2); sum += creal( conj(state[state_index]) * state[state_index] ) * sign; } return sum; } // calculate expectation value for single-qubit pauli operator double expectation_value_single_qubit_Pauli_operator(UINT target_qubit_index, UINT Pauli_operator_type, const CTYPE *state, ITYPE dim) { if(Pauli_operator_type == 0){ return state_norm(state,dim); }else if(Pauli_operator_type == 1){ return expectation_value_X_Pauli_operator(target_qubit_index, state, dim); }else if(Pauli_operator_type == 2){ return expectation_value_Y_Pauli_operator(target_qubit_index, state, dim); }else if(Pauli_operator_type == 3){ return expectation_value_Z_Pauli_operator(target_qubit_index, state, dim); }else{ fprintf(stderr,"invalid expectation value of pauli operator is called"); exit(1); } } // calculate expectation value of multi-qubit Pauli operator on qubits. // bit-flip mask : the n-bit binary string of which the i-th element is 1 iff the i-th pauli operator is X or Y // phase-flip mask : the n-bit binary string of which the i-th element is 1 iff the i-th pauli operator is Y or Z // We assume bit-flip mask is nonzero, namely, there is at least one X or Y operator. // the pivot qubit is any qubit index which has X or Y // To generate bit-flip mask and phase-flip mask, see get_masks_*_list at utility.h double expectation_value_multi_qubit_Pauli_operator_XZ_mask(ITYPE bit_flip_mask, ITYPE phase_flip_mask, UINT global_phase_90rot_count,UINT pivot_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE pivot_mask = 1ULL << pivot_qubit_index; ITYPE state_index; double sum = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_0 = insert_zero_to_basis_index(state_index, pivot_mask, pivot_qubit_index); ITYPE basis_1 = basis_0 ^ bit_flip_mask; UINT sign_0 = count_population(basis_0 & phase_flip_mask)%2; sum += creal(state[basis_0] * conj(state[basis_1]) * PHASE_90ROT[ (global_phase_90rot_count + sign_0*2)%4 ] * 2.0); } return sum; } double expectation_value_multi_qubit_Pauli_operator_Z_mask(ITYPE phase_flip_mask, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim; ITYPE state_index; double sum = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ UINT bit_parity = count_population(state_index & phase_flip_mask)%2; int sign = 1 - 2*bit_parity; sum += pow(cabs(state[state_index]),2) * sign; } return sum; } CTYPE transition_amplitude_multi_qubit_Pauli_operator_XZ_mask(ITYPE bit_flip_mask, ITYPE phase_flip_mask, UINT global_phase_90rot_count, UINT pivot_qubit_index, const CTYPE* state_bra, const CTYPE* state_ket, ITYPE dim) { const ITYPE loop_dim = dim / 2; const ITYPE pivot_mask = 1ULL << pivot_qubit_index; ITYPE state_index; #ifndef _MSC_VER CTYPE sum = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_0 = insert_zero_to_basis_index(state_index, pivot_mask, pivot_qubit_index); ITYPE basis_1 = basis_0 ^ bit_flip_mask; UINT sign_0 = count_population(basis_0 & phase_flip_mask) % 2; sum += state_ket[basis_0] * conj(state_bra[basis_1]) * PHASE_90ROT[(global_phase_90rot_count + sign_0 * 2) % 4]; UINT sign_1 = count_population(basis_1 & phase_flip_mask) % 2; sum += state_ket[basis_1] * conj(state_bra[basis_0]) * PHASE_90ROT[(global_phase_90rot_count + sign_1 * 2) % 4]; } #else double sum_real = 0.; double sum_imag = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum_real, sum_imag) #endif for (state_index = 0; state_index < loop_dim; ++state_index) { ITYPE basis_0 = insert_zero_to_basis_index(state_index, pivot_mask, pivot_qubit_index); ITYPE basis_1 = basis_0 ^ bit_flip_mask; UINT sign_0 = count_population(basis_0 & phase_flip_mask) % 2; UINT sign_1 = count_population(basis_1 & phase_flip_mask) % 2; CTYPE val1 = state_ket[basis_0] * conj(state_bra[basis_1]) * PHASE_90ROT[(global_phase_90rot_count + sign_0 * 2) % 4]; CTYPE val2 = state_ket[basis_1] * conj(state_bra[basis_0]) * PHASE_90ROT[(global_phase_90rot_count + sign_1 * 2) % 4]; sum_real += creal(val1); sum_imag += cimag(val1); sum_real += creal(val2); sum_imag += cimag(val2); } CTYPE sum(sum_real, sum_imag); #endif return sum; } CTYPE transition_amplitude_multi_qubit_Pauli_operator_Z_mask(ITYPE phase_flip_mask, const CTYPE* state_bra, const CTYPE* state_ket, ITYPE dim) { const ITYPE loop_dim = dim; ITYPE state_index; #ifndef _MSC_VER CTYPE sum = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for (state_index = 0; state_index < loop_dim; ++state_index) { UINT bit_parity = count_population(state_index & phase_flip_mask) % 2; double sign = 1 - 2 * bit_parity; sum += sign*state_ket[state_index] * conj(state_bra[state_index]); } return sum; #else double sum_real = 0.; double sum_imag = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum_real, sum_imag) #endif for (state_index = 0; state_index < loop_dim; ++state_index) { UINT bit_parity = count_population(state_index & phase_flip_mask) % 2; double sign = 1 - 2 * bit_parity; CTYPE val = sign * state_ket[state_index] * conj(state_bra[state_index]); sum_real += creal(val); sum_imag += cimag(val); } CTYPE sum(sum_real, sum_imag); #endif return sum; } double expectation_value_multi_qubit_Pauli_operator_partial_list(const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list, UINT target_qubit_index_count, const CTYPE* state, ITYPE dim){ ITYPE bit_flip_mask = 0; ITYPE phase_flip_mask = 0; UINT global_phase_90rot_count = 0; UINT pivot_qubit_index = 0; get_Pauli_masks_partial_list(target_qubit_index_list, Pauli_operator_type_list, target_qubit_index_count, &bit_flip_mask, &phase_flip_mask, &global_phase_90rot_count, &pivot_qubit_index); double result; if(bit_flip_mask == 0){ result = expectation_value_multi_qubit_Pauli_operator_Z_mask(phase_flip_mask, state,dim); }else{ result = expectation_value_multi_qubit_Pauli_operator_XZ_mask(bit_flip_mask, phase_flip_mask, global_phase_90rot_count, pivot_qubit_index, state, dim); } return result; } double expectation_value_multi_qubit_Pauli_operator_whole_list(const UINT* Pauli_operator_type_list, UINT qubit_count, const CTYPE* state, ITYPE dim){ ITYPE bit_flip_mask = 0; ITYPE phase_flip_mask = 0; UINT global_phase_90rot_count = 0; UINT pivot_qubit_index = 0; get_Pauli_masks_whole_list(Pauli_operator_type_list, qubit_count, &bit_flip_mask, &phase_flip_mask, &global_phase_90rot_count, &pivot_qubit_index); double result; if(bit_flip_mask == 0){ result = expectation_value_multi_qubit_Pauli_operator_Z_mask(phase_flip_mask, state, dim); }else{ result = expectation_value_multi_qubit_Pauli_operator_XZ_mask(bit_flip_mask, phase_flip_mask, global_phase_90rot_count, pivot_qubit_index, state, dim); } return result; } CTYPE transition_amplitude_multi_qubit_Pauli_operator_partial_list(const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list, UINT target_qubit_index_count, const CTYPE* state_bra, const CTYPE* state_ket, ITYPE dim) { ITYPE bit_flip_mask = 0; ITYPE phase_flip_mask = 0; UINT global_phase_90rot_count = 0; UINT pivot_qubit_index = 0; get_Pauli_masks_partial_list(target_qubit_index_list, Pauli_operator_type_list, target_qubit_index_count, &bit_flip_mask, &phase_flip_mask, &global_phase_90rot_count, &pivot_qubit_index); CTYPE result; if (bit_flip_mask == 0) { result = transition_amplitude_multi_qubit_Pauli_operator_Z_mask(phase_flip_mask, state_bra, state_ket, dim); } else { result = transition_amplitude_multi_qubit_Pauli_operator_XZ_mask(bit_flip_mask, phase_flip_mask, global_phase_90rot_count, pivot_qubit_index, state_bra, state_ket, dim); } return result; } CTYPE transition_amplitude_multi_qubit_Pauli_operator_whole_list(const UINT* Pauli_operator_type_list, UINT qubit_count, const CTYPE* state_bra, const CTYPE* state_ket, ITYPE dim) { ITYPE bit_flip_mask = 0; ITYPE phase_flip_mask = 0; UINT global_phase_90rot_count = 0; UINT pivot_qubit_index = 0; get_Pauli_masks_whole_list(Pauli_operator_type_list, qubit_count, &bit_flip_mask, &phase_flip_mask, &global_phase_90rot_count, &pivot_qubit_index); CTYPE result; if (bit_flip_mask == 0) { result = transition_amplitude_multi_qubit_Pauli_operator_Z_mask(phase_flip_mask, state_bra, state_ket, dim); } else { result = transition_amplitude_multi_qubit_Pauli_operator_XZ_mask(bit_flip_mask, phase_flip_mask, global_phase_90rot_count, pivot_qubit_index, state_bra, state_ket, dim); } return result; }
GB_unop__identity_int32_int64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_int32_int64 // op(A') function: GB_unop_tran__identity_int32_int64 // C type: int32_t // A type: int64_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int32_t z = (int32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = (int32_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int32_int64 ( int32_t *Cx, // Cx and Ax may be aliased const int64_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++) { int64_t aij = Ax [p] ; int32_t z = (int32_t) aij ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_int32_int64 ( 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
private-clauseModificado.c
#include <stdio.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int main(){ int i, n = 7; int a[n], suma; for (i=0; i<n; i++) a[i] = i; suma = 10000; #pragma omp parallel private(suma) { //suma=500; #pragma omp for for (i=0; i<n; i++){ suma = suma + a[i]; printf("thread %d suma a[%d] / ", omp_get_thread_num(), i); } printf("\n* thread %d suma= %d", omp_get_thread_num(), suma); } printf("\n"); }
DRB060-matrixmultiply-orig-no.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http:www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https:github.comLLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Classic i-k-j matrix multiplication */ double a[100][100], b[100][100], c[100][100]; int init() { int i, j, k; int _ret_val_0; #pragma cetus firstprivate(a, b, c) #pragma cetus private(i, j, k) #pragma cetus lastprivate(a, b, c) #pragma loop name init#0 #pragma cetus parallel #pragma omp parallel for private(i, j, k) firstprivate(a, b, c) lastprivate(a, b, c) for (i=0; i<100; i ++ ) { #pragma cetus firstprivate(a, c) #pragma cetus private(j, k) #pragma cetus lastprivate(a, c) #pragma loop name init#0#0 #pragma cetus parallel #pragma omp parallel for private(j, k) firstprivate(a, c) lastprivate(a, c) for (k=0; k<100; k ++ ) { #pragma cetus firstprivate(a) #pragma cetus private(j) #pragma cetus lastprivate(a) #pragma loop name init#0#0#0 #pragma cetus parallel #pragma omp parallel for private(j) firstprivate(a) lastprivate(a) for (j=0; j<100; j ++ ) { c[i][j]=(i*j); a[i][k]=(i*j); b[k][j]=(i*j); } } } _ret_val_0=0; return _ret_val_0; } int mmm() { int i, j, k; int _ret_val_0; #pragma cetus private(i, j, k) #pragma loop name mmm#0 #pragma cetus parallel #pragma omp parallel for private(i, j, k) for (i=0; i<100; i ++ ) { #pragma cetus private(j, k) #pragma loop name mmm#0#0 #pragma cetus reduction(+: c[i][j]) #pragma cetus parallel #pragma omp parallel for private(j, k) reduction(+: c[i][j]) for (k=0; k<100; k ++ ) { #pragma cetus private(j) #pragma loop name mmm#0#0#0 #pragma cetus parallel #pragma omp parallel for private(j) for (j=0; j<100; j ++ ) { c[i][j]=(c[i][j]+(a[i][k]*b[k][j])); } } } _ret_val_0=0; return _ret_val_0; } int print() { int i, j, k; int _ret_val_0; #pragma cetus private(i, j, k) #pragma loop name print#0 for (i=0; i<100; i ++ ) { #pragma cetus private(j, k) #pragma loop name print#0#0 for (k=0; k<100; k ++ ) { #pragma cetus private(j) #pragma loop name print#0#0#0 for (j=0; j<100; j ++ ) { printf("%lf %lf %lf\n", c[i][j], a[i][k], b[k][j]); } } } _ret_val_0=0; return _ret_val_0; } int main() { int _ret_val_0; init(); mmm(); print(); _ret_val_0=0; return _ret_val_0; }
GB_binop__lt_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__lt_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__lt_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__lt_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__lt_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_uint32) // A*D function (colscale): GB (_AxD__lt_uint32) // D*A function (rowscale): GB (_DxB__lt_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__lt_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__lt_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_uint32) // C=scalar+B GB (_bind1st__lt_uint32) // C=scalar+B' GB (_bind1st_tran__lt_uint32) // C=A+scalar GB (_bind2nd__lt_uint32) // C=A'+scalar GB (_bind2nd_tran__lt_uint32) // C type: bool // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // 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) \ uint32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ 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_LT || GxB_NO_UINT32 || GxB_NO_LT_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__lt_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__lt_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__lt_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__lt_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else 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__lt_uint32) ( 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__lt_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__lt_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__lt_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__lt_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__lt_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__lt_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = (x < bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__lt_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = (aij < y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__lt_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__lt_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__cos_fc32_fc32.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__cos_fc32_fc32) // op(A') function: GB (_unop_tran__cos_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = ccosf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ccosf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = aij ; \ Cx [pC] = ccosf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_COS || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__cos_fc32_fc32) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = ccosf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = ccosf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__cos_fc32_fc32) ( 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
kmp_taskwait_nowait.c
// RUN: %libomp-compile-and-run // test checks IN dep kind in depend clause on taskwait nowait // uses codegen emulation // Note: no outlined task routine used #include <stdio.h> #include <omp.h> // --------------------------------------------------------------------------- // internal data to emulate compiler codegen #define TIED 1 typedef struct DEP { size_t addr; size_t len; int flags; } _dep; typedef struct ID { int reserved_1; int flags; int reserved_2; int reserved_3; char *psource; } _id; typedef struct task { void** shareds; void* entry; int part_id; void* destr_thunk; int priority; long long device_id; int f_priv; } task_t; typedef int(*entry_t)(int, task_t*); #ifdef __cplusplus extern "C" { #endif extern int __kmpc_global_thread_num(_id*); task_t *__kmpc_omp_task_alloc(_id *loc, int gtid, int flags, size_t sz, size_t shar, entry_t rtn); int __kmpc_omp_task_with_deps(_id *loc, int gtid, task_t *task, int ndeps, _dep *dep_lst, int nd_noalias, _dep *noalias_l); #ifdef __cplusplus } // extern "C" #endif int main() { int i1,i2,i3; omp_set_num_threads(2); printf("addresses: %p %p %p\n", &i1, &i2, &i3); #pragma omp parallel { int t = omp_get_thread_num(); printf("thread %d enters parallel\n", t); #pragma omp single { #pragma omp task depend(in: i3) { int th = omp_get_thread_num(); printf("task 0 created by th %d, executed by th %d\n", t, th); } #pragma omp task depend(in: i2) { int th = omp_get_thread_num(); printf("task 1 created by th %d, executed by th %d\n", t, th); } // #pragma omp taskwait depend(in: i1, i2) nowait { _dep sdep[2]; static _id loc = {0, 2, 0, 0, ";test.c;func;67;0;;"}; int gtid = __kmpc_global_thread_num(&loc); // instead of creating an empty task function we can now send NULL to runtime task_t *ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, NULL); sdep[0].addr = (size_t)&i2; sdep[0].flags = 1; // 1-in, 2-out, 3-inout, 4-mtx, 8-inoutset sdep[1].addr = (size_t)&i1; sdep[1].flags = 1; // in __kmpc_omp_task_with_deps(&loc, gtid, ptr, 2, sdep, 0, NULL); } printf("single done\n"); } } printf("passed\n"); return 0; }
omp_pragma_example2.c
#if 0 //inputBug342-3.c // -rose:C // roseomp: main.C:3114: static int // OmpMidend::transOmpFor(SgPragmaDeclaration*): Assertion isSgForStatement(forstmt) != __null failed. int i; int m; void foo() { // Extra block inserted around subcollection of statements in original block! { //#pragma omp for for (i = 0; i < 10; i++) { m++; } // If we uncomment this statement then we get proper blocking // m++; #pragma omp for } for (i = 1; i < 10; i++) { m++; } } #endif int i,m; void foo () { //#pragma omp for for (i = 0; i < 10; i++) m++; // If we uncomment this statement then we get proper blocking // m++; #pragma omp for for (i = 1; i < 10; i++) m++; }
GB_unop__floor_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__floor_fc64_fc64) // op(A') function: GB (_unop_tran__floor_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = GB_cfloor (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_cfloor (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = GB_cfloor (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_FLOOR || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__floor_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_cfloor (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_cfloor (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__floor_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
6.norace2.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s // Taken from ompVerify, Fig. 4 #include <omp.h> #define N 20 #define M 20 int main() { int uold[N][M], u[N][M]; int i, j; double b = 1.0, omega = 0.8, resid, error = 0.0; #pragma omp parallel for private(j, resid) reduction(+ : error) for (i = 1; i < N; i++) { for (j = 1; j < M; j++) { resid = (uold[i][j] + uold[i - 1][j] + uold[i + 1][j] + uold[i][j - 1] + uold[i][j + 1]) / b; u[i][j] = uold[i][j] - omega * resid; error = error + resid * resid; } } } // CHECK: Region is Data Race Free. // END
GB_unop__identity_uint64_int32.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_uint64_int32 // op(A') function: GB_unop_tran__identity_uint64_int32 // C type: uint64_t // A type: int32_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = (uint64_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_UINT64 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint64_int32 ( uint64_t *Cx, // Cx and Ax may be aliased const int32_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++) { int32_t aij = Ax [p] ; uint64_t z = (uint64_t) aij ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_uint64_int32 ( 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
mxnet_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file mxnet_op.h * \brief * \author Junyuan Xie */ #ifndef MXNET_OPERATOR_MXNET_OP_H_ #define MXNET_OPERATOR_MXNET_OP_H_ #include <dmlc/omp.h> #include <mxnet/base.h> #include <mxnet/engine.h> #include <mxnet/op_attr_types.h> #include <algorithm> #include "./operator_tune.h" #include "../engine/openmp.h" #ifdef __CUDACC__ #include "../common/cuda_utils.h" #endif // __CUDACC__ namespace mxnet { namespace op { namespace mxnet_op { using namespace mshadow; #ifdef __CUDA_ARCH__ __constant__ const float PI = 3.14159265358979323846; #else const float PI = 3.14159265358979323846; using std::isnan; #endif template<typename xpu> int get_num_threads(const int N); #ifdef __CUDACC__ #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) inline cudaDeviceProp cuda_get_device_prop() { int device; CUDA_CALL(cudaGetDevice(&device)); cudaDeviceProp deviceProp; CUDA_CALL(cudaGetDeviceProperties(&deviceProp, device)); return deviceProp; } /*! * \brief Get the number of blocks for cuda kernel given N */ inline int cuda_get_num_blocks(const int N) { using namespace mshadow::cuda; return std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); } template<> inline int get_num_threads<gpu>(const int N) { using namespace mshadow::cuda; return kBaseThreadNum * cuda_get_num_blocks(N); } #endif // __CUDACC__ template<> inline int get_num_threads<cpu>(const int N) { return engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); } /*! \brief operator request type switch */ #define MXNET_ASSIGN_REQ_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } /*! \brief operator request type switch */ #define MXNET_REQ_TYPE_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ { \ const OpReqType ReqType = kNullOp; \ {__VA_ARGS__} \ } \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } #define MXNET_NDIM_SWITCH(NDim, ndim, ...) \ if (NDim == 0) { \ } else if (NDim == 1) { \ const int ndim = 1; \ {__VA_ARGS__} \ } else if (NDim == 2) { \ const int ndim = 2; \ {__VA_ARGS__} \ } else if (NDim == 3) { \ const int ndim = 3; \ {__VA_ARGS__} \ } else if (NDim == 4) { \ const int ndim = 4; \ {__VA_ARGS__} \ } else if (NDim == 5) { \ const int ndim = 5; \ {__VA_ARGS__} \ } else { \ LOG(FATAL) << "ndim=" << NDim << "too large "; \ } #define MXNET_NDIM_SWITCH_EX(NDim, ndim, ...) \ if (NDim == 0) { \ } else if (NDim == 1) { \ const int ndim = 1; \ {__VA_ARGS__} \ } else if (NDim == 2) { \ const int ndim = 2; \ {__VA_ARGS__} \ } else if (NDim == 3) { \ const int ndim = 3; \ {__VA_ARGS__} \ } else if (NDim == 4) { \ const int ndim = 4; \ {__VA_ARGS__} \ } else if (NDim == 5) { \ const int ndim = 5; \ {__VA_ARGS__} \ } else if (NDim == 6) { \ const int ndim = 6; \ {__VA_ARGS__} \ } else if (NDim == 7) { \ const int ndim = 7; \ {__VA_ARGS__} \ } else if (NDim == 8) { \ const int ndim = 8; \ {__VA_ARGS__} \ } else if (NDim == 9) { \ const int ndim = 9; \ {__VA_ARGS__} \ } else if (NDim == 10) { \ const int ndim = 10; \ {__VA_ARGS__} \ } else { \ LOG(FATAL) << "ndim=" << NDim << "too large "; \ } #define MXNET_NO_INT8_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_NO_FLOAT16_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ LOG(FATAL) << "This operation does not " \ "support float16"; \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } template <typename T> struct AccType { using type = T; }; template <> struct AccType<mshadow::half::half_t> { using type = float; }; #define MXNET_REAL_ACC_TYPE_SWITCH(type, DType, AType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ typedef float AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ typedef uint8_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types not uint8"; \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ typedef int8_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types not int8"; \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ typedef int32_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types, not int32"; \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ typedef int64_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types, not int64"; \ } \ break; \ case mshadow::kBool: \ { \ typedef bool DType; \ typedef int64_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types, not bool"; \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_ACC_TYPE_SWITCH(type, DType, AType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ typedef float AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ typedef uint32_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ typedef int32_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ typedef int64_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ typedef int64_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kBool: \ { \ typedef bool DType; \ typedef int64_t AType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_INT_TYPE_SWITCH(type, DType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float32"; \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float64"; \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float16"; \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kBool: \ { \ typedef bool DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_INT32_INT64_TYPE_SWITCH(type, DType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float32"; \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float64"; \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float16"; \ } \ break; \ case mshadow::kUint8: \ { \ LOG(FATAL) << "This operation only support " \ "integer types, not uint8"; \ } \ break; \ case mshadow::kInt8: \ { \ LOG(FATAL) << "This operation only support " \ "integer types, not int8"; \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kBool: \ { \ LOG(FATAL) << "This operation only support " \ "integer types, not bool"; \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_LOAD_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Invalid loading enum type " << type; \ } /*! * \brief assign the val to out according * to request in Kernel::Launch * \param out the data to be assigned * \param req the assignment request * \param val the value to be assigned to out * \tparam OType output type * \tparam VType value type */ #define KERNEL_ASSIGN(out, req, val) \ { \ switch (req) { \ case kNullOp: \ break; \ case kWriteTo: \ case kWriteInplace: \ (out) = (val); \ break; \ case kAddTo: \ (out) += (val); \ break; \ default: \ break; \ } \ } #define MXNET_ADD_ALL_TYPES \ .add_enum("float32", mshadow::kFloat32) \ .add_enum("float64", mshadow::kFloat64) \ .add_enum("float16", mshadow::kFloat16) \ .add_enum("uint8", mshadow::kUint8) \ .add_enum("int8", mshadow::kInt8) \ .add_enum("int32", mshadow::kInt32) \ .add_enum("int64", mshadow::kInt64) #define MXNET_ADD_ALL_TYPES_WITH_BOOL \ .add_enum("float32", mshadow::kFloat32) \ .add_enum("float64", mshadow::kFloat64) \ .add_enum("float16", mshadow::kFloat16) \ .add_enum("uint8", mshadow::kUint8) \ .add_enum("int8", mshadow::kInt8) \ .add_enum("int32", mshadow::kInt32) \ .add_enum("int64", mshadow::kInt64) \ .add_enum("bool", mshadow::kBool) /* \brief Compute flattened index given coordinates and shape. */ template<int ndim> MSHADOW_XINLINE index_t ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) { index_t ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret = ret * shape[i] + (shape[i] > coord[i]) * coord[i]; } return ret; } /* Compute coordinates from flattened index given shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> unravel(const index_t idx, const Shape<ndim>& shape) { Shape<ndim> ret; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret[i] = j - tmp*shape[i]; j = tmp; } return ret; } /* Compute dot product of two vector */ template<int ndim> MSHADOW_XINLINE index_t dot(const Shape<ndim>& coord, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret += coord[i] * stride[i]; } return ret; } /* Combining unravel and dot */ template<int ndim> MSHADOW_XINLINE index_t unravel_dot(const index_t idx, const Shape<ndim>& shape, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret += (j - tmp*shape[i])*stride[i]; j = tmp; } return ret; } /* Calculate stride of each dim from shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) { Shape<ndim> stride; index_t cumprod = 1; #pragma unroll for (int i = ndim - 1; i >= 0; --i) { stride[i] = (shape[i] > 1) ? cumprod : 0; cumprod *= shape[i]; } return stride; } /* Increment coordinates */ template<int ndim> MSHADOW_XINLINE bool inc(Shape<ndim>* coord, const Shape<ndim>& shape) { ++(*coord)[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; } return (*coord)[0] < shape[0]; } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx, const Shape<ndim>& stride) { ++(*coord)[ndim-1]; *idx += stride[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx = *idx + stride[i-1] - shape[i] * stride[i]; } } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx1, const Shape<ndim>& stride1, index_t* idx2, const Shape<ndim>& stride2) { ++(*coord)[ndim-1]; *idx1 += stride1[ndim-1]; *idx2 += stride2[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx1 = *idx1 + stride1[i-1] - shape[i] * stride1[i]; *idx2 = *idx2 + stride2[i-1] - shape[i] * stride2[i]; } } /*! * \brief Simple copy data from one blob to another * \param to Destination blob * \param from Source blob */ template <typename xpu> MSHADOW_CINLINE void copy(mshadow::Stream<xpu> *s, const TBlob& to, const TBlob& from) { CHECK_EQ(from.Size(), to.Size()); CHECK_EQ(from.dev_mask(), to.dev_mask()); MSHADOW_TYPE_SWITCH_WITH_BOOL(to.type_flag_, DType, { if (to.type_flag_ == from.type_flag_) { mshadow::Copy(to.FlatTo1D<xpu, DType>(s), from.FlatTo1D<xpu, DType>(s), s); } else { MSHADOW_TYPE_SWITCH_WITH_BOOL(from.type_flag_, SrcDType, { to.FlatTo1D<xpu, DType>(s) = mshadow::expr::tcast<DType>(from.FlatTo1D<xpu, SrcDType>(s)); }) } }) } /*! \brief Binary op backward gradient OP wrapper */ template<typename GRAD_OP> struct backward_grad { /* \brief Backward calc with grad * \param a - output grad * \param args... - data to grad calculation op (what this is -- input, output, etc. -- varies) * \return input grad */ template<typename DType, typename ...Args> MSHADOW_XINLINE static DType Map(DType a, Args... args) { return DType(a * GRAD_OP::Map(args...)); } }; /*! \brief Binary op backward gradient OP wrapper (tuned) */ template<typename GRAD_OP> struct backward_grad_tuned : public backward_grad<GRAD_OP>, public tunable { using backward_grad<GRAD_OP>::Map; }; /*! \brief Select assignment operation based upon the req value * Also useful for mapping mshadow Compute (F<OP>) to Kernel<OP>::Launch */ template<typename OP, int req> struct op_with_req { typedef OP Operation; /*! \brief input is one tensor */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i])); } /*! \brief inputs are two tensors */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief input is tensor and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } /*! \brief input is tensor and two scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value_1, const DType value_2) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value_1, value_2)); } /*! \brief No inputs (ie fill to constant value) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { KERNEL_ASSIGN(out[i], req, OP::Map()); } /*! \brief input is single scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(value)); } /*! \brief inputs are two tensors and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *input_1, const DType *input_2, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], value)); } /*! \brief inputs are three tensors (ie backward grad with binary grad function) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *input_1, const DType *input_2, const DType *input_3) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], input_3[i])); } /*! \brief input is a tensor and the output is a boolean tensor */ template<typename DType, typename std::enable_if<!std::is_same<DType, bool>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, bool *out, const DType *in) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i])); } /*! \brief inputs are two tensors with a boolean output tensor */ template<typename DType, typename std::enable_if<!std::is_same<DType, bool>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, bool *out, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief input is tensor and two scalar value with a boolean output tensor */ template<typename DType, typename std::enable_if<!std::is_same<DType, bool>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, bool *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } #ifndef _WIN32 /*! \brief inputs are two tensors with a half_t output tensor */ template<typename DType, typename std::enable_if<std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, mshadow::half::half_t *out, const DType *lhs, const mshadow::half::half_t *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief inputs are two tensors with a float output tensor */ template<typename DType, typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value || std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *lhs, const float *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief inputs are two tensors with a double output tensor */ template<typename DType, typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value || std::is_same<DType, float>::value || std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, double *out, const DType *lhs, const double *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief inputs are two tensors with a half_t output tensor */ template<typename DType, typename std::enable_if<std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, mshadow::half::half_t *out, const DType *lhs, const mshadow::half::half_t value) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], value)); } /*! \brief inputs are two tensors with a float output tensor */ template<typename DType, typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value || std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *lhs, const float value) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], value)); } /*! \brief inputs are two tensors with a double output tensor */ template<typename DType, typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value || std::is_same<DType, float>::value || std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, double *out, const DType *lhs, const double value) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], value)); } #endif /*! \brief inputs are two tensors with a float output tensor */ template<typename DType, typename std::enable_if<std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief input is a tensor and a scalar value with a float output tensor */ template<typename DType, typename std::enable_if<std::is_integral<DType>::value, int>::type = 0> MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } }; template<typename OP, typename xpu> struct Kernel; /*! * \brief CPU Kernel launcher * \tparam OP Operator to launch */ template<typename OP> struct Kernel<OP, cpu> { /*! * \brief Launch a generic CPU kernel. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool Launch(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch a generic CPU kernel with dynamic schedule. This is recommended * for irregular workloads such as spmv. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool LaunchDynamic(mshadow::Stream<cpu> *, const int64_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(false); if (omp_threads < 2) { for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) schedule(dynamic) for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } #else for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch CPU kernel which has OMP tuning data available. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam PRIMITIVE_OP The primitive operation to use for tuning * \tparam DType Data type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param dest Destination pointer (used to infer DType) * \param args Varargs to eventually pass to the OP::Map() function */ template<typename PRIMITIVE_OP, typename DType, typename ...Args> static void LaunchTuned(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2 || !tuned_op<PRIMITIVE_OP, DType>::UseOMP( N, static_cast<size_t>(omp_threads))) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif } /*! * \brief Launch custom-tuned kernel where each thread is set to * operate on a contiguous partition * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the UseOMP() and OP::Map() functions */ template<typename ...Args> inline static void LaunchEx(mshadow::Stream<cpu> *s, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { OP::Map(0, N, args...); } else { const auto length = (N + omp_threads - 1) / omp_threads; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); i += length) { OP::Map(i, i + length > N ? N - i : length, args...); } } #else OP::Map(0, N, args...); #endif } /*! * \brief Launch a tunable OP with implicitly-supplied data type * \tparam DType Data type * \tparam T OP type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, T>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<T, DType>(s, N, dest, args...); return true; } /*! * \brief Launch a tunable OP wrapper with explicitly-supplied data type (ie op_with_req) * \tparam DType Data type * \tparam T Wrapper type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, typename T::Operation>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<typename T::Operation, DType>(s, N, dest, args...); return true; } }; #ifdef __CUDACC__ template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, args...); } } template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel_ex(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, 1, args...); } } template<typename OP> struct Kernel<OP, gpu> { /*! \brief Launch GPU kernel */ template<typename ...Args> inline static void Launch(mshadow::Stream<gpu> *s, int N, Args... args) { if (0 == N) return; using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); mxnet_generic_kernel<OP, Args...> <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>( N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel); } template<typename ...Args> inline static void LaunchEx(mshadow::Stream<gpu> *s, const int N, Args... args) { if (0 == N) return; using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); mxnet_generic_kernel_ex<OP, Args...> <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>( N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel_ex); } }; #endif // __CUDACC__ /*! * \brief Set to immediate scalar value kernel * \tparam val Scalar immediate */ template<int val> struct set_to_int : public tunable { // mxnet_op version (when used directly with Kernel<>::Launch()) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { out[i] = DType(val); } // mshadow_op version (when used with op_with_req<>) MSHADOW_XINLINE static int Map() { return val; } }; /*! * \brief Special-case kernel shortcut for setting to zero and one */ using set_zero = set_to_int<0>; using set_one = set_to_int<1>; /*! * \brief Set to immediate scalar value kernel * \tparam val Scalar immediate */ template<bool val> struct set_to_bool : public tunable { // mxnet_op version (when used directly with Kernel<>::Launch()) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { out[i] = DType(val); } // mshadow_op version (when used with op_with_req<>) MSHADOW_XINLINE static int Map() { return val; } }; /*! * \brief Special-case kernel shortcut for setting to true and false */ using set_true = set_to_bool<true>; using set_false = set_to_bool<false>; } // namespace mxnet_op } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_MXNET_OP_H_
SVRGUpdater.h
/* * Copyright 2016 [See AUTHORS file for list of authors] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _SVRG_UPDATER_ #define _SVRG_UPDATER_ #include "Updater.h" #include "../Gradient/Gradient.h" class SVRGUpdater : public Updater { protected: double n_updates_so_far; std::vector<double> model_copy; // Vectors for computing SVRG related data. REGISTER_THREAD_LOCAL_1D_VECTOR(lambda); REGISTER_THREAD_LOCAL_2D_VECTOR(h_x); REGISTER_THREAD_LOCAL_2D_VECTOR(h_y); REGISTER_GLOBAL_1D_VECTOR(g); // Vectors for computing the sum of gradients (g). REGISTER_THREAD_LOCAL_2D_VECTOR(g_kappa); REGISTER_THREAD_LOCAL_1D_VECTOR(g_lambda); REGISTER_THREAD_LOCAL_2D_VECTOR(g_h_bar); REGISTER_GLOBAL_1D_VECTOR(n_zeroes); void PrepareMu(std::vector<int> &coordinates) override { std::vector<double> &cur_model = model->ModelData(); std::vector<double> &lambda = GET_THREAD_LOCAL_VECTOR(lambda); for (int i = 0; i < coordinates.size(); i++) { int index = coordinates[i]; model->Lambda(index, lambda[index], cur_model); } } void PrepareNu(std::vector<int> &coordinates) override { } void PrepareH(Datapoint *datapoint, Gradient *g) override { std::vector<double> &cur_model = model->ModelData(); std::vector<std::vector<double> > &h_x = GET_THREAD_LOCAL_VECTOR(h_x); std::vector<std::vector<double> > &h_y = GET_THREAD_LOCAL_VECTOR(h_y); g->datapoint = datapoint; model->PrecomputeCoefficients(datapoint, g, cur_model); int coord_size = model->CoordinateSize(); for (int i = 0; i < datapoint->GetCoordinates().size(); i++) { int index = datapoint->GetCoordinates()[i]; model->H_bar(index, h_x[index], g, cur_model); } model->PrecomputeCoefficients(datapoint, g, model_copy); for (int i = 0; i < datapoint->GetCoordinates().size(); i++) { int index = datapoint->GetCoordinates()[i]; model->H_bar(index, h_y[index], g, model_copy); } } double H(int coordinate, int index_into_coordinate_vector) { return -FLAGS_learning_rate * (GET_THREAD_LOCAL_VECTOR(h_x)[coordinate][index_into_coordinate_vector] - GET_THREAD_LOCAL_VECTOR(h_y)[coordinate][index_into_coordinate_vector]); } double Nu(int coordinate, int index_into_coordinate_vector) { return FLAGS_learning_rate * (GET_GLOBAL_VECTOR(g)[coordinate*model->CoordinateSize()+index_into_coordinate_vector] - GET_THREAD_LOCAL_VECTOR(lambda)[coordinate] * model_copy[coordinate*model->CoordinateSize()+index_into_coordinate_vector]); } double Mu(int coordinate) { return GET_THREAD_LOCAL_VECTOR(lambda)[coordinate] * FLAGS_learning_rate; } void ModelCopy() { // Make a copy of the model every epoch. model_copy = model->ModelData(); // Clear the sum of gradients. std::vector<double> &g = GET_GLOBAL_VECTOR(g); std::fill(g.begin(), g.end(), 0); // Compute average sum of gradients on the model copy. std::vector<double> &n_zeroes = GET_GLOBAL_VECTOR(n_zeroes); int coord_size = model->CoordinateSize(); // zero gradients. #pragma omp parallel for num_threads(FLAGS_n_threads) for (int coordinate = 0; coordinate < model->NumParameters(); coordinate++) { std::vector<std::vector<double> > &g_kappa = GET_THREAD_LOCAL_VECTOR(g_kappa); std::vector<double> &g_lambda = GET_THREAD_LOCAL_VECTOR(g_lambda); model->Kappa(coordinate, g_kappa[coordinate], model_copy); model->Lambda(coordinate, g_lambda[coordinate], model_copy); for (int j = 0; j < coord_size; j++) { g[coordinate*coord_size+j] = (g_lambda[coordinate] * model_copy[coordinate*coord_size+j] - g_kappa[coordinate][j]) * n_zeroes[coordinate]; } } // non zero gradients. Essentially do SGD here, on the same partitioning pattern. #pragma omp parallel num_threads(FLAGS_n_threads) { int thread = omp_get_thread_num(); for (int batch = 0; batch < datapoint_partitions->NumBatches(); batch++) { #pragma omp barrier for (int index = 0; index < datapoint_partitions->NumDatapointsInBatch(thread, batch); index++) { Datapoint *datapoint = datapoint_partitions->GetDatapoint(thread, batch, index); Gradient *grad = &thread_gradients[omp_get_thread_num()]; grad->datapoint = datapoint; model->PrecomputeCoefficients(datapoint, grad, model_copy); std::vector<std::vector<double> > &g_kappa = GET_THREAD_LOCAL_VECTOR(g_kappa); std::vector<double> &g_lambda = GET_THREAD_LOCAL_VECTOR(g_lambda); std::vector<std::vector<double> > &g_h_bar = GET_THREAD_LOCAL_VECTOR(g_h_bar); for (auto & coord : datapoint->GetCoordinates()) { model->H_bar(coord, g_h_bar[coord], grad, model_copy); model->Lambda(coord, g_lambda[coord], model_copy); model->Kappa(coord, g_kappa[coord], model_copy); } for (auto & coord : datapoint->GetCoordinates()) { for (int j = 0; j < coord_size; j++) { g[coord*coord_size+j] += g_lambda[coord] * model_copy[coord*coord_size+j] - g_kappa[coord][j] + g_h_bar[coord][j]; } } } } } #pragma omp parallel for num_threads(FLAGS_n_threads) for (int i = 0; i < model->NumParameters(); i++) { for (int j = 0; j < coord_size; j++) { g[i*coord_size+j] /= datapoints.size(); } } } public: SVRGUpdater(Model *model, std::vector<Datapoint *> &datapoints) : Updater(model, datapoints) { INITIALIZE_GLOBAL_1D_VECTOR(g, model->NumParameters() * model->CoordinateSize()); INITIALIZE_THREAD_LOCAL_1D_VECTOR(lambda, model->NumParameters()); INITIALIZE_THREAD_LOCAL_2D_VECTOR(h_x, model->NumParameters(), model->CoordinateSize()); INITIALIZE_THREAD_LOCAL_2D_VECTOR(h_y, model->NumParameters(), model->CoordinateSize()); model_copy.resize(model->ModelData().size()); INITIALIZE_THREAD_LOCAL_2D_VECTOR(g_kappa, model->NumParameters(), model->CoordinateSize()); INITIALIZE_THREAD_LOCAL_1D_VECTOR(g_lambda, model->NumParameters()); INITIALIZE_THREAD_LOCAL_2D_VECTOR(g_h_bar, model->NumParameters(), model->CoordinateSize()); // Compute number of zeroes for each column (parameters) of the model. INITIALIZE_GLOBAL_1D_VECTOR(n_zeroes, model->NumParameters()); std::vector<double> &n_zeroes = GET_GLOBAL_VECTOR(n_zeroes); for (int i = 0; i < model->NumParameters(); i++) { n_zeroes[i] = datapoints.size(); } int sum = 0; for (int dp = 0; dp < datapoints.size(); dp++) { for (auto &coordinate : datapoints[dp]->GetCoordinates()) { n_zeroes[coordinate]--; sum++; } } } void Update(Model *model, Datapoint *datapoint) override { Updater::Update(model, datapoint); } void EpochBegin() override { Updater::EpochBegin(); ModelCopy(); } ~SVRGUpdater() { } }; #endif
my_dgemm.c
#include "bl_dgemm_kernel.h" #include "bl_dgemm.h" inline void packA_mcxkc_d( int m, int k, double *XA, int ldXA, int offseta, double *packA ) { int i, p; double *a_pntr[ DGEMM_MR ]; for ( i = 0; i < m; i ++ ) { a_pntr[ i ] = XA + ( offseta + i ); } for ( i = m; i < DGEMM_MR; i ++ ) { a_pntr[ i ] = XA + ( offseta + 0 ); } for ( p = 0; p < k; p ++ ) { for ( i = 0; i < DGEMM_MR; i ++ ) { *packA = *a_pntr[ i ]; packA ++; a_pntr[ i ] = a_pntr[ i ] + ldXA; } } } /* * -------------------------------------------------------------------------- */ inline void packB_kcxnc_d( int n, int k, double *XB, int ldXB, // ldXB is the original k int offsetb, double *packB ) { int j, p; double *b_pntr[ DGEMM_NR ]; for ( j = 0; j < n; j ++ ) { b_pntr[ j ] = XB + ldXB * ( offsetb + j ); } for ( j = n; j < DGEMM_NR; j ++ ) { b_pntr[ j ] = XB + ldXB * ( offsetb + 0 ); } for ( p = 0; p < k; p ++ ) { for ( j = 0; j < DGEMM_NR; j ++ ) { *packB ++ = *b_pntr[ j ] ++; } } } /* * -------------------------------------------------------------------------- */ void bl_macro_kernel( int m, int n, int k, double *packA, double *packB, double *C, int ldc ) { int bl_ic_nt; int i, ii, j; aux_t aux; char *str; aux.b_next = packB; // We can also parallelize with OMP here. //// sequential is the default situation //bl_ic_nt = 1; //// check the environment variable //str = getenv( "BLISLAB_IC_NT" ); //if ( str != NULL ) { // bl_ic_nt = (int)strtol( str, NULL, 10 ); //} //#pragma omp parallel for num_threads( bl_ic_nt ) private( j, i, aux ) for ( j = 0; j < n; j += DGEMM_NR ) { // 2-th loop around micro-kernel aux.n = min( n - j, DGEMM_NR ); for ( i = 0; i < m; i += DGEMM_MR ) { // 1-th loop around micro-kernel aux.m = min( m - i, DGEMM_MR ); if ( i + DGEMM_MR >= m ) { aux.b_next += DGEMM_NR * k; } ( *bl_micro_kernel ) ( k, &packA[ i * k ], &packB[ j * k ], &C[ j * ldc + i ], (unsigned long long) ldc, &aux ); } // 1-th loop around micro-kernel } // 2-th loop around micro-kernel } // C must be aligned void bl_dgemm( int m, int n, int k, double *XA, int lda, double *XB, int ldb, double *C, // must be aligned int ldc // ldc must also be aligned ) { int i, j, p, bl_ic_nt; int ic, ib, jc, jb, pc, pb; int ir, jr; double *packA, *packB; char *str; // Early return if possible if ( m == 0 || n == 0 || k == 0 ) { printf( "bl_dgemm(): early return\n" ); return; } // sequential is the default situation bl_ic_nt = 1; // check the environment variable str = getenv( "BLISLAB_IC_NT" ); if ( str != NULL ) { bl_ic_nt = (int)strtol( str, NULL, 10 ); } // Allocate packing buffers packA = bl_malloc_aligned( DGEMM_KC, ( DGEMM_MC + 1 ) * bl_ic_nt, sizeof(double) ); packB = bl_malloc_aligned( DGEMM_KC, ( DGEMM_NC + 1 ) , sizeof(double) ); for ( jc = 0; jc < n; jc += DGEMM_NC ) { // 5-th loop around micro-kernel jb = min( n - jc, DGEMM_NC ); for ( pc = 0; pc < k; pc += DGEMM_KC ) { // 4-th loop around micro-kernel pb = min( k - pc, DGEMM_KC ); #pragma omp parallel for num_threads( bl_ic_nt ) private( jr ) for ( j = 0; j < jb; j += DGEMM_NR ) { packB_kcxnc_d( min( jb - j, DGEMM_NR ), pb, &XB[ pc ], ldb, jc + j, &packB[ j * pb ] ); } //#pragma omp parallel for num_threads( bl_ic_nt ) private( ic, ib, i, ir ) #pragma omp parallel num_threads( bl_ic_nt ) private( ic, ib, i, ir ) { int tid = omp_get_thread_num(); int my_start; int my_end; bl_get_range( m, DGEMM_MR, &my_start, &my_end ); for ( ic = my_start; ic < my_end; ic += DGEMM_MC ) { // 3-rd loop around micro-kernel ib = min( my_end - ic, DGEMM_MC ); for ( i = 0; i < ib; i += DGEMM_MR ) { packA_mcxkc_d( min( ib - i, DGEMM_MR ), pb, &XA[ pc * lda ], lda, ic + i, &packA[ tid * DGEMM_MC * pb + i * pb ] ); } bl_macro_kernel( ib, jb, pb, packA + tid * DGEMM_MC * pb, packB, &C[ jc * ldc + ic ], ldc ); } // End 3.rd loop around micro-kernel } } // End 4.th loop around micro-kernel } // End 5.th loop around micro-kernel free( packA ); free( packB ); }
GB_binop__min_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_uint32) // A*D function (colscale): GB (_AxD__min_uint32) // D*A function (rowscale): GB (_DxB__min_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__min_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__min_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_uint32) // C=scalar+B GB (_bind1st__min_uint32) // C=scalar+B' GB (_bind1st_tran__min_uint32) // C=A+scalar GB (_bind2nd__min_uint32) // C=A'+scalar GB (_bind2nd_tran__min_uint32) // C type: uint32_t // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // 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) \ uint32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMIN (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MIN || GxB_NO_UINT32 || GxB_NO_MIN_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__min_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__min_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__min_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__min_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__min_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__min_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__min_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__min_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__min_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__min_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__min_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMIN (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__ge_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__ge_int32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__ge_int32) // A.*B function (eWiseMult): GB (_AemultB_03__ge_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ge_int32) // A*D function (colscale): GB (_AxD__ge_int32) // D*A function (rowscale): GB (_DxB__ge_int32) // C+=B function (dense accum): GB (_Cdense_accumB__ge_int32) // C+=b function (dense accum): GB (_Cdense_accumb__ge_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ge_int32) // C=scalar+B GB (_bind1st__ge_int32) // C=scalar+B' GB (_bind1st_tran__ge_int32) // C=A+scalar GB (_bind2nd__ge_int32) // C=A'+scalar GB (_bind2nd_tran__ge_int32) // C type: bool // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ 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) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, 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_INT32 || GxB_NO_GE_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__ge_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__ge_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #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_int32) ( 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 int32_t int32_t bwork = (*((int32_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_int32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__ge_int32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ge_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__ge_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__ge_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__ge_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__ge_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__ge_int32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = Bx [p] ; Cx [p] = (x >= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__ge_int32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = Ax [p] ; Cx [p] = (aij >= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB (_bind1st_tran__ge_int32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB (_bind2nd_tran__ge_int32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mediancut.c
/* ** © 2009-2018 by Kornel Lesiński. ** © 1989, 1991 by Jef Poskanzer. ** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider. ** ** See COPYRIGHT file for license. */ #include <stdlib.h> #include <stddef.h> #include "libimagequant.h" #include "pam.h" #include "mediancut.h" #define index_of_channel(ch) (offsetof(f_pixel,ch)/sizeof(float)) static f_pixel averagepixels(unsigned int clrs, const hist_item achv[]); struct box { f_pixel color; f_pixel variance; double sum, total_error, max_error; unsigned int ind; unsigned int colors; }; ALWAYS_INLINE static double variance_diff(double val, const double good_enough); inline static double variance_diff(double val, const double good_enough) { val *= val; if (val < good_enough*good_enough) return val*0.25; return val; } /** Weighted per-channel variance of the box. It's used to decide which channel to split by */ static f_pixel box_variance(const hist_item achv[], const struct box *box) { f_pixel mean = box->color; double variancea=0, variancer=0, varianceg=0, varianceb=0; for(unsigned int i = 0; i < box->colors; ++i) { const f_pixel px = achv[box->ind + i].acolor; double weight = achv[box->ind + i].adjusted_weight; variancea += variance_diff(mean.a - px.a, 2.0/256.0)*weight; variancer += variance_diff(mean.r - px.r, 1.0/256.0)*weight; varianceg += variance_diff(mean.g - px.g, 1.0/256.0)*weight; varianceb += variance_diff(mean.b - px.b, 1.0/256.0)*weight; } return (f_pixel){ .a = variancea*(4.0/16.0), .r = variancer*(7.0/16.0), .g = varianceg*(9.0/16.0), .b = varianceb*(5.0/16.0), }; } static double box_max_error(const hist_item achv[], const struct box *box) { f_pixel mean = box->color; double max_error = 0; for(unsigned int i = 0; i < box->colors; ++i) { const double diff = colordifference(mean, achv[box->ind + i].acolor); if (diff > max_error) { max_error = diff; } } return max_error; } ALWAYS_INLINE static double color_weight(f_pixel median, hist_item h); static inline void hist_item_swap(hist_item *l, hist_item *r) { if (l != r) { hist_item t = *l; *l = *r; *r = t; } } ALWAYS_INLINE static unsigned int qsort_pivot(const hist_item *const base, const unsigned int len); inline static unsigned int qsort_pivot(const hist_item *const base, const unsigned int len) { if (len < 32) { return len/2; } const unsigned int aidx=8, bidx=len/2, cidx=len-1; const unsigned int a=base[aidx].tmp.sort_value, b=base[bidx].tmp.sort_value, c=base[cidx].tmp.sort_value; return (a < b) ? ((b < c) ? bidx : ((a < c) ? cidx : aidx )) : ((b > c) ? bidx : ((a < c) ? aidx : cidx )); } ALWAYS_INLINE static unsigned int qsort_partition(hist_item *const base, const unsigned int len); inline static unsigned int qsort_partition(hist_item *const base, const unsigned int len) { unsigned int l = 1, r = len; if (len >= 8) { hist_item_swap(&base[0], &base[qsort_pivot(base,len)]); } const unsigned int pivot_value = base[0].tmp.sort_value; while (l < r) { if (base[l].tmp.sort_value >= pivot_value) { l++; } else { while(l < --r && base[r].tmp.sort_value <= pivot_value) {} hist_item_swap(&base[l], &base[r]); } } l--; hist_item_swap(&base[0], &base[l]); return l; } /** quick select algorithm */ static void hist_item_sort_range(hist_item base[], unsigned int len, unsigned int sort_start) { for(;;) { const unsigned int l = qsort_partition(base, len), r = l+1; if (l > 0 && sort_start < l) { len = l; } else if (r < len && sort_start > r) { base += r; len -= r; sort_start -= r; } else break; } } /** sorts array to make sum of weights lower than halfvar one side, returns edge between <halfvar and >halfvar parts of the set */ static hist_item *hist_item_sort_halfvar(hist_item base[], unsigned int len, double *const lowervar, const double halfvar) { do { const unsigned int l = qsort_partition(base, len), r = l+1; // check if sum of left side is smaller than half, // if it is, then it doesn't need to be sorted unsigned int t = 0; double tmpsum = *lowervar; while (t <= l && tmpsum < halfvar) tmpsum += base[t++].color_weight; if (tmpsum < halfvar) { *lowervar = tmpsum; } else { if (l > 0) { hist_item *res = hist_item_sort_halfvar(base, l, lowervar, halfvar); if (res) return res; } else { // End of left recursion. This will be executed in order from the first element. *lowervar += base[0].color_weight; if (*lowervar > halfvar) return &base[0]; } } if (len > r) { base += r; len -= r; // tail-recursive "call" } else { *lowervar += base[r].color_weight; return (*lowervar > halfvar) ? &base[r] : NULL; } } while(1); } static f_pixel get_median(const struct box *b, hist_item achv[]); typedef struct { unsigned int chan; float variance; } channelvariance; static int comparevariance(const void *ch1, const void *ch2) { return ((const channelvariance*)ch1)->variance > ((const channelvariance*)ch2)->variance ? -1 : (((const channelvariance*)ch1)->variance < ((const channelvariance*)ch2)->variance ? 1 : 0); } /** Finds which channels need to be sorted first and preproceses achv for fast sort */ static double prepare_sort(struct box *b, hist_item achv[]) { /* ** Sort dimensions by their variance, and then sort colors first by dimension with highest variance */ channelvariance channels[4] = { {index_of_channel(a), b->variance.a}, {index_of_channel(r), b->variance.r}, {index_of_channel(g), b->variance.g}, {index_of_channel(b), b->variance.b}, }; qsort(channels, 4, sizeof(channels[0]), comparevariance); const unsigned int ind1 = b->ind; const unsigned int colors = b->colors; #if __GNUC__ >= 9 #pragma omp parallel for if (colors > 25000) \ schedule(static) default(none) shared(achv, channels, colors, ind1) #else #pragma omp parallel for if (colors > 25000) \ schedule(static) default(none) shared(achv, channels) #endif for(unsigned int i=0; i < colors; i++) { const float *chans = (const float *)&achv[ind1 + i].acolor; // Only the first channel really matters. When trying median cut many times // with different histogram weights, I don't want sort randomness to influence outcome. achv[ind1 + i].tmp.sort_value = ((unsigned int)(chans[channels[0].chan]*65535.0)<<16) | (unsigned int)((chans[channels[2].chan] + chans[channels[1].chan]/2.0 + chans[channels[3].chan]/4.0)*65535.0); } const f_pixel median = get_median(b, achv); // box will be split to make color_weight of each side even const unsigned int ind = b->ind, end = ind+b->colors; double totalvar = 0; #pragma omp parallel for if (end - ind > 15000) \ schedule(static) default(shared) reduction(+:totalvar) for(unsigned int j=ind; j < end; j++) totalvar += (achv[j].color_weight = color_weight(median, achv[j])); return totalvar / 2.0; } /** finds median in unsorted set by sorting only minimum required */ static f_pixel get_median(const struct box *b, hist_item achv[]) { const unsigned int median_start = (b->colors-1)/2; hist_item_sort_range(&(achv[b->ind]), b->colors, median_start); if (b->colors&1) return achv[b->ind + median_start].acolor; // technically the second color is not guaranteed to be sorted correctly // but most of the time it is good enough to be useful return averagepixels(2, &achv[b->ind + median_start]); } /* ** Find the best splittable box. -1 if no boxes are splittable. */ static int best_splittable_box(struct box bv[], unsigned int boxes, const double max_mse) { int bi=-1; double maxsum=0; for(unsigned int i=0; i < boxes; i++) { if (bv[i].colors < 2) { continue; } // looks only at max variance, because it's only going to split by it const double cv = MAX(bv[i].variance.r, MAX(bv[i].variance.g,bv[i].variance.b)); double thissum = bv[i].sum * MAX(bv[i].variance.a, cv); if (bv[i].max_error > max_mse) { thissum = thissum* bv[i].max_error/max_mse; } if (thissum > maxsum) { maxsum = thissum; bi = i; } } return bi; } inline static double color_weight(f_pixel median, hist_item h) { float diff = colordifference(median, h.acolor); return sqrt(diff) * (sqrt(1.0+h.adjusted_weight)-1.0); } static void set_colormap_from_boxes(colormap *map, struct box bv[], unsigned int boxes, hist_item *achv); static void adjust_histogram(hist_item *achv, const struct box bv[], unsigned int boxes); static double box_error(const struct box *box, const hist_item achv[]) { f_pixel avg = box->color; double total_error=0; for (unsigned int i = 0; i < box->colors; ++i) { total_error += colordifference(avg, achv[box->ind + i].acolor) * achv[box->ind + i].perceptual_weight; } return total_error; } static bool total_box_error_below_target(double target_mse, struct box bv[], unsigned int boxes, const histogram *hist) { target_mse *= hist->total_perceptual_weight; double total_error=0; for(unsigned int i=0; i < boxes; i++) { // error is (re)calculated lazily if (bv[i].total_error >= 0) { total_error += bv[i].total_error; } if (total_error > target_mse) return false; } for(unsigned int i=0; i < boxes; i++) { if (bv[i].total_error < 0) { bv[i].total_error = box_error(&bv[i], hist->achv); total_error += bv[i].total_error; } if (total_error > target_mse) return false; } return true; } static void box_init(struct box *box, const hist_item *achv, const unsigned int ind, const unsigned int colors, const double sum) { box->ind = ind; box->colors = colors; box->sum = sum; box->total_error = -1; box->color = averagepixels(colors, &achv[ind]); box->variance = box_variance(achv, box); box->max_error = box_max_error(achv, box); } /* ** Here is the fun part, the median-cut colormap generator. This is based ** on Paul Heckbert's paper, "Color Image Quantization for Frame Buffer ** Display," SIGGRAPH 1982 Proceedings, page 297. */ LIQ_PRIVATE colormap *mediancut(histogram *hist, unsigned int newcolors, const double target_mse, const double max_mse, void* (*malloc)(size_t), void (*free)(void*)) { hist_item *achv = hist->achv; LIQ_ARRAY(struct box, bv, newcolors); unsigned int boxes = 1; /* ** Set up the initial box. */ { double sum = 0; for(unsigned int i=0; i < hist->size; i++) { sum += achv[i].adjusted_weight; } box_init(&bv[0], achv, 0, hist->size, sum); /* ** Main loop: split boxes until we have enough. */ while (boxes < newcolors) { // first splits boxes that exceed quality limit (to have colors for things like odd green pixel), // later raises the limit to allow large smooth areas/gradients get colors. const double current_max_mse = max_mse + (boxes/(double)newcolors)*16.0*max_mse; const int bi = best_splittable_box(bv, boxes, current_max_mse); if (bi < 0) { break; /* ran out of colors! */ } unsigned int indx = bv[bi].ind; unsigned int clrs = bv[bi].colors; /* Classic implementation tries to get even number of colors or pixels in each subdivision. Here, instead of popularity I use (sqrt(popularity)*variance) metric. Each subdivision balances number of pixels (popular colors) and low variance - boxes can be large if they have similar colors. Later boxes with high variance will be more likely to be split. Median used as expected value gives much better results than mean. */ const double halfvar = prepare_sort(&bv[bi], achv); double lowervar=0; // hist_item_sort_halfvar sorts and sums lowervar at the same time // returns item to break at …minus one, which does smell like an off-by-one error. hist_item *break_p = hist_item_sort_halfvar(&achv[indx], clrs, &lowervar, halfvar); unsigned int break_at = MIN(clrs-1, break_p - &achv[indx] + 1); /* ** Split the box. */ double sm = bv[bi].sum; double lowersum = 0; for(unsigned int i=0; i < break_at; i++) lowersum += achv[indx + i].adjusted_weight; box_init(&bv[bi], achv, indx, break_at, lowersum); box_init(&bv[boxes], achv, indx + break_at, clrs - break_at, sm - lowersum); ++boxes; if (total_box_error_below_target(target_mse, bv, boxes, hist)) { break; } } } colormap *map = pam_colormap(boxes, malloc, free); set_colormap_from_boxes(map, bv, boxes, achv); adjust_histogram(achv, bv, boxes); return map; } static void set_colormap_from_boxes(colormap *map, struct box* bv, unsigned int boxes, hist_item *achv) { /* ** Ok, we've got enough boxes. Now choose a representative color for ** each box. There are a number of possible ways to make this choice. ** One would be to choose the center of the box; this ignores any structure ** within the boxes. Another method would be to average all the colors in ** the box - this is the method specified in Heckbert's paper. */ for(unsigned int bi = 0; bi < boxes; ++bi) { map->palette[bi].acolor = bv[bi].color; /* store total color popularity (perceptual_weight is approximation of it) */ map->palette[bi].popularity = 0; for(unsigned int i=bv[bi].ind; i < bv[bi].ind+bv[bi].colors; i++) { map->palette[bi].popularity += achv[i].perceptual_weight; } } } /* increase histogram popularity by difference from the final color (this is used as part of feedback loop) */ static void adjust_histogram(hist_item *achv, const struct box* bv, unsigned int boxes) { for(unsigned int bi = 0; bi < boxes; ++bi) { for(unsigned int i=bv[bi].ind; i < bv[bi].ind+bv[bi].colors; i++) { achv[i].tmp.likely_colormap_index = bi; } } } static f_pixel averagepixels(unsigned int clrs, const hist_item achv[]) { double r = 0, g = 0, b = 0, a = 0, sum = 0; #pragma omp parallel for if (clrs > 25000) \ schedule(static) default(shared) reduction(+:a) reduction(+:r) reduction(+:g) reduction(+:b) reduction(+:sum) for(unsigned int i = 0; i < clrs; i++) { const f_pixel px = achv[i].acolor; const double weight = achv[i].adjusted_weight; sum += weight; a += px.a * weight; r += px.r * weight; g += px.g * weight; b += px.b * weight; } if (sum) { a /= sum; r /= sum; g /= sum; b /= sum; } assert(!isnan(r) && !isnan(g) && !isnan(b) && !isnan(a)); return (f_pixel){.r=r, .g=g, .b=b, .a=a}; }
YAKL_atomics.h
#pragma once // Included by YAKL.h namespace yakl { // These are YAKL's atomic operations: atomicAdd, atomicMin, and atomicMax // Where possible, hardware atomics are used. Where that's not possible, CompareAndSwap (CAS) // implementations are used. template <class T> inline void atomicAdd_host(T &update, T value) { update += value; } template <class T> inline void atomicMin_host(T &update, T value) { update = update < value ? update : value; } template <class T> inline void atomicMax_host(T &update, T value) { update = update > value ? update : value; } #ifdef YAKL_ARCH_CUDA __device__ __forceinline__ void atomicMin_device(float &update , float value) { int oldval, newval, readback; oldval = __float_as_int(update); newval = __float_as_int( __int_as_float(oldval) < value ? __int_as_float(oldval) : value ); while ( ( readback = atomicCAS( (int *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __float_as_int( __int_as_float(oldval) < value ? __int_as_float(oldval) : value ); } } __device__ __forceinline__ void atomicMin_device(double &update , double value) { unsigned long long oldval, newval, readback; oldval = __double_as_longlong(update); newval = __double_as_longlong( __longlong_as_double(oldval) < value ? __longlong_as_double(oldval) : value ); while ( ( readback = atomicCAS( (unsigned long long *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __double_as_longlong( __longlong_as_double(oldval) < value ? __longlong_as_double(oldval) : value ); } } __device__ __forceinline__ void atomicMin_device(int &update , int value) { ::atomicMin( &update , value ); } __device__ __forceinline__ void atomicMin_device(unsigned int &update , unsigned int value) { ::atomicMin( &update , value ); } __device__ __forceinline__ void atomicMin_device(unsigned long long int &update , unsigned long long int value) { #if __CUDA_ARCH__ >= 350 ::atomicMin( &update , value ); #else yakl_throw("ERROR: atomicMin not implemented for unsigned long long int for this CUDA architecture"); #endif } template <class T> __host__ __device__ __forceinline__ void atomicMin(T &update , T value) { #if YAKL_CURRENTLY_ON_DEVICE() atomicMin_device(update,value); #else atomicMin_host (update,value); #endif } __device__ __forceinline__ void atomicMax_device(float &update , float value) { int oldval, newval, readback; oldval = __float_as_int(update); newval = __float_as_int( __int_as_float(oldval) > value ? __int_as_float(oldval) : value ); while ( ( readback = atomicCAS( (int *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __float_as_int( __int_as_float(oldval) > value ? __int_as_float(oldval) : value ); } } __device__ __forceinline__ void atomicMax_device(double &update , double value) { unsigned long long oldval, newval, readback; oldval = __double_as_longlong(update); newval = __double_as_longlong( __longlong_as_double(oldval) > value ? __longlong_as_double(oldval) : value ); while ( ( readback = atomicCAS( (unsigned long long *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __double_as_longlong( __longlong_as_double(oldval) > value ? __longlong_as_double(oldval) : value ); } } __device__ __forceinline__ void atomicMax_device(int &update , int value) { ::atomicMax( &update , value ); } __device__ __forceinline__ void atomicMax_device(unsigned int &update , unsigned int value) { ::atomicMax( &update , value ); } __device__ __forceinline__ void atomicMax_device(unsigned long long int &update , unsigned long long int value) { #if __CUDA_ARCH__ >= 350 ::atomicMax( &update , value ); #else yakl_throw("ERROR: atomicMin not implemented for unsigned long long int for this CUDA architecture"); #endif } template <class T> __host__ __device__ __forceinline__ void atomicMax(T &update , T value) { #if YAKL_CURRENTLY_ON_DEVICE() atomicMax_device(update,value); #else atomicMax_host (update,value); #endif } __device__ __forceinline__ void atomicAdd_device(float &update , float value) { ::atomicAdd( &update , value ); } __device__ __forceinline__ void atomicAdd_device(double &update , double value) { #if __CUDA_ARCH__ >= 600 ::atomicAdd( &update , value ); #else unsigned long long oldval, newval, readback; oldval = __double_as_longlong(update); newval = __double_as_longlong( __longlong_as_double(oldval) + value ); while ( ( readback = atomicCAS( (unsigned long long *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __double_as_longlong( __longlong_as_double(oldval) + value ); } #endif } __device__ __forceinline__ void atomicAdd_device(int &update , int value) { ::atomicAdd( &update , value ); } __device__ __forceinline__ void atomicAdd_device(unsigned int &update , unsigned int value) { ::atomicAdd( &update , value ); } __device__ __forceinline__ void atomicAdd_device(unsigned long long int &update , unsigned long long int value) { ::atomicAdd( &update , value ); } template <class T> __host__ __device__ __forceinline__ void atomicAdd(T &update , T value) { #if YAKL_CURRENTLY_ON_DEVICE() atomicAdd_device(update,value); #else atomicAdd_host (update,value); #endif } #elif defined(YAKL_ARCH_SYCL) template <typename T, sycl::access::address_space addressSpace = sycl::access::address_space::global_space> using relaxed_atomic_ref = sycl::atomic_ref< T, sycl::memory_order::seq_cst, sycl::memory_scope::device, addressSpace>; template <typename T, sycl::access::address_space addressSpace = sycl::access::address_space::global_space> __inline__ __attribute__((always_inline)) void atomicMin(T &update , T value) { relaxed_atomic_ref<T, addressSpace>( update ).fetch_min( value ); } template <typename T, sycl::access::address_space addressSpace = sycl::access::address_space::global_space> __inline__ __attribute__((always_inline)) void atomicMax(T &update , T value) { relaxed_atomic_ref<T, addressSpace>( update ).fetch_max( value ); } template <typename T, sycl::access::address_space addressSpace = sycl::access::address_space::global_space> __inline__ __attribute__((always_inline)) void atomicAdd(T &update , T value) { relaxed_atomic_ref<T, addressSpace>( update ).fetch_add( value ); } #elif defined(YAKL_ARCH_HIP) __device__ __forceinline__ void atomicMin_device(float &update , float value) { int oldval, newval, readback; oldval = __float_as_int(update); newval = __float_as_int( __int_as_float(oldval) < value ? __int_as_float(oldval) : value ); while ( ( readback = atomicCAS( (int *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __float_as_int( __int_as_float(oldval) < value ? __int_as_float(oldval) : value ); } } __device__ __forceinline__ void atomicMin_device(double &update , double value) { unsigned long long oldval, newval, readback; oldval = __double_as_longlong(update); newval = __double_as_longlong( __longlong_as_double(oldval) < value ? __longlong_as_double(oldval) : value ); while ( ( readback = atomicCAS( (unsigned long long *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __double_as_longlong( __longlong_as_double(oldval) < value ? __longlong_as_double(oldval) : value ); } } __device__ __forceinline__ void atomicMin_device(int &update , int value) { ::atomicMin( &update , value ); } __device__ __forceinline__ void atomicMin_device(unsigned int &update , unsigned int value) { ::atomicMin( &update , value ); } __device__ __forceinline__ void atomicMin_device(unsigned long long int &update , unsigned long long int value) { ::atomicMin( &update , value ); } template <class T> __host__ __device__ __forceinline__ void atomicMin(T &update , T value) { #if YAKL_CURRENTLY_ON_DEVICE() atomicMin_device(update,value); #else atomicMin_host (update,value); #endif } __device__ __forceinline__ void atomicMax_device(float &update , float value) { int oldval, newval, readback; oldval = __float_as_int(update); newval = __float_as_int( __int_as_float(oldval) > value ? __int_as_float(oldval) : value ); while ( ( readback = atomicCAS( (int *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __float_as_int( __int_as_float(oldval) > value ? __int_as_float(oldval) : value ); } } __device__ __forceinline__ void atomicMax_device(double &update , double value) { unsigned long long oldval, newval, readback; oldval = __double_as_longlong(update); newval = __double_as_longlong( __longlong_as_double(oldval) > value ? __longlong_as_double(oldval) : value ); while ( ( readback = atomicCAS( (unsigned long long *) &update , oldval , newval ) ) != oldval ) { oldval = readback; newval = __double_as_longlong( __longlong_as_double(oldval) > value ? __longlong_as_double(oldval) : value ); } } __device__ __forceinline__ void atomicMax_device(int &update , int value) { ::atomicMax( &update , value ); } __device__ __forceinline__ void atomicMax_device(unsigned int &update , unsigned int value) { ::atomicMax( &update , value ); } __device__ __forceinline__ void atomicMax_device(unsigned long long int &update , unsigned long long int value) { ::atomicMax( &update , value ); } template <class T> __host__ __device__ __forceinline__ void atomicMax(T &update , T value) { #if YAKL_CURRENTLY_ON_DEVICE() atomicMax_device(update,value); #else atomicMax_host (update,value); #endif } __device__ __forceinline__ void atomicAdd_device(float &update , float value) { ::atomicAdd( &update , value ); } __device__ __forceinline__ void atomicAdd_device(double &update , double value) { ::atomicAdd( &update , value ); } __device__ __forceinline__ void atomicAdd_device(int &update , int value) { ::atomicAdd( &update , value ); } __device__ __forceinline__ void atomicAdd_device(unsigned int &update , unsigned int value) { ::atomicAdd( &update , value ); } __device__ __forceinline__ void atomicAdd_device(unsigned long long int &update , unsigned long long int value) { ::atomicAdd( &update , value ); } template <class T> __host__ __device__ __forceinline__ void atomicAdd(T &update , T value) { #if YAKL_CURRENTLY_ON_DEVICE() atomicAdd_device(update,value); #else atomicAdd_host (update,value); #endif } #elif defined(YAKL_ARCH_OPENMP) template <class T> inline void atomicMin(T &update, T value) { #pragma omp critical { update = value < update ? value : update; } } template <class T> inline void atomicMax(T &update, T value) { #pragma omp critical { update = value > update ? value : update; } } template <class T> inline void atomicAdd(T &update, T value) { #pragma omp atomic update update += value; } #else template <class T> inline void atomicMin(T &update, T value) { atomicMin_host(update,value); } template <class T> inline void atomicMax(T &update, T value) { atomicMax_host(update,value); } template <class T> inline void atomicAdd(T &update, T value) { atomicAdd_host(update,value); } #endif }
2008.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "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 for schedule(static, 2) simd num_threads(2) 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 parallel for schedule(static, 2) simd num_threads(2) 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 parallel for schedule(static, 2) simd num_threads(2) for (i = 0; i < _PB_N; i++) { #pragma omp parallel for schedule(static, 2) simd num_threads(2) 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 parallel for schedule(static, 2) simd num_threads(2) 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; }
StmtOpenMP.h
//===- StmtOpenMP.h - Classes for OpenMP directives ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file defines OpenMP AST classes for executable directives and /// clauses. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMTOPENMP_H #define LLVM_CLANG_AST_STMTOPENMP_H #include "clang/AST/Expr.h" #include "clang/AST/OpenMPClause.h" #include "clang/AST/Stmt.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" namespace clang { //===----------------------------------------------------------------------===// // AST classes for directives. //===----------------------------------------------------------------------===// /// This is a basic class for representing single OpenMP executable /// directive. /// class OMPExecutableDirective : public Stmt { friend class ASTStmtReader; /// Kind of the directive. OpenMPDirectiveKind Kind; /// Starting location of the directive (directive keyword). SourceLocation StartLoc; /// Ending location of the directive. SourceLocation EndLoc; /// Numbers of clauses. const unsigned NumClauses; /// Number of child expressions/stmts. const unsigned NumChildren; /// Offset from this to the start of clauses. /// There are NumClauses pointers to clauses, they are followed by /// NumChildren pointers to child stmts/exprs (if the directive type /// requires an associated stmt, then it has to be the first of them). const unsigned ClausesOffset; /// Get the clauses storage. MutableArrayRef<OMPClause *> getClauses() { OMPClause **ClauseStorage = reinterpret_cast<OMPClause **>( reinterpret_cast<char *>(this) + ClausesOffset); return MutableArrayRef<OMPClause *>(ClauseStorage, NumClauses); } protected: /// Build instance of directive of class \a K. /// /// \param SC Statement class. /// \param K Kind of OpenMP directive. /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending location of the directive. /// template <typename T> OMPExecutableDirective(const T *, StmtClass SC, OpenMPDirectiveKind K, SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses, unsigned NumChildren) : Stmt(SC), Kind(K), StartLoc(std::move(StartLoc)), EndLoc(std::move(EndLoc)), NumClauses(NumClauses), NumChildren(NumChildren), ClausesOffset(llvm::alignTo(sizeof(T), alignof(OMPClause *))) {} /// Sets the list of variables for this clause. /// /// \param Clauses The list of clauses for the directive. /// void setClauses(ArrayRef<OMPClause *> Clauses); /// Set the associated statement for the directive. /// /// /param S Associated statement. /// void setAssociatedStmt(Stmt *S) { assert(hasAssociatedStmt() && "no associated statement."); *child_begin() = S; } public: /// Iterates over a filtered subrange of clauses applied to a /// directive. /// /// This iterator visits only clauses of type SpecificClause. template <typename SpecificClause> class specific_clause_iterator : public llvm::iterator_adaptor_base< specific_clause_iterator<SpecificClause>, ArrayRef<OMPClause *>::const_iterator, std::forward_iterator_tag, const SpecificClause *, ptrdiff_t, const SpecificClause *, const SpecificClause *> { ArrayRef<OMPClause *>::const_iterator End; void SkipToNextClause() { while (this->I != End && !isa<SpecificClause>(*this->I)) ++this->I; } public: explicit specific_clause_iterator(ArrayRef<OMPClause *> Clauses) : specific_clause_iterator::iterator_adaptor_base(Clauses.begin()), End(Clauses.end()) { SkipToNextClause(); } const SpecificClause *operator*() const { return cast<SpecificClause>(*this->I); } const SpecificClause *operator->() const { return **this; } specific_clause_iterator &operator++() { ++this->I; SkipToNextClause(); return *this; } }; template <typename SpecificClause> static llvm::iterator_range<specific_clause_iterator<SpecificClause>> getClausesOfKind(ArrayRef<OMPClause *> Clauses) { return {specific_clause_iterator<SpecificClause>(Clauses), specific_clause_iterator<SpecificClause>( llvm::makeArrayRef(Clauses.end(), 0))}; } template <typename SpecificClause> llvm::iterator_range<specific_clause_iterator<SpecificClause>> getClausesOfKind() const { return getClausesOfKind<SpecificClause>(clauses()); } /// Gets a single clause of the specified kind associated with the /// current directive iff there is only one clause of this kind (and assertion /// is fired if there is more than one clause is associated with the /// directive). Returns nullptr if no clause of this kind is associated with /// the directive. template <typename SpecificClause> const SpecificClause *getSingleClause() const { auto Clauses = getClausesOfKind<SpecificClause>(); if (Clauses.begin() != Clauses.end()) { assert(std::next(Clauses.begin()) == Clauses.end() && "There are at least 2 clauses of the specified kind"); return *Clauses.begin(); } return nullptr; } /// Returns true if the current directive has one or more clauses of a /// specific kind. template <typename SpecificClause> bool hasClausesOfKind() const { auto Clauses = getClausesOfKind<SpecificClause>(); return Clauses.begin() != Clauses.end(); } /// Returns starting location of directive kind. SourceLocation getBeginLoc() const { return StartLoc; } /// Returns ending location of directive. SourceLocation getEndLoc() const { return EndLoc; } /// Set starting location of directive kind. /// /// \param Loc New starting location of directive. /// void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// Set ending location of directive. /// /// \param Loc New ending location of directive. /// void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// Get number of clauses. unsigned getNumClauses() const { return NumClauses; } /// Returns specified clause. /// /// \param i Number of clause. /// OMPClause *getClause(unsigned i) const { return clauses()[i]; } /// Returns true if directive has associated statement. bool hasAssociatedStmt() const { return NumChildren > 0; } /// Returns statement associated with the directive. const Stmt *getAssociatedStmt() const { assert(hasAssociatedStmt() && "no associated statement."); return *child_begin(); } Stmt *getAssociatedStmt() { assert(hasAssociatedStmt() && "no associated statement."); return *child_begin(); } /// Returns the captured statement associated with the /// component region within the (combined) directive. // // \param RegionKind Component region kind. const CapturedStmt *getCapturedStmt(OpenMPDirectiveKind RegionKind) const { SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind()); assert(std::any_of( CaptureRegions.begin(), CaptureRegions.end(), [=](const OpenMPDirectiveKind K) { return K == RegionKind; }) && "RegionKind not found in OpenMP CaptureRegions."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (auto ThisCaptureRegion : CaptureRegions) { if (ThisCaptureRegion == RegionKind) return CS; CS = cast<CapturedStmt>(CS->getCapturedStmt()); } llvm_unreachable("Incorrect RegionKind specified for directive."); } /// Get innermost captured statement for the construct. CapturedStmt *getInnermostCapturedStmt() { assert(hasAssociatedStmt() && getAssociatedStmt() && "Must have associated statement."); SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; getOpenMPCaptureRegions(CaptureRegions, getDirectiveKind()); assert(!CaptureRegions.empty() && "At least one captured statement must be provided."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (unsigned Level = CaptureRegions.size(); Level > 1; --Level) CS = cast<CapturedStmt>(CS->getCapturedStmt()); return CS; } const CapturedStmt *getInnermostCapturedStmt() const { return const_cast<OMPExecutableDirective *>(this) ->getInnermostCapturedStmt(); } OpenMPDirectiveKind getDirectiveKind() const { return Kind; } static bool classof(const Stmt *S) { return S->getStmtClass() >= firstOMPExecutableDirectiveConstant && S->getStmtClass() <= lastOMPExecutableDirectiveConstant; } child_range children() { if (!hasAssociatedStmt()) return child_range(child_iterator(), child_iterator()); Stmt **ChildStorage = reinterpret_cast<Stmt **>(getClauses().end()); /// Do not mark all the special expression/statements as children, except /// for the associated statement. return child_range(ChildStorage, ChildStorage + 1); } ArrayRef<OMPClause *> clauses() { return getClauses(); } ArrayRef<OMPClause *> clauses() const { return const_cast<OMPExecutableDirective *>(this)->getClauses(); } }; /// This represents '#pragma omp parallel' directive. /// /// \code /// #pragma omp parallel private(a,b) reduction(+: c,d) /// \endcode /// In this example directive '#pragma omp parallel' has clauses 'private' /// with the variables 'a' and 'b' and 'reduction' with operator '+' and /// variables 'c' and 'd'. /// class OMPParallelDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending Location of the directive. /// OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPParallelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement associated with the directive. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPParallelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPParallelDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelDirectiveClass; } }; /// This is a common base class for loop directives ('omp simd', 'omp /// for', 'omp for simd' etc.). It is responsible for the loop code generation. /// class OMPLoopDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Number of collapsed loops as specified by 'collapse' clause. unsigned CollapsedNum; /// Offsets to the stored exprs. /// This enumeration contains offsets to all the pointers to children /// expressions stored in OMPLoopDirective. /// The first 9 children are necessary for all the loop directives, /// the next 8 are specific to the worksharing ones, and the next 11 are /// used for combined constructs containing two pragmas associated to loops. /// After the fixed children, three arrays of length CollapsedNum are /// allocated: loop counters, their updates and final values. /// PrevLowerBound and PrevUpperBound are used to communicate blocking /// information in composite constructs which require loop blocking /// DistInc is used to generate the increment expression for the distribute /// loop when combined with a further nested loop /// PrevEnsureUpperBound is used as the EnsureUpperBound expression for the /// for loop when combined with a previous distribute loop in the same pragma /// (e.g. 'distribute parallel for') /// enum { AssociatedStmtOffset = 0, IterationVariableOffset = 1, LastIterationOffset = 2, CalcLastIterationOffset = 3, PreConditionOffset = 4, CondOffset = 5, InitOffset = 6, IncOffset = 7, PreInitsOffset = 8, // The '...End' enumerators do not correspond to child expressions - they // specify the offset to the end (and start of the following counters/ // updates/finals arrays). DefaultEnd = 9, // The following 8 exprs are used by worksharing and distribute loops only. IsLastIterVariableOffset = 9, LowerBoundVariableOffset = 10, UpperBoundVariableOffset = 11, StrideVariableOffset = 12, EnsureUpperBoundOffset = 13, NextLowerBoundOffset = 14, NextUpperBoundOffset = 15, NumIterationsOffset = 16, // Offset to the end for worksharing loop directives. WorksharingEnd = 17, PrevLowerBoundVariableOffset = 17, PrevUpperBoundVariableOffset = 18, DistIncOffset = 19, PrevEnsureUpperBoundOffset = 20, CombinedLowerBoundVariableOffset = 21, CombinedUpperBoundVariableOffset = 22, CombinedEnsureUpperBoundOffset = 23, CombinedInitOffset = 24, CombinedConditionOffset = 25, CombinedNextLowerBoundOffset = 26, CombinedNextUpperBoundOffset = 27, CombinedDistConditionOffset = 28, CombinedParForInDistConditionOffset = 29, // Offset to the end (and start of the following counters/updates/finals // arrays) for combined distribute loop directives. CombinedDistributeEnd = 30, }; /// Get the counters storage. MutableArrayRef<Expr *> getCounters() { Expr **Storage = reinterpret_cast<Expr **>( &(*(std::next(child_begin(), getArraysOffset(getDirectiveKind()))))); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the private counters storage. MutableArrayRef<Expr *> getPrivateCounters() { Expr **Storage = reinterpret_cast<Expr **>(&*std::next( child_begin(), getArraysOffset(getDirectiveKind()) + CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the updates storage. MutableArrayRef<Expr *> getInits() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 2 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the updates storage. MutableArrayRef<Expr *> getUpdates() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 3 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// Get the final counter updates storage. MutableArrayRef<Expr *> getFinals() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 4 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } protected: /// Build instance of loop directive of class \a Kind. /// /// \param SC Statement class. /// \param Kind Kind of OpenMP directive. /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed loops from 'collapse' clause. /// \param NumClauses Number of clauses. /// \param NumSpecialChildren Number of additional directive-specific stmts. /// template <typename T> OMPLoopDirective(const T *That, StmtClass SC, OpenMPDirectiveKind Kind, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses, unsigned NumSpecialChildren = 0) : OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses, numLoopChildren(CollapsedNum, Kind) + NumSpecialChildren), CollapsedNum(CollapsedNum) {} /// Offset to the start of children expression arrays. static unsigned getArraysOffset(OpenMPDirectiveKind Kind) { if (isOpenMPLoopBoundSharingDirective(Kind)) return CombinedDistributeEnd; if (isOpenMPWorksharingDirective(Kind) || isOpenMPTaskLoopDirective(Kind) || isOpenMPDistributeDirective(Kind)) return WorksharingEnd; return DefaultEnd; } /// Children number. static unsigned numLoopChildren(unsigned CollapsedNum, OpenMPDirectiveKind Kind) { return getArraysOffset(Kind) + 5 * CollapsedNum; // Counters, // PrivateCounters, Inits, // Updates and Finals } void setIterationVariable(Expr *IV) { *std::next(child_begin(), IterationVariableOffset) = IV; } void setLastIteration(Expr *LI) { *std::next(child_begin(), LastIterationOffset) = LI; } void setCalcLastIteration(Expr *CLI) { *std::next(child_begin(), CalcLastIterationOffset) = CLI; } void setPreCond(Expr *PC) { *std::next(child_begin(), PreConditionOffset) = PC; } void setCond(Expr *Cond) { *std::next(child_begin(), CondOffset) = Cond; } void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; } void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; } void setPreInits(Stmt *PreInits) { *std::next(child_begin(), PreInitsOffset) = PreInits; } void setIsLastIterVariable(Expr *IL) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), IsLastIterVariableOffset) = IL; } void setLowerBoundVariable(Expr *LB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), LowerBoundVariableOffset) = LB; } void setUpperBoundVariable(Expr *UB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), UpperBoundVariableOffset) = UB; } void setStrideVariable(Expr *ST) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), StrideVariableOffset) = ST; } void setEnsureUpperBound(Expr *EUB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), EnsureUpperBoundOffset) = EUB; } void setNextLowerBound(Expr *NLB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NextLowerBoundOffset) = NLB; } void setNextUpperBound(Expr *NUB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NextUpperBoundOffset) = NUB; } void setNumIterations(Expr *NI) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NumIterationsOffset) = NI; } void setPrevLowerBoundVariable(Expr *PrevLB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), PrevLowerBoundVariableOffset) = PrevLB; } void setPrevUpperBoundVariable(Expr *PrevUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), PrevUpperBoundVariableOffset) = PrevUB; } void setDistInc(Expr *DistInc) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), DistIncOffset) = DistInc; } void setPrevEnsureUpperBound(Expr *PrevEUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), PrevEnsureUpperBoundOffset) = PrevEUB; } void setCombinedLowerBoundVariable(Expr *CombLB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedLowerBoundVariableOffset) = CombLB; } void setCombinedUpperBoundVariable(Expr *CombUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedUpperBoundVariableOffset) = CombUB; } void setCombinedEnsureUpperBound(Expr *CombEUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedEnsureUpperBoundOffset) = CombEUB; } void setCombinedInit(Expr *CombInit) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedInitOffset) = CombInit; } void setCombinedCond(Expr *CombCond) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedConditionOffset) = CombCond; } void setCombinedNextLowerBound(Expr *CombNLB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedNextLowerBoundOffset) = CombNLB; } void setCombinedNextUpperBound(Expr *CombNUB) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); *std::next(child_begin(), CombinedNextUpperBoundOffset) = CombNUB; } void setCombinedDistCond(Expr *CombDistCond) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound distribute sharing directive"); *std::next(child_begin(), CombinedDistConditionOffset) = CombDistCond; } void setCombinedParForInDistCond(Expr *CombParForInDistCond) { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound distribute sharing directive"); *std::next(child_begin(), CombinedParForInDistConditionOffset) = CombParForInDistCond; } void setCounters(ArrayRef<Expr *> A); void setPrivateCounters(ArrayRef<Expr *> A); void setInits(ArrayRef<Expr *> A); void setUpdates(ArrayRef<Expr *> A); void setFinals(ArrayRef<Expr *> A); public: /// The expressions built to support OpenMP loops in combined/composite /// pragmas (e.g. pragma omp distribute parallel for) struct DistCombinedHelperExprs { /// DistributeLowerBound - used when composing 'omp distribute' with /// 'omp for' in a same construct. Expr *LB; /// DistributeUpperBound - used when composing 'omp distribute' with /// 'omp for' in a same construct. Expr *UB; /// DistributeEnsureUpperBound - used when composing 'omp distribute' /// with 'omp for' in a same construct, EUB depends on DistUB Expr *EUB; /// Distribute loop iteration variable init used when composing 'omp /// distribute' /// with 'omp for' in a same construct Expr *Init; /// Distribute Loop condition used when composing 'omp distribute' /// with 'omp for' in a same construct Expr *Cond; /// Update of LowerBound for statically scheduled omp loops for /// outer loop in combined constructs (e.g. 'distribute parallel for') Expr *NLB; /// Update of UpperBound for statically scheduled omp loops for /// outer loop in combined constructs (e.g. 'distribute parallel for') Expr *NUB; /// Distribute Loop condition used when composing 'omp distribute' /// with 'omp for' in a same construct when schedule is chunked. Expr *DistCond; /// 'omp parallel for' loop condition used when composed with /// 'omp distribute' in the same construct and when schedule is /// chunked and the chunk size is 1. Expr *ParForInDistCond; }; /// The expressions built for the OpenMP loop CodeGen for the /// whole collapsed loop nest. struct HelperExprs { /// Loop iteration variable. Expr *IterationVarRef; /// Loop last iteration number. Expr *LastIteration; /// Loop number of iterations. Expr *NumIterations; /// Calculation of last iteration. Expr *CalcLastIteration; /// Loop pre-condition. Expr *PreCond; /// Loop condition. Expr *Cond; /// Loop iteration variable init. Expr *Init; /// Loop increment. Expr *Inc; /// IsLastIteration - local flag variable passed to runtime. Expr *IL; /// LowerBound - local variable passed to runtime. Expr *LB; /// UpperBound - local variable passed to runtime. Expr *UB; /// Stride - local variable passed to runtime. Expr *ST; /// EnsureUpperBound -- expression UB = min(UB, NumIterations). Expr *EUB; /// Update of LowerBound for statically scheduled 'omp for' loops. Expr *NLB; /// Update of UpperBound for statically scheduled 'omp for' loops. Expr *NUB; /// PreviousLowerBound - local variable passed to runtime in the /// enclosing schedule or null if that does not apply. Expr *PrevLB; /// PreviousUpperBound - local variable passed to runtime in the /// enclosing schedule or null if that does not apply. Expr *PrevUB; /// DistInc - increment expression for distribute loop when found /// combined with a further loop level (e.g. in 'distribute parallel for') /// expression IV = IV + ST Expr *DistInc; /// PrevEUB - expression similar to EUB but to be used when loop /// scheduling uses PrevLB and PrevUB (e.g. in 'distribute parallel for' /// when ensuring that the UB is either the calculated UB by the runtime or /// the end of the assigned distribute chunk) /// expression UB = min (UB, PrevUB) Expr *PrevEUB; /// Counters Loop counters. SmallVector<Expr *, 4> Counters; /// PrivateCounters Loop counters. SmallVector<Expr *, 4> PrivateCounters; /// Expressions for loop counters inits for CodeGen. SmallVector<Expr *, 4> Inits; /// Expressions for loop counters update for CodeGen. SmallVector<Expr *, 4> Updates; /// Final loop counter values for GodeGen. SmallVector<Expr *, 4> Finals; /// Init statement for all captured expressions. Stmt *PreInits; /// Expressions used when combining OpenMP loop pragmas DistCombinedHelperExprs DistCombinedFields; /// Check if all the expressions are built (does not check the /// worksharing ones). bool builtAll() { return IterationVarRef != nullptr && LastIteration != nullptr && NumIterations != nullptr && PreCond != nullptr && Cond != nullptr && Init != nullptr && Inc != nullptr; } /// Initialize all the fields to null. /// \param Size Number of elements in the counters/finals/updates arrays. void clear(unsigned Size) { IterationVarRef = nullptr; LastIteration = nullptr; CalcLastIteration = nullptr; PreCond = nullptr; Cond = nullptr; Init = nullptr; Inc = nullptr; IL = nullptr; LB = nullptr; UB = nullptr; ST = nullptr; EUB = nullptr; NLB = nullptr; NUB = nullptr; NumIterations = nullptr; PrevLB = nullptr; PrevUB = nullptr; DistInc = nullptr; PrevEUB = nullptr; Counters.resize(Size); PrivateCounters.resize(Size); Inits.resize(Size); Updates.resize(Size); Finals.resize(Size); for (unsigned i = 0; i < Size; ++i) { Counters[i] = nullptr; PrivateCounters[i] = nullptr; Inits[i] = nullptr; Updates[i] = nullptr; Finals[i] = nullptr; } PreInits = nullptr; DistCombinedFields.LB = nullptr; DistCombinedFields.UB = nullptr; DistCombinedFields.EUB = nullptr; DistCombinedFields.Init = nullptr; DistCombinedFields.Cond = nullptr; DistCombinedFields.NLB = nullptr; DistCombinedFields.NUB = nullptr; DistCombinedFields.DistCond = nullptr; DistCombinedFields.ParForInDistCond = nullptr; } }; /// Get number of collapsed loops. unsigned getCollapsedNumber() const { return CollapsedNum; } Expr *getIterationVariable() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), IterationVariableOffset))); } Expr *getLastIteration() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), LastIterationOffset))); } Expr *getCalcLastIteration() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CalcLastIterationOffset))); } Expr *getPreCond() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PreConditionOffset))); } Expr *getCond() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), CondOffset))); } Expr *getInit() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), InitOffset))); } Expr *getInc() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset))); } const Stmt *getPreInits() const { return *std::next(child_begin(), PreInitsOffset); } Stmt *getPreInits() { return *std::next(child_begin(), PreInitsOffset); } Expr *getIsLastIterVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), IsLastIterVariableOffset))); } Expr *getLowerBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), LowerBoundVariableOffset))); } Expr *getUpperBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), UpperBoundVariableOffset))); } Expr *getStrideVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), StrideVariableOffset))); } Expr *getEnsureUpperBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), EnsureUpperBoundOffset))); } Expr *getNextLowerBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NextLowerBoundOffset))); } Expr *getNextUpperBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NextUpperBoundOffset))); } Expr *getNumIterations() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NumIterationsOffset))); } Expr *getPrevLowerBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevLowerBoundVariableOffset))); } Expr *getPrevUpperBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevUpperBoundVariableOffset))); } Expr *getDistInc() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), DistIncOffset))); } Expr *getPrevEnsureUpperBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevEnsureUpperBoundOffset))); } Expr *getCombinedLowerBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedLowerBoundVariableOffset))); } Expr *getCombinedUpperBoundVariable() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedUpperBoundVariableOffset))); } Expr *getCombinedEnsureUpperBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedEnsureUpperBoundOffset))); } Expr *getCombinedInit() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedInitOffset))); } Expr *getCombinedCond() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedConditionOffset))); } Expr *getCombinedNextLowerBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedNextLowerBoundOffset))); } Expr *getCombinedNextUpperBound() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedNextUpperBoundOffset))); } Expr *getCombinedDistCond() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound distribute sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedDistConditionOffset))); } Expr *getCombinedParForInDistCond() const { assert(isOpenMPLoopBoundSharingDirective(getDirectiveKind()) && "expected loop bound distribute sharing directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CombinedParForInDistConditionOffset))); } const Stmt *getBody() const { // This relies on the loop form is already checked by Sema. const Stmt *Body = getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); Body = cast<ForStmt>(Body)->getBody(); for (unsigned Cnt = 1; Cnt < CollapsedNum; ++Cnt) { Body = Body->IgnoreContainers(); Body = cast<ForStmt>(Body)->getBody(); } return Body; } ArrayRef<Expr *> counters() { return getCounters(); } ArrayRef<Expr *> counters() const { return const_cast<OMPLoopDirective *>(this)->getCounters(); } ArrayRef<Expr *> private_counters() { return getPrivateCounters(); } ArrayRef<Expr *> private_counters() const { return const_cast<OMPLoopDirective *>(this)->getPrivateCounters(); } ArrayRef<Expr *> inits() { return getInits(); } ArrayRef<Expr *> inits() const { return const_cast<OMPLoopDirective *>(this)->getInits(); } ArrayRef<Expr *> updates() { return getUpdates(); } ArrayRef<Expr *> updates() const { return const_cast<OMPLoopDirective *>(this)->getUpdates(); } ArrayRef<Expr *> finals() { return getFinals(); } ArrayRef<Expr *> finals() const { return const_cast<OMPLoopDirective *>(this)->getFinals(); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSimdDirectiveClass || T->getStmtClass() == OMPForDirectiveClass || T->getStmtClass() == OMPForSimdDirectiveClass || T->getStmtClass() == OMPParallelForDirectiveClass || T->getStmtClass() == OMPParallelForSimdDirectiveClass || T->getStmtClass() == OMPTaskLoopDirectiveClass || T->getStmtClass() == OMPTaskLoopSimdDirectiveClass || T->getStmtClass() == OMPDistributeDirectiveClass || T->getStmtClass() == OMPTargetParallelForDirectiveClass || T->getStmtClass() == OMPDistributeParallelForDirectiveClass || T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPDistributeSimdDirectiveClass || T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass || T->getStmtClass() == OMPTargetSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeDirectiveClass || T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeParallelForDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass || T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp simd' directive. /// /// \code /// #pragma omp simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp simd' has clauses 'private' /// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and /// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'. /// class OMPSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPSimdDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSimdDirectiveClass; } }; /// This represents '#pragma omp for' directive. /// /// \code /// #pragma omp for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp for' has clauses 'private' with the /// variables 'a' and 'b' and 'reduction' with operator '+' and variables 'c' /// and 'd'. /// class OMPForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPForDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPForDirectiveClass; } }; /// This represents '#pragma omp for simd' directive. /// /// \code /// #pragma omp for simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp for simd' has clauses 'private' /// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and /// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'. /// class OMPForSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPForSimdDirectiveClass; } }; /// This represents '#pragma omp sections' directive. /// /// \code /// #pragma omp sections private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp sections' has clauses 'private' with /// the variables 'a' and 'b' and 'reduction' with operator '+' and variables /// 'c' and 'd'. /// class OMPSectionsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPSectionsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner directive. /// static OMPSectionsDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPSectionsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSectionsDirectiveClass; } }; /// This represents '#pragma omp section' directive. /// /// \code /// #pragma omp section /// \endcode /// class OMPSectionDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPSectionDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section, StartLoc, EndLoc, 0, 1), HasCancel(false) {} /// Build an empty directive. /// explicit OMPSectionDirective() : OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section, SourceLocation(), SourceLocation(), 0, 1), HasCancel(false) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner directive. /// static OMPSectionDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive. /// /// \param C AST context. /// static OMPSectionDirective *CreateEmpty(const ASTContext &C, EmptyShell); /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSectionDirectiveClass; } }; /// This represents '#pragma omp single' directive. /// /// \code /// #pragma omp single private(a,b) copyprivate(c,d) /// \endcode /// In this example directive '#pragma omp single' has clauses 'private' with /// the variables 'a' and 'b' and 'copyprivate' with variables 'c' and 'd'. /// class OMPSingleDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPSingleDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPSingleDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPSingleDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPSingleDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSingleDirectiveClass; } }; /// This represents '#pragma omp master' directive. /// /// \code /// #pragma omp master /// \endcode /// class OMPMasterDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master, StartLoc, EndLoc, 0, 1) {} /// Build an empty directive. /// explicit OMPMasterDirective() : OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master, SourceLocation(), SourceLocation(), 0, 1) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPMasterDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AssociatedStmt); /// Creates an empty directive. /// /// \param C AST context. /// static OMPMasterDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPMasterDirectiveClass; } }; /// This represents '#pragma omp critical' directive. /// /// \code /// #pragma omp critical /// \endcode /// class OMPCriticalDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Name of the directive. DeclarationNameInfo DirName; /// Build directive with the given start and end location. /// /// \param Name Name of the directive. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPCriticalDirective(const DeclarationNameInfo &Name, SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical, StartLoc, EndLoc, NumClauses, 1), DirName(Name) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPCriticalDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical, SourceLocation(), SourceLocation(), NumClauses, 1), DirName() {} /// Set name of the directive. /// /// \param Name Name of the directive. /// void setDirectiveName(const DeclarationNameInfo &Name) { DirName = Name; } public: /// Creates directive. /// /// \param C AST context. /// \param Name Name of the directive. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPCriticalDirective * Create(const ASTContext &C, const DeclarationNameInfo &Name, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPCriticalDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return name of the directive. /// DeclarationNameInfo getDirectiveName() const { return DirName; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCriticalDirectiveClass; } }; /// This represents '#pragma omp parallel for' directive. /// /// \code /// #pragma omp parallel for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel for' has clauses 'private' /// with the variables 'a' and 'b' and 'reduction' with operator '+' and /// variables 'c' and 'd'. /// class OMPParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if current region has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelForDirectiveClass; } }; /// This represents '#pragma omp parallel for simd' directive. /// /// \code /// #pragma omp parallel for simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel for simd' has clauses /// 'private' with the variables 'a' and 'b', 'linear' with variables 'i', 'j' /// and linear step 's', 'reduction' with operator '+' and variables 'c' and /// 'd'. /// class OMPParallelForSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass, OMPD_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass, OMPD_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPParallelForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp parallel sections' directive. /// /// \code /// #pragma omp parallel sections private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel sections' has clauses /// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+' /// and variables 'c' and 'd'. /// class OMPParallelSectionsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if current directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPParallelSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass, OMPD_parallel_sections, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPParallelSectionsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass, OMPD_parallel_sections, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPParallelSectionsDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPParallelSectionsDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelSectionsDirectiveClass; } }; /// This represents '#pragma omp task' directive. /// /// \code /// #pragma omp task private(a,b) final(d) /// \endcode /// In this example directive '#pragma omp task' has clauses 'private' with the /// variables 'a' and 'b' and 'final' with condition 'd'. /// class OMPTaskDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// true if this directive has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTaskDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTaskDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true, if current directive has inner cancel directive. /// static OMPTaskDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTaskDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskDirectiveClass; } }; /// This represents '#pragma omp taskyield' directive. /// /// \code /// #pragma omp taskyield /// \endcode /// class OMPTaskyieldDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield, StartLoc, EndLoc, 0, 0) {} /// Build an empty directive. /// explicit OMPTaskyieldDirective() : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield, SourceLocation(), SourceLocation(), 0, 0) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPTaskyieldDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates an empty directive. /// /// \param C AST context. /// static OMPTaskyieldDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskyieldDirectiveClass; } }; /// This represents '#pragma omp barrier' directive. /// /// \code /// #pragma omp barrier /// \endcode /// class OMPBarrierDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier, StartLoc, EndLoc, 0, 0) {} /// Build an empty directive. /// explicit OMPBarrierDirective() : OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier, SourceLocation(), SourceLocation(), 0, 0) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPBarrierDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates an empty directive. /// /// \param C AST context. /// static OMPBarrierDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPBarrierDirectiveClass; } }; /// This represents '#pragma omp taskwait' directive. /// /// \code /// #pragma omp taskwait /// \endcode /// class OMPTaskwaitDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait, StartLoc, EndLoc, 0, 0) {} /// Build an empty directive. /// explicit OMPTaskwaitDirective() : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait, SourceLocation(), SourceLocation(), 0, 0) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPTaskwaitDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates an empty directive. /// /// \param C AST context. /// static OMPTaskwaitDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskwaitDirectiveClass; } }; /// This represents '#pragma omp taskgroup' directive. /// /// \code /// #pragma omp taskgroup /// \endcode /// class OMPTaskgroupDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup, StartLoc, EndLoc, NumClauses, 2) {} /// Build an empty directive. /// \param NumClauses Number of clauses. /// explicit OMPTaskgroupDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup, SourceLocation(), SourceLocation(), NumClauses, 2) {} /// Sets the task_reduction return variable. void setReductionRef(Expr *RR) { *std::next(child_begin(), 1) = RR; } public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param ReductionRef Reference to the task_reduction return variable. /// static OMPTaskgroupDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *ReductionRef); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTaskgroupDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Returns reference to the task_reduction return variable. const Expr *getReductionRef() const { return static_cast<const Expr *>(*std::next(child_begin(), 1)); } Expr *getReductionRef() { return static_cast<Expr *>(*std::next(child_begin(), 1)); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskgroupDirectiveClass; } }; /// This represents '#pragma omp flush' directive. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has 2 arguments- variables 'a' /// and 'b'. /// 'omp flush' directive does not have clauses but have an optional list of /// variables to flush. This list of variables is stored within some fake clause /// FlushClause. class OMPFlushDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPFlushDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush, StartLoc, EndLoc, NumClauses, 0) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPFlushDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush, SourceLocation(), SourceLocation(), NumClauses, 0) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses (only single OMPFlushClause clause is /// allowed). /// static OMPFlushDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPFlushDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPFlushDirectiveClass; } }; /// This represents '#pragma omp ordered' directive. /// /// \code /// #pragma omp ordered /// \endcode /// class OMPOrderedDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPOrderedDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPOrderedDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPOrderedDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPOrderedDirectiveClass; } }; /// This represents '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic capture /// \endcode /// In this example directive '#pragma omp atomic' has clause 'capture'. /// class OMPAtomicDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Used for 'atomic update' or 'atomic capture' constructs. They may /// have atomic expressions of forms /// \code /// x = x binop expr; /// x = expr binop x; /// \endcode /// This field is true for the first form of the expression and false for the /// second. Required for correct codegen of non-associative operations (like /// << or >>). bool IsXLHSInRHSPart; /// Used for 'atomic update' or 'atomic capture' constructs. They may /// have atomic expressions of forms /// \code /// v = x; <update x>; /// <update x>; v = x; /// \endcode /// This field is true for the first(postfix) form of the expression and false /// otherwise. bool IsPostfixUpdate; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic, StartLoc, EndLoc, NumClauses, 5), IsXLHSInRHSPart(false), IsPostfixUpdate(false) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPAtomicDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic, SourceLocation(), SourceLocation(), NumClauses, 5), IsXLHSInRHSPart(false), IsPostfixUpdate(false) {} /// Set 'x' part of the associated expression/statement. void setX(Expr *X) { *std::next(child_begin()) = X; } /// Set helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. void setUpdateExpr(Expr *UE) { *std::next(child_begin(), 2) = UE; } /// Set 'v' part of the associated expression/statement. void setV(Expr *V) { *std::next(child_begin(), 3) = V; } /// Set 'expr' part of the associated expression/statement. void setExpr(Expr *E) { *std::next(child_begin(), 4) = E; } public: /// Creates directive with a list of \a Clauses and 'x', 'v' and 'expr' /// parts of the atomic construct (see Section 2.12.6, atomic Construct, for /// detailed description of 'x', 'v' and 'expr'). /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param X 'x' part of the associated expression/statement. /// \param V 'v' part of the associated expression/statement. /// \param E 'expr' part of the associated expression/statement. /// \param UE Helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. /// \param IsXLHSInRHSPart true if \a UE has the first form and false if the /// second. /// \param IsPostfixUpdate true if original value of 'x' must be stored in /// 'v', not an updated one. static OMPAtomicDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *X, Expr *V, Expr *E, Expr *UE, bool IsXLHSInRHSPart, bool IsPostfixUpdate); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPAtomicDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Get 'x' part of the associated expression/statement. Expr *getX() { return cast_or_null<Expr>(*std::next(child_begin())); } const Expr *getX() const { return cast_or_null<Expr>(*std::next(child_begin())); } /// Get helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. Expr *getUpdateExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 2)); } const Expr *getUpdateExpr() const { return cast_or_null<Expr>(*std::next(child_begin(), 2)); } /// Return true if helper update expression has form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and false if it has form /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } /// Return true if 'v' expression must be updated to original value of /// 'x', false if 'v' must be updated to the new value of 'x'. bool isPostfixUpdate() const { return IsPostfixUpdate; } /// Get 'v' part of the associated expression/statement. Expr *getV() { return cast_or_null<Expr>(*std::next(child_begin(), 3)); } const Expr *getV() const { return cast_or_null<Expr>(*std::next(child_begin(), 3)); } /// Get 'expr' part of the associated expression/statement. Expr *getExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 4)); } const Expr *getExpr() const { return cast_or_null<Expr>(*std::next(child_begin(), 4)); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPAtomicDirectiveClass; } }; /// This represents '#pragma omp target' directive. /// /// \code /// #pragma omp target if(a) /// \endcode /// In this example directive '#pragma omp target' has clause 'if' with /// condition 'a'. /// class OMPTargetDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetDirectiveClass; } }; /// This represents '#pragma omp target data' directive. /// /// \code /// #pragma omp target data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target data' has clauses 'device' /// with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetDataDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetDataDirectiveClass; } }; /// This represents '#pragma omp target enter data' directive. /// /// \code /// #pragma omp target enter data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target enter data' has clauses /// 'device' with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetEnterDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetEnterDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass, OMPD_target_enter_data, StartLoc, EndLoc, NumClauses, /*NumChildren=*/1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetEnterDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass, OMPD_target_enter_data, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetEnterDataDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetEnterDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetEnterDataDirectiveClass; } }; /// This represents '#pragma omp target exit data' directive. /// /// \code /// #pragma omp target exit data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target exit data' has clauses /// 'device' with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetExitDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetExitDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass, OMPD_target_exit_data, StartLoc, EndLoc, NumClauses, /*NumChildren=*/1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetExitDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass, OMPD_target_exit_data, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetExitDataDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetExitDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetExitDataDirectiveClass; } }; /// This represents '#pragma omp target parallel' directive. /// /// \code /// #pragma omp target parallel if(a) /// \endcode /// In this example directive '#pragma omp target parallel' has clause 'if' with /// condition 'a'. /// class OMPTargetParallelDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass, OMPD_target_parallel, StartLoc, EndLoc, NumClauses, /*NumChildren=*/1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass, OMPD_target_parallel, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetParallelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetParallelDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelDirectiveClass; } }; /// This represents '#pragma omp target parallel for' directive. /// /// \code /// #pragma omp target parallel for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp target parallel for' has clauses /// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+' /// and variables 'c' and 'd'. /// class OMPTargetParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if current region has inner cancel directive. bool HasCancel; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass, OMPD_target_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass, OMPD_target_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPTargetParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelForDirectiveClass; } }; /// This represents '#pragma omp teams' directive. /// /// \code /// #pragma omp teams if(a) /// \endcode /// In this example directive '#pragma omp teams' has clause 'if' with /// condition 'a'. /// class OMPTeamsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTeamsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTeamsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDirectiveClass; } }; /// This represents '#pragma omp cancellation point' directive. /// /// \code /// #pragma omp cancellation point for /// \endcode /// /// In this example a cancellation point is created for innermost 'for' region. class OMPCancellationPointDirective : public OMPExecutableDirective { friend class ASTStmtReader; OpenMPDirectiveKind CancelRegion; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass, OMPD_cancellation_point, StartLoc, EndLoc, 0, 0), CancelRegion(OMPD_unknown) {} /// Build an empty directive. /// explicit OMPCancellationPointDirective() : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass, OMPD_cancellation_point, SourceLocation(), SourceLocation(), 0, 0), CancelRegion(OMPD_unknown) {} /// Set cancel region for current cancellation point. /// \param CR Cancellation region. void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; } public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPCancellationPointDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Creates an empty directive. /// /// \param C AST context. /// static OMPCancellationPointDirective *CreateEmpty(const ASTContext &C, EmptyShell); /// Get cancellation region for the current cancellation point. OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCancellationPointDirectiveClass; } }; /// This represents '#pragma omp cancel' directive. /// /// \code /// #pragma omp cancel for /// \endcode /// /// In this example a cancel is created for innermost 'for' region. class OMPCancelDirective : public OMPExecutableDirective { friend class ASTStmtReader; OpenMPDirectiveKind CancelRegion; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPCancelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel, StartLoc, EndLoc, NumClauses, 0), CancelRegion(OMPD_unknown) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. explicit OMPCancelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel, SourceLocation(), SourceLocation(), NumClauses, 0), CancelRegion(OMPD_unknown) {} /// Set cancel region for current cancellation point. /// \param CR Cancellation region. void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; } public: /// Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// static OMPCancelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, OpenMPDirectiveKind CancelRegion); /// Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPCancelDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// Get cancellation region for the current cancellation point. OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCancelDirectiveClass; } }; /// This represents '#pragma omp taskloop' directive. /// /// \code /// #pragma omp taskloop private(a,b) grainsize(val) num_tasks(num) /// \endcode /// In this example directive '#pragma omp taskloop' has clauses 'private' /// with the variables 'a' and 'b', 'grainsize' with expression 'val' and /// 'num_tasks' with expression 'num'. /// class OMPTaskLoopDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTaskLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTaskLoopDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTaskLoopDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTaskLoopDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskLoopDirectiveClass; } }; /// This represents '#pragma omp taskloop simd' directive. /// /// \code /// #pragma omp taskloop simd private(a,b) grainsize(val) num_tasks(num) /// \endcode /// In this example directive '#pragma omp taskloop simd' has clauses 'private' /// with the variables 'a' and 'b', 'grainsize' with expression 'val' and /// 'num_tasks' with expression 'num'. /// class OMPTaskLoopSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTaskLoopSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass, OMPD_taskloop_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTaskLoopSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass, OMPD_taskloop_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTaskLoopSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTaskLoopSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskLoopSimdDirectiveClass; } }; /// This represents '#pragma omp distribute' directive. /// /// \code /// #pragma omp distribute private(a,b) /// \endcode /// In this example directive '#pragma omp distribute' has clauses 'private' /// with the variables 'a' and 'b' /// class OMPDistributeDirective : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeDirectiveClass; } }; /// This represents '#pragma omp target update' directive. /// /// \code /// #pragma omp target update to(a) from(b) device(1) /// \endcode /// In this example directive '#pragma omp target update' has clause 'to' with /// argument 'a', clause 'from' with argument 'b' and clause 'device' with /// argument '1'. /// class OMPTargetUpdateDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetUpdateDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass, OMPD_target_update, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetUpdateDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass, OMPD_target_update, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetUpdateDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses The number of clauses. /// static OMPTargetUpdateDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetUpdateDirectiveClass; } }; /// This represents '#pragma omp distribute parallel for' composite /// directive. /// /// \code /// #pragma omp distribute parallel for private(a,b) /// \endcode /// In this example directive '#pragma omp distribute parallel for' has clause /// 'private' with the variables 'a' and 'b' /// class OMPDistributeParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel = false; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass, OMPD_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass, OMPD_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp distribute parallel for simd' composite /// directive. /// /// \code /// #pragma omp distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp distribute parallel for simd' has /// clause 'private' with the variables 'x' /// class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, OMPD_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, OMPD_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeParallelForSimdDirective *Create( const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeParallelForSimdDirective *CreateEmpty( const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp distribute simd' composite directive. /// /// \code /// #pragma omp distribute simd private(x) /// \endcode /// In this example directive '#pragma omp distribute simd' has clause /// 'private' with the variables 'x' /// class OMPDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass, OMPD_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass, OMPD_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp target parallel for simd' directive. /// /// \code /// #pragma omp target parallel for simd private(a) map(b) safelen(c) /// \endcode /// In this example directive '#pragma omp target parallel for simd' has clauses /// 'private' with the variable 'a', 'map' with the variable 'b' and 'safelen' /// with the variable 'c'. /// class OMPTargetParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass, OMPD_target_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass, OMPD_target_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetParallelForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp target simd' directive. /// /// \code /// #pragma omp target simd private(a) map(b) safelen(c) /// \endcode /// In this example directive '#pragma omp target simd' has clauses 'private' /// with the variable 'a', 'map' with the variable 'b' and 'safelen' with /// the variable 'c'. /// class OMPTargetSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, SourceLocation(),SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute' directive. /// /// \code /// #pragma omp teams distribute private(a,b) /// \endcode /// In this example directive '#pragma omp teams distribute' has clauses /// 'private' with the variables 'a' and 'b' /// class OMPTeamsDistributeDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, OMPD_teams_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, OMPD_teams_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeDirectiveClass; } }; /// This represents '#pragma omp teams distribute simd' /// combined directive. /// /// \code /// #pragma omp teams distribute simd private(a,b) /// \endcode /// In this example directive '#pragma omp teams distribute simd' /// has clause 'private' with the variables 'a' and 'b' /// class OMPTeamsDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass, OMPD_teams_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass, OMPD_teams_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute parallel for simd' composite /// directive. /// /// \code /// #pragma omp teams distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp teams distribute parallel for simd' /// has clause 'private' with the variables 'x' /// class OMPTeamsDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, OMPD_teams_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, OMPD_teams_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeParallelForSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute parallel for' composite /// directive. /// /// \code /// #pragma omp teams distribute parallel for private(x) /// \endcode /// In this example directive '#pragma omp teams distribute parallel for' /// has clause 'private' with the variables 'x' /// class OMPTeamsDistributeParallelForDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel = false; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass, OMPD_teams_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass, OMPD_teams_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPTeamsDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeParallelForDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp target teams' directive. /// /// \code /// #pragma omp target teams if(a>0) /// \endcode /// In this example directive '#pragma omp target teams' has clause 'if' with /// condition 'a>0'. /// class OMPTargetTeamsDirective final : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass, OMPD_target_teams, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass, OMPD_target_teams, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDirectiveClass; } }; /// This represents '#pragma omp target teams distribute' combined directive. /// /// \code /// #pragma omp target teams distribute private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute' has clause /// 'private' with the variables 'x' /// class OMPTargetTeamsDistributeDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass, OMPD_target_teams_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass, OMPD_target_teams_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass; } }; /// This represents '#pragma omp target teams distribute parallel for' combined /// directive. /// /// \code /// #pragma omp target teams distribute parallel for private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute parallel /// for' has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeParallelForDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// true if the construct has inner cancel directive. bool HasCancel = false; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeParallelForDirectiveClass, OMPD_target_teams_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective( this, OMPTargetTeamsDistributeParallelForDirectiveClass, OMPD_target_teams_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPTargetTeamsDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeParallelForDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp target teams distribute parallel for simd' /// combined directive. /// /// \code /// #pragma omp target teams distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute parallel /// for simd' has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass, OMPD_target_teams_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeParallelForSimdDirective( unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective( this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass, OMPD_target_teams_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeParallelForSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp target teams distribute simd' combined /// directive. /// /// \code /// #pragma omp target teams distribute simd private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute simd' /// has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass, OMPD_target_teams_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeSimdDirectiveClass, OMPD_target_teams_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeSimdDirectiveClass; } }; } // end namespace clang #endif
GB_unop__isnan_bool_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__isnan_bool_fc64) // op(A') function: GB (_unop_tran__isnan_bool_fc64) // C type: bool // A type: GxB_FC64_t // cast: GxB_FC64_t cij = (aij) // unaryop: cij = GB_cisnan (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_cisnan (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = (aij) ; \ Cx [pC] = GB_cisnan (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNAN || GxB_NO_BOOL || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__isnan_bool_fc64) ( bool *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = GB_cisnan (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = GB_cisnan (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__isnan_bool_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
resize.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % RRRR EEEEE SSSSS IIIII ZZZZZ EEEEE % % R R E SS I ZZ E % % RRRR EEE SSS I ZZZ EEE % % R R E SS I ZZ E % % R R EEEEE SSSSS IIIII ZZZZZ EEEEE % % % % % % MagickCore Image Resize Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/magick.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resize-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #if defined(MAGICKCORE_LQR_DELEGATE) #include <lqr.h> #endif /* Typedef declarations. */ struct _ResizeFilter { double (*filter)(const double,const ResizeFilter *), (*window)(const double,const ResizeFilter *), support, /* filter region of support - the filter support limit */ window_support, /* window support, usally equal to support (expert only) */ scale, /* dimension scaling to fit window support (usally 1.0) */ blur, /* x-scale (blur-sharpen) */ coefficient[7]; /* cubic coefficents for BC-cubic filters */ ResizeWeightingFunctionType filterWeightingType, windowWeightingType; size_t signature; }; /* Forward declaractions. */ static double I0(double x), BesselOrderOne(double), Sinc(const double, const ResizeFilter *), SincFast(const double, const ResizeFilter *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F i l t e r F u n c t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % These are the various filter and windowing functions that are provided. % % They are internal to this module only. See AcquireResizeFilterInfo() for % details of the access to these functions, via the GetResizeFilterSupport() % and GetResizeFilterWeight() API interface. % % The individual filter functions have this format... % % static MagickRealtype *FilterName(const double x,const double support) % % A description of each parameter follows: % % o x: the distance from the sampling point generally in the range of 0 to % support. The GetResizeFilterWeight() ensures this a positive value. % % o resize_filter: current filter information. This allows function to % access support, and possibly other pre-calculated information defining % the functions. % */ static double Blackman(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Blackman: 2nd order cosine windowing function: 0.42 + 0.5 cos(pi x) + 0.08 cos(2pi x) Refactored by Chantal Racette and Nicolas Robidoux to one trig call and five flops. */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.34+cosine*(0.5+cosine*0.16)); } static double Bohman(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Bohman: 2rd Order cosine windowing function: (1-x) cos(pi x) + sin(pi x) / pi. Refactored by Nicolas Robidoux to one trig call, one sqrt call, and 7 flops, taking advantage of the fact that the support of Bohman is 1.0 (so that we know that sin(pi x) >= 0). */ const double cosine = cos((double) (MagickPI*x)); const double sine=sqrt(1.0-cosine*cosine); magick_unreferenced(resize_filter); return((1.0-x)*cosine+(1.0/MagickPI)*sine); } static double Box(const double magick_unused(x), const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(x); magick_unreferenced(resize_filter); /* A Box filter is a equal weighting function (all weights equal). DO NOT LIMIT results by support or resize point sampling will work as it requests points beyond its normal 0.0 support size. */ return(1.0); } static double Cosine(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Cosine window function: cos((pi/2)*x). */ return(cos((double) (MagickPI2*x))); } static double CubicBC(const double x,const ResizeFilter *resize_filter) { /* Cubic Filters using B,C determined values: Mitchell-Netravali B = 1/3 C = 1/3 "Balanced" cubic spline filter Catmull-Rom B = 0 C = 1/2 Interpolatory and exact on linears Spline B = 1 C = 0 B-Spline Gaussian approximation Hermite B = 0 C = 0 B-Spline interpolator See paper by Mitchell and Netravali, Reconstruction Filters in Computer Graphics Computer Graphics, Volume 22, Number 4, August 1988 http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/ Mitchell.pdf. Coefficents are determined from B,C values: P0 = ( 6 - 2*B )/6 = coeff[0] P1 = 0 P2 = (-18 +12*B + 6*C )/6 = coeff[1] P3 = ( 12 - 9*B - 6*C )/6 = coeff[2] Q0 = ( 8*B +24*C )/6 = coeff[3] Q1 = ( -12*B -48*C )/6 = coeff[4] Q2 = ( 6*B +30*C )/6 = coeff[5] Q3 = ( - 1*B - 6*C )/6 = coeff[6] which are used to define the filter: P0 + P1*x + P2*x^2 + P3*x^3 0 <= x < 1 Q0 + Q1*x + Q2*x^2 + Q3*x^3 1 <= x < 2 which ensures function is continuous in value and derivative (slope). */ if (x < 1.0) return(resize_filter->coefficient[0]+x*(x* (resize_filter->coefficient[1]+x*resize_filter->coefficient[2]))); if (x < 2.0) return(resize_filter->coefficient[3]+x*(resize_filter->coefficient[4]+x* (resize_filter->coefficient[5]+x*resize_filter->coefficient[6]))); return(0.0); } static double CubicSpline(const double x,const ResizeFilter *resize_filter) { if (resize_filter->support <= 2.0) { /* 2-lobe Spline filter. */ if (x < 1.0) return(((x-9.0/5.0)*x-1.0/5.0)*x+1.0); if (x < 2.0) return(((-1.0/3.0*(x-1.0)+4.0/5.0)*(x-1.0)-7.0/15.0)*(x-1.0)); return(0.0); } if (resize_filter->support <= 3.0) { /* 3-lobe Spline filter. */ if (x < 1.0) return(((13.0/11.0*x-453.0/209.0)*x-3.0/209.0)*x+1.0); if (x < 2.0) return(((-6.0/11.0*(x-1.0)+270.0/209.0)*(x-1.0)-156.0/209.0)*(x-1.0)); if (x < 3.0) return(((1.0/11.0*(x-2.0)-45.0/209.0)*(x-2.0)+26.0/209.0)*(x-2.0)); return(0.0); } /* 4-lobe Spline filter. */ if (x < 1.0) return(((49.0/41.0*x-6387.0/2911.0)*x-3.0/2911.0)*x+1.0); if (x < 2.0) return(((-24.0/41.0*(x-1.0)+4032.0/2911.0)*(x-1.0)-2328.0/2911.0)*(x-1.0)); if (x < 3.0) return(((6.0/41.0*(x-2.0)-1008.0/2911.0)*(x-2.0)+582.0/2911.0)*(x-2.0)); if (x < 4.0) return(((-1.0/41.0*(x-3.0)+168.0/2911.0)*(x-3.0)-97.0/2911.0)*(x-3.0)); return(0.0); } static double Gaussian(const double x,const ResizeFilter *resize_filter) { /* Gaussian with a sigma = 1/2 (or as user specified) Gaussian Formula (1D) ... exp( -(x^2)/((2.0*sigma^2) ) / (sqrt(2*PI)*sigma^2)) Gaussian Formula (2D) ... exp( -(x^2+y^2)/(2.0*sigma^2) ) / (PI*sigma^2) ) or for radius exp( -(r^2)/(2.0*sigma^2) ) / (PI*sigma^2) ) Note that it is only a change from 1-d to radial form is in the normalization multiplier which is not needed or used when Gaussian is used as a filter. The constants are pre-calculated... coeff[0]=sigma; coeff[1]=1.0/(2.0*sigma^2); coeff[2]=1.0/(sqrt(2*PI)*sigma^2); exp( -coeff[1]*(x^2)) ) * coeff[2]; However the multiplier coeff[1] is need, the others are informative only. This separates the gaussian 'sigma' value from the 'blur/support' settings allowing for its use in special 'small sigma' gaussians, without the filter 'missing' pixels because the support becomes too small. */ return(exp((double)(-resize_filter->coefficient[1]*x*x))); } static double Hann(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Cosine window function: 0.5+0.5*cos(pi*x). */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.5+0.5*cosine); } static double Hamming(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Offset cosine window function: .54 + .46 cos(pi x). */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.54+0.46*cosine); } static double Jinc(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* See Pratt "Digital Image Processing" p.97 for Jinc/Bessel functions. http://mathworld.wolfram.com/JincFunction.html and page 11 of http://www.ph.ed.ac.uk/%7ewjh/teaching/mo/slides/lens/lens.pdf The original "zoom" program by Paul Heckbert called this "Bessel". But really it is more accurately named "Jinc". */ if (x == 0.0) return(0.5*MagickPI); return(BesselOrderOne(MagickPI*x)/x); } static double Kaiser(const double x,const ResizeFilter *resize_filter) { /* Kaiser Windowing Function (bessel windowing) I0( beta * sqrt( 1-x^2) ) / IO(0) Beta (coeff[0]) is a free value from 5 to 8 (defaults to 6.5). However it is typically defined in terms of Alpha*PI The normalization factor (coeff[1]) is not actually needed, but without it the filters has a large value at x=0 making it difficult to compare the function with other windowing functions. */ return(resize_filter->coefficient[1]*I0(resize_filter->coefficient[0]* sqrt((double) (1.0-x*x)))); } static double Lagrange(const double x,const ResizeFilter *resize_filter) { double value; register ssize_t i; ssize_t n, order; /* Lagrange piecewise polynomial fit of sinc: N is the 'order' of the lagrange function and depends on the overall support window size of the filter. That is: for a support of 2, it gives a lagrange-4 (piecewise cubic function). "n" identifies the piece of the piecewise polynomial. See Survey: Interpolation Methods, IEEE Transactions on Medical Imaging, Vol 18, No 11, November 1999, p1049-1075, -- Equation 27 on p1064. */ if (x > resize_filter->support) return(0.0); order=(ssize_t) (2.0*resize_filter->window_support); /* number of pieces */ n=(ssize_t) (resize_filter->window_support+x); value=1.0f; for (i=0; i < order; i++) if (i != n) value*=(n-i-x)/(n-i); return(value); } static double Quadratic(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* 2rd order (quadratic) B-Spline approximation of Gaussian. */ if (x < 0.5) return(0.75-x*x); if (x < 1.5) return(0.5*(x-1.5)*(x-1.5)); return(0.0); } static double Sinc(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Scaled sinc(x) function using a trig call: sinc(x) == sin(pi x)/(pi x). */ if (x != 0.0) { const double alpha=(double) (MagickPI*x); return(sin((double) alpha)/alpha); } return((double) 1.0); } static double SincFast(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Approximations of the sinc function sin(pi x)/(pi x) over the interval [-4,4] constructed by Nicolas Robidoux and Chantal Racette with funding from the Natural Sciences and Engineering Research Council of Canada. Although the approximations are polynomials (for low order of approximation) and quotients of polynomials (for higher order of approximation) and consequently are similar in form to Taylor polynomials / Pade approximants, the approximations are computed with a completely different technique. Summary: These approximations are "the best" in terms of bang (accuracy) for the buck (flops). More specifically: Among the polynomial quotients that can be computed using a fixed number of flops (with a given "+ - * / budget"), the chosen polynomial quotient is the one closest to the approximated function with respect to maximum absolute relative error over the given interval. The Remez algorithm, as implemented in the boost library's minimax package, is the key to the construction: http://www.boost.org/doc/libs/1_36_0/libs/ math/doc/sf_and_dist/html/math_toolkit/backgrounders/remez.html If outside of the interval of approximation, use the standard trig formula. */ if (x > 4.0) { const double alpha=(double) (MagickPI*x); return(sin((double) alpha)/alpha); } { /* The approximations only depend on x^2 (sinc is an even function). */ const double xx = x*x; #if MAGICKCORE_QUANTUM_DEPTH <= 8 /* Maximum absolute relative error 6.3e-6 < 1/2^17. */ const double c0 = 0.173610016489197553621906385078711564924e-2L; const double c1 = -0.384186115075660162081071290162149315834e-3L; const double c2 = 0.393684603287860108352720146121813443561e-4L; const double c3 = -0.248947210682259168029030370205389323899e-5L; const double c4 = 0.107791837839662283066379987646635416692e-6L; const double c5 = -0.324874073895735800961260474028013982211e-8L; const double c6 = 0.628155216606695311524920882748052490116e-10L; const double c7 = -0.586110644039348333520104379959307242711e-12L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #elif MAGICKCORE_QUANTUM_DEPTH <= 16 /* Max. abs. rel. error 2.2e-8 < 1/2^25. */ const double c0 = 0.173611107357320220183368594093166520811e-2L; const double c1 = -0.384240921114946632192116762889211361285e-3L; const double c2 = 0.394201182359318128221229891724947048771e-4L; const double c3 = -0.250963301609117217660068889165550534856e-5L; const double c4 = 0.111902032818095784414237782071368805120e-6L; const double c5 = -0.372895101408779549368465614321137048875e-8L; const double c6 = 0.957694196677572570319816780188718518330e-10L; const double c7 = -0.187208577776590710853865174371617338991e-11L; const double c8 = 0.253524321426864752676094495396308636823e-13L; const double c9 = -0.177084805010701112639035485248501049364e-15L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*(c7+xx*(c8+xx*c9)))))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #else /* Max. abs. rel. error 1.2e-12 < 1/2^39. */ const double c0 = 0.173611111110910715186413700076827593074e-2L; const double c1 = -0.289105544717893415815859968653611245425e-3L; const double c2 = 0.206952161241815727624413291940849294025e-4L; const double c3 = -0.834446180169727178193268528095341741698e-6L; const double c4 = 0.207010104171026718629622453275917944941e-7L; const double c5 = -0.319724784938507108101517564300855542655e-9L; const double c6 = 0.288101675249103266147006509214934493930e-11L; const double c7 = -0.118218971804934245819960233886876537953e-13L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); const double d0 = 1.0L; const double d1 = 0.547981619622284827495856984100563583948e-1L; const double d2 = 0.134226268835357312626304688047086921806e-2L; const double d3 = 0.178994697503371051002463656833597608689e-4L; const double d4 = 0.114633394140438168641246022557689759090e-6L; const double q = d0+xx*(d1+xx*(d2+xx*(d3+xx*d4))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)/q*p); #endif } } static double Triangle(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* 1st order (linear) B-Spline, bilinear interpolation, Tent 1D filter, or a Bartlett 2D Cone filter. Also used as a Bartlett Windowing function for Sinc(). */ if (x < 1.0) return(1.0-x); return(0.0); } static double Welch(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Welch parabolic windowing filter. */ if (x < 1.0) return(1.0-x*x); return(0.0); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireResizeFilter() allocates the ResizeFilter structure. Choose from % these filters: % % FIR (Finite impulse Response) Filters % Box Triangle Quadratic % Spline Hermite Catrom % Mitchell % % IIR (Infinite impulse Response) Filters % Gaussian Sinc Jinc (Bessel) % % Windowed Sinc/Jinc Filters % Blackman Bohman Lanczos % Hann Hamming Cosine % Kaiser Welch Parzen % Bartlett % % Special Purpose Filters % Cubic SincFast LanczosSharp Lanczos2 Lanczos2Sharp % Robidoux RobidouxSharp % % The users "-filter" selection is used to lookup the default 'expert' % settings for that filter from a internal table. However any provided % 'expert' settings (see below) may override this selection. % % FIR filters are used as is, and are limited to that filters support window % (unless over-ridden). 'Gaussian' while classed as an IIR filter, is also % simply clipped by its support size (currently 1.5 or approximately 3*sigma % as recommended by many references) % % The special a 'cylindrical' filter flag will promote the default 4-lobed % Windowed Sinc filter to a 3-lobed Windowed Jinc equivalent, which is better % suited to this style of image resampling. This typically happens when using % such a filter for images distortions. % % SPECIFIC FILTERS: % % Directly requesting 'Sinc', 'Jinc' function as a filter will force the use % of function without any windowing, or promotion for cylindrical usage. This % is not recommended, except by image processing experts, especially as part % of expert option filter function selection. % % Two forms of the 'Sinc' function are available: Sinc and SincFast. Sinc is % computed using the traditional sin(pi*x)/(pi*x); it is selected if the user % specifically specifies the use of a Sinc filter. SincFast uses highly % accurate (and fast) polynomial (low Q) and rational (high Q) approximations, % and will be used by default in most cases. % % The Lanczos filter is a special 3-lobed Sinc-windowed Sinc filter (promoted % to Jinc-windowed Jinc for cylindrical (Elliptical Weighted Average) use). % The Sinc version is the most popular windowed filter. % % LanczosSharp is a slightly sharpened (blur=0.9812505644269356 < 1) form of % the Lanczos filter, specifically designed for EWA distortion (as a % Jinc-Jinc); it can also be used as a slightly sharper orthogonal Lanczos % (Sinc-Sinc) filter. The chosen blur value comes as close as possible to % satisfying the following condition without changing the character of the % corresponding EWA filter: % % 'No-Op' Vertical and Horizontal Line Preservation Condition: Images with % only vertical or horizontal features are preserved when performing 'no-op" % with EWA distortion. % % The Lanczos2 and Lanczos2Sharp filters are 2-lobe versions of the Lanczos % filters. The 'sharp' version uses a blur factor of 0.9549963639785485, % again chosen because the resulting EWA filter comes as close as possible to % satisfying the above condition. % % Robidoux is another filter tuned for EWA. It is the Keys cubic filter % defined by B=(228 - 108 sqrt(2))/199. Robidoux satisfies the "'No-Op' % Vertical and Horizontal Line Preservation Condition" exactly, and it % moderately blurs high frequency 'pixel-hash' patterns under no-op. It turns % out to be close to both Mitchell and Lanczos2Sharp. For example, its first % crossing is at (36 sqrt(2) + 123)/(72 sqrt(2) + 47), almost the same as the % first crossing of Mitchell and Lanczos2Sharp. % % RodidouxSharp is a slightly sharper version of Rodidoux, some believe it % is too sharp. It is designed to minimize the maximum possible change in % a pixel value which is at one of the extremes (e.g., 0 or 255) under no-op % conditions. Amazingly Mitchell falls roughly between Rodidoux and % RodidouxSharp, though this seems to have been pure coincidence. % % 'EXPERT' OPTIONS: % % These artifact "defines" are not recommended for production use without % expert knowledge of resampling, filtering, and the effects they have on the % resulting resampled (resized or distorted) image. % % They can be used to override any and all filter default, and it is % recommended you make good use of "filter:verbose" to make sure that the % overall effect of your selection (before and after) is as expected. % % "filter:verbose" controls whether to output the exact results of the % filter selections made, as well as plotting data for graphing the % resulting filter over the filters support range. % % "filter:filter" select the main function associated with this filter % name, as the weighting function of the filter. This can be used to % set a windowing function as a weighting function, for special % purposes, such as graphing. % % If a "filter:window" operation has not been provided, a 'Box' % windowing function will be set to denote that no windowing function is % being used. % % "filter:window" Select this windowing function for the filter. While any % filter could be used as a windowing function, using the 'first lobe' of % that filter over the whole support window, using a non-windowing % function is not advisible. If no weighting filter function is specified % a 'SincFast' filter is used. % % "filter:lobes" Number of lobes to use for the Sinc/Jinc filter. This a % simpler method of setting filter support size that will correctly % handle the Sinc/Jinc switch for an operators filtering requirements. % Only integers should be given. % % "filter:support" Set the support size for filtering to the size given. % This not recommended for Sinc/Jinc windowed filters (lobes should be % used instead). This will override any 'filter:lobes' option. % % "filter:win-support" Scale windowing function to this size instead. This % causes the windowing (or self-windowing Lagrange filter) to act is if % the support window it much much larger than what is actually supplied % to the calling operator. The filter however is still clipped to the % real support size given, by the support range supplied to the caller. % If unset this will equal the normal filter support size. % % "filter:blur" Scale the filter and support window by this amount. A value % of > 1 will generally result in a more blurred image with more ringing % effects, while a value <1 will sharpen the resulting image with more % aliasing effects. % % "filter:sigma" The sigma value to use for the Gaussian filter only. % Defaults to '1/2'. Using a different sigma effectively provides a % method of using the filter as a 'blur' convolution. Particularly when % using it for Distort. % % "filter:b" % "filter:c" Override the preset B,C values for a Cubic filter. % If only one of these are given it is assumes to be a 'Keys' type of % filter such that B+2C=1, where Keys 'alpha' value = C. % % Examples: % % Set a true un-windowed Sinc filter with 10 lobes (very slow): % -define filter:filter=Sinc % -define filter:lobes=8 % % Set an 8 lobe Lanczos (Sinc or Jinc) filter: % -filter Lanczos % -define filter:lobes=8 % % The format of the AcquireResizeFilter method is: % % ResizeFilter *AcquireResizeFilter(const Image *image, % const FilterType filter_type,const MagickBooleanType cylindrical, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filter: the filter type, defining a preset filter, window and support. % The artifact settings listed above will override those selections. % % o blur: blur the filter by this amount, use 1.0 if unknown. Image % artifact "filter:blur" will override this API call usage, including any % internal change (such as for cylindrical usage). % % o radial: use a 1D orthogonal filter (Sinc) or 2D cylindrical (radial) % filter (Jinc). % % o exception: return any errors or warnings in this structure. % */ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image, const FilterType filter,const MagickBooleanType cylindrical, ExceptionInfo *exception) { const char *artifact; FilterType filter_type, window_type; double B, C, value; register ResizeFilter *resize_filter; /* Table Mapping given Filter, into Weighting and Windowing functions. A 'Box' windowing function means its a simble non-windowed filter. An 'SincFast' filter function could be upgraded to a 'Jinc' filter if a "cylindrical" is requested, unless a 'Sinc' or 'SincFast' filter was specifically requested by the user. WARNING: The order of this table must match the order of the FilterType enumeration specified in "resample.h", or the filter names will not match the filter being setup. You can check filter setups with the "filter:verbose" expert setting. */ static struct { FilterType filter, window; } const mapping[SentinelFilter] = { { UndefinedFilter, BoxFilter }, /* Undefined (default to Box) */ { PointFilter, BoxFilter }, /* SPECIAL: Nearest neighbour */ { BoxFilter, BoxFilter }, /* Box averaging filter */ { TriangleFilter, BoxFilter }, /* Linear interpolation filter */ { HermiteFilter, BoxFilter }, /* Hermite interpolation filter */ { SincFastFilter, HannFilter }, /* Hann -- cosine-sinc */ { SincFastFilter, HammingFilter }, /* Hamming -- '' variation */ { SincFastFilter, BlackmanFilter }, /* Blackman -- 2*cosine-sinc */ { GaussianFilter, BoxFilter }, /* Gaussian blur filter */ { QuadraticFilter, BoxFilter }, /* Quadratic Gaussian approx */ { CubicFilter, BoxFilter }, /* General Cubic Filter, Spline */ { CatromFilter, BoxFilter }, /* Cubic-Keys interpolator */ { MitchellFilter, BoxFilter }, /* 'Ideal' Cubic-Keys filter */ { JincFilter, BoxFilter }, /* Raw 3-lobed Jinc function */ { SincFilter, BoxFilter }, /* Raw 4-lobed Sinc function */ { SincFastFilter, BoxFilter }, /* Raw fast sinc ("Pade"-type) */ { SincFastFilter, KaiserFilter }, /* Kaiser -- square root-sinc */ { LanczosFilter, WelchFilter }, /* Welch -- parabolic (3 lobe) */ { SincFastFilter, CubicFilter }, /* Parzen -- cubic-sinc */ { SincFastFilter, BohmanFilter }, /* Bohman -- 2*cosine-sinc */ { SincFastFilter, TriangleFilter }, /* Bartlett -- triangle-sinc */ { LagrangeFilter, BoxFilter }, /* Lagrange self-windowing */ { LanczosFilter, LanczosFilter }, /* Lanczos Sinc-Sinc filters */ { LanczosSharpFilter, LanczosSharpFilter }, /* | these require */ { Lanczos2Filter, Lanczos2Filter }, /* | special handling */ { Lanczos2SharpFilter, Lanczos2SharpFilter }, { RobidouxFilter, BoxFilter }, /* Cubic Keys tuned for EWA */ { RobidouxSharpFilter, BoxFilter }, /* Sharper Cubic Keys for EWA */ { LanczosFilter, CosineFilter }, /* Cosine window (3 lobes) */ { SplineFilter, BoxFilter }, /* Spline Cubic Filter */ { LanczosRadiusFilter, LanczosFilter }, /* Lanczos with integer radius */ { CubicSplineFilter, BoxFilter }, /* CubicSpline (2/3/4 lobes) */ }; /* Table mapping the filter/window from the above table to an actual function. The default support size for that filter as a weighting function, the range to scale with to use that function as a sinc windowing function, (typ 1.0). Note that the filter_type -> function is 1 to 1 except for Sinc(), SincFast(), and CubicBC() functions, which may have multiple filter to function associations. See "filter:verbose" handling below for the function -> filter mapping. */ static struct { double (*function)(const double,const ResizeFilter*), support, /* Default lobes/support size of the weighting filter. */ scale, /* Support when function used as a windowing function Typically equal to the location of the first zero crossing. */ B,C; /* BC-spline coefficients, ignored if not a CubicBC filter. */ ResizeWeightingFunctionType weightingFunctionType; } const filters[SentinelFilter] = { /* .--- support window (if used as a Weighting Function) | .--- first crossing (if used as a Windowing Function) | | .--- B value for Cubic Function | | | .---- C value for Cubic Function | | | | */ { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Undefined (default to Box) */ { Box, 0.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Point (special handling) */ { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Box */ { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Triangle */ { CubicBC, 1.0, 1.0, 0.0, 0.0, CubicBCWeightingFunction }, /* Hermite (cubic B=C=0) */ { Hann, 1.0, 1.0, 0.0, 0.0, HannWeightingFunction }, /* Hann, cosine window */ { Hamming, 1.0, 1.0, 0.0, 0.0, HammingWeightingFunction }, /* Hamming, '' variation */ { Blackman, 1.0, 1.0, 0.0, 0.0, BlackmanWeightingFunction }, /* Blackman, 2*cosine window */ { Gaussian, 2.0, 1.5, 0.0, 0.0, GaussianWeightingFunction }, /* Gaussian */ { Quadratic, 1.5, 1.5, 0.0, 0.0, QuadraticWeightingFunction },/* Quadratic gaussian */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* General Cubic Filter */ { CubicBC, 2.0, 1.0, 0.0, 0.5, CubicBCWeightingFunction }, /* Catmull-Rom (B=0,C=1/2) */ { CubicBC, 2.0, 8.0/7.0, 1./3., 1./3., CubicBCWeightingFunction }, /* Mitchell (B=C=1/3) */ { Jinc, 3.0, 1.2196698912665045, 0.0, 0.0, JincWeightingFunction }, /* Raw 3-lobed Jinc */ { Sinc, 4.0, 1.0, 0.0, 0.0, SincWeightingFunction }, /* Raw 4-lobed Sinc */ { SincFast, 4.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Raw fast sinc ("Pade"-type) */ { Kaiser, 1.0, 1.0, 0.0, 0.0, KaiserWeightingFunction }, /* Kaiser (square root window) */ { Welch, 1.0, 1.0, 0.0, 0.0, WelchWeightingFunction }, /* Welch (parabolic window) */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Parzen (B-Spline window) */ { Bohman, 1.0, 1.0, 0.0, 0.0, BohmanWeightingFunction }, /* Bohman, 2*Cosine window */ { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Bartlett (triangle window) */ { Lagrange, 2.0, 1.0, 0.0, 0.0, LagrangeWeightingFunction }, /* Lagrange sinc approximation */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 3-lobed Sinc-Sinc */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Sharpened */ { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 2-lobed */ { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos2, sharpened */ /* Robidoux: Keys cubic close to Lanczos2D sharpened */ { CubicBC, 2.0, 1.1685777620836932, 0.37821575509399867, 0.31089212245300067, CubicBCWeightingFunction }, /* RobidouxSharp: Sharper version of Robidoux */ { CubicBC, 2.0, 1.105822933719019, 0.2620145123990142, 0.3689927438004929, CubicBCWeightingFunction }, { Cosine, 1.0, 1.0, 0.0, 0.0, CosineWeightingFunction }, /* Low level cosine window */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Cubic B-Spline (B=1,C=0) */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Interger Radius */ { CubicSpline,2.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Spline Lobes 2-lobed */ }; /* The known zero crossings of the Jinc() or more accurately the Jinc(x*PI) function being used as a filter. It is used by the "filter:lobes" expert setting and for 'lobes' for Jinc functions in the previous table. This way users do not have to deal with the highly irrational lobe sizes of the Jinc filter. Values taken from http://cose.math.bas.bg/webMathematica/webComputing/BesselZeros.jsp using Jv-function with v=1, then dividing by PI. */ static double jinc_zeros[16] = { 1.2196698912665045, 2.2331305943815286, 3.2383154841662362, 4.2410628637960699, 5.2427643768701817, 6.2439216898644877, 7.2447598687199570, 8.2453949139520427, 9.2458926849494673, 10.246293348754916, 11.246622794877883, 12.246898461138105, 13.247132522181061, 14.247333735806849, 15.247508563037300, 16.247661874700962 }; /* Allocate resize filter. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(UndefinedFilter < filter && filter < SentinelFilter); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); (void) exception; resize_filter=(ResizeFilter *) AcquireCriticalMemory(sizeof(*resize_filter)); (void) memset(resize_filter,0,sizeof(*resize_filter)); /* Defaults for the requested filter. */ filter_type=mapping[filter].filter; window_type=mapping[filter].window; resize_filter->blur=1.0; /* Promote 1D Windowed Sinc Filters to a 2D Windowed Jinc filters */ if ((cylindrical != MagickFalse) && (filter_type == SincFastFilter) && (filter != SincFastFilter)) filter_type=JincFilter; /* 1D Windowed Sinc => 2D Windowed Jinc filters */ /* Expert filter setting override */ artifact=GetImageArtifact(image,"filter:filter"); if (IsStringTrue(artifact) != MagickFalse) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { /* Raw filter request - no window function. */ filter_type=(FilterType) option; window_type=BoxFilter; } /* Filter override with a specific window function. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) window_type=(FilterType) option; } } else { /* Window specified, but no filter function? Assume Sinc/Jinc. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { filter_type= cylindrical != MagickFalse ? JincFilter : SincFastFilter; window_type=(FilterType) option; } } } /* Assign the real functions to use for the filters selected. */ resize_filter->filter=filters[filter_type].function; resize_filter->support=filters[filter_type].support; resize_filter->filterWeightingType=filters[filter_type].weightingFunctionType; resize_filter->window=filters[window_type].function; resize_filter->windowWeightingType=filters[window_type].weightingFunctionType; resize_filter->scale=filters[window_type].scale; resize_filter->signature=MagickCoreSignature; /* Filter Modifications for orthogonal/cylindrical usage */ if (cylindrical != MagickFalse) switch (filter_type) { case BoxFilter: /* Support for Cylindrical Box should be sqrt(2)/2 */ resize_filter->support=(double) MagickSQ1_2; break; case LanczosFilter: case LanczosSharpFilter: case Lanczos2Filter: case Lanczos2SharpFilter: case LanczosRadiusFilter: resize_filter->filter=filters[JincFilter].function; resize_filter->window=filters[JincFilter].function; resize_filter->scale=filters[JincFilter].scale; /* number of lobes (support window size) remain unchanged */ break; default: break; } /* Global Sharpening (regardless of orthoginal/cylindrical) */ switch (filter_type) { case LanczosSharpFilter: resize_filter->blur *= 0.9812505644269356; break; case Lanczos2SharpFilter: resize_filter->blur *= 0.9549963639785485; break; /* case LanczosRadius: blur adjust is done after lobes */ default: break; } /* Expert Option Modifications. */ /* User Gaussian Sigma Override - no support change */ if ((resize_filter->filter == Gaussian) || (resize_filter->window == Gaussian) ) { value=0.5; /* guassian sigma default, half pixel */ artifact=GetImageArtifact(image,"filter:sigma"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); /* Define coefficents for Gaussian */ resize_filter->coefficient[0]=value; /* note sigma too */ resize_filter->coefficient[1]=PerceptibleReciprocal(2.0*value*value); /* sigma scaling */ resize_filter->coefficient[2]=PerceptibleReciprocal(Magick2PI*value*value); /* normalization - not actually needed or used! */ if ( value > 0.5 ) resize_filter->support *= 2*value; /* increase support linearly */ } /* User Kaiser Alpha Override - no support change */ if ((resize_filter->filter == Kaiser) || (resize_filter->window == Kaiser) ) { value=6.5; /* default beta value for Kaiser bessel windowing function */ artifact=GetImageArtifact(image,"filter:alpha"); /* FUTURE: depreciate */ if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"filter:kaiser-beta"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"filter:kaiser-alpha"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL)*MagickPI; /* Define coefficents for Kaiser Windowing Function */ resize_filter->coefficient[0]=value; /* alpha */ resize_filter->coefficient[1]=PerceptibleReciprocal(I0(value)); /* normalization */ } /* Support Overrides */ artifact=GetImageArtifact(image,"filter:lobes"); if (artifact != (const char *) NULL) { ssize_t lobes; lobes=(ssize_t) StringToLong(artifact); if (lobes < 1) lobes=1; resize_filter->support=(double) lobes; } if (resize_filter->filter == Jinc) { /* Convert a Jinc function lobes value to a real support value. */ if (resize_filter->support > 16) resize_filter->support=jinc_zeros[15]; /* largest entry in table */ else resize_filter->support=jinc_zeros[((long) resize_filter->support)-1]; /* Blur this filter so support is a integer value (lobes dependant). */ if (filter_type == LanczosRadiusFilter) resize_filter->blur*=floor(resize_filter->support)/ resize_filter->support; } /* Expert blur override. */ artifact=GetImageArtifact(image,"filter:blur"); if (artifact != (const char *) NULL) resize_filter->blur*=StringToDouble(artifact,(char **) NULL); if (resize_filter->blur < MagickEpsilon) resize_filter->blur=(double) MagickEpsilon; /* Expert override of the support setting. */ artifact=GetImageArtifact(image,"filter:support"); if (artifact != (const char *) NULL) resize_filter->support=fabs(StringToDouble(artifact,(char **) NULL)); /* Scale windowing function separately to the support 'clipping' window that calling operator is planning to actually use. (Expert override) */ resize_filter->window_support=resize_filter->support; /* default */ artifact=GetImageArtifact(image,"filter:win-support"); if (artifact != (const char *) NULL) resize_filter->window_support=fabs(StringToDouble(artifact,(char **) NULL)); /* Adjust window function scaling to match windowing support for weighting function. This avoids a division on every filter call. */ resize_filter->scale*=PerceptibleReciprocal(resize_filter->window_support); /* Set Cubic Spline B,C values, calculate Cubic coefficients. */ B=0.0; C=0.0; if ((resize_filter->filter == CubicBC) || (resize_filter->window == CubicBC) ) { B=filters[filter_type].B; C=filters[filter_type].C; if (filters[window_type].function == CubicBC) { B=filters[window_type].B; C=filters[window_type].C; } artifact=GetImageArtifact(image,"filter:b"); if (artifact != (const char *) NULL) { B=StringToDouble(artifact,(char **) NULL); C=(1.0-B)/2.0; /* Calculate C to get a Keys cubic filter. */ artifact=GetImageArtifact(image,"filter:c"); /* user C override */ if (artifact != (const char *) NULL) C=StringToDouble(artifact,(char **) NULL); } else { artifact=GetImageArtifact(image,"filter:c"); if (artifact != (const char *) NULL) { C=StringToDouble(artifact,(char **) NULL); B=1.0-2.0*C; /* Calculate B to get a Keys cubic filter. */ } } { const double twoB = B+B; /* Convert B,C values into Cubic Coefficents. See CubicBC(). */ resize_filter->coefficient[0]=1.0-(1.0/3.0)*B; resize_filter->coefficient[1]=-3.0+twoB+C; resize_filter->coefficient[2]=2.0-1.5*B-C; resize_filter->coefficient[3]=(4.0/3.0)*B+4.0*C; resize_filter->coefficient[4]=-8.0*C-twoB; resize_filter->coefficient[5]=B+5.0*C; resize_filter->coefficient[6]=(-1.0/6.0)*B-C; } } /* Expert Option Request for verbose details of the resulting filter. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp master { #endif if (IsStringTrue(GetImageArtifact(image,"filter:verbose")) != MagickFalse) { double support, x; /* Set the weighting function properly when the weighting function may not exactly match the filter of the same name. EG: a Point filter is really uses a Box weighting function with a different support than is typically used. */ if (resize_filter->filter == Box) filter_type=BoxFilter; if (resize_filter->filter == Sinc) filter_type=SincFilter; if (resize_filter->filter == SincFast) filter_type=SincFastFilter; if (resize_filter->filter == Jinc) filter_type=JincFilter; if (resize_filter->filter == CubicBC) filter_type=CubicFilter; if (resize_filter->window == Box) window_type=BoxFilter; if (resize_filter->window == Sinc) window_type=SincFilter; if (resize_filter->window == SincFast) window_type=SincFastFilter; if (resize_filter->window == Jinc) window_type=JincFilter; if (resize_filter->window == CubicBC) window_type=CubicFilter; /* Report Filter Details. */ support=GetResizeFilterSupport(resize_filter); /* practical_support */ (void) FormatLocaleFile(stdout, "# Resampling Filter (for graphing)\n#\n"); (void) FormatLocaleFile(stdout,"# filter = %s\n", CommandOptionToMnemonic(MagickFilterOptions,filter_type)); (void) FormatLocaleFile(stdout,"# window = %s\n", CommandOptionToMnemonic(MagickFilterOptions,window_type)); (void) FormatLocaleFile(stdout,"# support = %.*g\n", GetMagickPrecision(),(double) resize_filter->support); (void) FormatLocaleFile(stdout,"# window-support = %.*g\n", GetMagickPrecision(),(double) resize_filter->window_support); (void) FormatLocaleFile(stdout,"# scale-blur = %.*g\n", GetMagickPrecision(),(double) resize_filter->blur); if ((filter_type == GaussianFilter) || (window_type == GaussianFilter)) (void) FormatLocaleFile(stdout,"# gaussian-sigma = %.*g\n", GetMagickPrecision(),(double) resize_filter->coefficient[0]); if ( filter_type == KaiserFilter || window_type == KaiserFilter ) (void) FormatLocaleFile(stdout,"# kaiser-beta = %.*g\n", GetMagickPrecision(),(double) resize_filter->coefficient[0]); (void) FormatLocaleFile(stdout,"# practical-support = %.*g\n", GetMagickPrecision(), (double) support); if ((filter_type == CubicFilter) || (window_type == CubicFilter)) (void) FormatLocaleFile(stdout,"# B,C = %.*g,%.*g\n", GetMagickPrecision(),(double) B,GetMagickPrecision(),(double) C); (void) FormatLocaleFile(stdout,"\n"); /* Output values of resulting filter graph -- for graphing filter result. */ for (x=0.0; x <= support; x+=0.01f) (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",x, GetMagickPrecision(),(double) GetResizeFilterWeight(resize_filter,x)); /* A final value so gnuplot can graph the 'stop' properly. */ (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",support, GetMagickPrecision(),0.0); } /* Output the above once only for each image - remove setting */ (void) DeleteImageArtifact((Image *) image,"filter:verbose"); #if defined(MAGICKCORE_OPENMP_SUPPORT) } #endif return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveResizeImage() adaptively resize image with pixel resampling. % % This is shortcut function for a fast interpolative resize using mesh % interpolation. It works well for small resizes of less than +/- 50% % of the original image size. For larger resizing on images a full % filtered and slower resize function should be used instead. % % The format of the AdaptiveResizeImage method is: % % Image *AdaptiveResizeImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveResizeImage(const Image *image, const size_t columns,const size_t rows,ExceptionInfo *exception) { Image *resize_image; resize_image=InterpolativeResizeImage(image,columns,rows,MeshInterpolatePixel, exception); return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + B e s s e l O r d e r O n e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BesselOrderOne() computes the Bessel function of x of the first kind of % order 0. This is used to create the Jinc() filter function below. % % Reduce x to |x| since j1(x)= -j1(-x), and for x in (0,8] % % j1(x) = x*j1(x); % % For x in (8,inf) % % j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1)) % % where x1 = x-3*pi/4. Compute sin(x1) and cos(x1) as follow: % % cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) % = 1/sqrt(2) * (sin(x) - cos(x)) % sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) % = -1/sqrt(2) * (sin(x) + cos(x)) % % The format of the BesselOrderOne method is: % % double BesselOrderOne(double x) % % A description of each parameter follows: % % o x: double value. % */ #undef I0 static double I0(double x) { double sum, t, y; register ssize_t i; /* Zeroth order Bessel function of the first kind. */ sum=1.0; y=x*x/4.0; t=y; for (i=2; t > MagickEpsilon; i++) { sum+=t; t*=y/((double) i*i); } return(sum); } #undef J1 static double J1(double x) { double p, q; register ssize_t i; static const double Pone[] = { 0.581199354001606143928050809e+21, -0.6672106568924916298020941484e+20, 0.2316433580634002297931815435e+19, -0.3588817569910106050743641413e+17, 0.2908795263834775409737601689e+15, -0.1322983480332126453125473247e+13, 0.3413234182301700539091292655e+10, -0.4695753530642995859767162166e+7, 0.270112271089232341485679099e+4 }, Qone[] = { 0.11623987080032122878585294e+22, 0.1185770712190320999837113348e+20, 0.6092061398917521746105196863e+17, 0.2081661221307607351240184229e+15, 0.5243710262167649715406728642e+12, 0.1013863514358673989967045588e+10, 0.1501793594998585505921097578e+7, 0.1606931573481487801970916749e+4, 0.1e+1 }; p=Pone[8]; q=Qone[8]; for (i=7; i >= 0; i--) { p=p*x*x+Pone[i]; q=q*x*x+Qone[i]; } return(p/q); } #undef P1 static double P1(double x) { double p, q; register ssize_t i; static const double Pone[] = { 0.352246649133679798341724373e+5, 0.62758845247161281269005675e+5, 0.313539631109159574238669888e+5, 0.49854832060594338434500455e+4, 0.2111529182853962382105718e+3, 0.12571716929145341558495e+1 }, Qone[] = { 0.352246649133679798068390431e+5, 0.626943469593560511888833731e+5, 0.312404063819041039923015703e+5, 0.4930396490181088979386097e+4, 0.2030775189134759322293574e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } #undef Q1 static double Q1(double x) { double p, q; register ssize_t i; static const double Pone[] = { 0.3511751914303552822533318e+3, 0.7210391804904475039280863e+3, 0.4259873011654442389886993e+3, 0.831898957673850827325226e+2, 0.45681716295512267064405e+1, 0.3532840052740123642735e-1 }, Qone[] = { 0.74917374171809127714519505e+4, 0.154141773392650970499848051e+5, 0.91522317015169922705904727e+4, 0.18111867005523513506724158e+4, 0.1038187585462133728776636e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } static double BesselOrderOne(double x) { double p, q; if (x == 0.0) return(0.0); p=x; if (x < 0.0) x=(-x); if (x < 8.0) return(p*J1(x)); q=sqrt((double) (2.0/(MagickPI*x)))*(P1(x)*(1.0/sqrt(2.0)*(sin(x)- cos(x)))-8.0/x*Q1(x)*(-1.0/sqrt(2.0)*(sin(x)+cos(x)))); if (p < 0.0) q=(-q); return(q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyResizeFilter() destroy the resize filter. % % The format of the DestroyResizeFilter method is: % % ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) % % A description of each parameter follows: % % o resize_filter: the resize filter. % */ MagickPrivate ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); resize_filter->signature=(~MagickCoreSignature); resize_filter=(ResizeFilter *) RelinquishMagickMemory(resize_filter); return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r S u p p o r t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterSupport() return the current support window size for this % filter. Note that this may have been enlarged by filter:blur factor. % % The format of the GetResizeFilterSupport method is: % % double GetResizeFilterSupport(const ResizeFilter *resize_filter) % % A description of each parameter follows: % % o filter: Image filter to use. % */ MagickPrivate double *GetResizeFilterCoefficient( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return((double *) resize_filter->coefficient); } MagickPrivate double GetResizeFilterBlur(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->blur); } MagickPrivate double GetResizeFilterScale(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->scale); } MagickPrivate double GetResizeFilterWindowSupport( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->window_support); } MagickPrivate ResizeWeightingFunctionType GetResizeFilterWeightingType( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->filterWeightingType); } MagickPrivate ResizeWeightingFunctionType GetResizeFilterWindowWeightingType( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->windowWeightingType); } MagickPrivate double GetResizeFilterSupport(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->support*resize_filter->blur); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r W e i g h t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterWeight evaluates the specified resize filter at the point x % which usally lies between zero and the filters current 'support' and % returns the weight of the filter function at that point. % % The format of the GetResizeFilterWeight method is: % % double GetResizeFilterWeight(const ResizeFilter *resize_filter, % const double x) % % A description of each parameter follows: % % o filter: the filter type. % % o x: the point. % */ MagickPrivate double GetResizeFilterWeight(const ResizeFilter *resize_filter, const double x) { double scale, weight, x_blur; /* Windowing function - scale the weighting filter by this amount. */ assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); x_blur=fabs((double) x)/resize_filter->blur; /* X offset with blur scaling */ if ((resize_filter->window_support < MagickEpsilon) || (resize_filter->window == Box)) scale=1.0; /* Point or Box Filter -- avoid division by zero */ else { scale=resize_filter->scale; scale=resize_filter->window(x_blur*scale,resize_filter); } weight=scale*resize_filter->filter(x_blur,resize_filter); return(weight); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t i v e R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolativeResizeImage() resizes an image using the specified % interpolation method. % % The format of the InterpolativeResizeImage method is: % % Image *InterpolativeResizeImage(const Image *image,const size_t columns, % const size_t rows,const PixelInterpolateMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *InterpolativeResizeImage(const Image *image, const size_t columns,const size_t rows,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define InterpolativeResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; Image *resize_image; MagickBooleanType status; MagickOffsetType progress; PointInfo scale; ssize_t y; /* Interpolatively resize image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(resize_image,DirectClass,exception) == MagickFalse) { resize_image=DestroyImage(resize_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); scale.x=(double) image->columns/resize_image->columns; scale.y=(double) image->rows/resize_image->rows; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->rows,1) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { PointInfo offset; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if (q == (Quantum *) NULL) continue; offset.y=((double) y+0.5)*scale.y-0.5; for (x=0; x < (ssize_t) resize_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait resize_traits, traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; offset.x=((double) x+0.5)*scale.x-0.5; status=InterpolatePixelChannels(image,image_view,resize_image,method, offset.x,offset.y,q,exception); if (status == MagickFalse) break; } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,InterpolativeResizeImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) resize_image=DestroyImage(resize_image); return(resize_image); } #if defined(MAGICKCORE_LQR_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i q u i d R e s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiquidRescaleImage() rescales image with seam carving. % % The format of the LiquidRescaleImage method is: % % Image *LiquidRescaleImage(const Image *image,const size_t columns, % const size_t rows,const double delta_x,const double rigidity, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the rescaled image. % % o rows: the number of rows in the rescaled image. % % o delta_x: maximum seam transversal step (0 means straight seams). % % o rigidity: introduce a bias for non-straight seams (typically 0). % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *LiquidRescaleImage(const Image *image,const size_t columns, const size_t rows,const double delta_x,const double rigidity, ExceptionInfo *exception) { #define LiquidRescaleImageTag "Rescale/Image" CacheView *image_view, *rescale_view; gfloat *packet, *pixels; Image *rescale_image; int x_offset, y_offset; LqrCarver *carver; LqrRetVal lqr_status; MagickBooleanType status; MemoryInfo *pixel_info; register gfloat *q; ssize_t y; /* Liquid rescale image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); if ((columns <= 2) || (rows <= 2)) return(ResizeImage(image,columns,rows,image->filter,exception)); pixel_info=AcquireVirtualMemory(image->columns,image->rows*MaxPixelChannels* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) return((Image *) NULL); pixels=(gfloat *) GetVirtualMemoryBlob(pixel_info); status=MagickTrue; q=pixels; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register 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++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) *q++=QuantumScale*p[i]; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); carver=lqr_carver_new_ext(pixels,(int) image->columns,(int) image->rows, (int) GetPixelChannels(image),LQR_COLDEPTH_32F); if (carver == (LqrCarver *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } lqr_carver_set_preserve_input_image(carver); lqr_status=lqr_carver_init(carver,(int) delta_x,rigidity); lqr_status=lqr_carver_resize(carver,(int) columns,(int) rows); (void) lqr_status; rescale_image=CloneImage(image,lqr_carver_get_width(carver), lqr_carver_get_height(carver),MagickTrue,exception); if (rescale_image == (Image *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); return((Image *) NULL); } if (SetImageStorageClass(rescale_image,DirectClass,exception) == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); rescale_image=DestroyImage(rescale_image); return((Image *) NULL); } rescale_view=AcquireAuthenticCacheView(rescale_image,exception); (void) lqr_carver_scan_reset(carver); while (lqr_carver_scan_ext(carver,&x_offset,&y_offset,(void **) &packet) != 0) { register Quantum *magick_restrict p; register ssize_t i; p=QueueCacheViewAuthenticPixels(rescale_view,x_offset,y_offset,1,1, exception); if (p == (Quantum *) NULL) break; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait rescale_traits, traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); rescale_traits=GetPixelChannelTraits(rescale_image,channel); if ((traits == UndefinedPixelTrait) || (rescale_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rescale_image,channel,ClampToQuantum(QuantumRange* packet[i]),p); } if (SyncCacheViewAuthenticPixels(rescale_view,exception) == MagickFalse) break; } rescale_view=DestroyCacheView(rescale_view); pixel_info=RelinquishVirtualMemory(pixel_info); lqr_carver_destroy(carver); return(rescale_image); } #else MagickExport Image *LiquidRescaleImage(const Image *image, const size_t magick_unused(columns),const size_t magick_unused(rows), const double magick_unused(delta_x),const double magick_unused(rigidity), ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError, "DelegateLibrarySupportNotBuiltIn","'%s' (LQR)",image->filename); return((Image *) NULL); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagnifyImage() doubles the size of the image with a pixel art scaling % algorithm. % % The format of the MagnifyImage method is: % % Image *MagnifyImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline void CopyPixels(const Quantum *source,const ssize_t source_offset, Quantum *destination,const ssize_t destination_offset,const size_t channels) { register ssize_t i; for (i=0; i < (ssize_t) channels; i++) destination[channels*destination_offset+i]=source[source_offset*channels+i]; } static inline void MixPixels(const Quantum *source,const ssize_t *source_offset, const size_t source_size,Quantum *destination, const ssize_t destination_offset,const size_t channels) { ssize_t sum; register ssize_t i; for (i=0; i < (ssize_t) channels; i++) { register ssize_t j; sum=0; for (j=0; j < (ssize_t) source_size; j++) sum+=source[source_offset[j]*channels+i]; destination[channels*destination_offset+i]=(Quantum) (sum/source_size); } } static inline void Mix2Pixels(const Quantum *source, const ssize_t source_offset1,const ssize_t source_offset2, Quantum *destination,const ssize_t destination_offset,const size_t channels) { const ssize_t offsets[2] = { source_offset1, source_offset2 }; MixPixels(source,offsets,2,destination,destination_offset,channels); } static inline int PixelsEqual(const Quantum *source1,ssize_t offset1, const Quantum *source2,ssize_t offset2,const size_t channels) { register ssize_t i; offset1*=channels; offset2*=channels; for (i=0; i < (ssize_t) channels; i++) if (source1[offset1+i] != source2[offset2+i]) return(0); return(1); } static inline void Eagle2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { ssize_t i; (void) source; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); if (PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,1,pixels,3,channels)) CopyPixels(pixels,0,result,0,channels); if (PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels)) CopyPixels(pixels,2,result,1,channels); if (PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels)) CopyPixels(pixels,6,result,2,channels); if (PixelsEqual(pixels,5,pixels,8,channels) && PixelsEqual(pixels,8,pixels,7,channels)) CopyPixels(pixels,8,result,3,channels); } static void Hq2XHelper(const unsigned int rule,const Quantum *source, Quantum *destination,const ssize_t destination_offset,const size_t channels, const ssize_t e,const ssize_t a,const ssize_t b,const ssize_t d, const ssize_t f,const ssize_t h) { #define caseA(N,A,B,C,D) \ case N: \ { \ const ssize_t \ offsets[4] = { A, B, C, D }; \ \ MixPixels(source,offsets,4,destination,destination_offset,channels);\ break; \ } #define caseB(N,A,B,C,D,E,F,G,H) \ case N: \ { \ const ssize_t \ offsets[8] = { A, B, C, D, E, F, G, H }; \ \ MixPixels(source,offsets,8,destination,destination_offset,channels);\ break; \ } switch (rule) { case 0: { CopyPixels(source,e,destination,destination_offset,channels); break; } caseA(1,e,e,e,a) caseA(2,e,e,e,d) caseA(3,e,e,e,b) caseA(4,e,e,d,b) caseA(5,e,e,a,b) caseA(6,e,e,a,d) caseB(7,e,e,e,e,e,b,b,d) caseB(8,e,e,e,e,e,d,d,b) caseB(9,e,e,e,e,e,e,d,b) caseB(10,e,e,d,d,d,b,b,b) case 11: { const ssize_t offsets[16] = { e, e, e, e, e, e, e, e, e, e, e, e, e, e, d, b }; MixPixels(source,offsets,16,destination,destination_offset,channels); break; } case 12: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[4] = { e, e, d, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 13: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, d, d, d, b, b, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 14: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[16] = { e, e, e, e, e, e, e, e, e, e, e, e, e, e, d, b }; MixPixels(source,offsets,16,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 15: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[4] = { e, e, d, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 16: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, e, d, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 17: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, d, d, d, b, b, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 18: { if (PixelsEqual(source,b,source,f,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, b, b, d }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, d }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } default: { if (PixelsEqual(source,d,source,h,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, d, d, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } } #undef caseA #undef caseB } static inline unsigned int Hq2XPatternToNumber(const int *pattern) { ssize_t i; unsigned int result, order; result=0; order=1; for (i=7; i >= 0; i--) { result+=order*pattern[i]; order*=2; } return(result); } static inline void Hq2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { static const unsigned int Hq2XTable[] = { 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13, 4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 12, 12, 5, 3, 1, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14, 4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 16, 12, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 12, 12, 5, 19, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 1, 12, 5, 19, 1, 14, 4, 4, 6, 2, 4, 4, 6, 18, 5, 3, 16, 12, 5, 19, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 13, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 13, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 1, 12, 5, 3, 1, 14 }; const int pattern1[] = { !PixelsEqual(pixels,4,pixels,8,channels), !PixelsEqual(pixels,4,pixels,7,channels), !PixelsEqual(pixels,4,pixels,6,channels), !PixelsEqual(pixels,4,pixels,5,channels), !PixelsEqual(pixels,4,pixels,3,channels), !PixelsEqual(pixels,4,pixels,2,channels), !PixelsEqual(pixels,4,pixels,1,channels), !PixelsEqual(pixels,4,pixels,0,channels) }; #define Rotated(p) p[2], p[4], p[7], p[1], p[6], p[0], p[3], p[5] const int pattern2[] = { Rotated(pattern1) }; const int pattern3[] = { Rotated(pattern2) }; const int pattern4[] = { Rotated(pattern3) }; #undef Rotated Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern1)],pixels,result,0, channels,4,0,1,3,5,7); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern2)],pixels,result,1, channels,4,2,5,1,7,3); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern3)],pixels,result,3, channels,4,8,7,5,3,1); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern4)],pixels,result,2, channels,4,6,3,7,1,5); } static void Fish2X(const Image *source,const Quantum *pixels,Quantum *result, const size_t channels) { #define Corner(A,B,C,D) \ { \ if (intensities[B] > intensities[A]) \ { \ ssize_t \ offsets[3] = { B, C, D }; \ \ MixPixels(pixels,offsets,3,result,3,channels); \ } \ else \ { \ ssize_t \ offsets[3] = { A, B, C }; \ \ MixPixels(pixels,offsets,3,result,3,channels); \ } \ } #define Line(A,B,C,D) \ { \ if (intensities[C] > intensities[A]) \ Mix2Pixels(pixels,C,D,result,3,channels); \ else \ Mix2Pixels(pixels,A,B,result,3,channels); \ } MagickFloatType intensities[9]; int ae, bd, ab, ad, be, de; register ssize_t i; ssize_t offsets[4] = { 0, 1, 3, 4 }; for (i=0; i < 9; i++) intensities[i]=GetPixelIntensity(source,pixels + i*channels); CopyPixels(pixels,0,result,0,channels); CopyPixels(pixels,(ssize_t) (intensities[0] > intensities[1] ? 0 : 1),result, 1,channels); CopyPixels(pixels,(ssize_t) (intensities[0] > intensities[3] ? 0 : 3),result, 2,channels); ae=PixelsEqual(pixels,0,pixels,4,channels); bd=PixelsEqual(pixels,1,pixels,3,channels); ab=PixelsEqual(pixels,0,pixels,1,channels); de=PixelsEqual(pixels,3,pixels,4,channels); ad=PixelsEqual(pixels,0,pixels,3,channels); be=PixelsEqual(pixels,1,pixels,4,channels); if (ae && bd && ab) { CopyPixels(pixels,0,result,3,channels); return; } if (ad && de && !ab) { Corner(1,0,4,3) return; } if (be && de && !ab) { Corner(0,1,3,4) return; } if (ad && ab && !be) { Corner(4,3,1,0) return; } if (ab && be && !ad) { Corner(3,0,4,1) return; } if (ae && (!bd || intensities[1] > intensities[0])) { Mix2Pixels(pixels,0,4,result,3,channels); return; } if (bd && (!ae || intensities[0] > intensities[1])) { Mix2Pixels(pixels,1,3,result,3,channels); return; } if (ab) { Line(0,1,3,4) return; } if (de) { Line(3,4,0,1) return; } if (ad) { Line(0,3,1,4) return; } if (be) { Line(1,4,0,3) return; } MixPixels(pixels,offsets,4,result,3,channels); #undef Corner #undef Line } static void Xbr2X(const Image *source,const Quantum *pixels,Quantum *result, const size_t channels) { #define WeightVar(M,N) const int w_##M##_##N = \ PixelsEqual(pixels,M,pixels,N,channels) ? 0 : 1; WeightVar(12,11) WeightVar(12,7) WeightVar(12,13) WeightVar(12,17) WeightVar(12,16) WeightVar(12,8) WeightVar(6,10) WeightVar(6,2) WeightVar(11,7) WeightVar(11,17) WeightVar(11,5) WeightVar(7,13) WeightVar(7,1) WeightVar(12,6) WeightVar(12,18) WeightVar(8,14) WeightVar(8,2) WeightVar(13,17) WeightVar(13,9) WeightVar(7,3) WeightVar(16,10) WeightVar(16,22) WeightVar(17,21) WeightVar(11,15) WeightVar(18,14) WeightVar(18,22) WeightVar(17,23) WeightVar(17,19) #undef WeightVar if ( w_12_16 + w_12_8 + w_6_10 + w_6_2 + (4 * w_11_7) < w_11_17 + w_11_5 + w_7_13 + w_7_1 + (4 * w_12_6) ) Mix2Pixels(pixels,(ssize_t) (w_12_11 <= w_12_7 ? 11 : 7),12,result,0, channels); else CopyPixels(pixels,12,result,0,channels); if ( w_12_18 + w_12_6 + w_8_14 + w_8_2 + (4 * w_7_13) < w_13_17 + w_13_9 + w_11_7 + w_7_3 + (4 * w_12_8) ) Mix2Pixels(pixels,(ssize_t) (w_12_7 <= w_12_13 ? 7 : 13),12,result,1, channels); else CopyPixels(pixels,12,result,1,channels); if ( w_12_6 + w_12_18 + w_16_10 + w_16_22 + (4 * w_11_17) < w_11_7 + w_11_15 + w_13_17 + w_17_21 + (4 * w_12_16) ) Mix2Pixels(pixels,(ssize_t) (w_12_11 <= w_12_17 ? 11 : 17),12,result,2, channels); else CopyPixels(pixels,12,result,2,channels); if ( w_12_8 + w_12_16 + w_18_14 + w_18_22 + (4 * w_13_17) < w_11_17 + w_17_23 + w_17_19 + w_7_13 + (4 * w_12_18) ) Mix2Pixels(pixels,(ssize_t) (w_12_13 <= w_12_17 ? 13 : 17),12,result,3, channels); else CopyPixels(pixels,12,result,3,channels); } static void Scale2X(const Image *source,const Quantum *pixels,Quantum *result, const size_t channels) { if (PixelsEqual(pixels,1,pixels,7,channels) || PixelsEqual(pixels,3,pixels,5,channels)) { register ssize_t i; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); return; } if (PixelsEqual(pixels,1,pixels,3,channels)) CopyPixels(pixels,3,result,0,channels); else CopyPixels(pixels,4,result,0,channels); if (PixelsEqual(pixels,1,pixels,5,channels)) CopyPixels(pixels,5,result,1,channels); else CopyPixels(pixels,4,result,1,channels); if (PixelsEqual(pixels,3,pixels,7,channels)) CopyPixels(pixels,3,result,2,channels); else CopyPixels(pixels,4,result,2,channels); if (PixelsEqual(pixels,5,pixels,7,channels)) CopyPixels(pixels,5,result,3,channels); else CopyPixels(pixels,4,result,3,channels); } static void Epbx2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { #define HelperCond(a,b,c,d,e,f,g) ( \ PixelsEqual(pixels,a,pixels,b,channels) && ( \ PixelsEqual(pixels,c,pixels,d,channels) || \ PixelsEqual(pixels,c,pixels,e,channels) || \ PixelsEqual(pixels,a,pixels,f,channels) || \ PixelsEqual(pixels,b,pixels,g,channels) \ ) \ ) register ssize_t i; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); if ( !PixelsEqual(pixels,3,pixels,5,channels) && !PixelsEqual(pixels,1,pixels,7,channels) && ( PixelsEqual(pixels,4,pixels,3,channels) || PixelsEqual(pixels,4,pixels,7,channels) || PixelsEqual(pixels,4,pixels,5,channels) || PixelsEqual(pixels,4,pixels,1,channels) || ( ( !PixelsEqual(pixels,0,pixels,8,channels) || PixelsEqual(pixels,4,pixels,6,channels) || PixelsEqual(pixels,3,pixels,2,channels) ) && ( !PixelsEqual(pixels,6,pixels,2,channels) || PixelsEqual(pixels,4,pixels,0,channels) || PixelsEqual(pixels,4,pixels,8,channels) ) ) ) ) { if (HelperCond(1,3,4,0,8,2,6)) Mix2Pixels(pixels,1,3,result,0,channels); if (HelperCond(5,1,4,2,6,8,0)) Mix2Pixels(pixels,5,1,result,1,channels); if (HelperCond(3,7,4,6,2,0,8)) Mix2Pixels(pixels,3,7,result,2,channels); if (HelperCond(7,5,4,8,0,6,2)) Mix2Pixels(pixels,7,5,result,3,channels); } #undef HelperCond } static inline void Eagle3X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { ssize_t corner_tl, corner_tr, corner_bl, corner_br; corner_tl=PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,0,pixels,3,channels); corner_tr=PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels); corner_bl=PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels); corner_br=PixelsEqual(pixels,5,pixels,7,channels) && PixelsEqual(pixels,7,pixels,8,channels); CopyPixels(pixels,(ssize_t) (corner_tl ? 0 : 4),result,0,channels); if (corner_tl && corner_tr) Mix2Pixels(pixels,0,2,result,1,channels); else CopyPixels(pixels,4,result,1,channels); CopyPixels(pixels,(ssize_t) (corner_tr ? 1 : 4),result,2,channels); if (corner_tl && corner_bl) Mix2Pixels(pixels,0,6,result,3,channels); else CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); if (corner_tr && corner_br) Mix2Pixels(pixels,2,8,result,5,channels); else CopyPixels(pixels,4,result,5,channels); CopyPixels(pixels,(ssize_t) (corner_bl ? 3 : 4),result,6,channels); if (corner_bl && corner_br) Mix2Pixels(pixels,6,8,result,7,channels); else CopyPixels(pixels,4,result,7,channels); CopyPixels(pixels,(ssize_t) (corner_br ? 5 : 4),result,8,channels); } static inline void Eagle3XB(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { ssize_t corner_tl, corner_tr, corner_bl, corner_br; corner_tl=PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,0,pixels,3,channels); corner_tr=PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels); corner_bl=PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels); corner_br=PixelsEqual(pixels,5,pixels,7,channels) && PixelsEqual(pixels,7,pixels,8,channels); CopyPixels(pixels,(ssize_t) (corner_tl ? 0 : 4),result,0,channels); CopyPixels(pixels,4,result,1,channels); CopyPixels(pixels,(ssize_t) (corner_tr ? 1 : 4),result,2,channels); CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); CopyPixels(pixels,4,result,5,channels); CopyPixels(pixels,(ssize_t) (corner_bl ? 3 : 4),result,6,channels); CopyPixels(pixels,4,result,7,channels); CopyPixels(pixels,(ssize_t) (corner_br ? 5 : 4),result,8,channels); } static inline void Scale3X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { if (!PixelsEqual(pixels,1,pixels,7,channels) && !PixelsEqual(pixels,3,pixels,5,channels)) { if (PixelsEqual(pixels,3,pixels,1,channels)) CopyPixels(pixels,3,result,0,channels); else CopyPixels(pixels,4,result,0,channels); if ( ( PixelsEqual(pixels,3,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,2,channels) ) || ( PixelsEqual(pixels,5,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,0,channels) ) ) CopyPixels(pixels,1,result,1,channels); else CopyPixels(pixels,4,result,1,channels); if (PixelsEqual(pixels,5,pixels,1,channels)) CopyPixels(pixels,5,result,2,channels); else CopyPixels(pixels,4,result,2,channels); if ( ( PixelsEqual(pixels,3,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,6,channels) ) || ( PixelsEqual(pixels,3,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,0,channels) ) ) CopyPixels(pixels,3,result,3,channels); else CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); if ( ( PixelsEqual(pixels,5,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,8,channels) ) || ( PixelsEqual(pixels,5,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,2,channels) ) ) CopyPixels(pixels,5,result,5,channels); else CopyPixels(pixels,4,result,5,channels); if (PixelsEqual(pixels,3,pixels,7,channels)) CopyPixels(pixels,3,result,6,channels); else CopyPixels(pixels,4,result,6,channels); if ( ( PixelsEqual(pixels,3,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,8,channels) ) || ( PixelsEqual(pixels,5,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,6,channels) ) ) CopyPixels(pixels,7,result,7,channels); else CopyPixels(pixels,4,result,7,channels); if (PixelsEqual(pixels,5,pixels,7,channels)) CopyPixels(pixels,5,result,8,channels); else CopyPixels(pixels,4,result,8,channels); } else { register ssize_t i; for (i=0; i < 9; i++) CopyPixels(pixels,4,result,i,channels); } } MagickExport Image *MagnifyImage(const Image *image,ExceptionInfo *exception) { #define MagnifyImageTag "Magnify/Image" CacheView *image_view, *magnify_view; const char *option; Image *source_image, *magnify_image; MagickBooleanType status; MagickOffsetType progress; OffsetInfo offset; RectangleInfo rectangle; ssize_t y; unsigned char magnification, width; void (*scaling_method)(const Image *,const Quantum *,Quantum *,size_t); /* Initialize magnified image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); option=GetImageOption(image->image_info,"magnify:method"); if (option == (char *) NULL) option="scale2x"; scaling_method=Scale2X; magnification=1; width=1; switch (*option) { case 'e': { if (LocaleCompare(option,"eagle2x") == 0) { scaling_method=Eagle2X; magnification=2; width=3; break; } if (LocaleCompare(option,"eagle3x") == 0) { scaling_method=Eagle3X; magnification=3; width=3; break; } if (LocaleCompare(option,"eagle3xb") == 0) { scaling_method=Eagle3XB; magnification=3; width=3; break; } if (LocaleCompare(option,"epbx2x") == 0) { scaling_method=Epbx2X; magnification=2; width=3; break; } break; } case 'f': { if (LocaleCompare(option,"fish2x") == 0) { scaling_method=Fish2X; magnification=2; width=3; break; } break; } case 'h': { if (LocaleCompare(option,"hq2x") == 0) { scaling_method=Hq2X; magnification=2; width=3; break; } break; } case 's': { if (LocaleCompare(option,"scale2x") == 0) { scaling_method=Scale2X; magnification=2; width=3; break; } if (LocaleCompare(option,"scale3x") == 0) { scaling_method=Scale3X; magnification=3; width=3; break; } break; } case 'x': { if (LocaleCompare(option,"xbr2x") == 0) { scaling_method=Xbr2X; magnification=2; width=5; } break; } default: break; } /* Make a working copy of the source image and convert it to RGB colorspace. */ source_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (source_image == (Image *) NULL) return((Image *) NULL); offset.x=0; offset.y=0; rectangle.x=0; rectangle.y=0; rectangle.width=image->columns; rectangle.height=image->rows; (void) CopyImagePixels(source_image,image,&rectangle,&offset,exception); (void) SetImageColorspace(source_image,RGBColorspace,exception); magnify_image=CloneImage(source_image,magnification*source_image->columns, magnification*source_image->rows,MagickTrue,exception); if (magnify_image == (Image *) NULL) { source_image=DestroyImage(source_image); return((Image *) NULL); } /* Magnify the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(source_image,exception); magnify_view=AcquireAuthenticCacheView(magnify_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,magnify_image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { Quantum r[128]; /* to hold result pixels */ register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(magnify_view,0,magnification*y, magnify_image->columns,magnification,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } /* Magnify this row of pixels. */ for (x=0; x < (ssize_t) source_image->columns; x++) { register const Quantum *magick_restrict p; size_t channels; register ssize_t i; ssize_t j; p=GetCacheViewVirtualPixels(image_view,x-width/2,y-width/2,width,width, exception); channels=GetPixelChannels(source_image); scaling_method(source_image,p,r,channels); /* Copy the result pixels into the final image. */ for (j=0; j < (ssize_t) magnification; j++) for (i=0; i < (ssize_t) (channels*magnification); i++) q[j*channels*magnify_image->columns+i]=r[j*magnification*channels+i]; q+=magnification*GetPixelChannels(magnify_image); } if (SyncCacheViewAuthenticPixels(magnify_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MagnifyImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } magnify_view=DestroyCacheView(magnify_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); if (status == MagickFalse) magnify_image=DestroyImage(magnify_image); return(magnify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M i n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MinifyImage() is a convenience method that scales an image proportionally to % half its size. % % The format of the MinifyImage method is: % % Image *MinifyImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MinifyImage(const Image *image,ExceptionInfo *exception) { Image *minify_image; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); minify_image=ResizeImage(image,image->columns/2,image->rows/2,SplineFilter, exception); return(minify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResampleImage() resize image in terms of its pixel size, so that when % displayed at the given resolution it will be the same size in terms of % real world units as the original image at the original resolution. % % The format of the ResampleImage method is: % % Image *ResampleImage(Image *image,const double x_resolution, % const double y_resolution,const FilterType filter, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to be resized to fit the given resolution. % % o x_resolution: the new image x resolution. % % o y_resolution: the new image y resolution. % % o filter: Image filter to use. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ResampleImage(const Image *image,const double x_resolution, const double y_resolution,const FilterType filter,ExceptionInfo *exception) { #define ResampleImageTag "Resample/Image" Image *resample_image; size_t height, width; /* Initialize sampled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=(size_t) (x_resolution*image->columns/(image->resolution.x == 0.0 ? 72.0 : image->resolution.x)+0.5); height=(size_t) (y_resolution*image->rows/(image->resolution.y == 0.0 ? 72.0 : image->resolution.y)+0.5); resample_image=ResizeImage(image,width,height,filter,exception); if (resample_image != (Image *) NULL) { resample_image->resolution.x=x_resolution; resample_image->resolution.y=y_resolution; } return(resample_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeImage() scales an image to the desired dimensions, using the given % filter (see AcquireFilterInfo()). % % If an undefined filter is given the filter defaults to Mitchell for a % colormapped image, a image with a matte channel, or if the image is % enlarged. Otherwise the filter defaults to a Lanczos. % % ResizeImage() was inspired by Paul Heckbert's "zoom" program. % % The format of the ResizeImage method is: % % Image *ResizeImage(Image *image,const size_t columns,const size_t rows, % const FilterType filter,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o filter: Image filter to use. % % o exception: return any errors or warnings in this structure. % */ typedef struct _ContributionInfo { double weight; ssize_t pixel; } ContributionInfo; static ContributionInfo **DestroyContributionThreadSet( ContributionInfo **contribution) { register ssize_t i; assert(contribution != (ContributionInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (contribution[i] != (ContributionInfo *) NULL) contribution[i]=(ContributionInfo *) RelinquishAlignedMemory( contribution[i]); contribution=(ContributionInfo **) RelinquishMagickMemory(contribution); return(contribution); } static ContributionInfo **AcquireContributionThreadSet(const size_t count) { register ssize_t i; ContributionInfo **contribution; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); contribution=(ContributionInfo **) AcquireQuantumMemory(number_threads, sizeof(*contribution)); if (contribution == (ContributionInfo **) NULL) return((ContributionInfo **) NULL); (void) memset(contribution,0,number_threads*sizeof(*contribution)); for (i=0; i < (ssize_t) number_threads; i++) { contribution[i]=(ContributionInfo *) MagickAssumeAligned( AcquireAlignedMemory(count,sizeof(**contribution))); if (contribution[i] == (ContributionInfo *) NULL) return(DestroyContributionThreadSet(contribution)); } return(contribution); } static MagickBooleanType HorizontalFilter( const ResizeFilter *magick_restrict resize_filter, const Image *magick_restrict image,Image *magick_restrict resize_image, const double x_factor,const MagickSizeType span, MagickOffsetType *magick_restrict progress,ExceptionInfo *exception) { #define ResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **magick_restrict contributions; MagickBooleanType status; double scale, support; ssize_t x; /* Apply filter to resize horizontally from image to resize image. */ scale=MagickMax(1.0/x_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class,exception) == MagickFalse) return(MagickFalse); if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(double) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=PerceptibleReciprocal(scale); image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->columns,1) #endif for (x=0; x < (ssize_t) resize_image->columns; x++) { const int id = GetOpenMPThreadId(); double bisect, density; register const Quantum *magick_restrict p; register ContributionInfo *magick_restrict contribution; register Quantum *magick_restrict q; register ssize_t y; ssize_t n, start, stop; if (status == MagickFalse) continue; bisect=(double) (x+0.5)/x_factor+MagickEpsilon; start=(ssize_t) MagickMax(bisect-support+0.5,0.0); stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->columns); density=0.0; contribution=contributions[id]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((double) (start+n)-bisect+0.5)); density+=contribution[n].weight; } if (n == 0) continue; if ((density != 0.0) && (density != 1.0)) { register ssize_t i; /* Normalize. */ density=PerceptibleReciprocal(density); for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,contribution[0].pixel,0,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1),image->rows,exception); q=QueueCacheViewAuthenticPixels(resize_view,x,0,1,resize_image->rows, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (y=0; y < (ssize_t) resize_image->rows; y++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait resize_traits, traits; register ssize_t j; ssize_t k; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; if (((resize_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(resize_image,q) <= (QuantumRange/2))) { j=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-1.0)+0.5); k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j-start].pixel-contribution[0].pixel); SetPixelChannel(resize_image,channel,p[k*GetPixelChannels(image)+i], q); continue; } pixel=0.0; if ((resize_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (j=0; j < n; j++) { k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j].pixel-contribution[0].pixel); alpha=contribution[j].weight; pixel+=alpha*p[k*GetPixelChannels(image)+i]; } SetPixelChannel(resize_image,channel,ClampToQuantum(pixel),q); continue; } /* Alpha blending. */ gamma=0.0; for (j=0; j < n; j++) { k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j].pixel-contribution[0].pixel); alpha=contribution[j].weight*QuantumScale* GetPixelAlpha(image,p+k*GetPixelChannels(image)); pixel+=alpha*p[k*GetPixelChannels(image)+i]; gamma+=alpha; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(resize_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif (*progress)++; proceed=SetImageProgress(image,ResizeImageTag,*progress,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } static MagickBooleanType VerticalFilter( const ResizeFilter *magick_restrict resize_filter, const Image *magick_restrict image,Image *magick_restrict resize_image, const double y_factor,const MagickSizeType span, MagickOffsetType *magick_restrict progress,ExceptionInfo *exception) { CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **magick_restrict contributions; double scale, support; MagickBooleanType status; ssize_t y; /* Apply filter to resize vertically from image to resize image. */ scale=MagickMax(1.0/y_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class,exception) == MagickFalse) return(MagickFalse); if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(double) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=PerceptibleReciprocal(scale); image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->rows,1) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { const int id = GetOpenMPThreadId(); double bisect, density; register const Quantum *magick_restrict p; register ContributionInfo *magick_restrict contribution; register Quantum *magick_restrict q; register ssize_t x; ssize_t n, start, stop; if (status == MagickFalse) continue; bisect=(double) (y+0.5)/y_factor+MagickEpsilon; start=(ssize_t) MagickMax(bisect-support+0.5,0.0); stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->rows); density=0.0; contribution=contributions[id]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((double) (start+n)-bisect+0.5)); density+=contribution[n].weight; } if (n == 0) continue; if ((density != 0.0) && (density != 1.0)) { register ssize_t i; /* Normalize. */ density=PerceptibleReciprocal(density); for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,0,contribution[0].pixel, image->columns,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1), exception); q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) resize_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait resize_traits, traits; register ssize_t j; ssize_t k; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; if (((resize_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(resize_image,q) <= (QuantumRange/2))) { j=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-1.0)+0.5); k=(ssize_t) ((contribution[j-start].pixel-contribution[0].pixel)* image->columns+x); SetPixelChannel(resize_image,channel,p[k*GetPixelChannels(image)+i], q); continue; } pixel=0.0; if ((resize_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (j=0; j < n; j++) { k=(ssize_t) ((contribution[j].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[j].weight; pixel+=alpha*p[k*GetPixelChannels(image)+i]; } SetPixelChannel(resize_image,channel,ClampToQuantum(pixel),q); continue; } gamma=0.0; for (j=0; j < n; j++) { k=(ssize_t) ((contribution[j].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[j].weight*QuantumScale*GetPixelAlpha(image,p+k* GetPixelChannels(image)); pixel+=alpha*p[k*GetPixelChannels(image)+i]; gamma+=alpha; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(resize_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif (*progress)++; proceed=SetImageProgress(image,ResizeImageTag,*progress,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } MagickExport Image *ResizeImage(const Image *image,const size_t columns, const size_t rows,const FilterType filter,ExceptionInfo *exception) { double x_factor, y_factor; FilterType filter_type; Image *filter_image, *resize_image; MagickOffsetType offset; MagickSizeType span; MagickStatusType status; ResizeFilter *resize_filter; /* Acquire resize image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows) && (filter == UndefinedFilter)) return(CloneImage(image,0,0,MagickTrue,exception)); /* Acquire resize filter. */ x_factor=(double) columns/(double) image->columns; y_factor=(double) rows/(double) image->rows; filter_type=LanczosFilter; if (filter != UndefinedFilter) filter_type=filter; else if ((x_factor == 1.0) && (y_factor == 1.0)) filter_type=PointFilter; else if ((image->storage_class == PseudoClass) || (image->alpha_trait != UndefinedPixelTrait) || ((x_factor*y_factor) > 1.0)) filter_type=MitchellFilter; resize_filter=AcquireResizeFilter(image,filter_type,MagickFalse,exception); #if defined(MAGICKCORE_OPENCL_SUPPORT) resize_image=AccelerateResizeImage(image,columns,rows,resize_filter, exception); if (resize_image != (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(resize_image); } #endif resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(resize_image); } if (x_factor > y_factor) filter_image=CloneImage(image,columns,image->rows,MagickTrue,exception); else filter_image=CloneImage(image,image->columns,rows,MagickTrue,exception); if (filter_image == (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(DestroyImage(resize_image)); } /* Resize image. */ offset=0; if (x_factor > y_factor) { span=(MagickSizeType) (filter_image->columns+rows); status=HorizontalFilter(resize_filter,image,filter_image,x_factor,span, &offset,exception); status&=VerticalFilter(resize_filter,filter_image,resize_image,y_factor, span,&offset,exception); } else { span=(MagickSizeType) (filter_image->rows+columns); status=VerticalFilter(resize_filter,image,filter_image,y_factor,span, &offset,exception); status&=HorizontalFilter(resize_filter,filter_image,resize_image,x_factor, span,&offset,exception); } /* Free resources. */ filter_image=DestroyImage(filter_image); resize_filter=DestroyResizeFilter(resize_filter); if (status == MagickFalse) { resize_image=DestroyImage(resize_image); return((Image *) NULL); } resize_image->type=image->type; return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SampleImage() scales an image to the desired dimensions with pixel % sampling. Unlike other scaling methods, this method does not introduce % any additional color into the scaled image. % % The format of the SampleImage method is: % % Image *SampleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the sampled image. % % o rows: the number of rows in the sampled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SampleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleImageTag "Sample/Image" CacheView *image_view, *sample_view; Image *sample_image; MagickBooleanType status; MagickOffsetType progress; register ssize_t x1; ssize_t *x_offset, y; PointInfo sample_offset; /* Initialize sampled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); sample_image=CloneImage(image,columns,rows,MagickTrue,exception); if (sample_image == (Image *) NULL) return((Image *) NULL); /* Set the sampling offset, default is in the mid-point of sample regions. */ sample_offset.x=sample_offset.y=0.5-MagickEpsilon; { const char *value; value=GetImageArtifact(image,"sample:offset"); if (value != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; (void) ParseGeometry(value,&geometry_info); flags=ParseGeometry(value,&geometry_info); sample_offset.x=sample_offset.y=geometry_info.rho/100.0-MagickEpsilon; if ((flags & SigmaValue) != 0) sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon; } } /* Allocate scan line buffer and column offset buffers. */ x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns, sizeof(*x_offset)); if (x_offset == (ssize_t *) NULL) { sample_image=DestroyImage(sample_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (x1=0; x1 < (ssize_t) sample_image->columns; x1++) x_offset[x1]=(ssize_t) ((((double) x1+sample_offset.x)*image->columns)/ sample_image->columns); /* Sample each row. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sample_view=AcquireAuthenticCacheView(sample_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,sample_image,sample_image->rows,1) #endif for (y=0; y < (ssize_t) sample_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; ssize_t y_offset; if (status == MagickFalse) continue; y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/ sample_image->rows); p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1, exception); q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } /* Sample each column. */ for (x=0; x < (ssize_t) sample_image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(sample_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(sample_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(sample_image); i++) { PixelChannel channel; PixelTrait image_traits, traits; channel=GetPixelChannelChannel(sample_image,i); traits=GetPixelChannelTraits(sample_image,channel); image_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (image_traits == UndefinedPixelTrait)) continue; SetPixelChannel(sample_image,channel,p[x_offset[x]*GetPixelChannels( image)+i],q); } q+=GetPixelChannels(sample_image); } if (SyncCacheViewAuthenticPixels(sample_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SampleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); sample_view=DestroyCacheView(sample_view); x_offset=(ssize_t *) RelinquishMagickMemory(x_offset); sample_image->type=image->type; if (status == MagickFalse) sample_image=DestroyImage(sample_image); return(sample_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleImage() changes the size of an image to the given dimensions. % % The format of the ScaleImage method is: % % Image *ScaleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ScaleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define ScaleImageTag "Scale/Image" CacheView *image_view, *scale_view; double alpha, pixel[CompositePixelChannel], *scale_scanline, *scanline, *x_vector, *y_vector; Image *scale_image; MagickBooleanType next_column, next_row, proceed, status; PixelTrait scale_traits; PointInfo scale, span; register ssize_t i; ssize_t n, number_rows, y; /* Initialize scaled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); scale_image=CloneImage(image,columns,rows,MagickTrue,exception); if (scale_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(scale_image,DirectClass,exception) == MagickFalse) { scale_image=DestroyImage(scale_image); return((Image *) NULL); } /* Allocate memory. */ x_vector=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*x_vector)); scanline=x_vector; if (image->rows != scale_image->rows) scanline=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*scanline)); scale_scanline=(double *) AcquireQuantumMemory((size_t) scale_image->columns, MaxPixelChannels*sizeof(*scale_scanline)); y_vector=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*y_vector)); if ((scanline == (double *) NULL) || (scale_scanline == (double *) NULL) || (x_vector == (double *) NULL) || (y_vector == (double *) NULL)) { if ((image->rows != scale_image->rows) && (scanline != (double *) NULL)) scanline=(double *) RelinquishMagickMemory(scanline); if (scale_scanline != (double *) NULL) scale_scanline=(double *) RelinquishMagickMemory(scale_scanline); if (x_vector != (double *) NULL) x_vector=(double *) RelinquishMagickMemory(x_vector); if (y_vector != (double *) NULL) y_vector=(double *) RelinquishMagickMemory(y_vector); scale_image=DestroyImage(scale_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Scale image. */ number_rows=0; next_row=MagickTrue; span.y=1.0; scale.y=(double) scale_image->rows/(double) image->rows; (void) memset(y_vector,0,(size_t) MaxPixelChannels*image->columns* sizeof(*y_vector)); n=0; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); scale_view=AcquireAuthenticCacheView(scale_image,exception); for (y=0; y < (ssize_t) scale_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) break; q=QueueCacheViewAuthenticPixels(scale_view,0,y,scale_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } alpha=1.0; if (scale_image->rows == image->rows) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } } else { /* Scale Y direction. */ while (scale.y < span.y) { if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } number_rows++; } for (x=0; x < (ssize_t) image->columns; x++) for (i=0; i < (ssize_t) GetPixelChannels(image); i++) y_vector[x*GetPixelChannels(image)+i]+=scale.y* x_vector[x*GetPixelChannels(image)+i]; span.y-=scale.y; scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } number_rows++; next_row=MagickFalse; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { pixel[i]=y_vector[x*GetPixelChannels(image)+i]+span.y* x_vector[x*GetPixelChannels(image)+i]; scanline[x*GetPixelChannels(image)+i]=pixel[i]; y_vector[x*GetPixelChannels(image)+i]=0.0; } } scale.y-=span.y; if (scale.y <= 0) { scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } span.y=1.0; } if (scale_image->columns == image->columns) { /* Transfer scanline to scaled image. */ for (x=0; x < (ssize_t) scale_image->columns; x++) { if (GetPixelWriteMask(scale_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(scale_image); continue; } if (image->alpha_trait != UndefinedPixelTrait) { alpha=QuantumScale*scanline[x*GetPixelChannels(image)+ GetPixelChannelOffset(image,AlphaPixelChannel)]; alpha=PerceptibleReciprocal(alpha); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); scale_traits=GetPixelChannelTraits(scale_image,channel); if ((traits == UndefinedPixelTrait) || (scale_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) { SetPixelChannel(scale_image,channel,ClampToQuantum( scanline[x*GetPixelChannels(image)+i]),q); continue; } SetPixelChannel(scale_image,channel,ClampToQuantum(alpha*scanline[ x*GetPixelChannels(image)+i]),q); } q+=GetPixelChannels(scale_image); } } else { ssize_t t; /* Scale X direction. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; next_column=MagickFalse; span.x=1.0; t=0; for (x=0; x < (ssize_t) image->columns; x++) { scale.x=(double) scale_image->columns/(double) image->columns; while (scale.x >= span.x) { if (next_column != MagickFalse) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; t++; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; pixel[i]+=span.x*scanline[x*GetPixelChannels(image)+i]; scale_scanline[t*GetPixelChannels(image)+i]=pixel[i]; } scale.x-=span.x; span.x=1.0; next_column=MagickTrue; } if (scale.x > 0) { if (next_column != MagickFalse) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; next_column=MagickFalse; t++; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]+=scale.x*scanline[x*GetPixelChannels(image)+i]; span.x-=scale.x; } } if (span.x > 0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]+=span.x*scanline[(x-1)*GetPixelChannels(image)+i]; } if ((next_column == MagickFalse) && (t < (ssize_t) scale_image->columns)) for (i=0; i < (ssize_t) GetPixelChannels(image); i++) scale_scanline[t*GetPixelChannels(image)+i]=pixel[i]; /* Transfer scanline to scaled image. */ for (x=0; x < (ssize_t) scale_image->columns; x++) { if (GetPixelWriteMask(scale_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(scale_image); continue; } if (image->alpha_trait != UndefinedPixelTrait) { alpha=QuantumScale*scale_scanline[x*GetPixelChannels(image)+ GetPixelChannelOffset(image,AlphaPixelChannel)]; alpha=PerceptibleReciprocal(alpha); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); scale_traits=GetPixelChannelTraits(scale_image,channel); if ((traits == UndefinedPixelTrait) || (scale_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) { SetPixelChannel(scale_image,channel,ClampToQuantum( scale_scanline[x*GetPixelChannels(image)+i]),q); continue; } SetPixelChannel(scale_image,channel,ClampToQuantum(alpha* scale_scanline[x*GetPixelChannels(image)+i]),q); } q+=GetPixelChannels(scale_image); } } if (SyncCacheViewAuthenticPixels(scale_view,exception) == MagickFalse) { status=MagickFalse; break; } proceed=SetImageProgress(image,ScaleImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) { status=MagickFalse; break; } } scale_view=DestroyCacheView(scale_view); image_view=DestroyCacheView(image_view); /* Free allocated memory. */ y_vector=(double *) RelinquishMagickMemory(y_vector); scale_scanline=(double *) RelinquishMagickMemory(scale_scanline); if (scale_image->rows != image->rows) scanline=(double *) RelinquishMagickMemory(scanline); x_vector=(double *) RelinquishMagickMemory(x_vector); scale_image->type=image->type; if (status == MagickFalse) scale_image=DestroyImage(scale_image); return(scale_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h u m b n a i l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThumbnailImage() changes the size of an image to the given dimensions and % removes any associated profiles. The goal is to produce small low cost % thumbnail images suited for display on the Web. % % The format of the ThumbnailImage method is: % % Image *ThumbnailImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ThumbnailImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleFactor 5 char filename[MagickPathExtent], value[MagickPathExtent]; const char *name; Image *thumbnail_image; double x_factor, y_factor; struct stat attributes; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); x_factor=(double) columns/(double) image->columns; y_factor=(double) rows/(double) image->rows; if ((x_factor*y_factor) > 0.1) thumbnail_image=ResizeImage(image,columns,rows,image->filter,exception); else if (((SampleFactor*columns) < 128) || ((SampleFactor*rows) < 128)) thumbnail_image=ResizeImage(image,columns,rows,image->filter,exception); else { Image *sample_image; sample_image=SampleImage(image,SampleFactor*columns,SampleFactor*rows, exception); if (sample_image == (Image *) NULL) return((Image *) NULL); thumbnail_image=ResizeImage(sample_image,columns,rows,image->filter, exception); sample_image=DestroyImage(sample_image); } if (thumbnail_image == (Image *) NULL) return(thumbnail_image); (void) ParseAbsoluteGeometry("0x0+0+0",&thumbnail_image->page); if (thumbnail_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(thumbnail_image,OpaqueAlphaChannel,exception); thumbnail_image->depth=8; thumbnail_image->interlace=NoInterlace; /* Strip all profiles except color profiles. */ ResetImageProfileIterator(thumbnail_image); for (name=GetNextImageProfile(thumbnail_image); name != (const char *) NULL; ) { if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) { (void) DeleteImageProfile(thumbnail_image,name); ResetImageProfileIterator(thumbnail_image); } name=GetNextImageProfile(thumbnail_image); } (void) DeleteImageProperty(thumbnail_image,"comment"); (void) CopyMagickString(value,image->magick_filename,MagickPathExtent); if (strstr(image->magick_filename,"//") == (char *) NULL) (void) FormatLocaleString(value,MagickPathExtent,"file://%s", image->magick_filename); (void) SetImageProperty(thumbnail_image,"Thumb::URI",value,exception); GetPathComponent(image->magick_filename,TailPath,filename); (void) CopyMagickString(value,filename,MagickPathExtent); if ( GetPathAttributes(image->filename,&attributes) != MagickFalse ) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) attributes.st_mtime); (void) SetImageProperty(thumbnail_image,"Thumb::MTime",value,exception); } (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) attributes.st_mtime); (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B",MagickPathExtent, value); (void) SetImageProperty(thumbnail_image,"Thumb::Size",value,exception); (void) FormatLocaleString(value,MagickPathExtent,"image/%s",image->magick); LocaleLower(value); (void) SetImageProperty(thumbnail_image,"Thumb::Mimetype",value,exception); (void) SetImageProperty(thumbnail_image,"software",MagickAuthoritativeURL, exception); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->magick_columns); (void) SetImageProperty(thumbnail_image,"Thumb::Image::Width",value, exception); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->magick_rows); (void) SetImageProperty(thumbnail_image,"Thumb::Image::Height",value, exception); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageListLength(image)); (void) SetImageProperty(thumbnail_image,"Thumb::Document::Pages",value, exception); return(thumbnail_image); }
dbj_omp.c
#include <assert.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> // for testing make it 0 #define DBJ_BENCHMARKING 1 // when on godbolt make it 1 // godbolt times out for even small sizes // is is used just to confirm code compiles with no warnings #define DBJ_ON_GODBOLT 0 #ifdef _MSC_VER #pragma region common trash #endif #define FOR(C, R) for (unsigned C = 0; C < R; ++C) #if (defined(__clang__) || defined(__GNUC__)) #define DBJ_CLANGNUC 1 #else #define DBJ_CLANGNUC 0 #endif #if !DBJ_ON_GODBOLT #include "build_time_stamp.inc" // DBJ_BUILD_TIMESTAMP #if DBJ_BENCHMARKING #include "ubench/ubench.h" #else #include "utest/utest.h" #endif // ! DBJ_BENCHMARKING #else // on godbolt #if DBJ_BENCHMARKING #include "https://raw.githubusercontent.com/sheredom/ubench.h/master/ubench.h" #else #include "https://raw.githubusercontent.com/sheredom/utest.h/master/utest.h" #endif // ! DBJ_BENCHMARKING #define DBJ_BUILD_TIMESTAMP __DATE__ " " __TIME__ #endif // DBJ_ON_GODBOLT #define DBJ_VT_RESET "\033[0m" #define DBJ_VT_GREEN "\033[32m" #define DBJ_VT_RED "\033[31m" // currently ctor/dtor feature is not used #if DBJ_CLANGNUC #define DBJ_CTOR __attribute__((constructor)) #define DBJ_DTOR __attribute__((destructor)) #else #define DBJ_CTOR #define DBJ_DTOR #endif #ifdef _MSC_VER #pragma endregion // common trash #endif /* too much for WIN10 8GB RAM #define DATA_SIZE 0xFFFFFFFF */ #define DATA_SIZE 0xFFFFFFF #define N_THREADS 2 #define range DATA_SIZE / N_THREADS static struct { double *X; // [DATA_SIZE]; double *Y; // [DATA_SIZE]; } *app_data = 0; static void app_start(int argc, const char *const argv[]) { app_data = calloc(1, sizeof(*app_data)); assert(app_data); app_data->X = calloc(DATA_SIZE, sizeof(double)); assert(app_data->X); app_data->Y = calloc(DATA_SIZE, sizeof(double)); assert(app_data->Y); FOR(i, DATA_SIZE) { app_data->X[i] = 1.0; app_data->Y[i] = 2.0; } printf("\nStarting %s", argv[0]); printf("\nMeasuring: double[%d] /= double[%d]\n\n", DATA_SIZE, DATA_SIZE); } static void app_end(void) { free(app_data->X); free(app_data->Y); free(app_data); } #ifdef _MSC_VER #pragma range benches #endif UBENCH(omp_measuring, adding_two_arrays_of_doubles) { #pragma omp parallel for num_threads(N_THREADS) FOR(i, DATA_SIZE) { app_data->X[i] /= app_data->Y[i]; } } UBENCH(NOT_omp_measuring, adding_two_arrays_of_doubles) { FOR(i, DATA_SIZE) { app_data->X[i] /= app_data->Y[i]; } } #ifdef _MSC_VER #pragma endrange // benches #endif UBENCH_STATE(); int main(int argc, const char *const argv[]) { app_start(argc, argv); return ubench_main(argc, argv); app_end(); }
parallel_queue_first_n_push.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <omp.h> #define MAX 20 int intArray[MAX]; int front = 0; int rear = -1; int itemCount = 0; bool isEmpty() { return itemCount == 0; } bool isFull() { return itemCount == MAX; } int size() { return itemCount; } void insert(int data) { if(!isFull()) { if(rear == MAX-1) { rear = -1; } intArray[++rear] = data; itemCount++; } } int removeData() { int data = intArray[front++]; if(front == MAX) { front = 0; } itemCount--; return data; } int main(){ int id, num = 1; int n; printf("Enter value of N = "); scanf("%d",&n); omp_set_dynamic(0); #pragma omp parallel num_threads(2) { id = omp_get_thread_num(); if(id == 0){ while(1){ #pragma omp critical { if(num <= n){ insert(num); printf("Inserted %d to Queue", num); num++; } else { printf("Already entered first %d natural numbers", n); } // for infinite insertion // if(!isFull()){ // insert(num); // printf("Inserted %d to Queue", num); // num++; // } else { // printf("Queue Full"); // } fgetc(stdin); } } } else { while(1){ #pragma omp critical { if(!isEmpty()){ printf("Deleted item = %d\n", removeData()); } else { printf("Queue is empty"); num = 1; } fgetc(stdin); } } } } return 0; }
target_implicit_partial_map.c
// RUN: %libomptarget-compile-generic // RUN: %libomptarget-run-generic 2>&1 \ // RUN: | %fcheck-generic // END. #include <omp.h> #include <stdio.h> int main() { int arr[100]; #pragma omp target data map(alloc: arr[50:2]) // partially mapped { #pragma omp target // would implicitly map with full size but already present { arr[50] = 5; arr[51] = 6; } // must treat as present (dec ref count) even though full size not present } // wouldn't delete if previous ref count dec didn't happen // CHECK: still present: 0 fprintf(stderr, "still present: %d\n", omp_target_is_present(&arr[50], omp_get_default_device())); return 0; }
producer-consumer.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <omp.h> #define MAX 10 int arr[MAX]; int front = 0; int rear = -1; int itemCount = 0; int peek() { return arr[front]; } bool isEmpty() { return itemCount == 0; } bool isFull() { return itemCount == MAX; } int size() { return itemCount; } void insert(int data) { if(!isFull()) { if(rear == MAX-1) { rear = -1; } arr[++rear] = data; itemCount++; } } int removeData() { int data = arr[front++]; if(front == MAX) { front = 0; } itemCount--; return data; } void produce(int el){ // #pragma omp critical // { insert(el); printf("Produced %d\n", el); // } } void consume(){ // #pragma omp critical // { int n = removeData(); printf("Consumed %d\n", n); // } } int main() { int id, el = 1; printf("Element at front: %d\n", peek()); #pragma omp parallel num_threads(2) { id = omp_get_thread_num(); if(id == 0){ while(1){ #pragma omp critical { if(!isFull()){ produce(el); el++; } else { printf("Quese full. Cannot produce."); } fgetc(stdin); } } } else { while(1){ #pragma omp critical { if(!isEmpty()){ consume(); } else { printf("Quese Empty. Cannot consume."); } fgetc(stdin); } } } } printf("Element at front: %d\n", peek()); return 0; }
eval.h
#pragma once #include<string> using std::string; #include"files.h" #include<fstream> using std::fstream; using std::ios; #include<unordered_map> using std::unordered_map; using std::pair; #include<cmath> #include<vector> using std::vector; #include<algorithm> using std::sort; #include<limits> using std::numeric_limits; #include<functional> using std::function; const vector<string> SCORE_NAMES = { "TopicNetCCoef", "TopicWalkBtwn", "TopicCorr", "BestTopicPerWord", "BestCentrL2", "L2" }; class Eval{ public: Eval(const string& path, bool isPos):isPositive(isPos){ if(!isFile(path)) throw runtime_error("Not a file: " + path); fstream fin(path, ios::in); string line, metricName; float score; while(getline(fin, line)){ stringstream ss(line); ss >> metricName >> score; scores[metricName] = score; } fin.close(); } vector<float> toVec(const vector<string>& scoreNames) const{ vector<float> res(scoreNames.size(), 0.0f); for(size_t i = 0; i < scoreNames.size(); ++i){ res[i] = getScore(scoreNames[i]); } return res; } float getScore(const string& name) const { if(scores.find(name) != scores.end()){ return scores.at(name); } throw runtime_error("Failed to find score:" + name); } void scale(const unordered_map<string, pair<float, float>>& ranges){ for(const auto p: ranges){ const string& name = p.first; float minScore = p.second.first; float scoreRange = p.second.second; if(scoreRange == 0){ throw runtime_error("Cannot divide by zero. Don't put it in the scale map."); } if(scores.find(name) != scores.end()){ scores[name] = (scores[name] - minScore) / scoreRange; } else { throw runtime_error("Failed to find score:" + name); } } } float polyMulti(const unordered_map<string, pair<float, float>> name2CoefPow) const { float res = 0; for(const auto p: name2CoefPow){ const string& name = p.first; pair<float, float> coefPow = p.second; if(scores.find(name) != scores.end()){ res += coefPow.first * pow(scores.at(name), coefPow.second); } else { throw runtime_error("Failed to find score:" + name); } } return res; } bool getLabel() const { return isPositive; } private: // want alphabetical order unordered_map<string, float> scores; bool isPositive; }; //precondition: sorted in x float getAUC(const vector<pair<float, float>>& xyPts){ float area = 0; #pragma omp parallel { float localArea = 0; #pragma omp for for(size_t i = 1; i < xyPts.size(); ++i){ // trapezoids const pair<float, float> & a = xyPts[i-1]; const pair<float, float> & b = xyPts[i]; float w = b.first - a.first; float h = (b.second + a.second) / 2; localArea += w * h; } #pragma omp critical area += localArea; } return area; } float calcROC(const vector<Eval>& evals, const function<float(const Eval&)>& eval2score, vector<pair<float, float>>* rocRet = nullptr){ // start by making a helper array vector<pair<float, bool>> score2label(evals.size()); #pragma omp parallel for for(size_t i = 0; i < evals.size(); ++i){ const auto& e = evals[i]; score2label[i] = {eval2score(e), e.getLabel()}; } // sort in reverse order by first, true breaks ties static auto cmp = [](const pair<float, bool>& a, const pair<float, bool>& b) -> bool { if(a.first == b.first){ if(a.second == b.second) return false; return b.second; } return a.first > b.first; }; sort(score2label.begin(), score2label.end(), cmp); float conPos = 0, conNeg = 0; #pragma omp parallel { float localTP = 0, localTN = 0; #pragma omp for for(size_t i = 0; i < score2label.size(); ++i){ if(score2label[i].second){ ++localTP; }else{ ++localTN; } } #pragma omp critical { conPos += localTP; conNeg += localTN; } } //TODO: someday I might parallelize this, but I'm lazy vector<pair<float, float>> fracts; fracts.reserve(score2label.size()); float tp = 0, fp = 0, lastScore = -numeric_limits<float>::infinity(); for(const auto& p : score2label){ float score = p.first; bool lbl = p.second; if(score != lastScore){ fracts.emplace_back(tp/conPos, fp/conNeg); lastScore = score; } if(lbl){ ++tp; } else { ++fp; } } // adds (1, 1) fracts.emplace_back(tp/conPos, fp/conNeg); // optional return value if(rocRet){ *rocRet = fracts; } return getAUC(fracts); }