source
stringlengths
3
92
c
stringlengths
26
2.25M
rawSHA384_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 2010 by Solar Designer * based on rawMD4_fmt.c code, with trivial changes by groszek. * * Rewritten Spring 2013, JimF. SSE code added and released with the following terms: * No copyright is claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the public * domain is deemed null and void, then the software is Copyright (c) 2011 JimF * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_rawSHA384; #elif FMT_REGISTERS_H john_register_one(&fmt_rawSHA384); #else #include <stdint.h> #include "arch.h" #include "sha2.h" #include "params.h" #include "common.h" #include "johnswap.h" #include "formats.h" //#undef SIMD_COEF_64 //#undef SIMD_PARA_SHA512 /* * Only effective for SIMD. * Undef to disable reversing steps for benchmarking. */ #define REVERSE_STEPS #ifdef _OPENMP #ifdef SIMD_COEF_64 #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 #endif #endif #include <omp.h> #endif #include "simd-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "Raw-SHA384" #define FORMAT_NAME "" #define FORMAT_TAG "$SHA384$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #ifdef SIMD_COEF_64 #define ALGORITHM_NAME SHA512_ALGORITHM_NAME #else #define ALGORITHM_NAME "32/" ARCH_BITS_STR " " SHA2_LIB #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #ifdef SIMD_COEF_64 #define PLAINTEXT_LENGTH 111 #else #define PLAINTEXT_LENGTH 125 #endif #define CIPHERTEXT_LENGTH 96 #define BINARY_SIZE DIGEST_SIZE #define DIGEST_SIZE 48 #define DIGEST_SIZE_512 64 #define BINARY_ALIGN 8 #define SALT_SIZE 0 #define SALT_ALIGN 1 #ifdef SIMD_COEF_64 #define MIN_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests tests[] = { {"a8b64babd0aca91a59bdbb7761b421d4f2bb38280d3a75ba0f21f2bebc45583d446c598660c94ce680c47d19c30783a7", "password"}, {"$SHA384$a8b64babd0aca91a59bdbb7761b421d4f2bb38280d3a75ba0f21f2bebc45583d446c598660c94ce680c47d19c30783a7", "password"}, {"$SHA384$8cafed2235386cc5855e75f0d34f103ccc183912e5f02446b77c66539f776e4bf2bf87339b4518a7cb1c2441c568b0f8", "12345678"}, {"$SHA384$38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b", ""}, {"94e75dd8e1f16d7df761d76c021ad98c283791008b98368e891f411fc5aa1a83ef289e348abdecf5e1ba6971604a0cb0", "UPPERCASE"}, {NULL} }; #ifdef SIMD_COEF_64 #define GETPOS(i, index) ( (index&(SIMD_COEF_64-1))*8 + ((i)&(0xffffffff-7))*SIMD_COEF_64 + (7-((i)&7)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64*8 ) static uint64_t (*saved_key); static uint64_t (*crypt_out); #else static int (*saved_len); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint64_t (*crypt_out)[DIGEST_SIZE / sizeof(uint64_t)]; #endif static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif #ifndef SIMD_COEF_64 saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); #else saved_key = mem_calloc_align(self->params.max_keys_per_crypt * SHA_BUF_SIZ, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_out = mem_calloc_align(self->params.max_keys_per_crypt * DIGEST_SIZE_512 / sizeof(uint64_t), sizeof(*crypt_out), MEM_ALIGN_SIMD); #endif } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); #ifndef SIMD_COEF_64 MEM_FREE(saved_len); #endif } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += TAG_LENGTH; q = p; while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q && q - p == CIPHERTEXT_LENGTH; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[TAG_LENGTH + CIPHERTEXT_LENGTH + 1]; if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) ciphertext += TAG_LENGTH; memcpy(out, FORMAT_TAG, TAG_LENGTH); memcpy(out + TAG_LENGTH, ciphertext, CIPHERTEXT_LENGTH + 1); strlwr(out + TAG_LENGTH); return out; } void *get_binary(char *ciphertext) { static uint64_t *outw; unsigned char *out; char *p; int i; if (!outw) outw = mem_calloc_tiny(DIGEST_SIZE, BINARY_ALIGN); out = (unsigned char*)outw; p = ciphertext + TAG_LENGTH; for (i = 0; i < DIGEST_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #ifdef SIMD_COEF_64 alter_endianity_to_BE64(out, DIGEST_SIZE/8); #ifdef REVERSE_STEPS sha384_reverse(outw); #endif #endif return out; } #ifdef SIMD_COEF_64 #define HASH_IDX (((unsigned int)index&(SIMD_COEF_64-1))+(unsigned int)index/SIMD_COEF_64*8*SIMD_COEF_64 + 3*SIMD_COEF_64) static int get_hash_0 (int index) { return crypt_out[HASH_IDX] & PH_MASK_0; } static int get_hash_1 (int index) { return crypt_out[HASH_IDX] & PH_MASK_1; } static int get_hash_2 (int index) { return crypt_out[HASH_IDX] & PH_MASK_2; } static int get_hash_3 (int index) { return crypt_out[HASH_IDX] & PH_MASK_3; } static int get_hash_4 (int index) { return crypt_out[HASH_IDX] & PH_MASK_4; } static int get_hash_5 (int index) { return crypt_out[HASH_IDX] & PH_MASK_5; } static int get_hash_6 (int index) { return crypt_out[HASH_IDX] & PH_MASK_6; } #else static int get_hash_0(int index) { return crypt_out[index][3] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][3] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][3] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][3] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][3] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][3] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][3] & PH_MASK_6; } #endif static int binary_hash_0(void *binary) { return ((uint64_t*)binary)[3] & PH_MASK_0; } static int binary_hash_1(void *binary) { return ((uint64_t*)binary)[3] & PH_MASK_1; } static int binary_hash_2(void *binary) { return ((uint64_t*)binary)[3] & PH_MASK_2; } static int binary_hash_3(void *binary) { return ((uint64_t*)binary)[3] & PH_MASK_3; } static int binary_hash_4(void *binary) { return ((uint64_t*)binary)[3] & PH_MASK_4; } static int binary_hash_5(void *binary) { return ((uint64_t*)binary)[3] & PH_MASK_5; } static int binary_hash_6(void *binary) { return ((uint64_t*)binary)[3] & PH_MASK_6; } static void set_key(char *key, int index) { #ifdef SIMD_COEF_64 #if ARCH_ALLOWS_UNALIGNED const uint64_t *wkey = (uint64_t*)key; #else char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint64_t)); const uint64_t *wkey = is_aligned(key, sizeof(uint64_t)) ? (uint64_t*)key : (uint64_t*)strcpy(buf_aligned, key); #endif uint64_t *keybuffer = &((uint64_t*)saved_key)[(index&(SIMD_COEF_64-1)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64]; uint64_t *keybuf_word = keybuffer; unsigned int len; uint64_t temp; len = 0; while((unsigned char)(temp = *wkey++)) { if (!(temp & 0xff00)) { *keybuf_word = JOHNSWAP64((temp & 0xff) | (0x80 << 8)); len++; goto key_cleaning; } if (!(temp & 0xff0000)) { *keybuf_word = JOHNSWAP64((temp & 0xffff) | (0x80 << 16)); len+=2; goto key_cleaning; } if (!(temp & 0xff000000)) { *keybuf_word = JOHNSWAP64((temp & 0xffffff) | (0x80ULL << 24)); len+=3; goto key_cleaning; } if (!(temp & 0xff00000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffff) | (0x80ULL << 32)); len+=4; goto key_cleaning; } if (!(temp & 0xff0000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffULL) | (0x80ULL << 40)); len+=5; goto key_cleaning; } if (!(temp & 0xff000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffULL) | (0x80ULL << 48)); len+=6; goto key_cleaning; } if (!(temp & 0xff00000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffffULL) | (0x80ULL << 56)); len+=7; goto key_cleaning; } *keybuf_word = JOHNSWAP64(temp); len += 8; keybuf_word += SIMD_COEF_64; } *keybuf_word = 0x8000000000000000ULL; key_cleaning: keybuf_word += SIMD_COEF_64; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_64; } keybuffer[15*SIMD_COEF_64] = len << 3; #else int len = strlen(key); saved_len[index] = len; if (len > PLAINTEXT_LENGTH) len = saved_len[index] = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, len); #endif } static char *get_key(int index) { #ifdef SIMD_COEF_64 unsigned i; uint64_t s; static char out[PLAINTEXT_LENGTH + 1]; unsigned char *wucp = (unsigned char*)saved_key; s = ((uint64_t*)saved_key)[15*SIMD_COEF_64 + (index&(SIMD_COEF_64-1)) + index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64] >> 3; for (i = 0; i < (unsigned)s; i++) out[i] = wucp[ GETPOS(i, index) ]; out[i] = 0; return (char*) out; #else saved_key[index][saved_len[index]] = 0; return saved_key[index]; #endif } #ifndef REVERSE_STEPS #undef SSEi_REVERSE_STEPS #define SSEi_REVERSE_STEPS 0 #endif static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { #ifdef SIMD_COEF_64 SIMDSHA512body(&saved_key[index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64], &crypt_out[index/SIMD_COEF_64*8*SIMD_COEF_64], NULL, SSEi_REVERSE_STEPS|SSEi_MIXED_IN|SSEi_CRYPT_SHA384); #else SHA512_CTX ctx; SHA384_Init(&ctx); SHA384_Update(&ctx, saved_key[index], saved_len[index]); SHA384_Final((unsigned char *)crypt_out[index], &ctx); #endif } return count; } static int cmp_all(void *binary, int count) { unsigned int index; for (index = 0; index < count; index++) #ifdef SIMD_COEF_64 if (((uint64_t*)binary)[3] == crypt_out[HASH_IDX]) #else if ( ((uint64_t*)binary)[0] == crypt_out[index][0] ) #endif return 1; return 0; } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_64 return ((uint64_t*)binary)[3] == crypt_out[HASH_IDX]; #else return *(uint64_t*)binary == crypt_out[index][0]; #endif } static int cmp_exact(char *source, int index) { uint64_t *binary = get_binary(source); char *key = get_key(index); SHA512_CTX ctx; uint64_t crypt_out[DIGEST_SIZE / sizeof(uint64_t)]; SHA384_Init(&ctx); SHA384_Update(&ctx, key, strlen(key)); SHA384_Final((unsigned char*)crypt_out, &ctx); #ifdef SIMD_COEF_64 alter_endianity_to_BE64(crypt_out, DIGEST_SIZE/8); #ifdef REVERSE_STEPS sha384_reverse(crypt_out); #endif #endif return !memcmp(binary, crypt_out, DIGEST_SIZE); } struct fmt_main fmt_rawSHA384 = { { FORMAT_LABEL, FORMAT_NAME, "SHA384 " ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD | FMT_SPLIT_UNIFIES_CASE, { NULL }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, fmt_default_salt, { NULL }, fmt_default_source, { binary_hash_0, binary_hash_1, binary_hash_2, binary_hash_3, binary_hash_4, binary_hash_5, binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
convolution_pack8to1_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convolution_pack8to1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_int8, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { int* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { int sum = 0; const signed char* kptr = weight_data_int8.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const signed char* sptr = m.row<const signed char>(i * stride_h) + j * stride_w * 8; for (int k = 0; k < maxk; k++) { // TODO use _mm_cvtepi8_epi16 on sse4.1 __m128i _val = _mm_loadl_epi64((const __m128i*)(sptr + space_ofs[k] * 8)); _val = _mm_unpacklo_epi8(_val, _mm_cmpgt_epi8(_mm_setzero_si128(), _val)); __m128i _w = _mm_loadl_epi64((const __m128i*)kptr); _w = _mm_unpacklo_epi8(_w, _mm_cmpgt_epi8(_mm_setzero_si128(), _w)); __m128i _sl = _mm_mullo_epi16(_val, _w); __m128i _sh = _mm_mulhi_epi16(_val, _w); __m128i _s0 = _mm_unpacklo_epi16(_sl, _sh); __m128i _s1 = _mm_unpackhi_epi16(_sl, _sh); __m128i _s4 = _mm_add_epi32(_s0, _s1); // TODO use _mm_hadd_epi32 on ssse3 int s4[4]; _mm_storeu_si128((__m128i*)s4, _s4); sum += s4[0] + s4[1] + s4[2] + s4[3]; // dot kptr += 8; } } outptr[j] = sum; } outptr += outw; } } }
cpu_utils.h
/* * Copyright (c) Intel Corporation. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <omp.h> #include <cstdint> #include <utility> template <typename T> using Radix_Sort_Pair = std::pair<T, T>; // histogram size per thread const int RDX_HIST_SIZE = 256; template <typename T> Radix_Sort_Pair<T>* radix_sort_parallel( Radix_Sort_Pair<T>* inp_buf, Radix_Sort_Pair<T>* tmp_buf, int64_t elements_count, int64_t max_value) { int maxthreads = omp_get_max_threads(); alignas(64) int histogram[RDX_HIST_SIZE * maxthreads], histogram_ps[RDX_HIST_SIZE * maxthreads + 1]; if (max_value == 0) return inp_buf; int num_bits = sizeof(T) * 8 - __builtin_clz(max_value); unsigned int num_passes = (num_bits + 7) / 8; #pragma omp parallel { int tid = omp_get_thread_num(); int nthreads = omp_get_num_threads(); int* local_histogram = &histogram[RDX_HIST_SIZE * tid]; int* local_histogram_ps = &histogram_ps[RDX_HIST_SIZE * tid]; int elements_count_4 = elements_count / 4 * 4; Radix_Sort_Pair<T>* input = inp_buf; Radix_Sort_Pair<T>* output = tmp_buf; for (unsigned int pass = 0; pass < num_passes; pass++) { // Step 1: compute histogram for (int i = 0; i < RDX_HIST_SIZE; i++) local_histogram[i] = 0; #pragma omp for schedule(static) for (int64_t i = 0; i < elements_count_4; i += 4) { T val_1 = input[i].first; T val_2 = input[i + 1].first; T val_3 = input[i + 2].first; T val_4 = input[i + 3].first; local_histogram[(val_1 >> (pass * 8)) & 0xFF]++; local_histogram[(val_2 >> (pass * 8)) & 0xFF]++; local_histogram[(val_3 >> (pass * 8)) & 0xFF]++; local_histogram[(val_4 >> (pass * 8)) & 0xFF]++; } if (tid == (nthreads - 1)) { for (int64_t i = elements_count_4; i < elements_count; i++) { T val = input[i].first; local_histogram[(val >> (pass * 8)) & 0xFF]++; } } #pragma omp barrier // Step 2: prefix sum if (tid == 0) { int sum = 0, prev_sum = 0; for (int bins = 0; bins < RDX_HIST_SIZE; bins++) for (int t = 0; t < nthreads; t++) { sum += histogram[t * RDX_HIST_SIZE + bins]; histogram_ps[t * RDX_HIST_SIZE + bins] = prev_sum; prev_sum = sum; } histogram_ps[RDX_HIST_SIZE * nthreads] = prev_sum; if (prev_sum != elements_count) { } } #pragma omp barrier // Step 3: scatter #pragma omp for schedule(static) for (int64_t i = 0; i < elements_count_4; i += 4) { T val_1 = input[i].first; T val_2 = input[i + 1].first; T val_3 = input[i + 2].first; T val_4 = input[i + 3].first; T bin_1 = (val_1 >> (pass * 8)) & 0xFF; T bin_2 = (val_2 >> (pass * 8)) & 0xFF; T bin_3 = (val_3 >> (pass * 8)) & 0xFF; T bin_4 = (val_4 >> (pass * 8)) & 0xFF; int pos; pos = local_histogram_ps[bin_1]++; output[pos] = input[i]; pos = local_histogram_ps[bin_2]++; output[pos] = input[i + 1]; pos = local_histogram_ps[bin_3]++; output[pos] = input[i + 2]; pos = local_histogram_ps[bin_4]++; output[pos] = input[i + 3]; } if (tid == (nthreads - 1)) { for (int64_t i = elements_count_4; i < elements_count; i++) { T val = input[i].first; int pos = local_histogram_ps[(val >> (pass * 8)) & 0xFF]++; output[pos] = input[i]; } } Radix_Sort_Pair<T>* temp = input; input = output; output = temp; #pragma omp barrier } } return (num_passes % 2 == 0 ? inp_buf : tmp_buf); }
CGOpenMPRuntime.h
//===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This provides a class for OpenMP runtime code generation. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H #include "CGValue.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/GlobalDecl.h" #include "clang/AST/Type.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" #include "llvm/IR/Function.h" #include "llvm/IR/ValueHandle.h" #include "llvm/Support/AtomicOrdering.h" namespace llvm { class ArrayType; class Constant; class FunctionType; class GlobalVariable; class StructType; class Type; class Value; class OpenMPIRBuilder; } // namespace llvm namespace clang { class Expr; class OMPDependClause; class OMPExecutableDirective; class OMPLoopDirective; class VarDecl; class OMPDeclareReductionDecl; class IdentifierInfo; namespace CodeGen { class Address; class CodeGenFunction; class CodeGenModule; /// A basic class for pre|post-action for advanced codegen sequence for OpenMP /// region. class PrePostActionTy { public: explicit PrePostActionTy() {} virtual void Enter(CodeGenFunction &CGF) {} virtual void Exit(CodeGenFunction &CGF) {} virtual ~PrePostActionTy() {} }; /// Class provides a way to call simple version of codegen for OpenMP region, or /// an advanced with possible pre|post-actions in codegen. class RegionCodeGenTy final { intptr_t CodeGen; typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &); CodeGenTy Callback; mutable PrePostActionTy *PrePostAction; RegionCodeGenTy() = delete; template <typename Callable> static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF, PrePostActionTy &Action) { return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action); } public: template <typename Callable> RegionCodeGenTy( Callable &&CodeGen, std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>, RegionCodeGenTy>::value> * = nullptr) : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)), Callback(CallbackFn<std::remove_reference_t<Callable>>), PrePostAction(nullptr) {} void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; } void operator()(CodeGenFunction &CGF) const; }; struct OMPTaskDataTy final { SmallVector<const Expr *, 4> PrivateVars; SmallVector<const Expr *, 4> PrivateCopies; SmallVector<const Expr *, 4> FirstprivateVars; SmallVector<const Expr *, 4> FirstprivateCopies; SmallVector<const Expr *, 4> FirstprivateInits; SmallVector<const Expr *, 4> LastprivateVars; SmallVector<const Expr *, 4> LastprivateCopies; SmallVector<const Expr *, 4> ReductionVars; SmallVector<const Expr *, 4> ReductionOrigs; SmallVector<const Expr *, 4> ReductionCopies; SmallVector<const Expr *, 4> ReductionOps; SmallVector<CanonicalDeclPtr<const VarDecl>, 4> PrivateLocals; struct DependData { OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; const Expr *IteratorExpr = nullptr; SmallVector<const Expr *, 4> DepExprs; explicit DependData() = default; DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr) : DepKind(DepKind), IteratorExpr(IteratorExpr) {} }; SmallVector<DependData, 4> Dependences; llvm::PointerIntPair<llvm::Value *, 1, bool> Final; llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule; llvm::PointerIntPair<llvm::Value *, 1, bool> Priority; llvm::Value *Reductions = nullptr; unsigned NumberOfParts = 0; bool Tied = true; bool Nogroup = false; bool IsReductionWithTaskMod = false; bool IsWorksharingReduction = false; }; /// Class intended to support codegen of all kind of the reduction clauses. class ReductionCodeGen { private: /// Data required for codegen of reduction clauses. struct ReductionData { /// Reference to the item shared between tasks to reduce into. const Expr *Shared = nullptr; /// Reference to the original item. const Expr *Ref = nullptr; /// Helper expression for generation of private copy. const Expr *Private = nullptr; /// Helper expression for generation reduction operation. const Expr *ReductionOp = nullptr; ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private, const Expr *ReductionOp) : Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) { } }; /// List of reduction-based clauses. SmallVector<ReductionData, 4> ClausesData; /// List of addresses of shared variables/expressions. SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses; /// List of addresses of original variables/expressions. SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses; /// Sizes of the reduction items in chars. SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes; /// Base declarations for the reduction items. SmallVector<const VarDecl *, 4> BaseDecls; /// Emits lvalue for shared expression. LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E); /// Emits upper bound for shared expression (if array section). LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E); /// Performs aggregate initialization. /// \param N Number of reduction item in the common list. /// \param PrivateAddr Address of the corresponding private item. /// \param SharedLVal Address of the original shared variable. /// \param DRD Declare reduction construct used for reduction item. void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, const OMPDeclareReductionDecl *DRD); public: ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> ReductionOps); /// Emits lvalue for the shared and original reduction item. /// \param N Number of the reduction item. void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N); /// Emits the code for the variable-modified type, if required. /// \param N Number of the reduction item. void emitAggregateType(CodeGenFunction &CGF, unsigned N); /// Emits the code for the variable-modified type, if required. /// \param N Number of the reduction item. /// \param Size Size of the type in chars. void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size); /// Performs initialization of the private copy for the reduction item. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. /// \param DefaultInit Default initialization sequence that should be /// performed if no reduction specific initialization is found. /// \param SharedLVal Address of the original shared variable. void emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, llvm::function_ref<bool(CodeGenFunction &)> DefaultInit); /// Returns true if the private copy requires cleanups. bool needCleanups(unsigned N); /// Emits cleanup code for the reduction item. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); /// Adjusts \p PrivatedAddr for using instead of the original variable /// address in normal operations. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); /// Returns LValue for the reduction item. LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; } /// Returns LValue for the original reduction item. LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; } /// Returns the size of the reduction item (in chars and total number of /// elements in the item), or nullptr, if the size is a constant. std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const { return Sizes[N]; } /// Returns the base declaration of the reduction item. const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; } /// Returns the base declaration of the reduction item. const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; } /// Returns true if the initialization of the reduction item uses initializer /// from declare reduction construct. bool usesReductionInitializer(unsigned N) const; }; class CGOpenMPRuntime { public: /// Allows to disable automatic handling of functions used in target regions /// as those marked as `omp declare target`. class DisableAutoDeclareTargetRAII { CodeGenModule &CGM; bool SavedShouldMarkAsGlobal; public: DisableAutoDeclareTargetRAII(CodeGenModule &CGM); ~DisableAutoDeclareTargetRAII(); }; /// Manages list of nontemporal decls for the specified directive. class NontemporalDeclsRAII { CodeGenModule &CGM; const bool NeedToPush; public: NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S); ~NontemporalDeclsRAII(); }; /// Manages list of nontemporal decls for the specified directive. class UntiedTaskLocalDeclsRAII { CodeGenModule &CGM; const bool NeedToPush; public: UntiedTaskLocalDeclsRAII( CodeGenFunction &CGF, const llvm::MapVector<CanonicalDeclPtr<const VarDecl>, std::pair<Address, Address>> &LocalVars); ~UntiedTaskLocalDeclsRAII(); }; /// Maps the expression for the lastprivate variable to the global copy used /// to store new value because original variables are not mapped in inner /// parallel regions. Only private copies are captured but we need also to /// store private copy in shared address. /// Also, stores the expression for the private loop counter and it /// threaprivate name. struct LastprivateConditionalData { llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>> DeclToUniqueName; LValue IVLVal; llvm::Function *Fn = nullptr; bool Disabled = false; }; /// Manages list of lastprivate conditional decls for the specified directive. class LastprivateConditionalRAII { enum class ActionToDo { DoNotPush, PushAsLastprivateConditional, DisableLastprivateConditional, }; CodeGenModule &CGM; ActionToDo Action = ActionToDo::DoNotPush; /// Check and try to disable analysis of inner regions for changes in /// lastprivate conditional. void tryToDisableInnerAnalysis(const OMPExecutableDirective &S, llvm::DenseSet<CanonicalDeclPtr<const Decl>> &NeedToAddForLPCsAsDisabled) const; LastprivateConditionalRAII(CodeGenFunction &CGF, const OMPExecutableDirective &S); public: explicit LastprivateConditionalRAII(CodeGenFunction &CGF, const OMPExecutableDirective &S, LValue IVLVal); static LastprivateConditionalRAII disable(CodeGenFunction &CGF, const OMPExecutableDirective &S); ~LastprivateConditionalRAII(); }; llvm::OpenMPIRBuilder &getOMPBuilder() { return OMPBuilder; } protected: CodeGenModule &CGM; StringRef FirstSeparator, Separator; /// An OpenMP-IR-Builder instance. llvm::OpenMPIRBuilder OMPBuilder; /// Constructor allowing to redefine the name separator for the variables. explicit CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator, StringRef Separator); /// Creates offloading entry for the provided entry ID \a ID, /// address \a Addr, size \a Size, and flags \a Flags. virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags, llvm::GlobalValue::LinkageTypes Linkage); /// Helper to emit outlined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Lambda codegen specific to an accelerator device. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen); /// Emits object of ident_t type with info for source location. /// \param Flags Flags for OpenMP location. /// llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, unsigned Flags = 0); /// Returns pointer to ident_t type. llvm::Type *getIdentTyPointerTy(); /// Gets thread id value for the current thread. /// llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc); /// Get the function name of an outlined region. // The name can be customized depending on the target. // virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; } /// Emits \p Callee function call with arguments \p Args with location \p Loc. void emitCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee Callee, ArrayRef<llvm::Value *> Args = llvm::None) const; /// Emits address of the word in a memory where current thread id is /// stored. virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc); void setLocThreadIdInsertPt(CodeGenFunction &CGF, bool AtCurrentPoint = false); void clearLocThreadIdInsertPt(CodeGenFunction &CGF); /// Check if the default location must be constant. /// Default is false to support OMPT/OMPD. virtual bool isDefaultLocationConstant() const { return false; } /// Returns additional flags that can be stored in reserved_2 field of the /// default location. virtual unsigned getDefaultLocationReserved2Flags() const { return 0; } /// Returns default flags for the barriers depending on the directive, for /// which this barier is going to be emitted. static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind); /// Get the LLVM type for the critical name. llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;} /// Returns corresponding lock object for the specified critical region /// name. If the lock object does not exist it is created, otherwise the /// reference to the existing copy is returned. /// \param CriticalName Name of the critical region. /// llvm::Value *getCriticalRegionLock(StringRef CriticalName); private: /// Map for SourceLocation and OpenMP runtime library debug locations. typedef llvm::DenseMap<SourceLocation, llvm::Value *> OpenMPDebugLocMapTy; OpenMPDebugLocMapTy OpenMPDebugLocMap; /// The type for a microtask which gets passed to __kmpc_fork_call(). /// Original representation is: /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...); llvm::FunctionType *Kmpc_MicroTy = nullptr; /// Stores debug location and ThreadID for the function. struct DebugLocThreadIdTy { llvm::Value *DebugLoc; llvm::Value *ThreadID; /// Insert point for the service instructions. llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr; }; /// Map of local debug location, ThreadId and functions. typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy> OpenMPLocThreadIDMapTy; OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap; /// Map of UDRs and corresponding combiner/initializer. typedef llvm::DenseMap<const OMPDeclareReductionDecl *, std::pair<llvm::Function *, llvm::Function *>> UDRMapTy; UDRMapTy UDRMap; /// Map of functions and locally defined UDRs. typedef llvm::DenseMap<llvm::Function *, SmallVector<const OMPDeclareReductionDecl *, 4>> FunctionUDRMapTy; FunctionUDRMapTy FunctionUDRMap; /// Map from the user-defined mapper declaration to its corresponding /// functions. llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap; /// Map of functions and their local user-defined mappers. using FunctionUDMMapTy = llvm::DenseMap<llvm::Function *, SmallVector<const OMPDeclareMapperDecl *, 4>>; FunctionUDMMapTy FunctionUDMMap; /// Maps local variables marked as lastprivate conditional to their internal /// types. llvm::DenseMap<llvm::Function *, llvm::DenseMap<CanonicalDeclPtr<const Decl>, std::tuple<QualType, const FieldDecl *, const FieldDecl *, LValue>>> LastprivateConditionalToTypes; /// Maps function to the position of the untied task locals stack. llvm::DenseMap<llvm::Function *, unsigned> FunctionToUntiedTaskStackMap; /// Type kmp_critical_name, originally defined as typedef kmp_int32 /// kmp_critical_name[8]; llvm::ArrayType *KmpCriticalNameTy; /// An ordered map of auto-generated variables to their unique names. /// It stores variables with the following names: 1) ".gomp_critical_user_" + /// <critical_section_name> + ".var" for "omp critical" directives; 2) /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate /// variables. llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator> InternalVars; /// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); llvm::Type *KmpRoutineEntryPtrTy = nullptr; QualType KmpRoutineEntryPtrQTy; /// Type typedef struct kmp_task { /// void * shareds; /**< pointer to block of pointers to /// shared vars */ /// kmp_routine_entry_t routine; /**< pointer to routine to call for /// executing task */ /// kmp_int32 part_id; /**< part id for the task */ /// kmp_routine_entry_t destructors; /* pointer to function to invoke /// deconstructors of firstprivate C++ objects */ /// } kmp_task_t; QualType KmpTaskTQTy; /// Saved kmp_task_t for task directive. QualType SavedKmpTaskTQTy; /// Saved kmp_task_t for taskloop-based directive. QualType SavedKmpTaskloopTQTy; /// Type typedef struct kmp_depend_info { /// kmp_intptr_t base_addr; /// size_t len; /// struct { /// bool in:1; /// bool out:1; /// } flags; /// } kmp_depend_info_t; QualType KmpDependInfoTy; /// Type typedef struct kmp_task_affinity_info { /// kmp_intptr_t base_addr; /// size_t len; /// struct { /// bool flag1 : 1; /// bool flag2 : 1; /// kmp_int32 reserved : 30; /// } flags; /// } kmp_task_affinity_info_t; QualType KmpTaskAffinityInfoTy; /// struct kmp_dim { // loop bounds info casted to kmp_int64 /// kmp_int64 lo; // lower /// kmp_int64 up; // upper /// kmp_int64 st; // stride /// }; QualType KmpDimTy; /// Type struct __tgt_offload_entry{ /// void *addr; // Pointer to the offload entry info. /// // (function or global) /// char *name; // Name of the function or global. /// size_t size; // Size of the entry info (0 if it a function). /// int32_t flags; /// int32_t reserved; /// }; QualType TgtOffloadEntryQTy; /// Entity that registers the offloading constants that were emitted so /// far. class OffloadEntriesInfoManagerTy { CodeGenModule &CGM; /// Number of entries registered so far. unsigned OffloadingEntriesNum = 0; public: /// Base class of the entries info. class OffloadEntryInfo { public: /// Kind of a given entry. enum OffloadingEntryInfoKinds : unsigned { /// Entry is a target region. OffloadingEntryInfoTargetRegion = 0, /// Entry is a declare target variable. OffloadingEntryInfoDeviceGlobalVar = 1, /// Invalid entry info. OffloadingEntryInfoInvalid = ~0u }; protected: OffloadEntryInfo() = delete; explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {} explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, uint32_t Flags) : Flags(Flags), Order(Order), Kind(Kind) {} ~OffloadEntryInfo() = default; public: bool isValid() const { return Order != ~0u; } unsigned getOrder() const { return Order; } OffloadingEntryInfoKinds getKind() const { return Kind; } uint32_t getFlags() const { return Flags; } void setFlags(uint32_t NewFlags) { Flags = NewFlags; } llvm::Constant *getAddress() const { return cast_or_null<llvm::Constant>(Addr); } void setAddress(llvm::Constant *V) { assert(!Addr.pointsToAliveValue() && "Address has been set before!"); Addr = V; } static bool classof(const OffloadEntryInfo *Info) { return true; } private: /// Address of the entity that has to be mapped for offloading. llvm::WeakTrackingVH Addr; /// Flags associated with the device global. uint32_t Flags = 0u; /// Order this entry was emitted. unsigned Order = ~0u; OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid; }; /// Return true if a there are no entries defined. bool empty() const; /// Return number of entries defined so far. unsigned size() const { return OffloadingEntriesNum; } OffloadEntriesInfoManagerTy(CodeGenModule &CGM) : CGM(CGM) {} // // Target region entries related. // /// Kind of the target registry entry. enum OMPTargetRegionEntryKind : uint32_t { /// Mark the entry as target region. OMPTargetRegionEntryTargetRegion = 0x0, /// Mark the entry as a global constructor. OMPTargetRegionEntryCtor = 0x02, /// Mark the entry as a global destructor. OMPTargetRegionEntryDtor = 0x04, }; /// Target region entries info. class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo { /// Address that can be used as the ID of the entry. llvm::Constant *ID = nullptr; public: OffloadEntryInfoTargetRegion() : OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {} explicit OffloadEntryInfoTargetRegion(unsigned Order, llvm::Constant *Addr, llvm::Constant *ID, OMPTargetRegionEntryKind Flags) : OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags), ID(ID) { setAddress(Addr); } llvm::Constant *getID() const { return ID; } void setID(llvm::Constant *V) { assert(!ID && "ID has been set before!"); ID = V; } static bool classof(const OffloadEntryInfo *Info) { return Info->getKind() == OffloadingEntryInfoTargetRegion; } }; /// Initialize target region entry. void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, unsigned Order); /// Register target region entry. void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, llvm::Constant *Addr, llvm::Constant *ID, OMPTargetRegionEntryKind Flags); /// Return true if a target region entry with the provided information /// exists. bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, bool IgnoreAddressId = false) const; /// brief Applies action \a Action on all registered entries. typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned, const OffloadEntryInfoTargetRegion &)> OffloadTargetRegionEntryInfoActTy; void actOnTargetRegionEntriesInfo( const OffloadTargetRegionEntryInfoActTy &Action); // // Device global variable entries related. // /// Kind of the global variable entry.. enum OMPTargetGlobalVarEntryKind : uint32_t { /// Mark the entry as a to declare target. OMPTargetGlobalVarEntryTo = 0x0, /// Mark the entry as a to declare target link. OMPTargetGlobalVarEntryLink = 0x1, }; /// Device global variable entries info. class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo { /// Type of the global variable. CharUnits VarSize; llvm::GlobalValue::LinkageTypes Linkage; public: OffloadEntryInfoDeviceGlobalVar() : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {} explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, OMPTargetGlobalVarEntryKind Flags) : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {} explicit OffloadEntryInfoDeviceGlobalVar( unsigned Order, llvm::Constant *Addr, CharUnits VarSize, OMPTargetGlobalVarEntryKind Flags, llvm::GlobalValue::LinkageTypes Linkage) : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags), VarSize(VarSize), Linkage(Linkage) { setAddress(Addr); } CharUnits getVarSize() const { return VarSize; } void setVarSize(CharUnits Size) { VarSize = Size; } llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; } void setLinkage(llvm::GlobalValue::LinkageTypes LT) { Linkage = LT; } static bool classof(const OffloadEntryInfo *Info) { return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar; } }; /// Initialize device global variable entry. void initializeDeviceGlobalVarEntryInfo(StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order); /// Register device global variable entry. void registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr, CharUnits VarSize, OMPTargetGlobalVarEntryKind Flags, llvm::GlobalValue::LinkageTypes Linkage); /// Checks if the variable with the given name has been registered already. bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const { return OffloadEntriesDeviceGlobalVar.count(VarName) > 0; } /// Applies action \a Action on all registered entries. typedef llvm::function_ref<void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)> OffloadDeviceGlobalVarEntryInfoActTy; void actOnDeviceGlobalVarEntriesInfo( const OffloadDeviceGlobalVarEntryInfoActTy &Action); private: // Storage for target region entries kind. The storage is to be indexed by // file ID, device ID, parent function name and line number. typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion> OffloadEntriesTargetRegionPerLine; typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine> OffloadEntriesTargetRegionPerParentName; typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName> OffloadEntriesTargetRegionPerFile; typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile> OffloadEntriesTargetRegionPerDevice; typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy; OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion; /// Storage for device global variable entries kind. The storage is to be /// indexed by mangled name. typedef llvm::StringMap<OffloadEntryInfoDeviceGlobalVar> OffloadEntriesDeviceGlobalVarTy; OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar; }; OffloadEntriesInfoManagerTy OffloadEntriesInfoManager; bool ShouldMarkAsGlobal = true; /// List of the emitted declarations. llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls; /// List of the global variables with their addresses that should not be /// emitted for the target. llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables; /// List of variables that can become declare target implicitly and, thus, /// must be emitted. llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables; using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>; /// Stack for list of declarations in current context marked as nontemporal. /// The set is the union of all current stack elements. llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack; using UntiedLocalVarsAddressesMap = llvm::MapVector<CanonicalDeclPtr<const VarDecl>, std::pair<Address, Address>>; llvm::SmallVector<UntiedLocalVarsAddressesMap, 4> UntiedLocalVarsStack; /// Stack for list of addresses of declarations in current context marked as /// lastprivate conditional. The set is the union of all current stack /// elements. llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack; /// Flag for keeping track of weather a requires unified_shared_memory /// directive is present. bool HasRequiresUnifiedSharedMemory = false; /// Atomic ordering from the omp requires directive. llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic; /// Flag for keeping track of weather a target region has been emitted. bool HasEmittedTargetRegion = false; /// Flag for keeping track of weather a device routine has been emitted. /// Device routines are specific to the bool HasEmittedDeclareTargetRegion = false; /// Loads all the offload entries information from the host IR /// metadata. void loadOffloadInfoMetadata(); /// Returns __tgt_offload_entry type. QualType getTgtOffloadEntryQTy(); /// Start scanning from statement \a S and and emit all target regions /// found along the way. /// \param S Starting statement. /// \param ParentName Name of the function declaration that is being scanned. void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName); /// Build type kmp_routine_entry_t (if not built yet). void emitKmpRoutineEntryT(QualType KmpInt32Ty); /// Returns pointer to kmpc_micro type. llvm::Type *getKmpc_MicroPointerTy(); /// Returns __kmpc_for_static_init_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_init_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_next_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchNextFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_fini_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchFiniFunction(unsigned IVSize, bool IVSigned); /// If the specified mangled name is not in the module, create and /// return threadprivate cache object. This object is a pointer's worth of /// storage that's reserved for use by the OpenMP runtime. /// \param VD Threadprivate variable. /// \return Cache variable for the specified threadprivate. llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD); /// Gets (if variable with the given name already exist) or creates /// internal global variable with the specified Name. The created variable has /// linkage CommonLinkage by default and is initialized by null value. /// \param Ty Type of the global variable. If it is exist already the type /// must be the same. /// \param Name Name of the variable. llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace = 0); /// Set of threadprivate variables with the generated initializer. llvm::StringSet<> ThreadPrivateWithDefinition; /// Set of declare target variables with the generated initializer. llvm::StringSet<> DeclareTargetWithDefinition; /// Emits initialization code for the threadprivate variables. /// \param VDAddr Address of the global variable \a VD. /// \param Ctor Pointer to a global init function for \a VD. /// \param CopyCtor Pointer to a global copy function for \a VD. /// \param Dtor Pointer to a global destructor function for \a VD. /// \param Loc Location of threadprivate declaration. void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor, llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc); /// Emit the array initialization or deletion portion for user-defined mapper /// code generation. void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF, llvm::Value *Handle, llvm::Value *BasePtr, llvm::Value *Ptr, llvm::Value *Size, llvm::Value *MapType, llvm::Value *MapName, CharUnits ElementSize, llvm::BasicBlock *ExitBB, bool IsInit); struct TaskResultTy { llvm::Value *NewTask = nullptr; llvm::Function *TaskEntry = nullptr; llvm::Value *NewTaskNewTaskTTy = nullptr; LValue TDBase; const RecordDecl *KmpTaskTQTyRD = nullptr; llvm::Value *TaskDupFn = nullptr; }; /// Emit task region for the task directive. The task region is emitted in /// several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const OMPTaskDataTy &Data); /// Emit code that pushes the trip count of loops associated with constructs /// 'target teams distribute' and 'teams distribute parallel for'. /// \param SizeEmitter Emits the int64 value for the number of iterations of /// the associated loop. void emitTargetNumIterationsCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Value *DeviceID, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter); /// Emit update for lastprivate conditional data. void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal, StringRef UniqueDeclName, LValue LVal, SourceLocation Loc); /// Returns the number of the elements and the address of the depobj /// dependency array. /// \return Number of elements in depobj array and the pointer to the array of /// dependencies. std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF, LValue DepobjLVal, SourceLocation Loc); public: explicit CGOpenMPRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM, ".", ".") {} virtual ~CGOpenMPRuntime() {} virtual void clear(); /// Emits code for OpenMP 'if' clause using specified \a CodeGen /// function. Here is the logic: /// if (Cond) { /// ThenGen(); /// } else { /// ElseGen(); /// } void emitIfClause(CodeGenFunction &CGF, const Expr *Cond, const RegionCodeGenTy &ThenGen, const RegionCodeGenTy &ElseGen); /// Checks if the \p Body is the \a CompoundStmt and returns its child /// statement iff there is only one that is not evaluatable at the compile /// time. static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body); /// Get the platform-specific name separator. std::string getName(ArrayRef<StringRef> Parts) const; /// Emit code for the specified user defined reduction construct. virtual void emitUserDefinedReduction(CodeGenFunction *CGF, const OMPDeclareReductionDecl *D); /// Get combiner/initializer for the specified user-defined reduction, if any. virtual std::pair<llvm::Function *, llvm::Function *> getUserDefinedReduction(const OMPDeclareReductionDecl *D); /// Emit the function for the user defined mapper construct. void emitUserDefinedMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF = nullptr); /// Get the function for the specified user-defined mapper. If it does not /// exist, create one. llvm::Function * getOrCreateUserDefinedMapperFunc(const OMPDeclareMapperDecl *D); /// Emits outlined function for the specified OpenMP parallel directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. virtual llvm::Function *emitParallelOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); /// Emits outlined function for the specified OpenMP teams directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. virtual llvm::Function *emitTeamsOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); /// Emits outlined function for the OpenMP task directive \a D. This /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* /// TaskT). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param PartIDVar Variable for partition id in the current OpenMP untied /// task region. /// \param TaskTVar Variable for task_t argument. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param Tied true if task is generated for tied task, false otherwise. /// \param NumberOfParts Number of parts in untied task. Ignored for tied /// tasks. /// virtual llvm::Function *emitTaskOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, const VarDecl *PartIDVar, const VarDecl *TaskTVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool Tied, unsigned &NumberOfParts); /// Cleans up references to the objects in finished function. /// virtual void functionFinished(CodeGenFunction &CGF); /// Emits code for parallel or serial call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond); /// Emits a critical region. /// \param CriticalName Name of the critical region. /// \param CriticalOpGen Generator for the statement associated with the given /// critical region. /// \param Hint Value of the 'hint' clause (optional). virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint = nullptr); /// Emits a master region. /// \param MasterOpGen Generator for the statement associated with the given /// master region. virtual void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc); /// Emits a masked region. /// \param MaskedOpGen Generator for the statement associated with the given /// masked region. virtual void emitMaskedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc, const Expr *Filter = nullptr); /// Emits code for a taskyield directive. virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc); /// Emit a taskgroup region. /// \param TaskgroupOpGen Generator for the statement associated with the /// given taskgroup region. virtual void emitTaskgroupRegion(CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, SourceLocation Loc); /// Emits a single region. /// \param SingleOpGen Generator for the statement associated with the given /// single region. virtual void emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps); /// Emit an ordered region. /// \param OrderedOpGen Generator for the statement associated with the given /// ordered region. virtual void emitOrderedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &OrderedOpGen, SourceLocation Loc, bool IsThreads); /// Emit an implicit/explicit barrier for OpenMP threads. /// \param Kind Directive for which this implicit barrier call must be /// generated. Must be OMPD_barrier for explicit barrier generation. /// \param EmitChecks true if need to emit checks for cancellation barriers. /// \param ForceSimpleCall true simple barrier call must be emitted, false if /// runtime class decides which one to emit (simple or with cancellation /// checks). /// virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks = true, bool ForceSimpleCall = false); /// Check if the specified \a ScheduleKind is static non-chunked. /// This kind of worksharing directive is emitted without outer loop. /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static non-chunked. /// This kind of distribute directive is emitted without outer loop. /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static chunked. /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static non-chunked. /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is dynamic. /// This kind of worksharing directive is emitted without outer loop. /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause. /// virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const; /// struct with the values to be passed to the dispatch runtime function struct DispatchRTInput { /// Loop lower bound llvm::Value *LB = nullptr; /// Loop upper bound llvm::Value *UB = nullptr; /// Chunk size specified using 'schedule' clause (nullptr if chunk /// was not specified) llvm::Value *Chunk = nullptr; DispatchRTInput() = default; DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk) : LB(LB), UB(UB), Chunk(Chunk) {} }; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// This is used for non static scheduled types and when the ordered /// clause is present on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds \a LB and \a UB and stride \a ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param Ordered true if loop is ordered, false otherwise. /// \param DispatchValues struct containing llvm values for lower bound, upper /// bound, and chunk expression. /// For the default (nullptr) value, the chunk 1 will be used. /// virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues); /// Struct with the values to be passed to the static runtime function struct StaticRTInput { /// Size of the iteration variable in bits. unsigned IVSize = 0; /// Sign of the iteration variable. bool IVSigned = false; /// true if loop is ordered, false otherwise. bool Ordered = false; /// Address of the output variable in which the flag of the last iteration /// is returned. Address IL = Address::invalid(); /// Address of the output variable in which the lower iteration number is /// returned. Address LB = Address::invalid(); /// Address of the output variable in which the upper iteration number is /// returned. Address UB = Address::invalid(); /// Address of the output variable in which the stride value is returned /// necessary to generated the static_chunked scheduled loop. Address ST = Address::invalid(); /// Value of the chunk for the static_chunked scheduled loop. For the /// default (nullptr) value, the chunk 1 will be used. llvm::Value *Chunk = nullptr; StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL, Address LB, Address UB, Address ST, llvm::Value *Chunk = nullptr) : IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB), UB(UB), ST(ST), Chunk(Chunk) {} }; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// /// This is used only in case of static schedule, when the user did not /// specify a ordered clause on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds LB and UB and stride ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param Values Input arguments for the construct. /// virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values); /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. /// \param Values Input arguments for the construct. /// virtual void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values); /// Call the appropriate runtime routine to notify that we finished /// iteration of the ordered loop with the dynamic scheduling. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned); /// Call the appropriate runtime routine to notify that we finished /// all the work with current loop. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive for which the static finish is emitted. /// virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind); /// Call __kmpc_dispatch_next( /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, /// kmp_int[32|64] *p_stride); /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param IL Address of the output variable in which the flag of the /// last iteration is returned. /// \param LB Address of the output variable in which the lower iteration /// number is returned. /// \param UB Address of the output variable in which the upper iteration /// number is returned. /// \param ST Address of the output variable in which the stride value is /// returned. virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST); /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' /// clause. /// \param NumThreads An integer value of threads. virtual void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc); /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. virtual void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc); /// Returns address of the threadprivate variable for the current /// thread. /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of the reference to threadprivate var. /// \return Address of the threadprivate variable for the current thread. virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc); /// Returns the address of the variable marked as declare target with link /// clause OR as declare target with to clause and unified memory. virtual Address getAddrOfDeclareTargetVar(const VarDecl *VD); /// Emit a code for initialization of threadprivate variable. It emits /// a call to runtime library which adds initial value to the newly created /// threadprivate variable (if it is not constant) and registers destructor /// for the variable (if any). /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of threadprivate declaration. /// \param PerformInit true if initialization expression is not constant. virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF = nullptr); /// Emit a code for initialization of declare target variable. /// \param VD Declare target variable. /// \param Addr Address of the global variable \a VD. /// \param PerformInit true if initialization expression is not constant. virtual bool emitDeclareTargetVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Addr, bool PerformInit); /// Creates artificial threadprivate variable with name \p Name and type \p /// VarType. /// \param VarType Type of the artificial threadprivate variable. /// \param Name Name of the artificial threadprivate variable. virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, QualType VarType, StringRef Name); /// Emit flush of the variables specified in 'omp flush' directive. /// \param Vars List of variables to flush. virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, SourceLocation Loc, llvm::AtomicOrdering AO); /// Emit task region for the task directive. The task region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, /// kmp_task_t *new_task), where new_task is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data); /// Emit task region for the taskloop directive. The taskloop region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task /// is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data); /// Emit code for the directive that does not require outlining. /// /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param HasCancel true if region has inner cancel directive, false /// otherwise. virtual void emitInlinedDirective(CodeGenFunction &CGF, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool HasCancel = false); /// Emits reduction function. /// \param ArgsType Array type containing pointers to reduction variables. /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. llvm::Function *emitReductionFunction(SourceLocation Loc, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps); /// Emits single reduction combiner void emitSingleReductionCombiner(CodeGenFunction &CGF, const Expr *ReductionOp, const Expr *PrivateRef, const DeclRefExpr *LHS, const DeclRefExpr *RHS); struct ReductionOptionsTy { bool WithNowait; bool SimpleReduction; OpenMPDirectiveKind ReductionKind; }; /// Emit a code for reduction clause. Next code should be emitted for /// reduction: /// \code /// /// static kmp_critical_name lock = { 0 }; /// /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { /// ... /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); /// ... /// } /// /// ... /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), /// RedList, reduce_func, &<lock>)) { /// case 1: /// ... /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); /// ... /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); /// break; /// case 2: /// ... /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); /// ... /// break; /// default:; /// } /// \endcode /// /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. /// \param Options List of options for reduction codegen: /// WithNowait true if parent directive has also nowait clause, false /// otherwise. /// SimpleReduction Emit reduction operation only. Used for omp simd /// directive on the host. /// ReductionKind The kind of reduction to perform. virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options); /// Emit a code for initialization of task reduction clause. Next code /// should be emitted for reduction: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); /// \endcode /// For reduction clause with task modifier it emits the next call: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, /// red_data); /// \endcode /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. /// \param Data Additional data for task generation like tiedness, final /// state, list of privates, reductions etc. virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data); /// Emits the following code for reduction clause with task modifier: /// \code /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); /// \endcode virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, bool IsWorksharingReduction); /// Required to resolve existing problems in the runtime. Emits threadprivate /// variables to store the size of the VLAs/array sections for /// initializer/combiner/finalizer functions. /// \param RCG Allows to reuse an existing data for the reductions. /// \param N Reduction item for which fixups must be emitted. virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N); /// Get the address of `void *` type of the privatue copy of the reduction /// item specified by the \p SharedLVal. /// \param ReductionsPtr Pointer to the reduction data returned by the /// emitTaskReductionInit function. /// \param SharedLVal Address of the original reduction item. virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal); /// Emit code for 'taskwait' directive. virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc); /// Emit code for 'cancellation point' construct. /// \param CancelRegion Region kind for which the cancellation point must be /// emitted. /// virtual void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind CancelRegion); /// Emit code for 'cancel' construct. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param CancelRegion Region kind for which the cancel must be emitted. /// virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, const Expr *IfCond, OpenMPDirectiveKind CancelRegion); /// Emit outilined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Code generation sequence for the \a D directive. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen); /// Emit the target offloading code associated with \a D. The emitted /// code attempts offloading the execution to the device, an the event of /// a failure it executes the host version outlined in \a OutlinedFn. /// \param D Directive to emit. /// \param OutlinedFn Host version of the code to be offloaded. /// \param OutlinedFnID ID of host version of the code to be offloaded. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used and device modifier. /// \param SizeEmitter Callback to emit number of iterations for loop-based /// directives. virtual void emitTargetCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter); /// Emit the target regions enclosed in \a GD function definition or /// the function itself in case it is a valid device function. Returns true if /// \a GD was dealt with successfully. /// \param GD Function to scan. virtual bool emitTargetFunctions(GlobalDecl GD); /// Emit the global variable if it is a valid device global variable. /// Returns true if \a GD was dealt with successfully. /// \param GD Variable declaration to emit. virtual bool emitTargetGlobalVariable(GlobalDecl GD); /// Checks if the provided global decl \a GD is a declare target variable and /// registers it when emitting code for the host. virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr); /// Emit the global \a GD if it is meaningful for the target. Returns /// if it was emitted successfully. /// \param GD Global to scan. virtual bool emitTargetGlobal(GlobalDecl GD); /// Creates and returns a registration function for when at least one /// requires directives was used in the current module. llvm::Function *emitRequiresDirectiveRegFun(); /// Creates all the offload entries in the current compilation unit /// along with the associated metadata. void createOffloadEntriesAndInfoMetadata(); /// Emits code for teams call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run by team masters. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// virtual void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars); /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code /// for num_teams clause. /// \param NumTeams An integer expression of teams. /// \param ThreadLimit An integer expression of threads. virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc); /// Struct that keeps all the relevant information that should be kept /// throughout a 'target data' region. class TargetDataInfo { /// Set to true if device pointer information have to be obtained. bool RequiresDevicePointerInfo = false; /// Set to true if Clang emits separate runtime calls for the beginning and /// end of the region. These calls might have separate map type arrays. bool SeparateBeginEndCalls = false; public: /// The array of base pointer passed to the runtime library. llvm::Value *BasePointersArray = nullptr; /// The array of section pointers passed to the runtime library. llvm::Value *PointersArray = nullptr; /// The array of sizes passed to the runtime library. llvm::Value *SizesArray = nullptr; /// The array of map types passed to the runtime library for the beginning /// of the region or for the entire region if there are no separate map /// types for the region end. llvm::Value *MapTypesArray = nullptr; /// The array of map types passed to the runtime library for the end of the /// region, or nullptr if there are no separate map types for the region /// end. llvm::Value *MapTypesArrayEnd = nullptr; /// The array of user-defined mappers passed to the runtime library. llvm::Value *MappersArray = nullptr; /// The array of original declaration names of mapped pointers sent to the /// runtime library for debugging llvm::Value *MapNamesArray = nullptr; /// Indicate whether any user-defined mapper exists. bool HasMapper = false; /// The total number of pointers passed to the runtime library. unsigned NumberOfPtrs = 0u; /// Map between the a declaration of a capture and the corresponding base /// pointer address where the runtime returns the device pointers. llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap; explicit TargetDataInfo() {} explicit TargetDataInfo(bool RequiresDevicePointerInfo, bool SeparateBeginEndCalls) : RequiresDevicePointerInfo(RequiresDevicePointerInfo), SeparateBeginEndCalls(SeparateBeginEndCalls) {} /// Clear information about the data arrays. void clearArrayInfo() { BasePointersArray = nullptr; PointersArray = nullptr; SizesArray = nullptr; MapTypesArray = nullptr; MapTypesArrayEnd = nullptr; MapNamesArray = nullptr; MappersArray = nullptr; HasMapper = false; NumberOfPtrs = 0u; } /// Return true if the current target data information has valid arrays. bool isValid() { return BasePointersArray && PointersArray && SizesArray && MapTypesArray && (!HasMapper || MappersArray) && NumberOfPtrs; } bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; } bool separateBeginEndCalls() { return SeparateBeginEndCalls; } }; /// Emit the target data mapping code associated with \a D. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the /// target directive, or null if no device clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. /// \param Info A record used to store information that needs to be preserved /// until the region is closed. virtual void emitTargetDataCalls(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info); /// Emit the data mapping/movement code associated with the directive /// \a D that should be of the form 'target [{enter|exit} data | update]'. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device); /// Marks function \a Fn with properly mangled versions of vector functions. /// \param FD Function marked as 'declare simd'. /// \param Fn LLVM function that must be marked with 'declare simd' /// attributes. virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn); /// Emit initialization for doacross loop nesting support. /// \param D Loop-based construct used in doacross nesting construct. virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef<Expr *> NumIterations); /// Emit code for doacross ordered directive with 'depend' clause. /// \param C 'depend' clause with 'sink|source' dependency kind. virtual void emitDoacrossOrdered(CodeGenFunction &CGF, const OMPDependClause *C); /// Translates the native parameter of outlined function if this is required /// for target. /// \param FD Field decl from captured record for the parameter. /// \param NativeParam Parameter itself. virtual const VarDecl *translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const { return NativeParam; } /// Gets the address of the native argument basing on the address of the /// target-specific parameter. /// \param NativeParam Parameter itself. /// \param TargetParam Corresponding target-specific parameter. virtual Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const; /// Choose default schedule type and chunk value for the /// dist_schedule clause. virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const {} /// Choose default schedule type and chunk value for the /// schedule clause. virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const; /// Emits call of the outlined function with the provided arguments, /// translating these arguments to correct target-specific arguments. virtual void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef<llvm::Value *> Args = llvm::None) const; /// Emits OpenMP-specific function prolog. /// Required for device constructs. virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D); /// Gets the OpenMP-specific address of the local variable. virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD); /// Marks the declaration as already emitted for the device code and returns /// true, if it was marked already, and false, otherwise. bool markAsGlobalTarget(GlobalDecl GD); /// Emit deferred declare target variables marked for deferred emission. void emitDeferredTargetDecls() const; /// Adjust some parameters for the target-based directives, like addresses of /// the variables captured by reference in lambdas. virtual void adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, const OMPExecutableDirective &D) const; /// Perform check on requires decl to ensure that target architecture /// supports unified addressing virtual void processRequiresDirective(const OMPRequiresDecl *D); /// Gets default memory ordering as specified in requires directive. llvm::AtomicOrdering getDefaultMemoryOrdering() const; /// Checks if the variable has associated OMPAllocateDeclAttr attribute with /// the predefined allocator and translates it into the corresponding address /// space. virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS); /// Return whether the unified_shared_memory has been specified. bool hasRequiresUnifiedSharedMemory() const; /// Checks if the \p VD variable is marked as nontemporal declaration in /// current context. bool isNontemporalDecl(const ValueDecl *VD) const; /// Create specialized alloca to handle lastprivate conditionals. Address emitLastprivateConditionalInit(CodeGenFunction &CGF, const VarDecl *VD); /// Checks if the provided \p LVal is lastprivate conditional and emits the /// code to update the value of the original variable. /// \code /// lastprivate(conditional: a) /// ... /// <type> a; /// lp_a = ...; /// #pragma omp critical(a) /// if (last_iv_a <= iv) { /// last_iv_a = iv; /// global_a = lp_a; /// } /// \endcode virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, const Expr *LHS); /// Checks if the lastprivate conditional was updated in inner region and /// writes the value. /// \code /// lastprivate(conditional: a) /// ... /// <type> a;bool Fired = false; /// #pragma omp ... shared(a) /// { /// lp_a = ...; /// Fired = true; /// } /// if (Fired) { /// #pragma omp critical(a) /// if (last_iv_a <= iv) { /// last_iv_a = iv; /// global_a = lp_a; /// } /// Fired = false; /// } /// \endcode virtual void checkAndEmitSharedLastprivateConditional( CodeGenFunction &CGF, const OMPExecutableDirective &D, const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls); /// Gets the address of the global copy used for lastprivate conditional /// update, if any. /// \param PrivLVal LValue for the private copy. /// \param VD Original lastprivate declaration. virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF, LValue PrivLVal, const VarDecl *VD, SourceLocation Loc); /// Emits list of dependecies based on the provided data (array of /// dependence/expression pairs). /// \returns Pointer to the first element of the array casted to VoidPtr type. std::pair<llvm::Value *, Address> emitDependClause(CodeGenFunction &CGF, ArrayRef<OMPTaskDataTy::DependData> Dependencies, SourceLocation Loc); /// Emits list of dependecies based on the provided data (array of /// dependence/expression pairs) for depobj construct. In this case, the /// variable is allocated in dynamically. \returns Pointer to the first /// element of the array casted to VoidPtr type. Address emitDepobjDependClause(CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies, SourceLocation Loc); /// Emits the code to destroy the dependency object provided in depobj /// directive. void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, SourceLocation Loc); /// Updates the dependency kind in the specified depobj object. /// \param DepobjLVal LValue for the main depobj object. /// \param NewDepKind New dependency kind. void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, OpenMPDependClauseKind NewDepKind, SourceLocation Loc); /// Initializes user defined allocators specified in the uses_allocators /// clauses. void emitUsesAllocatorsInit(CodeGenFunction &CGF, const Expr *Allocator, const Expr *AllocatorTraits); /// Destroys user defined allocators specified in the uses_allocators clause. void emitUsesAllocatorsFini(CodeGenFunction &CGF, const Expr *Allocator); /// Returns true if the variable is a local variable in untied task. bool isLocalVarInUntiedTask(CodeGenFunction &CGF, const VarDecl *VD) const; }; /// Class supports emissionof SIMD-only code. class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime { public: explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {} ~CGOpenMPSIMDRuntime() override {} /// Emits outlined function for the specified OpenMP parallel directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. llvm::Function * emitParallelOutlinedFunction(const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override; /// Emits outlined function for the specified OpenMP teams directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. llvm::Function * emitTeamsOutlinedFunction(const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override; /// Emits outlined function for the OpenMP task directive \a D. This /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* /// TaskT). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param PartIDVar Variable for partition id in the current OpenMP untied /// task region. /// \param TaskTVar Variable for task_t argument. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param Tied true if task is generated for tied task, false otherwise. /// \param NumberOfParts Number of parts in untied task. Ignored for tied /// tasks. /// llvm::Function *emitTaskOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, const VarDecl *PartIDVar, const VarDecl *TaskTVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool Tied, unsigned &NumberOfParts) override; /// Emits code for parallel or serial call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) override; /// Emits a critical region. /// \param CriticalName Name of the critical region. /// \param CriticalOpGen Generator for the statement associated with the given /// critical region. /// \param Hint Value of the 'hint' clause (optional). void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint = nullptr) override; /// Emits a master region. /// \param MasterOpGen Generator for the statement associated with the given /// master region. void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc) override; /// Emits a masked region. /// \param MaskedOpGen Generator for the statement associated with the given /// masked region. void emitMaskedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MaskedOpGen, SourceLocation Loc, const Expr *Filter = nullptr) override; /// Emits a masked region. /// \param MaskedOpGen Generator for the statement associated with the given /// masked region. /// Emits code for a taskyield directive. void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override; /// Emit a taskgroup region. /// \param TaskgroupOpGen Generator for the statement associated with the /// given taskgroup region. void emitTaskgroupRegion(CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, SourceLocation Loc) override; /// Emits a single region. /// \param SingleOpGen Generator for the statement associated with the given /// single region. void emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) override; /// Emit an ordered region. /// \param OrderedOpGen Generator for the statement associated with the given /// ordered region. void emitOrderedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &OrderedOpGen, SourceLocation Loc, bool IsThreads) override; /// Emit an implicit/explicit barrier for OpenMP threads. /// \param Kind Directive for which this implicit barrier call must be /// generated. Must be OMPD_barrier for explicit barrier generation. /// \param EmitChecks true if need to emit checks for cancellation barriers. /// \param ForceSimpleCall true simple barrier call must be emitted, false if /// runtime class decides which one to emit (simple or with cancellation /// checks). /// void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks = true, bool ForceSimpleCall = false) override; /// This is used for non static scheduled types and when the ordered /// clause is present on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds \a LB and \a UB and stride \a ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param Ordered true if loop is ordered, false otherwise. /// \param DispatchValues struct containing llvm values for lower bound, upper /// bound, and chunk expression. /// For the default (nullptr) value, the chunk 1 will be used. /// void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues) override; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// /// This is used only in case of static schedule, when the user did not /// specify a ordered clause on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds LB and UB and stride ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param Values Input arguments for the construct. /// void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) override; /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. /// \param Values Input arguments for the construct. /// void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) override; /// Call the appropriate runtime routine to notify that we finished /// iteration of the ordered loop with the dynamic scheduling. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned) override; /// Call the appropriate runtime routine to notify that we finished /// all the work with current loop. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive for which the static finish is emitted. /// void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind) override; /// Call __kmpc_dispatch_next( /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, /// kmp_int[32|64] *p_stride); /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param IL Address of the output variable in which the flag of the /// last iteration is returned. /// \param LB Address of the output variable in which the lower iteration /// number is returned. /// \param UB Address of the output variable in which the upper iteration /// number is returned. /// \param ST Address of the output variable in which the stride value is /// returned. llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST) override; /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' /// clause. /// \param NumThreads An integer value of threads. void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc) override; /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc) override; /// Returns address of the threadprivate variable for the current /// thread. /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of the reference to threadprivate var. /// \return Address of the threadprivate variable for the current thread. Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc) override; /// Emit a code for initialization of threadprivate variable. It emits /// a call to runtime library which adds initial value to the newly created /// threadprivate variable (if it is not constant) and registers destructor /// for the variable (if any). /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of threadprivate declaration. /// \param PerformInit true if initialization expression is not constant. llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF = nullptr) override; /// Creates artificial threadprivate variable with name \p Name and type \p /// VarType. /// \param VarType Type of the artificial threadprivate variable. /// \param Name Name of the artificial threadprivate variable. Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, QualType VarType, StringRef Name) override; /// Emit flush of the variables specified in 'omp flush' directive. /// \param Vars List of variables to flush. void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, SourceLocation Loc, llvm::AtomicOrdering AO) override; /// Emit task region for the task directive. The task region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, /// kmp_task_t *new_task), where new_task is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data) override; /// Emit task region for the taskloop directive. The taskloop region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task /// is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data) override; /// Emit a code for reduction clause. Next code should be emitted for /// reduction: /// \code /// /// static kmp_critical_name lock = { 0 }; /// /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { /// ... /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); /// ... /// } /// /// ... /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), /// RedList, reduce_func, &<lock>)) { /// case 1: /// ... /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); /// ... /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); /// break; /// case 2: /// ... /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); /// ... /// break; /// default:; /// } /// \endcode /// /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. /// \param Options List of options for reduction codegen: /// WithNowait true if parent directive has also nowait clause, false /// otherwise. /// SimpleReduction Emit reduction operation only. Used for omp simd /// directive on the host. /// ReductionKind The kind of reduction to perform. void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) override; /// Emit a code for initialization of task reduction clause. Next code /// should be emitted for reduction: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); /// \endcode /// For reduction clause with task modifier it emits the next call: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, /// red_data); /// \endcode /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. /// \param Data Additional data for task generation like tiedness, final /// state, list of privates, reductions etc. llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) override; /// Emits the following code for reduction clause with task modifier: /// \code /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); /// \endcode void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, bool IsWorksharingReduction) override; /// Required to resolve existing problems in the runtime. Emits threadprivate /// variables to store the size of the VLAs/array sections for /// initializer/combiner/finalizer functions + emits threadprivate variable to /// store the pointer to the original reduction item for the custom /// initializer defined by declare reduction construct. /// \param RCG Allows to reuse an existing data for the reductions. /// \param N Reduction item for which fixups must be emitted. void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N) override; /// Get the address of `void *` type of the privatue copy of the reduction /// item specified by the \p SharedLVal. /// \param ReductionsPtr Pointer to the reduction data returned by the /// emitTaskReductionInit function. /// \param SharedLVal Address of the original reduction item. Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal) override; /// Emit code for 'taskwait' directive. void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc) override; /// Emit code for 'cancellation point' construct. /// \param CancelRegion Region kind for which the cancellation point must be /// emitted. /// void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind CancelRegion) override; /// Emit code for 'cancel' construct. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param CancelRegion Region kind for which the cancel must be emitted. /// void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, const Expr *IfCond, OpenMPDirectiveKind CancelRegion) override; /// Emit outilined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Code generation sequence for the \a D directive. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) override; /// Emit the target offloading code associated with \a D. The emitted /// code attempts offloading the execution to the device, an the event of /// a failure it executes the host version outlined in \a OutlinedFn. /// \param D Directive to emit. /// \param OutlinedFn Host version of the code to be offloaded. /// \param OutlinedFnID ID of host version of the code to be offloaded. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used and device modifier. void emitTargetCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter) override; /// Emit the target regions enclosed in \a GD function definition or /// the function itself in case it is a valid device function. Returns true if /// \a GD was dealt with successfully. /// \param GD Function to scan. bool emitTargetFunctions(GlobalDecl GD) override; /// Emit the global variable if it is a valid device global variable. /// Returns true if \a GD was dealt with successfully. /// \param GD Variable declaration to emit. bool emitTargetGlobalVariable(GlobalDecl GD) override; /// Emit the global \a GD if it is meaningful for the target. Returns /// if it was emitted successfully. /// \param GD Global to scan. bool emitTargetGlobal(GlobalDecl GD) override; /// Emits code for teams call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run by team masters. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars) override; /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code /// for num_teams clause. /// \param NumTeams An integer expression of teams. /// \param ThreadLimit An integer expression of threads. void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc) override; /// Emit the target data mapping code associated with \a D. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the /// target directive, or null if no device clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. /// \param Info A record used to store information that needs to be preserved /// until the region is closed. void emitTargetDataCalls(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) override; /// Emit the data mapping/movement code associated with the directive /// \a D that should be of the form 'target [{enter|exit} data | update]'. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. void emitTargetDataStandAloneCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device) override; /// Emit initialization for doacross loop nesting support. /// \param D Loop-based construct used in doacross nesting construct. void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef<Expr *> NumIterations) override; /// Emit code for doacross ordered directive with 'depend' clause. /// \param C 'depend' clause with 'sink|source' dependency kind. void emitDoacrossOrdered(CodeGenFunction &CGF, const OMPDependClause *C) override; /// Translates the native parameter of outlined function if this is required /// for target. /// \param FD Field decl from captured record for the parameter. /// \param NativeParam Parameter itself. const VarDecl *translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const override; /// Gets the address of the native argument basing on the address of the /// target-specific parameter. /// \param NativeParam Parameter itself. /// \param TargetParam Corresponding target-specific parameter. Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const override; /// Gets the OpenMP-specific address of the local variable. Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD) override { return Address::invalid(); } }; } // namespace CodeGen } // namespace clang #endif
wem.c
#include "seismic.h" #include "wem.h" void wem(float **d, float **m, float **wav, int nt, float ot, float dt, int nmx,float omx, float dmx, int nmy,float omy, float dmy, float sx,float sy, int nz, float oz, float dz, float gz, float sz, float **vel, int nref, float fmin, float fmax, int padt, int padx, bool adj, bool pspi, bool verbose) /*< wave equation depth migration operator. Can specify different velocities for src and rec side wavefields. >*/ { int iz,ix,imx,imy,igx,igy,ik,iw,it,nw,nkx,nky,ntfft; float dw,dkx,dky,w; int ifmin,ifmax; float *d_t; complex *d_w,**d_g_wx,**d_s_wx; fftwf_complex *a,*b; int *n; fftwf_plan p1,p2; float *po,**pd; float progress; int ithread,nthread; float **m_threads; /* decompose slowness into layer average, and layer purturbation */ po = alloc1float(nz); pd = alloc2float(nz,nmx*nmy); for (iz=0;iz<nz;iz++){ po[iz] = 0.; for (ix=0;ix<nmx*nmy;ix++) po[iz] += vel[ix][iz]; po[iz] /= (float) nmx*nmy; po[iz] = 1./po[iz]; for (ix=0;ix<nmx*nmy;ix++) pd[ix][iz] = 1.0/vel[ix][iz] - po[iz]; } /****************************************************************************************/ float **vref,vmin,vmax,v; int **iref1,**iref2; int iref; /* generate reference velocities for each depth step */ vref = alloc2float(nz,nref); /* reference velocities for each layer */ iref1 = alloc2int(nz,nmx*nmy); /* index of nearest lower reference velocity for each subsurface point */ iref2 = alloc2int(nz,nmx*nmy); /* index of nearest upper reference velocity for each subsurface point */ for (iz=0;iz<nz;iz++){ vmin=vel[0][iz]; for (ix=0;ix<nmx;ix++) if (vel[ix][iz] < vmin) vmin = vel[ix][iz]; vmax=vel[nmx-1][iz]; for (ix=0;ix<nmx*nmy;ix++) if (vel[ix][iz] > vmax) vmax = vel[ix][iz]; for (iref=0;iref<nref;iref++) vref[iref][iz] = vmin + (float) iref*(vmax-vmin)/((float) nref-1); for (ix=0;ix<nmx*nmy;ix++){ v = vel[ix][iz]; if (vmax>vmin+10){ iref = (int) (nref-1)*(v-vmin)/(vmax-vmin); iref1[ix][iz] = iref; iref2[ix][iz] = iref+1; if (iref>nref-2){ iref1[ix][iz] = nref-1; iref2[ix][iz] = nref-1; } } else{ iref1[ix][iz] = 0; iref2[ix][iz] = 0; } } } /****************************************************************************************/ if (adj){ for (ix=0;ix<nmx*nmy;ix++) for (iz=0;iz<nz;iz++) m[ix][iz] = 0.; } else{ for (ix=0;ix<nmx*nmy;ix++) for (it=0;it<nt;it++) d[ix][it] = 0.; } ntfft = (int) 2*padt*((float) nt)/2; nw = (int) ntfft/2 + 1; nkx = nmx > 1 ? padx*nmx : 1; nky = nmy > 1 ? padx*nmy : 1; dkx = 2*PI/((float) nkx)/dmx; dky = 2*PI/((float) nky)/dmy; dw = 2*PI/((float) ntfft)/dt; if(fmax*dt*ntfft+1<nw) ifmax = (int) fmax*dt*ntfft + 1; else ifmax = nw; if(fmin*dt*ntfft+1<ifmax) ifmin = (int) fmin*dt*ntfft; else ifmin = 0; d_g_wx = alloc2complex(nw,nmx*nmy); d_s_wx = alloc2complex(nw,nmx*nmy); d_t = alloc1float(nt); d_w = alloc1complex(nw); for (it=0;it<nt;it++) d_t[it] = 0.; for (iw=0;iw<nw;iw++) d_w[iw] = 0.; /* set up fftw plans and pass them to the OMP region of the code */ a = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); b = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); n = alloc1int(2); n[0] = nkx; n[1] = nky; p1 = fftwf_plan_dft(2, n, a, a, FFTW_FORWARD, FFTW_ESTIMATE); p2 = fftwf_plan_dft(2, n, b, b, FFTW_BACKWARD, FFTW_ESTIMATE); for (ik=0;ik<nkx*nky;ik++){ a[ik] = 0.; b[ik] = 0.; } fftwf_execute_dft(p1,a,a); fftwf_execute_dft(p2,b,b); /**********************************************************************/ igx = (int) (sx - omx)/dmx; /*position to inject source in x-dir*/ igy = (int) (sy - omy)/dmy; /*position to inject source in y-dir*/ /* source wavefield*/ for (ix=0;ix<nmx*nmy;ix++) for (iw=0;iw<nw;iw++) d_s_wx[ix][iw] = 0.; for (it=0;it<nt;it++) d_t[it] = wav[0][it]; f_op(d_w,d_t,nw,nt,1); /* d_t to d_w */ for (iw=0;iw<nw;iw++) d_s_wx[igx*nmy + igy][iw] = d_w[iw]; /* receiver wavefield*/ if (adj){ for (ix=0;ix<nmx*nmy;ix++){ for (it=0;it<nt;it++) d_t[it] = d[ix][it]; f_op(d_w,d_t,nw,nt,1); /* d_t to d_w */ for (iw=0;iw<ifmin;iw++) d_g_wx[ix][iw] = 0.; for (iw=ifmin;iw<ifmax;iw++){ w = iw*dw; d_g_wx[ix][iw] = w*w*d_w[iw]; } for (iw=ifmax;iw<nw;iw++) d_g_wx[ix][iw] = 0.; } } else{ for (ix=0;ix<nmx*nmy;ix++){ for (iw=0;iw<nw;iw++){ d_g_wx[ix][iw] = 0.; } } } nthread = omp_thread_count(); if (adj){ m_threads = alloc2float(nz,nmx*nmy*nthread); for (imx=0;imx<nmx;imx++){ for (imy=0;imy<nmy;imy++){ for (ithread=0;ithread<nthread;ithread++){ for (iz=0;iz<nz;iz++){ m_threads[imx*nmy*nthread + imy*nthread + ithread][iz] = 0.; } } } } } else{ m_threads = alloc2float(nz,nmx*nmy); for (imx=0;imx<nmx;imx++){ for (imy=0;imy<nmy;imy++){ for (iz=0;iz<nz;iz++){ m_threads[imx*nmy + imy][iz] = m[imx*nmy + imy][iz]; } } } } progress = 0.; #pragma omp parallel for private(iw) shared(m_threads,d_g_wx,d_s_wx) for (iw=ifmin;iw<ifmax;iw++){ progress += 1./((float) ifmax - ifmin); if (verbose) progress_msg(progress); extrap1f(m_threads,d_g_wx,d_s_wx,iw,ifmax,nw,ifmax,ntfft,dw,dkx,dky,nkx,nky,nz,oz,dz,gz,sz,nmx,omx,dmx,nmy,omy,dmy,nthread,vel,po,pd,vref,iref1,iref2,nref,p1,p2,adj,pspi,verbose); } if (verbose) fprintf(stderr,"\n"); if (adj){ // reduction over parallel axis for (imx=0;imx<nmx;imx++) for (imy=0;imy<nmy;imy++) for (ithread=0;ithread<nthread;ithread++) for (iz=0;iz<nz;iz++) m[imx*nmy + imy][iz] += m_threads[imx*nmy*nthread + imy*nthread + ithread][iz]; } else{ for (ix=0;ix<nmx*nmy;ix++){ for (iw=0;iw<ifmin;iw++) d_w[iw] = 0.; for (iw=ifmin;iw<ifmax;iw++){ w = iw*dw; d_w[iw] = w*w*d_g_wx[ix][iw]; } for (iw=ifmax;iw<nw;iw++) d_w[iw] = 0.; f_op(d_w,d_t,nw,nt,0); /* d_w to d_t */ for (it=0;it<nt;it++) d[ix][it] = d_t[it]; } } free1int(n); fftwf_free(a); fftwf_free(b); fftwf_destroy_plan(p1); fftwf_destroy_plan(p2); free1float(d_t); free1complex(d_w); free2float(m_threads); free2complex(d_g_wx); free2complex(d_s_wx); free2float(vref); free2int(iref1); free2int(iref2); return; } void extrap1f(float **m,complex **d_g_wx, complex **d_s_wx, int iw, int ang_iw_max, int nw,int ifmax,int ntfft,float dw,float dkx,float dky,int nkx,int nky, int nz, float oz, float dz, float gz, float sz, int nmx,float omx, float dmx, int nmy,float omy, float dmy, int nthread, float **v,float *po,float **pd, float **vref, int **iref1, int **iref2, int nref, fftwf_plan p1,fftwf_plan p2, bool adj, bool pspi, bool verbose) /*< extrapolate 1 frequency >*/ { float w,factor,z; int iz,ix,imx,imy,ithread; complex *d_xg,*d_xs,**smig; ithread = omp_get_thread_num(); d_xg = alloc1complex(nmx*nmy); d_xs = alloc1complex(nmx*nmy); for (ix=0;ix<nmx*nmy;ix++) d_xg[ix] = 0.; for (ix=0;ix<nmx*nmy;ix++) d_xs[ix] = 0.; if (iw==0) factor = 1.; else factor = 2.; w = iw*dw; if (adj){ for (ix=0;ix<nmx*nmy;ix++){ d_xs[ix] = d_s_wx[ix][iw]/sqrtf((float) ntfft); d_xg[ix] = d_g_wx[ix][iw]/sqrtf((float) ntfft); } for (iz=0;iz<nz;iz++){ // extrapolate source and receiver wavefields z = oz + dz*iz; if (z >= sz){ if (pspi) pspiop(d_xs,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,-dz,iz,v,po,pd,vref,iref1,iref2,nref,p1,p2,true,true,verbose); else ssop(d_xs,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,-dz,iz,v,po,pd,p1,p2,true,true,verbose); } if (z >= gz){ if (pspi) pspiop(d_xg,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,dz,iz,v,po,pd,vref,iref1,iref2,nref,p1,p2,true,false,verbose); else ssop(d_xg,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,dz,iz,v,po,pd,p1,p2,true,false,verbose); for (imx=0;imx<nmx;imx++){ for (imy=0;imy<nmy;imy++){ m[imx*nmy*nthread + imy*nthread + ithread][iz] += factor*crealf(d_xg[imx*nmy + imy]*conjf(d_xs[imx*nmy + imy])); } } } } } else{ smig = alloc2complex(nz,nmx*nmy); for (ix=0;ix<nmx*nmy;ix++) d_xs[ix] = d_s_wx[ix][iw]/sqrtf((float) ntfft); for (iz=0;iz<nz;iz++){ // extrapolate source wavefield z = oz + dz*iz; if (z >= sz){ if (pspi) pspiop(d_xs,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,-dz,iz,v,po,pd,vref,iref1,iref2,nref,p1,p2,true,true,verbose); else ssop(d_xs,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,-dz,iz,v,po,pd,p1,p2,true,true,verbose); for (ix=0;ix<nmx*nmy;ix++) smig[ix][iz] = d_xs[ix]; } else{ for (ix=0;ix<nmx*nmy;ix++) smig[ix][iz] = 0.; } } for (ix=0;ix<nmx*nmy;ix++) d_xg[ix] = 0.; for (iz=nz-1;iz>=0;iz--){ // extrapolate receiver wavefield z = oz + dz*iz; if (z >= gz){ for (ix=0;ix<nmx*nmy;ix++){ d_xg[ix] += m[ix][iz]*smig[ix][iz]; } if (pspi) pspiop(d_xg,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,-dz,iz,v,po,pd,vref,iref1,iref2,nref,p1,p2,false,false,verbose); else ssop(d_xg,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,-dz,iz,v,po,pd,p1,p2,false,false,verbose); } } for (ix=0;ix<nmx*nmy;ix++){ d_g_wx[ix][iw] = d_xg[ix]/sqrtf((float) ntfft); } free2complex(smig); } free1complex(d_xs); free1complex(d_xg); return; } void ssop(complex *d_x, float w,float dkx,float dky,int nkx,int nky,int nmx,float omx,float dmx,int nmy,float omy,float dmy,float dz,int iz, float **v,float *po,float **pd, fftwf_plan p1,fftwf_plan p2, bool adj, bool src, bool verbose) { float kx,ky,s; complex L; int ik,ikx,iky,imx,imy; complex *d_k; fftwf_complex *a,*b; int lmx,lmy; if (nmx>100) lmx=30; else lmx=0; if (nmy>100) lmy=30; else lmy=0; a = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); b = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); d_k = alloc1complex(nkx*nky); if (adj){ for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy) a[imx*nky + imy] = d_x[imx*nmy + imy]; else a[imx*nky + imy] = 0.; } } } else{ boundary_condition(d_x,nmx,lmx,nmy,lmy); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy){ L = cexpf(I*w*pd[imx*nmy + imy][iz]*dz); a[imx*nky + imy] = d_x[imx*nmy + imy]*L; // SS operator } else a[imx*nky + imy] = 0.; } } } fftwf_execute_dft(p1,a,a); for (ikx=0;ikx<nkx;ikx++){ if (ikx<= (int) nkx/2) kx = (float) dkx*ikx; else kx = -((float) dkx*nkx - dkx*ikx); for (iky=0;iky<nky;iky++){ if (iky<= (int) nky/2) ky = (float) dky*iky; else ky = -((float) dky*nky - dky*iky); s = (w*w)*(po[iz]*po[iz]) - (kx*kx) - (ky*ky); if (s>=0) L = cexp(I*sqrtf(s)*dz); else L = cexp(-0.2*sqrtf(fabs(s))*fabs(dz)); d_k[ikx*nky + iky] = ((complex) a[ikx*nky + iky])*L/sqrtf((float) nkx*nky); } } for(ik=0; ik<nkx*nky;ik++) b[ik] = (fftwf_complex) d_k[ik]; fftwf_execute_dft(p2,b,b); if (adj){ for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy){ L = cexpf(I*w*pd[imx*nmy + imy][iz]*dz); d_x[imx*nmy + imy] = ((complex) b[imx*nky + imy])*L/sqrtf((float) nkx*nky); // SS operator } } } boundary_condition(d_x,nmx,lmx,nmy,lmy); } else{ for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy){ d_x[imx*nmy + imy] = ((complex) b[imx*nky + imy])/sqrtf((float) nkx*nky); } } } } free1complex(d_k); fftwf_free(a); fftwf_free(b); return; } void pspiop(complex *d_x, float w,float dkx,float dky,int nkx,int nky, int nmx,float omx,float dmx,int nmy,float omy,float dmy, float dz,int iz, float **vel,float *po,float **pd, float **vref, int **iref1, int **iref2, int nref, fftwf_plan p1,fftwf_plan p2, bool adj, bool src, bool verbose) { float kx,ky,s; complex L; int ik,ikx,iky,imx,imy; complex *d_k; fftwf_complex *a,*b; int lmx,lmy; complex **dref; int iref; float v,vref1,vref2; if (nmx>100) lmx=30; else lmx=0; if (nmy>100) lmy=30; else lmy=0; a = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); b = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); dref = alloc2complex(nref,nmx*nmy); d_k = alloc1complex(nkx*nky); if (adj){ for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy) a[imx*nky + imy] = d_x[imx*nmy + imy]; else a[imx*nky + imy] = 0.; } } } else{ // boundary_condition(d_x,nmx,lmx,nmy,lmy); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy) a[imx*nky + imy] = d_x[imx*nmy + imy]; else a[imx*nky + imy] = 0.; } } } fftwf_execute_dft(p1,a,a); for (iref=0;iref<nref;iref++){ for (ikx=0;ikx<nkx;ikx++){ if (ikx<= (int) nkx/2) kx = (float) dkx*ikx; else kx = -((float) dkx*nkx - dkx*ikx); for (iky=0;iky<nky;iky++){ if (iky<= (int) nky/2) ky = (float) dky*iky; else ky = -((float) dky*nky - dky*iky); s = (w*w)*(1/(vref[iref][iz]*vref[iref][iz])) - (kx*kx) - (ky*ky); if (s>=0) L = cexpf(I*sqrtf(s)*dz); else L = cexpf(-0.2*sqrtf(fabs(s))*fabs(dz)); d_k[ikx*nky + iky] = ((complex) a[ikx*nky + iky])*L/sqrtf((float) nkx*nky); } } for(ik=0; ik<nkx*nky;ik++) b[ik] = (fftwf_complex) d_k[ik]; fftwf_execute_dft(p2,b,b); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy){ dref[imx*nmy + imy][iref] = ((complex) b[imx*nky + imy])/sqrtf((float) nkx*nky); } } } } for (imx=0;imx<nmx*nmy;imx++){ v = vel[imx][iz]; vref1 = vref[iref1[imx][iz]][iz]; vref2 = vref[iref2[imx][iz]][iz]; if (vref2 - vref1 > 10.0){ d_x[imx] = linear_interp(dref[imx][iref1[imx][iz]],dref[imx][iref2[imx][iz]],vref1,vref2,v); } else{ d_x[imx] = dref[imx][iref1[imx][iz]]; } } //if (adj){ // boundary_condition(d_x,nmx,lmx,nmy,lmy); //} free1complex(d_k); fftwf_free(a); fftwf_free(b); free2complex(dref); return; } float linear_interp(complex y1,complex y2,float x1,float x2,float x) /*< linear interpolation between two points. x2-x1 must be nonzero. >*/ { //return y1 + (y2-y1)*(x-x1)/(x2-x1); return y1; } void f_op(complex *m,float *d,int nw,int nt,bool adj) { fftwf_complex *out1a,*in1b; float *in1a,*out1b; int ntfft,it,iw; fftwf_plan p1a,p1b; ntfft = (nw-1)*2; if (adj){ /* data --> model */ out1a = fftwf_malloc(sizeof(fftwf_complex) * nw); in1a = alloc1float(ntfft); p1a = fftwf_plan_dft_r2c_1d(ntfft, in1a, (fftwf_complex*)out1a, FFTW_ESTIMATE); for(it=0;it<nt;it++) in1a[it] = d[it]; for(it=nt;it<ntfft;it++) in1a[it] = 0.; fftwf_execute(p1a); for(iw=0;iw<nw;iw++) m[iw] = out1a[iw]; fftwf_destroy_plan(p1a); fftwf_free(in1a); fftwf_free(out1a); } else{ /* model --> data */ out1b = alloc1float(ntfft); in1b = fftwf_malloc(sizeof(fftwf_complex) * ntfft); p1b = fftwf_plan_dft_c2r_1d(ntfft, (fftwf_complex*)in1b, out1b, FFTW_ESTIMATE); for(iw=0;iw<nw;iw++) in1b[iw] = m[iw]; for(iw=nw;iw<ntfft;iw++) in1b[iw] = 0.; fftwf_execute(p1b); for(it=0;it<nt;it++) d[it] = out1b[it]; fftwf_destroy_plan(p1b); fftwf_free(in1b); fftwf_free(out1b); } return; } void progress_msg(float progress) { fprintf(stderr,"\r[%6.2f%% complete] ",progress*100); return; } float signf(float a) /*< sign of a float >*/ { float b; if (a>0.) b = 1.; else if (a<0.) b =-1.; else b = 0.; return b; } int compare (const void * a, const void * b) { float fa = *(const float*) a; float fb = *(const float*) b; return (fa > fb) - (fa < fb); } int omp_thread_count() { int n = 0; #pragma omp parallel reduction(+:n) n += 1; return n; } void boundary_condition(complex *d_x,int nmx,int lmx,int nmy,int lmy) { int imx,imy; float tmx,tmy; tmx = 1.;tmy = 1.; for (imx=0;imx<nmx;imx++){ if (imx>=0 && imx<lmx) tmx = expf(-powf(0.015*((float) lmx - imx),2.)); if (imx>=lmx && imx<=nmx-lmx) tmx = 1.; if (imx>nmx-lmx && imx<nmx) tmx = expf(-powf(0.015*((float) imx - nmx + lmx),2.)); for (imy=0;imy<nmy;imy++){ if (imy>=0 && imy<lmy) tmy = expf(-powf(0.015*((float) lmy - imy),2.)); if (imy>=lmy && imy<=nmy-lmy) tmy = 1.; if (imy>nmy-lmy && imy<nmy) tmy = expf(-powf(0.015*((float) imy - nmy + lmy),2.)); d_x[imx*nmy + imy] *= tmx*tmy; } } return; } void compute_angles(float **angx, float **angy, float **wav, int nt, float ot, float dt, int nmx,float omx, float dmx, int nmy,float omy, float dmy, float sx,float sy, int nz, float oz, float dz, float sz, float **vel_p, float fmin, float fmax, bool verbose) /*< source side incidence angle computation using the one way wave equation. >*/ { int iz,ix,igx,igy,ik,iw,it,nw,nkx,nky,nkz,ntfft; float dw,dkx,dky,dkz; int ifmin,ifmax; float *d_t; complex *d_w,**d_s_wx; fftwf_complex *a1,*b1; fftwf_complex *a2,*b2; int *n1,*n2; fftwf_plan p1,p2,p3,p4; float *po_p,**pd_p; float progress; float **angx_sign,**angy_sign; ntfft = nt; nw = (int) ntfft/2 + 1; nkx = nmx; nky = nmy; nkz = nz; dkx = 2*PI/((float) nkx)/dmx; dky = 2*PI/((float) nky)/dmy; dkz = 2*PI/((float) nkz)/dz; dw = 2*PI/((float) ntfft)/dt; if(fmax*dt*ntfft+1<nw) ifmax = (int) fmax*dt*ntfft + 1; else ifmax = nw; if(fmin*dt*ntfft+1<ifmax) ifmin = (int) fmin*dt*ntfft; else ifmin = 0; d_s_wx = alloc2complex(nw,nmx*nmy); d_t = alloc1float(nt); d_w = alloc1complex(nw); for (it=0;it<nt;it++) d_t[it] = 0.; for (iw=0;iw<nw;iw++) d_w[iw] = 0.; /* decompose slowness into layer average, and layer purturbation */ po_p = alloc1float(nz); pd_p = alloc2float(nz,nmx*nmy); for (iz=0;iz<nz;iz++){ po_p[iz] = 0.; for (ix=0;ix<nmx*nmy;ix++) po_p[iz] += vel_p[ix][iz]; po_p[iz] /= (float) nmx*nmy; po_p[iz] = 1./po_p[iz]; for (ix=0;ix<nmx*nmy;ix++) pd_p[ix][iz] = 1.0/vel_p[ix][iz] - po_p[iz]; } // set up fftw plans and pass them to the OMP region of the code // plan for extrapolation a1 = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); b1 = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); n1 = alloc1int(2); n1[0] = nkx; n1[1] = nky; p1 = fftwf_plan_dft(2, n1, a1, a1, FFTW_FORWARD, FFTW_ESTIMATE); p2 = fftwf_plan_dft(2, n1, b1, b1, FFTW_BACKWARD, FFTW_ESTIMATE); for (ik=0;ik<nkx*nky;ik++) a1[ik] = 0.; for (ik=0;ik<nkx*nky;ik++) b1[ik] = 0.; fftwf_execute_dft(p1,a1,a1); fftwf_execute_dft(p2,b1,b1); // plan for calculation of spatial derivatives a2 = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky*nkz); b2 = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky*nkz); n2 = alloc1int(3); n2[0] = nkx; n2[1] = nky; n2[2] = nz; p3 = fftwf_plan_dft(3, n2, a2, a2, FFTW_FORWARD, FFTW_ESTIMATE); p4 = fftwf_plan_dft(3, n2, b2, b2, FFTW_BACKWARD, FFTW_ESTIMATE); for (ik=0;ik<nkx*nky*nkz;ik++) a2[ik] = 0.; for (ik=0;ik<nkx*nky*nkz;ik++) b2[ik] = 0.; fftwf_execute_dft(p3,a2,a2); fftwf_execute_dft(p4,b2,b2); /**********************************************************************/ igx = (int) (sx - omx)/dmx; /*position to inject source in x-dir*/ igy = (int) (sy - omy)/dmy; /*position to inject source in y-dir*/ /* source wavefield*/ for (ix=0;ix<nmx*nmy;ix++) for (iw=0;iw<nw;iw++) d_s_wx[ix][iw] = 0.; for (it=0;it<nt;it++) d_t[it] = wav[0][it]; f_op(d_w,d_t,nw,nt,1); /* d_t to d_w */ for (iw=0;iw<nw;iw++) d_s_wx[igx*nmy + igy][iw] = d_w[iw]; angx_sign = alloc2float(nz,nmx*nmy); angy_sign = alloc2float(nz,nmx*nmy); for (iz=0;iz<nz;iz++) for (ix=0;ix<nmx*nmy;ix++) angx_sign[ix][iz] = 0.0; for (iz=0;iz<nz;iz++) for (ix=0;ix<nmx*nmy;ix++) angy_sign[ix][iz] = 0.0; progress = 0.; #pragma omp parallel for private(iw) shared(d_s_wx,angx,angy) for (iw=ifmin;iw<ifmax;iw++){ progress += 1./((float) ifmax - ifmin); if (verbose) progress_msg(progress); extrapolate_source(d_s_wx,angx,angy,angx_sign,angy_sign, iw,nw,ifmin,ifmax,ntfft,dw, dkx,nkx,nmx,omx,dmx, dky,nky,nmy,omy,dmy, dkz,nkz,nz,oz,dz, sz, vel_p,po_p,pd_p, p1,p2,p3,p4,verbose); } if (verbose) fprintf(stderr,"\n"); for (iz=0;iz<nz;iz++) for (ix=0;ix<nmx*nmy;ix++) angx[ix][iz] *= signf1(angx_sign[ix][iz])/(float) (ifmax - ifmin + 1); for (iz=0;iz<nz;iz++) for (ix=0;ix<nmx*nmy;ix++) angy[ix][iz] *= signf1(angy_sign[ix][iz])/(float) (ifmax - ifmin + 1); free1int(n1); fftwf_free(a1); fftwf_free(b1); free1int(n2); fftwf_free(a2); fftwf_free(b2); fftwf_destroy_plan(p1); fftwf_destroy_plan(p2); fftwf_destroy_plan(p3); fftwf_destroy_plan(p4); free1float(d_t); free1complex(d_w); free2complex(d_s_wx); free1float(po_p); free2float(pd_p); free2float(angx_sign); free2float(angy_sign); return; } void extrapolate_source(complex **d_s_wx, float **angx, float **angy, float **angx_sign, float **angy_sign, int iw,int nw,int ifmin,int ifmax,int ntfft,float dw, float dkx,int nkx,int nmx,float omx,float dmx, float dky,int nky,int nmy,float omy,float dmy, float dkz,int nkz,int nz,float oz,float dz, float sz, float **v_p,float *po_p,float **pd_p, fftwf_plan p1,fftwf_plan p2,fftwf_plan p3,fftwf_plan p4, bool verbose) /*< extrapolate 1 frequency >*/ { float w,z; int iz,ix,imx,imy; complex *d_xs,*u_s,*u_sx,*u_sy,*u_sz; float *u_s_signx,*u_s_signy; d_xs = alloc1complex(nmx*nmy); u_s = alloc1complex(nmx*nmy*nz); for (ix=0;ix<nmx*nmy*nz;ix++) u_s[ix] = 0.; for (ix=0;ix<nmx*nmy;ix++) d_xs[ix] = 0.; w = iw*dw; for (ix=0;ix<nmx*nmy;ix++) d_xs[ix] = d_s_wx[ix][iw]/sqrtf((float) ntfft); for (iz=0;iz<nz;iz++){ // extrapolate source wavefield z = oz + dz*iz; if (z >= sz){ ssop_source(d_xs,w,dkx,dky,nkx,nky,nmx,omx,dmx,nmy,omy,dmy,-dz,iz,v_p,po_p,pd_p,p1,p2,verbose); for (imx=0;imx<nmx;imx++) for (imy=0;imy<nmy;imy++) u_s[imx*nmy*nz + imy*nz + iz] = d_xs[imx*nmy + imy]; } } u_sx = alloc1complex(nmx*nmy*nz); u_sy = alloc1complex(nmx*nmy*nz); u_sz = alloc1complex(nmx*nmy*nz); u_s_signx = alloc1float(nmx*nmy*nz); u_s_signy = alloc1float(nmx*nmy*nz); for (ix=0;ix<nmx*nmy*nz;ix++) u_sx[ix] = 0.; for (ix=0;ix<nmx*nmy*nz;ix++) u_sy[ix] = 0.; for (ix=0;ix<nmx*nmy*nz;ix++) u_sz[ix] = 0.; for (ix=0;ix<nmx*nmy*nz;ix++) u_s_signx[ix] = 1.; for (ix=0;ix<nmx*nmy*nz;ix++) u_s_signy[ix] = 1.; calculate_derivatives(u_s,u_sx,u_sy,u_sz,u_s_signx,u_s_signy,dkx,nkx,nmx,omx,dmx,dky,nky,nmy,omy,dmy,dkz,nkz,nz,oz,dz,p3,p4); for(imx=0;imx<nmx;imx++){ for(imy=0;imy<nmy;imy++){ for(iz=0;iz<nz;iz++){ angx_sign[imx*nmy + imy][iz] += u_s_signx[imx*nmy*nz + imy*nz + iz]/ (float) nw; angy_sign[imx*nmy + imy][iz] += u_s_signy[imx*nmy*nz + imy*nz + iz]/ (float) nw; } } } for(imx=0;imx<nmx;imx++){ for(imy=0;imy<nmy;imy++){ for(iz=0;iz<nz;iz++){ angx[imx*nmy + imy][iz] += (180/PI)*atanf(cabs(u_sx[imx*nmy*nz + imy*nz + iz])/(cabs(u_sz[imx*nmy*nz + imy*nz + iz]) + 1e-10)); angy[imx*nmy + imy][iz] += (180/PI)*atanf(cabs(u_sy[imx*nmy*nz + imy*nz + iz])/(cabs(u_sz[imx*nmy*nz + imy*nz + iz]) + 1e-10)); } } } free1complex(d_xs); free1complex(u_s); free1complex(u_sx); free1complex(u_sy); free1complex(u_sz); free1float(u_s_signx); free1float(u_s_signy); return; } void ssop_source(complex *d_x, float w,float dkx,float dky,int nkx,int nky,int nmx,float omx,float dmx,int nmy,float omy,float dmy,float dz,int iz, float **v,float *po,float **pd, fftwf_plan p1,fftwf_plan p2, bool verbose) { float kx,ky,s; complex L; int ik,ikx,iky,imx,imy; complex *d_k; fftwf_complex *a,*b; int lmx,lmy; if (nmx>100) lmx=30; else lmx=0; if (nmy>100) lmy=30; else lmy=0; a = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); b = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky); d_k = alloc1complex(nkx*nky); boundary_condition(d_x,nmx,lmx,nmy,lmy); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy){ L = cexpf(I*w*pd[imx*nmy + imy][iz]*dz); a[imx*nky + imy] = d_x[imx*nmy + imy]*L; // SS operator } else a[imx*nky + imy] = 0.; } } fftwf_execute_dft(p1,a,a); for (ikx=0;ikx<nkx;ikx++){ if (ikx<= (int) nkx/2) kx = (float) dkx*ikx; else kx = -((float) dkx*nkx - dkx*ikx); for (iky=0;iky<nky;iky++){ if (iky<= (int) nky/2) ky = (float) dky*iky; else ky = -((float) dky*nky - dky*iky); s = (w*w)*(po[iz]*po[iz]) - (kx*kx) - (ky*ky); if (s>=0) L = cexpf(I*sqrtf(s)*dz); else L = cexpf(-0.2*sqrtf(fabs(s))*fabs(dz)); d_k[ikx*nky + iky] = ((complex) a[ikx*nky + iky])*L/sqrtf((float) nkx*nky); } } for(ik=0; ik<nkx*nky;ik++) b[ik] = (fftwf_complex) d_k[ik]; fftwf_execute_dft(p2,b,b); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ if (imx < nmx && imy < nmy){ d_x[imx*nmy + imy] = ((complex) b[imx*nky + imy])/sqrtf((float) nkx*nky); } } } free1complex(d_k); fftwf_free(a); fftwf_free(b); return; } void calculate_derivatives(complex *u_s, complex *u_sx, complex *u_sy, complex *u_sz, float *u_s_signx, float *u_s_signy, float dkx, int nkx, int nmx, float omx, float dmx, float dky, int nky, int nmy, float omy, float dmy, float dkz, int nkz, int nz, float oz, float dz, fftwf_plan p3,fftwf_plan p4) /*< calculate spatial derivatives of the source wavefield >*/ { fftwf_complex *a,*b,*u_left,*u_right; int imx,imy,iz; float kx,ky,kz,kx_left,kx_right,ky_left,ky_right; /* set up fftw plans */ a = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky*nkz); b = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky*nkz); u_left = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky*nkz); u_right = fftwf_malloc(sizeof(fftwf_complex) * nkx*nky*nkz); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ for(iz=0; iz<nkz;iz++){ if (imx < nmx && imy < nmy && iz < nz){ a[imx*nky*nkz + imy*nkz + iz] = u_s[imx*nmy*nz + imy*nz + iz]; } else a[imx*nky*nkz + imy*nkz + iz] = 0.; } } } fftwf_execute_dft(p3,a,a); // x component for(imx=0;imx<nmx;imx++){ if (imx<= (int) nkx/2) kx = (float) dkx*imx; else kx = -((float) dkx*nkx - dkx*imx); for(imy=0;imy<nky;imy++){ for(iz=0;iz<nkz;iz++){ b[imx*nky*nkz + imy*nkz + iz] = I*kx*a[imx*nky*nkz + imy*nkz + iz]; } } } fftwf_execute_dft(p4,b,b); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ for(iz=0; iz<nkz;iz++){ if (imx < nmx && imy < nmy && iz < nz){ u_sx[imx*nmy*nz + imy*nz + iz] = b[imx*nky*nkz + imy*nkz + iz]/((float) nkx*nky*nkz); } } } } // y component for(imx=0;imx<nmx;imx++){ for(imy=0;imy<nky;imy++){ if (imy<= (int) nky/2) ky = (float) dky*imy; else ky = -((float) dky*nky - dky*imy); for(iz=0;iz<nkz;iz++){ b[imx*nky*nkz + imy*nkz + iz] = I*ky*a[imx*nky*nkz + imy*nkz + iz]; } } } fftwf_execute_dft(p4,b,b); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ for(iz=0; iz<nkz;iz++){ if (imx < nmx && imy < nmy && iz < nz){ u_sy[imx*nmy*nz + imy*nz + iz] = b[imx*nky*nkz + imy*nkz + iz]/((float) nkx*nky*nkz); } } } } // z component for(imx=0;imx<nmx;imx++){ for(imy=0;imy<nky;imy++){ for(iz=0;iz<nkz;iz++){ if (iz<= (int) nkz/2) kz = (float) dkz*iz; else kz = -((float) dkz*nkz - dkz*iz); b[imx*nky*nkz + imy*nkz + iz] = I*kz*a[imx*nky*nkz + imy*nkz + iz]; } } } fftwf_execute_dft(p4,b,b); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ for(iz=0; iz<nkz;iz++){ if (imx < nmx && imy < nmy && iz < nz){ u_sz[imx*nmy*nz + imy*nz + iz] = b[imx*nky*nkz + imy*nkz + iz]/((float) nkx*nky*nkz); } } } } // sign for x direction for(imx=0;imx<nmx;imx++){ if (imx<= (int) nkx/2) kx_left = 0.; else kx_left = -((float) dkx*nkx - dkx*imx); if (imx<= (int) nkx/2) kx_right = (float) dkx*imx; else kx_right = 0.; for(imy=0;imy<nky;imy++){ for(iz=0;iz<nkz;iz++){ u_left[imx*nky*nkz + imy*nkz + iz] = I*kx_left*a[imx*nky*nkz + imy*nkz + iz]; u_right[imx*nky*nkz + imy*nkz + iz] = I*kx_right*a[imx*nky*nkz + imy*nkz + iz]; } } } fftwf_execute_dft(p4,u_left,u_left); fftwf_execute_dft(p4,u_right,u_right); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ for(iz=0; iz<nkz;iz++){ if (imx < nmx && imy < nmy && iz < nz){ if (cabs(u_left[imx*nky*nkz + imy*nkz + iz]) >= cabs(u_right[imx*nky*nkz + imy*nkz + iz])){ u_s_signx[imx*nmy*nz + imy*nz + iz] = 1.*cabs(u_s[imx*nmy*nz + imy*nz + iz]); } else{ u_s_signx[imx*nmy*nz + imy*nz + iz] = -1.*cabs(u_s[imx*nmy*nz + imy*nz + iz]); } } } } } // sign for y direction for(imx=0;imx<nmx;imx++){ for(imy=0;imy<nky;imy++){ if (imy<= (int) nky/2) ky_left = 0.; else ky_left = -((float) dky*nky - dky*imy); if (imy<= (int) nky/2) ky_right = (float) dky*imy; else ky_right = 0.; for(iz=0;iz<nkz;iz++){ u_left[imx*nky*nkz + imy*nkz + iz] = I*ky_left*a[imx*nky*nkz + imy*nkz + iz]; u_right[imx*nky*nkz + imy*nkz + iz] = I*ky_right*a[imx*nky*nkz + imy*nkz + iz]; } } } fftwf_execute_dft(p4,u_left,u_left); fftwf_execute_dft(p4,u_right,u_right); for(imx=0; imx<nkx;imx++){ for(imy=0; imy<nky;imy++){ for(iz=0; iz<nkz;iz++){ if (imx < nmx && imy < nmy && iz < nz){ if (cabs(u_left[imx*nky*nkz + imy*nkz + iz]) >= cabs(u_right[imx*nky*nkz + imy*nkz + iz])){ u_s_signy[imx*nmy*nz + imy*nz + iz] = 1.*cabs(u_s[imx*nmy*nz + imy*nz + iz]); } else{ u_s_signy[imx*nmy*nz + imy*nz + iz] = -1.*cabs(u_s[imx*nmy*nz + imy*nz + iz]); } } } } } fftwf_free(a); fftwf_free(b); fftwf_free(u_left); fftwf_free(u_right); return; } float signf1(float a) /*< sign of a float, always has an amplitude of 1 >*/ { float b; if (a>=0.) b = 1.; else b =-1.; return b; }
GB_unop__floor_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__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) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_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 *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_cfloor (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = 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 *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Board.c
#include <malloc.h> #include <math.h> #include <mkl.h> #include <string.h> #include <assert.h> #include "Board.h" /* Readability macros */ /** * Update the state of a cell given its current state and its current number of neighbours * @param b (Initialized) board to update * @param x X-coordinate of the cell to update * @param y Y-coordinate of the cell to update */ #define update_state(b, x, y)\ b->arr[(x) * b->ld + (y)] = STATE_CHANGES[(int)(b->arr[(x) * b->ld + (y)] * 9 + b->nbNgbs[(x) * b->Ny + (y)])] /** * Copy the state of a source cell in a destination cell * @param b (Initialized) board to update * @param xDst X-coordinate of the destination cell * @param yDst Y-coordinate of the destination cell * @param xSrc X-coordinate of the source cell * @param ySrc Y-coordinate of the source cell */ #define copy_state(b, xDst, yDst, xSrc, ySrc)\ b->arr[(xDst) * b->ld + (yDst)] = b->arr[(xSrc) * b->ld + (ySrc)] /* Public definitions */ void init_board(Board *b, int Nx, int Ny) { b->Nx = Nx; b->Ny = Ny; b->ld = b->Ny + 2; b->arr = (float *) calloc((size_t) b->ld * b->ld, sizeof(float)); assert(b->arr != NULL); b->arr = b->arr + b->ld + 1; b->nbNgbs = (float *) calloc((size_t) b->Ny * b->Ny, sizeof(float)); assert(b->nbNgbs != NULL); } void set_col(Board *b, int x, int val) { for (int y = -1; y <= b->Ny; y++) b->arr[x * b->ld + y] = val; } void set_row(Board *b, int y, int val) { for (int x = -1; x <= b->Nx; x++) b->arr[x * b->ld + y] = val; } void count_neighbours_col(Board *b, int x) { vsAdd(b->Ny, &(b->arr[x * b->ld - 1]), &(b->arr[x * b->ld + 1]), &(b->nbNgbs[x * b->Ny])); // top and bottom neighbours cblas_saxpy(b->Ny, 1, &(b->arr[(x-1) * b->ld - 1]), 1, &(b->nbNgbs[x * b->Ny]), 1); // top left neighbours cblas_saxpy(b->Ny, 1, &(b->arr[(x-1) * b->ld]), 1, &(b->nbNgbs[x * b->Ny]), 1); // left neighbours cblas_saxpy(b->Ny, 1, &(b->arr[(x-1) * b->ld + 1]), 1, &(b->nbNgbs[x * b->Ny]), 1); // bottom left neighbours cblas_saxpy(b->Ny, 1, &(b->arr[(x+1) * b->ld - 1]), 1, &(b->nbNgbs[x * b->Ny]), 1); // top left neighbours cblas_saxpy(b->Ny, 1, &(b->arr[(x+1) * b->ld]), 1, &(b->nbNgbs[x * b->Ny]), 1); // left neighbours cblas_saxpy(b->Ny, 1, &(b->arr[(x+1) * b->ld + 1]), 1, &(b->nbNgbs[x * b->Ny]), 1); // bottom left neighbours } void update_state_col(Board *b, int x) { for (int y = 0; y < b->Ny; y++) update_state(b, x, y); copy_state(b, x, -1 , x, b->Ny - 1); // top ghost cell copy_state(b, x, b->Ny, x, 0 ); // bottom ghost cell } void copy_state_col(Board *b, int xDst, int xSrc) { memcpy(&(b->arr[xDst * b->ld - 1]), &(b->arr[xSrc *b->ld - 1]), b->ld * sizeof(float)); } void count_neighbours_block_col(Board *b, int xStart, int xStop, int blockSize) { int y; for (y = 0; y + blockSize <= b->Ny; y += blockSize) { #pragma omp for schedule(static) for (int x = xStart; x < xStop; x++) { vsAdd(blockSize, &(b->arr[x * b->ld + (y-1)]), &(b->arr[x * b->ld + (y+1)]), &(b->nbNgbs[x * b->Ny + y])); // top and bottom neighbours cblas_saxpy(blockSize, 1, &(b->arr[(x-1) * b->ld + (y-1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // top left neighbours cblas_saxpy(blockSize, 1, &(b->arr[(x-1) * b->ld + y ]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // left neighbours cblas_saxpy(blockSize, 1, &(b->arr[(x-1) * b->ld + (y+1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // bottom left neighbours cblas_saxpy(blockSize, 1, &(b->arr[(x+1) * b->ld + (y-1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // top left neighbours cblas_saxpy(blockSize, 1, &(b->arr[(x+1) * b->ld + y ]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // left neighbours cblas_saxpy(blockSize, 1, &(b->arr[(x+1) * b->ld + (y+1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // bottom left neighbours } } int left = b->Ny - y; if (left > 0) { #pragma omp for schedule(static) for (int x = xStart; x < xStop; x++) { vsAdd(left, &(b->arr[x * b->ld + (y - 1)]), &(b->arr[x * b->ld + (y + 1)]), &(b->nbNgbs[x * b->Ny + y])); // top and bottom neighbours cblas_saxpy(left, 1, &(b->arr[(x-1) * b->ld + (y-1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // top left neighbours cblas_saxpy(left, 1, &(b->arr[(x-1) * b->ld + y]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // left neighbours cblas_saxpy(left, 1, &(b->arr[(x-1) * b->ld + (y+1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // bottom left neighbours cblas_saxpy(left, 1, &(b->arr[(x+1) * b->ld + (y-1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // top left neighbours cblas_saxpy(left, 1, &(b->arr[(x+1) * b->ld + y]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // left neighbours cblas_saxpy(left, 1, &(b->arr[(x+1) * b->ld + (y+1)]), 1, &(b->nbNgbs[x * b->Ny + y]), 1); // bottom left neighbours } } } void update_state_block_col(Board *b, int xStart, int xStop) { #pragma omp for schedule(static) for (int x = xStart; x < xStop; x++) update_state_col(b, x); } int compare_boards_block_col(Board *b1, int xStart1, int xStop1, Board *b2, int xStart2, int xStop2) { if ((b1->Ny != b2->Ny) || ((xStop1-xStart1) != (xStop2-xStart2))) return 0; for (int x = 0; x < (xStop1 - xStart1); x++) for (int y = 0; y < b1->Ny; y++) if (fabsf(b1->arr[(xStart1 + x) * b1->ld + y] - b2->arr[(xStart2 + x) * b2->ld + y]) > 0.5) return 0; return 1; } void output_board(FILE *stream, Board *b) { for (int y = -1; y <= b->Ny; y++) { for (int x = -1; x <= b->Nx; x++) fprintf(stream, b->arr[x * b->ld + y] > 0.5 ? "X" : "."); fprintf(stream, "\n"); } } void free_board(Board *b) { free(b->nbNgbs); b->arr = b->arr - b->ld - 1; free(b->arr); }
enpass_fmt_plug.c
/* JtR format to crack Enpass Password Manager databases. * * This software is Copyright (c) 2017, Dhiru Kholia <dhiru at openwall.com>, * and it is hereby released to the general public under the following terms: * * Redistribution and use in source and binary forms, with or without modification, * are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_enpass; #elif FMT_REGISTERS_H john_register_one(&fmt_enpass); #else #include <string.h> #include <stdint.h> #include <assert.h> #include <errno.h> #include "aes.h" #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "johnswap.h" #include "enpass_common.h" #include "pbkdf2_hmac_sha1.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 4 // this is a slow format, so 4 should be enough #endif #endif #include "memdbg.h" #define FORMAT_LABEL "enpass" #define FORMAT_NAME "Enpass Password Manager" #define FORMAT_TAG "$enpass$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define BINARY_SIZE 0 #define PLAINTEXT_LENGTH 125 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN 1 #define SALT_ALIGN sizeof(unsigned int) #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define FILE_HEADER_SZ 16 #define SQLITE_FILE_HEADER "SQLite format 3" #define SQLITE_MAX_PAGE_SIZE 65536 static struct fmt_tests enpass_tests[] = { {"$enpass$0$24000$700dfb6d83ae3b4b87935ed8246123363656de4273979a1365197a632c6b1ce68ca801d0bb50d93c9a0509fbb061bba2ad579ed0d48ee781508c853b9bd042d3275cc92781770a211ecd08a254db873e50664a14b394d63e3e443a82d69c7df84c592a60b5b620e241c9675f097f931093f6ebf67f56e5db0d82eb61ff9da3636bf7c79598e6ee1f34b7abd2b1e5e3ae9e9a219de50d9c079fb7fb21910139468619c6ac562a4157c0e8e85df08b54aff33ec2005e2214549ba04d794882051e8e245f63f822d469c6588ccd38c02154f21cdfd06acd5ed1b97cbe7e23648ce70c471560222cd8927b0567cd0a3c317b7a8add994dc8fcda89ae4afc33c1260192e3c8c3ca9d50347a91a82025c1cb127aede8334286cc26f86591d34483b90d86d1e1372f74d1b7eee5aa233ed9199a3de01e7d16b092b4c902a602a16edcf03005596abc5c24f249dbb48236dc27738e93949c383734f6e39bf199fcd3fd22ab9268d1678d7259f94ab2c012e924ff2d26772ebf2cccc0ffe795264cd7a035f52f258b5ce78b7f1353c120f1aa30cbe943832fa70d3762222365109521c1a70a7ace321ddda173fb731c1d6f65c8e4af8f7b62660bc70a2c9ece21f8cddbe65d047f92aa6ca55a90864cb12c757030a7755ec4601a6f28dc2e728ee3f84fc1d39c261c845335a9d19e3356192b257186ff606756e58df67c11d2886870c90b69f5b51630f72d79f51884528214e9987865debb6b23ce8deecfb67cd43450a73675b53fcd20b6ae1da13f69dd349045d0b9b7dded042020ad081143231c79778d01f91c6e6df823885860ea781dd07867222b438599d02a815a4c18409c5e97a3d8e870ce1401bce7c556f05ac77af2659ef9b13d0d4df32a54674ef451cc2ffef50d4ca31efe19644db389ae9f0ce97686e5e53f1d82b98136258708911641b3a251eea41e6433534eb2810df49e040901367ee42b12cf7f853bab46f5360da2429989d232c9f6897e44221a2a5e946563db10423cfb073b6abf1e977f746e1d9c0fb929bb0e2c9dd50c11c76e0219a0004aa747de0db075305d4582293727f16f215403a9ca3d99af1750343101162954daebd58358b21276346519b2c05942223ad8314073900169b222b0e24f79c76dc61b4701edba670bc07bd4fa3c5a2179c69560f23ed925594f3ca230ed780904e82c7f8f6ee737c059d1af79eef0c1f8e6a0fdace62e87d88ad3b345afb96ea7b26eb0426585ea064933c8b8ec9264d910dc1573363dbec0755de36221eb368c5b2703c254a4d3d29d1b247c46200f743fe5f04f4b8fec2f143ba1276cc4b2bd7802bfe6fa63a49eb7a77f3443db74e0c889441fc2154d85bdbc0bbdc80eca3852ff8c7d7738ff9ba9eaa18174f4f65c526940289717bb87d05fd4eeef1272065b4bfa4d6f31a1b23c50e1355988", "openwall"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked; static struct custom_salt *cur_salt; static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = 1; 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(sizeof(*saved_key), self->params.max_keys_per_crypt); cracked = mem_calloc(sizeof(*cracked), self->params.max_keys_per_crypt); } static void done(void) { MEM_FREE(cracked); MEM_FREE(saved_key); } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { unsigned char master[MAX_KEYS_PER_CRYPT][32]; unsigned char output[24]; unsigned char *iv_in; unsigned char iv_out[16]; int size, i; AES_KEY akey; #ifdef SIMD_COEF_32 int len[MAX_KEYS_PER_CRYPT]; unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT]; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { len[i] = strlen(saved_key[i+index]); pin[i] = (unsigned char*)saved_key[i+index]; pout[i] = master[i]; } pbkdf2_sha1_sse((const unsigned char **)pin, len, cur_salt->salt, 16, cur_salt->iterations, pout, 32, 0); #else for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) pbkdf2_sha1((unsigned char *)saved_key[index+i], strlen(saved_key[index+i]), cur_salt->salt, 16, cur_salt->iterations, master[i], 32, 0); #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { // memcpy(output, SQLITE_FILE_HEADER, FILE_HEADER_SZ); // See "sqlcipher_page_cipher" and "sqlite3Codec" functions size = page_sz - reserve_sz; iv_in = cur_salt->data + 16 + size; // initial 16 bytes are salt memcpy(iv_out, iv_in, 16); AES_set_decrypt_key(master[i], 256, &akey); /* * decrypting 8 bytes from offset 16 is enough since the * verify_page function looks at output[16..23] only. */ AES_cbc_encrypt(cur_salt->data + 16, output + 16, 8, &akey, iv_out, AES_DECRYPT); if (enpass_common_verify_page(output) == 0) cracked[index+i] = 1; else cracked[index+i] = 0; } } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (cracked[index]) return 1; return 0; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static void enpass_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]; } struct fmt_main fmt_enpass = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT, { NULL }, { FORMAT_TAG }, enpass_tests }, { init, done, fmt_default_reset, fmt_default_prepare, enpass_common_valid, fmt_default_split, fmt_default_binary, enpass_common_get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, enpass_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
OpenMPClause.h
//===- OpenMPClause.h - Classes for OpenMP clauses --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file defines OpenMP AST classes for clauses. /// There are clauses for executable directives, clauses for declarative /// directives and clauses which can be used in both kinds of directives. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H #define LLVM_CLANG_AST_OPENMPCLAUSE_H #include "clang/AST/Expr.h" #include "clang/AST/Stmt.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" namespace clang { //===----------------------------------------------------------------------===// // AST classes for clauses. //===----------------------------------------------------------------------===// /// \brief This is a basic class for representing single OpenMP clause. /// class OMPClause { /// \brief Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// \brief Ending location of the clause. SourceLocation EndLoc; /// \brief Kind of the clause. OpenMPClauseKind Kind; protected: OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc) : StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {} public: /// \brief Returns the starting location of the clause. SourceLocation getLocStart() const { return StartLoc; } /// \brief Returns the ending location of the clause. SourceLocation getLocEnd() const { return EndLoc; } /// \brief Sets the starting location of the clause. void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// \brief Sets the ending location of the clause. void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// \brief Returns kind of OpenMP clause (private, shared, reduction, etc.). OpenMPClauseKind getClauseKind() const { return Kind; } bool isImplicit() const { return StartLoc.isInvalid(); } StmtRange children(); ConstStmtRange children() const { return const_cast<OMPClause *>(this)->children(); } static bool classof(const OMPClause *) { return true; } }; /// \brief This represents clauses with the list of variables like 'private', /// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the /// '#pragma omp ...' directives. template <class T> class OMPVarListClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Number of variables in the list. unsigned NumVars; protected: /// \brief Fetches list of variables associated with this clause. MutableArrayRef<Expr *> getVarRefs() { return MutableArrayRef<Expr *>( reinterpret_cast<Expr **>( reinterpret_cast<char *>(this) + llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>())), NumVars); } /// \brief Sets the list of variables for this clause. void setVarRefs(ArrayRef<Expr *> VL) { assert(VL.size() == NumVars && "Number of variables is not the same as the preallocated buffer"); std::copy( VL.begin(), VL.end(), reinterpret_cast<Expr **>( reinterpret_cast<char *>(this) + llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>()))); } /// \brief Build a clause with \a N variables /// /// \param K Kind of the clause. /// \param StartLoc Starting location of the clause (the clause keyword). /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {} public: typedef MutableArrayRef<Expr *>::iterator varlist_iterator; typedef ArrayRef<const Expr *>::iterator varlist_const_iterator; typedef llvm::iterator_range<varlist_iterator> varlist_range; typedef llvm::iterator_range<varlist_const_iterator> varlist_const_range; unsigned varlist_size() const { return NumVars; } bool varlist_empty() const { return NumVars == 0; } varlist_range varlists() { return varlist_range(varlist_begin(), varlist_end()); } varlist_const_range varlists() const { return varlist_const_range(varlist_begin(), varlist_end()); } varlist_iterator varlist_begin() { return getVarRefs().begin(); } varlist_iterator varlist_end() { return getVarRefs().end(); } varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); } varlist_const_iterator varlist_end() const { return getVarRefs().end(); } /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Fetches list of all variables in the clause. ArrayRef<const Expr *> getVarRefs() const { return llvm::makeArrayRef( reinterpret_cast<const Expr *const *>( reinterpret_cast<const char *>(this) + llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<const Expr *>())), NumVars); } }; /// \brief This represents 'if' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel if(a > 5) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'if' /// clause with condition 'a > 5'. /// class OMPIfClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Condition of the 'if' clause. Stmt *Condition; /// \brief Set condition. /// void setCondition(Expr *Cond) { Condition = Cond; } public: /// \brief Build 'if' clause with condition \a Cond. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Cond Condition of the clause. /// \param EndLoc Ending location of the clause. /// OMPIfClause(Expr *Cond, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_if, StartLoc, EndLoc), LParenLoc(LParenLoc), Condition(Cond) {} /// \brief Build an empty clause. /// OMPIfClause() : OMPClause(OMPC_if, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Condition(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_if; } StmtRange children() { return StmtRange(&Condition, &Condition + 1); } }; /// \brief This represents 'final' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task final(a > 5) /// \endcode /// In this example directive '#pragma omp task' has simple 'final' /// clause with condition 'a > 5'. /// class OMPFinalClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Condition of the 'if' clause. Stmt *Condition; /// \brief Set condition. /// void setCondition(Expr *Cond) { Condition = Cond; } public: /// \brief Build 'final' clause with condition \a Cond. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Cond Condition of the clause. /// \param EndLoc Ending location of the clause. /// OMPFinalClause(Expr *Cond, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_final, StartLoc, EndLoc), LParenLoc(LParenLoc), Condition(Cond) {} /// \brief Build an empty clause. /// OMPFinalClause() : OMPClause(OMPC_final, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Condition(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_final; } StmtRange children() { return StmtRange(&Condition, &Condition + 1); } }; /// \brief This represents 'num_threads' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel num_threads(6) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'num_threads' /// clause with number of threads '6'. /// class OMPNumThreadsClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Condition of the 'num_threads' clause. Stmt *NumThreads; /// \brief Set condition. /// void setNumThreads(Expr *NThreads) { NumThreads = NThreads; } public: /// \brief Build 'num_threads' clause with condition \a NumThreads. /// /// \param NumThreads Number of threads for the construct. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_num_threads, StartLoc, EndLoc), LParenLoc(LParenLoc), NumThreads(NumThreads) {} /// \brief Build an empty clause. /// OMPNumThreadsClause() : OMPClause(OMPC_num_threads, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), NumThreads(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns number of threads. Expr *getNumThreads() const { return cast_or_null<Expr>(NumThreads); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_num_threads; } StmtRange children() { return StmtRange(&NumThreads, &NumThreads + 1); } }; /// \brief This represents 'safelen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd safelen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'safelen' /// with single expression '4'. /// If the safelen clause is used then no two iterations executed /// concurrently with SIMD instructions can have a greater distance /// in the logical iteration space than its value. The parameter of /// the safelen clause must be a constant positive integer expression. /// class OMPSafelenClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Safe iteration space distance. Stmt *Safelen; /// \brief Set safelen. void setSafelen(Expr *Len) { Safelen = Len; } public: /// \brief Build 'safelen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_safelen, StartLoc, EndLoc), LParenLoc(LParenLoc), Safelen(Len) {} /// \brief Build an empty clause. /// explicit OMPSafelenClause() : OMPClause(OMPC_safelen, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Safelen(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Return safe iteration space distance. Expr *getSafelen() const { return cast_or_null<Expr>(Safelen); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_safelen; } StmtRange children() { return StmtRange(&Safelen, &Safelen + 1); } }; /// \brief This represents 'collapse' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd collapse(3) /// \endcode /// In this example directive '#pragma omp simd' has clause 'collapse' /// with single expression '3'. /// The parameter must be a constant positive integer expression, it specifies /// the number of nested loops that should be collapsed into a single iteration /// space. /// class OMPCollapseClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Number of for-loops. Stmt *NumForLoops; /// \brief Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// \brief Build 'collapse' clause. /// /// \param Num Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPCollapseClause(Expr *Num, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_collapse, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num) {} /// \brief Build an empty clause. /// explicit OMPCollapseClause() : OMPClause(OMPC_collapse, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), NumForLoops(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_collapse; } StmtRange children() { return StmtRange(&NumForLoops, &NumForLoops + 1); } }; /// \brief This represents 'default' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel default(shared) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'default' /// clause with kind 'shared'. /// class OMPDefaultClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief A kind of the 'default' clause. OpenMPDefaultClauseKind Kind; /// \brief Start location of the kind in source code. SourceLocation KindKwLoc; /// \brief Set kind of the clauses. /// /// \param K Argument of clause. /// void setDefaultKind(OpenMPDefaultClauseKind K) { Kind = K; } /// \brief Set argument location. /// /// \param KLoc Argument location. /// void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// \brief Build 'default' clause with argument \a A ('none' or 'shared'). /// /// \param A Argument of the clause ('none' or 'shared'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPDefaultClause(OpenMPDefaultClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// \brief Build an empty clause. /// OMPDefaultClause() : OMPClause(OMPC_default, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Kind(OMPC_DEFAULT_unknown), KindKwLoc(SourceLocation()) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns kind of the clause. OpenMPDefaultClauseKind getDefaultKind() const { return Kind; } /// \brief Returns location of clause kind. SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_default; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'proc_bind' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel proc_bind(master) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'proc_bind' /// clause with kind 'master'. /// class OMPProcBindClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief A kind of the 'proc_bind' clause. OpenMPProcBindClauseKind Kind; /// \brief Start location of the kind in source code. SourceLocation KindKwLoc; /// \brief Set kind of the clause. /// /// \param K Kind of clause. /// void setProcBindKind(OpenMPProcBindClauseKind K) { Kind = K; } /// \brief Set clause kind location. /// /// \param KLoc Kind location. /// void setProcBindKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// \brief Build 'proc_bind' clause with argument \a A ('master', 'close' or /// 'spread'). /// /// \param A Argument of the clause ('master', 'close' or 'spread'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPProcBindClause(OpenMPProcBindClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_proc_bind, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// \brief Build an empty clause. /// OMPProcBindClause() : OMPClause(OMPC_proc_bind, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Kind(OMPC_PROC_BIND_unknown), KindKwLoc(SourceLocation()) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns kind of the clause. OpenMPProcBindClauseKind getProcBindKind() const { return Kind; } /// \brief Returns location of clause kind. SourceLocation getProcBindKindKwLoc() const { return KindKwLoc; } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_proc_bind; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'schedule' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for schedule(static, 3) /// \endcode /// In this example directive '#pragma omp for' has 'schedule' clause with /// arguments 'static' and '3'. /// class OMPScheduleClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief A kind of the 'schedule' clause. OpenMPScheduleClauseKind Kind; /// \brief Start location of the schedule ind in source code. SourceLocation KindLoc; /// \brief Location of ',' (if any). SourceLocation CommaLoc; /// \brief Chunk size and a reference to pseudo variable for combined /// directives. enum { CHUNK_SIZE, HELPER_CHUNK_SIZE, NUM_EXPRS }; Stmt *ChunkSizes[NUM_EXPRS]; /// \brief Set schedule kind. /// /// \param K Schedule kind. /// void setScheduleKind(OpenMPScheduleClauseKind K) { Kind = K; } /// \brief Sets the location of '('. /// /// \param Loc Location of '('. /// void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Set schedule kind start location. /// /// \param KLoc Schedule kind location. /// void setScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// \brief Set location of ','. /// /// \param Loc Location of ','. /// void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// \brief Set chunk size. /// /// \param E Chunk size. /// void setChunkSize(Expr *E) { ChunkSizes[CHUNK_SIZE] = E; } /// \brief Set helper chunk size. /// /// \param E Helper chunk size. /// void setHelperChunkSize(Expr *E) { ChunkSizes[HELPER_CHUNK_SIZE] = E; } public: /// \brief Build 'schedule' clause with schedule kind \a Kind and chunk size /// expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind Schedule kind. /// \param ChunkSize Chunk size. /// \param HelperChunkSize Helper chunk size for combined directives. /// OMPScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, Expr *HelperChunkSize) : OMPClause(OMPC_schedule, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc) { ChunkSizes[CHUNK_SIZE] = ChunkSize; ChunkSizes[HELPER_CHUNK_SIZE] = HelperChunkSize; } /// \brief Build an empty clause. /// explicit OMPScheduleClause() : OMPClause(OMPC_schedule, SourceLocation(), SourceLocation()), Kind(OMPC_SCHEDULE_unknown) { ChunkSizes[CHUNK_SIZE] = nullptr; ChunkSizes[HELPER_CHUNK_SIZE] = nullptr; } /// \brief Get kind of the clause. /// OpenMPScheduleClauseKind getScheduleKind() const { return Kind; } /// \brief Get location of '('. /// SourceLocation getLParenLoc() { return LParenLoc; } /// \brief Get kind location. /// SourceLocation getScheduleKindLoc() { return KindLoc; } /// \brief Get location of ','. /// SourceLocation getCommaLoc() { return CommaLoc; } /// \brief Get chunk size. /// Expr *getChunkSize() { return dyn_cast_or_null<Expr>(ChunkSizes[CHUNK_SIZE]); } /// \brief Get chunk size. /// Expr *getChunkSize() const { return dyn_cast_or_null<Expr>(ChunkSizes[CHUNK_SIZE]); } /// \brief Get helper chunk size. /// Expr *getHelperChunkSize() { return dyn_cast_or_null<Expr>(ChunkSizes[HELPER_CHUNK_SIZE]); } /// \brief Get helper chunk size. /// Expr *getHelperChunkSize() const { return dyn_cast_or_null<Expr>(ChunkSizes[HELPER_CHUNK_SIZE]); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_schedule; } StmtRange children() { return StmtRange(&ChunkSizes[CHUNK_SIZE], &ChunkSizes[CHUNK_SIZE] + 1); } }; /// \brief This represents 'ordered' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for ordered /// \endcode /// In this example directive '#pragma omp for' has 'ordered' clause. /// class OMPOrderedClause : public OMPClause { public: /// \brief Build 'ordered' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_ordered, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPOrderedClause() : OMPClause(OMPC_ordered, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_ordered; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'nowait' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for nowait /// \endcode /// In this example directive '#pragma omp for' has 'nowait' clause. /// class OMPNowaitClause : public OMPClause { public: /// \brief Build 'nowait' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_nowait, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPNowaitClause() : OMPClause(OMPC_nowait, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_nowait; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'untied' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task untied /// \endcode /// In this example directive '#pragma omp task' has 'untied' clause. /// class OMPUntiedClause : public OMPClause { public: /// \brief Build 'untied' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_untied, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPUntiedClause() : OMPClause(OMPC_untied, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_untied; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'mergeable' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task mergeable /// \endcode /// In this example directive '#pragma omp task' has 'mergeable' clause. /// class OMPMergeableClause : public OMPClause { public: /// \brief Build 'mergeable' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_mergeable, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPMergeableClause() : OMPClause(OMPC_mergeable, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_mergeable; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'read' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic read /// \endcode /// In this example directive '#pragma omp atomic' has 'read' clause. /// class OMPReadClause : public OMPClause { public: /// \brief Build 'read' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_read, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPReadClause() : OMPClause(OMPC_read, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_read; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'write' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic write /// \endcode /// In this example directive '#pragma omp atomic' has 'write' clause. /// class OMPWriteClause : public OMPClause { public: /// \brief Build 'write' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_write, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPWriteClause() : OMPClause(OMPC_write, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_write; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'update' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic update /// \endcode /// In this example directive '#pragma omp atomic' has 'update' clause. /// class OMPUpdateClause : public OMPClause { public: /// \brief Build 'update' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_update, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPUpdateClause() : OMPClause(OMPC_update, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_update; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'capture' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic capture /// \endcode /// In this example directive '#pragma omp atomic' has 'capture' clause. /// class OMPCaptureClause : public OMPClause { public: /// \brief Build 'capture' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_capture, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPCaptureClause() : OMPClause(OMPC_capture, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_capture; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'seq_cst' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic seq_cst /// \endcode /// In this example directive '#pragma omp atomic' has 'seq_cst' clause. /// class OMPSeqCstClause : public OMPClause { public: /// \brief Build 'seq_cst' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_seq_cst, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPSeqCstClause() : OMPClause(OMPC_seq_cst, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_seq_cst; } StmtRange children() { return StmtRange(); } }; /// \brief This represents clause 'private' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// with the variables 'a' and 'b'. /// class OMPPrivateClause : public OMPVarListClause<OMPPrivateClause> { friend class OMPClauseReader; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPPrivateClause>(OMPC_private, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPPrivateClause(unsigned N) : OMPVarListClause<OMPPrivateClause>(OMPC_private, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// \brief Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// \brief Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param PrivateVL List of references to private copies with initializers. /// static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N); typedef MutableArrayRef<Expr *>::iterator private_copies_iterator; typedef ArrayRef<const Expr *>::iterator private_copies_const_iterator; typedef llvm::iterator_range<private_copies_iterator> private_copies_range; typedef llvm::iterator_range<private_copies_const_iterator> private_copies_const_range; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_private; } }; /// \brief This represents clause 'firstprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel firstprivate(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'firstprivate' /// with the variables 'a' and 'b'. /// class OMPFirstprivateClause : public OMPVarListClause<OMPFirstprivateClause> { friend class OMPClauseReader; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFirstprivateClause>(OMPC_firstprivate, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPFirstprivateClause(unsigned N) : OMPVarListClause<OMPFirstprivateClause>( OMPC_firstprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// \brief Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// \brief Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// \brief Sets the list of references to initializer variables for new /// private variables. /// \param VL List of references. void setInits(ArrayRef<Expr *> VL); /// \brief Gets the list of references to initializer variables for new /// private variables. MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. /// \param PrivateVL List of references to private copies with initializers. /// \param InitVL List of references to auto generated variables used for /// initialization of a single array element. Used if firstprivate variable is /// of array type. /// static OMPFirstprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL, ArrayRef<Expr *> InitVL); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N); typedef MutableArrayRef<Expr *>::iterator private_copies_iterator; typedef ArrayRef<const Expr *>::iterator private_copies_const_iterator; typedef llvm::iterator_range<private_copies_iterator> private_copies_range; typedef llvm::iterator_range<private_copies_const_iterator> private_copies_const_range; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } typedef MutableArrayRef<Expr *>::iterator inits_iterator; typedef ArrayRef<const Expr *>::iterator inits_const_iterator; typedef llvm::iterator_range<inits_iterator> inits_range; typedef llvm::iterator_range<inits_const_iterator> inits_const_range; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_firstprivate; } }; /// \brief This represents clause 'lastprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd lastprivate(a,b) /// \endcode /// In this example directive '#pragma omp simd' has clause 'lastprivate' /// with the variables 'a' and 'b'. class OMPLastprivateClause : public OMPVarListClause<OMPLastprivateClause> { // There are 4 additional tail-allocated arrays at the end of the class: // 1. Contains list of pseudo variables with the default initialization for // each non-firstprivate variables. Used in codegen for initialization of // lastprivate copies. // 2. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents private variables // (for arrays, single array element). // 3. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents original variables // (for arrays, single array element). // 4. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of final assignment performed by the // lastprivate clause. // friend class OMPClauseReader; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPLastprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPLastprivateClause>(OMPC_lastprivate, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPLastprivateClause(unsigned N) : OMPVarListClause<OMPLastprivateClause>( OMPC_lastprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// \brief Get the list of helper expressions for initialization of private /// copies for lastprivate variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent private variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// \brief Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent original variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// \brief Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// \brief Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign private copy of the variable to original variable. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// \brief Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// private variables (for arrays, single array element). /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// original variables (for arrays, single array element). /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// lastprivate clause. /// /// static OMPLastprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPLastprivateClause *CreateEmpty(const ASTContext &C, unsigned N); typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator; typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator; typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range; typedef llvm::iterator_range<helper_expr_const_iterator> helper_expr_const_range; /// \brief Set list of helper expressions, required for generation of private /// copies of original lastprivate variables. void setPrivateCopies(ArrayRef<Expr *> PrivateCopies); helper_expr_const_range private_copies() const { return helper_expr_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_range private_copies() { return helper_expr_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_lastprivate; } }; /// \brief This represents clause 'shared' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel shared(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'shared' /// with the variables 'a' and 'b'. /// class OMPSharedClause : public OMPVarListClause<OMPSharedClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPSharedClause>(OMPC_shared, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPSharedClause(unsigned N) : OMPVarListClause<OMPSharedClause>(OMPC_shared, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_shared; } }; /// \brief This represents clause 'reduction' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'reduction' /// with operator '+' and the variables 'a' and 'b'. /// class OMPReductionClause : public OMPVarListClause<OMPReductionClause> { friend class OMPClauseReader; /// \brief Location of ':'. SourceLocation ColonLoc; /// \brief Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// \brief Name of custom operator. DeclarationNameInfo NameInfo; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPReductionClause>(OMPC_reduction, StartLoc, LParenLoc, EndLoc, N), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPReductionClause(unsigned N) : OMPVarListClause<OMPReductionClause>(OMPC_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), ColonLoc(), QualifierLoc(), NameInfo() {} /// \brief Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// \brief Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// \brief Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent LHS expression in the final /// reduction expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// \brief Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent RHS expression in the final /// reduction expression performed by the reduction clause. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// \brief Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// \brief Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// \brief Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// static OMPReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// \brief Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// \brief Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// \brief Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator; typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator; typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range; typedef llvm::iterator_range<helper_expr_const_iterator> helper_expr_const_range; helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_reduction; } }; /// \brief This represents clause 'linear' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd linear(a,b : 2) /// \endcode /// In this example directive '#pragma omp simd' has clause 'linear' /// with variables 'a', 'b' and linear step '2'. /// class OMPLinearClause : public OMPVarListClause<OMPLinearClause> { friend class OMPClauseReader; /// \brief Location of ':'. SourceLocation ColonLoc; /// \brief Sets the linear step for clause. void setStep(Expr *Step) { *(getFinals().end()) = Step; } /// \brief Sets the expression to calculate linear step for clause. void setCalcStep(Expr *CalcStep) { *(getFinals().end() + 1) = CalcStep; } /// \brief Build 'linear' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. /// OMPLinearClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPLinearClause>(OMPC_linear, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// \brief Build an empty clause. /// /// \param NumVars Number of variables. /// explicit OMPLinearClause(unsigned NumVars) : OMPVarListClause<OMPLinearClause>(OMPC_linear, SourceLocation(), SourceLocation(), SourceLocation(), NumVars), ColonLoc(SourceLocation()) {} /// \brief Gets the list of initial values for linear variables. /// /// There are NumVars expressions with initial values allocated after the /// varlist, they are followed by NumVars update expressions (used to update /// the linear variable's value on current iteration) and they are followed by /// NumVars final expressions (used to calculate the linear variable's /// value after the loop body). After these lists, there are 2 helper /// expressions - linear step and a helper to calculate it before the /// loop body (used when the linear step is not constant): /// /// { Vars[] /* in OMPVarListClause */; Inits[]; Updates[]; Finals[]; /// Step; CalcStep; } /// MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// \brief Sets the list of update expressions for linear variables. MutableArrayRef<Expr *> getUpdates() { return MutableArrayRef<Expr *>(getInits().end(), varlist_size()); } ArrayRef<const Expr *> getUpdates() const { return llvm::makeArrayRef(getInits().end(), varlist_size()); } /// \brief Sets the list of final update expressions for linear variables. MutableArrayRef<Expr *> getFinals() { return MutableArrayRef<Expr *>(getUpdates().end(), varlist_size()); } ArrayRef<const Expr *> getFinals() const { return llvm::makeArrayRef(getUpdates().end(), varlist_size()); } /// \brief Sets the list of the initial values for linear variables. /// \param IL List of expressions. void setInits(ArrayRef<Expr *> IL); public: /// \brief Creates clause with a list of variables \a VL and a linear step /// \a Step. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param IL List of initial values for the variables. /// \param Step Linear step. /// \param CalcStep Calculation of the linear step. static OMPLinearClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> IL, Expr *Step, Expr *CalcStep); /// \brief Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. /// static OMPLinearClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// \brief Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getColonLoc() const { return ColonLoc; } /// \brief Returns linear step. Expr *getStep() { return *(getFinals().end()); } /// \brief Returns linear step. const Expr *getStep() const { return *(getFinals().end()); } /// \brief Returns expression to calculate linear step. Expr *getCalcStep() { return *(getFinals().end() + 1); } /// \brief Returns expression to calculate linear step. const Expr *getCalcStep() const { return *(getFinals().end() + 1); } /// \brief Sets the list of update expressions for linear variables. /// \param UL List of expressions. void setUpdates(ArrayRef<Expr *> UL); /// \brief Sets the list of final update expressions for linear variables. /// \param FL List of expressions. void setFinals(ArrayRef<Expr *> FL); typedef MutableArrayRef<Expr *>::iterator inits_iterator; typedef ArrayRef<const Expr *>::iterator inits_const_iterator; typedef llvm::iterator_range<inits_iterator> inits_range; typedef llvm::iterator_range<inits_const_iterator> inits_const_range; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } typedef MutableArrayRef<Expr *>::iterator updates_iterator; typedef ArrayRef<const Expr *>::iterator updates_const_iterator; typedef llvm::iterator_range<updates_iterator> updates_range; typedef llvm::iterator_range<updates_const_iterator> updates_const_range; updates_range updates() { return updates_range(getUpdates().begin(), getUpdates().end()); } updates_const_range updates() const { return updates_const_range(getUpdates().begin(), getUpdates().end()); } typedef MutableArrayRef<Expr *>::iterator finals_iterator; typedef ArrayRef<const Expr *>::iterator finals_const_iterator; typedef llvm::iterator_range<finals_iterator> finals_range; typedef llvm::iterator_range<finals_const_iterator> finals_const_range; finals_range finals() { return finals_range(getFinals().begin(), getFinals().end()); } finals_const_range finals() const { return finals_const_range(getFinals().begin(), getFinals().end()); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_linear; } }; /// \brief This represents clause 'aligned' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd aligned(a,b : 8) /// \endcode /// In this example directive '#pragma omp simd' has clause 'aligned' /// with variables 'a', 'b' and alignment '8'. /// class OMPAlignedClause : public OMPVarListClause<OMPAlignedClause> { friend class OMPClauseReader; /// \brief Location of ':'. SourceLocation ColonLoc; /// \brief Sets the alignment for clause. void setAlignment(Expr *A) { *varlist_end() = A; } /// \brief Build 'aligned' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. /// OMPAlignedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(OMPC_aligned, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// \brief Build an empty clause. /// /// \param NumVars Number of variables. /// explicit OMPAlignedClause(unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(OMPC_aligned, SourceLocation(), SourceLocation(), SourceLocation(), NumVars), ColonLoc(SourceLocation()) {} public: /// \brief Creates clause with a list of variables \a VL and alignment \a A. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param A Alignment. static OMPAlignedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, Expr *A); /// \brief Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. /// static OMPAlignedClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// \brief Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// \brief Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// \brief Returns alignment. Expr *getAlignment() { return *varlist_end(); } /// \brief Returns alignment. const Expr *getAlignment() const { return *varlist_end(); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_aligned; } }; /// \brief This represents clause 'copyin' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel copyin(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'copyin' /// with the variables 'a' and 'b'. /// class OMPCopyinClause : public OMPVarListClause<OMPCopyinClause> { // Class has 3 additional tail allocated arrays: // 1. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents sources. // 2. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents destinations. // 3. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of propagation of master's thread values of // threadprivate variables to local instances of that variables in other // implicit threads. friend class OMPClauseReader; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPCopyinClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyinClause>(OMPC_copyin, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPCopyinClause(unsigned N) : OMPVarListClause<OMPCopyinClause>(OMPC_copyin, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyin clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// \brief Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyin clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// \brief Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// \brief Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// \brief Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of propagation of master's thread values of /// threadprivate variables to local instances of that variables in other /// implicit threads. /// static OMPCopyinClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPCopyinClause *CreateEmpty(const ASTContext &C, unsigned N); typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator; typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator; typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range; typedef llvm::iterator_range<helper_expr_const_iterator> helper_expr_const_range; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_copyin; } }; /// \brief This represents clause 'copyprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp single copyprivate(a,b) /// \endcode /// In this example directive '#pragma omp single' has clause 'copyprivate' /// with the variables 'a' and 'b'. /// class OMPCopyprivateClause : public OMPVarListClause<OMPCopyprivateClause> { friend class OMPClauseReader; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPCopyprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyprivateClause>(OMPC_copyprivate, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPCopyprivateClause(unsigned N) : OMPVarListClause<OMPCopyprivateClause>( OMPC_copyprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// \brief Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// \brief Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// \brief Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// \brief Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// \brief Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// copyprivate clause. /// static OMPCopyprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPCopyprivateClause *CreateEmpty(const ASTContext &C, unsigned N); typedef MutableArrayRef<Expr *>::iterator helper_expr_iterator; typedef ArrayRef<const Expr *>::iterator helper_expr_const_iterator; typedef llvm::iterator_range<helper_expr_iterator> helper_expr_range; typedef llvm::iterator_range<helper_expr_const_iterator> helper_expr_const_range; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_copyprivate; } }; /// \brief This represents implicit clause 'flush' for the '#pragma omp flush' /// directive. /// This clause does not exist by itself, it can be only as a part of 'omp /// flush' directive. This clause is introduced to keep the original structure /// of \a OMPExecutableDirective class and its derivatives and to use the /// existing infrastructure of clauses with the list of variables. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has implicit clause 'flush' /// with the variables 'a' and 'b'. /// class OMPFlushClause : public OMPVarListClause<OMPFlushClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPFlushClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFlushClause>(OMPC_flush, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPFlushClause(unsigned N) : OMPVarListClause<OMPFlushClause>(OMPC_flush, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPFlushClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPFlushClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_flush; } }; /// \brief This represents implicit clause 'depend' for the '#pragma omp task' /// directive. /// /// \code /// #pragma omp task depend(in:a,b) /// \endcode /// In this example directive '#pragma omp task' with clause 'depend' with the /// variables 'a' and 'b' with dependency 'in'. /// class OMPDependClause : public OMPVarListClause<OMPDependClause> { friend class OMPClauseReader; /// \brief Dependency type (one of in, out, inout). OpenMPDependClauseKind DepKind; /// \brief Dependency type location. SourceLocation DepLoc; /// \brief Colon location. SourceLocation ColonLoc; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPDependClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPDependClause>(OMPC_depend, StartLoc, LParenLoc, EndLoc, N), DepKind(OMPC_DEPEND_unknown) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPDependClause(unsigned N) : OMPVarListClause<OMPDependClause>(OMPC_depend, SourceLocation(), SourceLocation(), SourceLocation(), N), DepKind(OMPC_DEPEND_unknown) {} /// \brief Set dependency kind. void setDependencyKind(OpenMPDependClauseKind K) { DepKind = K; } /// \brief Set dependency kind and its location. void setDependencyLoc(SourceLocation Loc) { DepLoc = Loc; } /// \brief Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param DepKind Dependency type. /// \param DepLoc Location of the dependency type. /// \param ColonLoc Colon location. /// \param VL List of references to the variables. /// static OMPDependClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPDependClause *CreateEmpty(const ASTContext &C, unsigned N); /// \brief Get dependency type. OpenMPDependClauseKind getDependencyKind() const { return DepKind; } /// \brief Get dependency type location. SourceLocation getDependencyLoc() const { return DepLoc; } /// \brief Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_depend; } }; } // end namespace clang #endif
mlp_mnist_bf16_avx512_numa.c
/****************************************************************************** * Copyright (c) Intel Corporation - All rights reserved. * * This file is part of the LIBXSMM library. * * * * For information on the license, see the LICENSE file. * * Further information: https://github.com/hfp/libxsmm/ * * SPDX-License-Identifier: BSD-3-Clause * ******************************************************************************/ /* Evangelos Georganas, Alexander Heinecke (Intel Corp.) ******************************************************************************/ #include <libxsmm.h> #include <libxsmm_sync.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #if defined(_OPENMP) # include <omp.h> #endif /* include c-based dnn library */ #include "../common/dnn_common.h" #include "../common/mnist.h" #define TEST_ACCURACY #define OVERWRITE_DOUTPUT_BWDUPD #define _mm512_load_fil(A) _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepi16_epi32(_mm256_loadu_si256((__m256i*)(A))),16)) #define _mm512_store_fil(A,B) _mm256_storeu_si256((__m256i*)(A), (__m256i)_mm512_cvtneps_pbh((B))) static int threads_per_numa = 0; LIBXSMM_INLINE void my_init_buf(float* buf, size_t size, int initPos, int initOne) { int i; zero_buf(buf, size); for (i = 0; i < (int)size; ++i) { buf[i] = (float)((initOne != 0) ? 1.0 : ((initPos != 0) ? libxsmm_rng_f64() : (0.05 - libxsmm_rng_f64()/10.0))); } } LIBXSMM_INLINE void my_init_buf_bf16(libxsmm_bfloat16* buf, size_t size, int initPos, int initOne) { int i; zero_buf_bf16(buf, size); for (i = 0; i < (int)size; ++i) { libxsmm_bfloat16_hp tmp; tmp.f = (float)((initOne != 0) ? 1.0 : ((initPos != 0) ? libxsmm_rng_f64() : (0.05 - libxsmm_rng_f64()/10.0))); buf[i] = tmp.i[1]; } } LIBXSMM_INLINE void init_buf_bf16_numa_aware(int threads, int ltid, int ft_mode, libxsmm_bfloat16* buf, size_t size, int initPos, int initOne) { int chunksize, chunks; int my_numa_node = ltid/threads_per_numa; int n_numa_nodes = threads/threads_per_numa; int l = 0; if (ft_mode == 0) { /* Mode 0 : Block cyclic assignment to NUMA nodes */ int bufsize = size * 2; chunksize = 4096; chunks = (bufsize + chunksize - 1)/chunksize; for (l = 0; l < chunks; l++) { int _chunksize = (l < chunks - 1) ? chunksize : bufsize - (chunks-1) * chunksize; if ( l % n_numa_nodes == my_numa_node) { my_init_buf_bf16((libxsmm_bfloat16*) buf+l*(chunksize/2), _chunksize/2, 0, 0 ); } } } else { /* Mode 1: Block assignement to NUMA nodes */ chunks = n_numa_nodes; chunksize = (size + chunks - 1) /chunks; for (l = 0; l < chunks; l++) { int _chunksize = (l < chunks - 1) ? chunksize : size - (chunks-1) * chunksize; if ( l == my_numa_node) { my_init_buf_bf16((libxsmm_bfloat16*) buf+l*chunksize, _chunksize, 0, 0 ); } } } } void init_buffer_block_numa(libxsmm_bfloat16* buf, size_t size) { int nThreads = omp_get_max_threads(); #if defined(_OPENMP) # pragma omp parallel #endif { #if defined(_OPENMP) const int tid = omp_get_thread_num(); #else const int tid = 0; #endif if (tid % threads_per_numa == 0) { init_buf_bf16_numa_aware(nThreads, tid, 1, buf, size, 0, 0); } } } void init_buffer_block_cyclic_numa(libxsmm_bfloat16* buf, size_t size) { int nThreads = omp_get_max_threads(); #if defined(_OPENMP) # pragma omp parallel #endif { #if defined(_OPENMP) const int tid = omp_get_thread_num(); #else const int tid = 0; #endif if (tid % threads_per_numa == 0) { init_buf_bf16_numa_aware(nThreads, tid, 0, buf, size, 0, 0); } } } #if 0 LIBXSMM_INLINE void my_matrix_copy_KCCK_to_KCCK_vnni(float *src, float *dst, int C, int K, int bc, int bk) { int k1, k2, c1, c2; int kBlocks = K/bk; int cBlocks = C/bc; LIBXSMM_VLA_DECL(4, float, real_src, src, cBlocks, bc, bk); LIBXSMM_VLA_DECL(5, float, real_dst, dst, cBlocks, bc/2, bk, 2); for (k1 = 0; k1 < kBlocks; k1++) { for (c1 = 0; c1 < cBlocks; c1++) { for (c2 = 0; c2 < bc; c2++) { for (k2 = 0; k2 < bk; k2++) { LIBXSMM_VLA_ACCESS(5, real_dst, k1, c1, c2/2, k2, c2%2, cBlocks, bc/2, bk, 2) = LIBXSMM_VLA_ACCESS(4, real_src, k1, c1, c2, k2, cBlocks, bc, bk); } } } } } #endif typedef enum my_eltwise_fuse { MY_ELTWISE_FUSE_NONE = 0, MY_ELTWISE_FUSE_BIAS = 1, MY_ELTWISE_FUSE_RELU = 2, MY_ELTWISE_FUSE_BIAS_RELU = MY_ELTWISE_FUSE_BIAS | MY_ELTWISE_FUSE_RELU } my_eltwise_fuse; typedef enum my_pass { MY_PASS_FWD = 1, MY_PASS_BWD_D = 2, MY_PASS_BWD_W = 4, MY_PASS_BWD = 6 } my_pass; typedef struct my_opt_config { libxsmm_blasint C; libxsmm_blasint K; libxsmm_blasint bc; libxsmm_blasint bk; libxsmm_blasint threads; float lr; size_t scratch_size; libxsmm_barrier* barrier; } my_opt_config; typedef struct my_smax_fwd_config { libxsmm_blasint N; libxsmm_blasint C; libxsmm_blasint bn; libxsmm_blasint bc; libxsmm_blasint threads; size_t scratch_size; libxsmm_barrier* barrier; } my_smax_fwd_config; typedef struct my_smax_bwd_config { libxsmm_blasint N; libxsmm_blasint C; libxsmm_blasint bn; libxsmm_blasint bc; libxsmm_blasint threads; size_t scratch_size; float loss_weight; libxsmm_barrier* barrier; } my_smax_bwd_config; typedef struct my_fc_fwd_config { libxsmm_blasint N; libxsmm_blasint C; libxsmm_blasint K; libxsmm_blasint bn; libxsmm_blasint bc; libxsmm_blasint bk; libxsmm_blasint threads; my_eltwise_fuse fuse_type; libxsmm_blasint fwd_bf; libxsmm_blasint fwd_2d_blocking; libxsmm_blasint fwd_col_teams; libxsmm_blasint fwd_row_teams; libxsmm_blasint fwd_M_hyperpartitions; libxsmm_blasint fwd_N_hyperpartitions; size_t scratch_size; libxsmm_barrier* barrier; libxsmm_bsmmfunction_reducebatch_strd gemm_fwd; libxsmm_bmmfunction_reducebatch_strd gemm_fwd2; libxsmm_bmmfunction_reducebatch_strd gemm_fwd3; libxsmm_meltwfunction_unary fwd_cvtfp32bf16_kernel; libxsmm_meltwfunction_unary fwd_cvtfp32bf16_relu_kernel; libxsmm_meltwfunction_unary fwd_sigmoid_cvtfp32bf16_kernel; libxsmm_meltwfunction_unary fwd_zero_kernel; libxsmm_meltwfunction_unary fwd_relu_kernel; libxsmm_meltwfunction_unary fwd_copy_bf16fp32_kernel; libxsmm_meltwfunction_unary fwd_colbcast_bf16fp32_copy_kernel; libxsmm_meltwfunction_unary fwd_colbcast_bf16bf16_copy_kernel; } my_fc_fwd_config; typedef struct my_fc_bwd_config { libxsmm_blasint N; libxsmm_blasint C; libxsmm_blasint K; libxsmm_blasint bn; libxsmm_blasint bc; libxsmm_blasint bk; libxsmm_blasint threads; my_eltwise_fuse fuse_type; libxsmm_blasint bwd_bf; libxsmm_blasint bwd_2d_blocking; libxsmm_blasint bwd_col_teams; libxsmm_blasint bwd_row_teams; libxsmm_blasint bwd_M_hyperpartitions; libxsmm_blasint bwd_N_hyperpartitions; libxsmm_blasint upd_bf; libxsmm_blasint upd_2d_blocking; libxsmm_blasint upd_col_teams; libxsmm_blasint upd_row_teams; libxsmm_blasint upd_M_hyperpartitions; libxsmm_blasint upd_N_hyperpartitions; libxsmm_blasint ifm_subtasks; libxsmm_blasint ofm_subtasks; size_t scratch_size; size_t doutput_scratch_mark; libxsmm_barrier* barrier; libxsmm_bsmmfunction_reducebatch_strd gemm_bwd; libxsmm_bsmmfunction_reducebatch_strd gemm_bwd2; libxsmm_bmmfunction_reducebatch_strd gemm_bwd3; libxsmm_bsmmfunction_reducebatch_strd gemm_upd; libxsmm_bmmfunction_reducebatch_strd gemm_upd3; libxsmm_meltwfunction_unary bwd_cvtfp32bf16_kernel; libxsmm_meltwfunction_unary upd_cvtfp32bf16_kernel; libxsmm_meltwfunction_unary bwd_relu_kernel; libxsmm_meltwfunction_unary bwd_zero_kernel; libxsmm_meltwfunction_unary upd_zero_kernel; libxsmm_meltwfunction_unary delbias_reduce_kernel; libxsmm_meltwfunction_unary vnni_to_vnniT_kernel; libxsmm_meltwfunction_unary norm_to_normT_kernel; libxsmm_meltwfunction_unary norm_to_vnni_kernel; libxsmm_meltwfunction_unary upd_norm_to_vnni_kernel; libxsmm_meltwfunction_unary norm_to_vnni_kernel_wt; } my_fc_bwd_config; my_fc_fwd_config setup_my_fc_fwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint K, libxsmm_blasint bn, libxsmm_blasint bc, libxsmm_blasint bk, libxsmm_blasint threads, my_eltwise_fuse fuse_type) { my_fc_fwd_config res; libxsmm_blasint lda = bk; libxsmm_blasint ldb = bc; libxsmm_blasint ldc = bk; libxsmm_blasint ld_zero = bk*bn; libxsmm_blasint ld_upconvert = K; float alpha = 1.0f; float beta = 1.0f; float zerobeta = 0.0f; libxsmm_meltw_flags fusion_flags; int l_flags, l_tc_flags; int l_tr_flags = LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ); libxsmm_blasint unroll_hint; /* setting up some handle values */ res.N = N; res.C = C; res.K = K; res.bn = bn; res.bc = bc; res.bk = bk; res.threads = threads; res.fuse_type = fuse_type; /* setup parallelization strategy */ res.fwd_M_hyperpartitions = 1; res.fwd_N_hyperpartitions = 1; if (threads == 16) { res.fwd_bf = 1; res.fwd_2d_blocking = 1; res.fwd_col_teams = 2; res.fwd_row_teams = 8; } else if (threads == 14) { res.fwd_bf = 1; res.fwd_2d_blocking = 1; res.fwd_col_teams = 2; res.fwd_row_teams = 7; } else if (threads == 56) { res.fwd_bf = 1; res.fwd_2d_blocking = 1; res.fwd_col_teams = 1; res.fwd_row_teams = 14; res.fwd_M_hyperpartitions = 1; res.fwd_N_hyperpartitions = 4; } else if (threads == 1) { res.fwd_bf = 1; res.fwd_2d_blocking = 1; res.fwd_col_teams = 1; res.fwd_row_teams = 1; res.fwd_M_hyperpartitions = 1; res.fwd_N_hyperpartitions = 1; } else { res.fwd_bf = 1; res.fwd_2d_blocking = 0; res.fwd_col_teams = 1; res.fwd_row_teams = 1; } #if 0 res.fwd_bf = atoi(getenv("FWD_BF")); res.fwd_2d_blocking = atoi(getenv("FWD_2D_BLOCKING")); res.fwd_col_teams = atoi(getenv("FWD_COL_TEAMS")); res.fwd_row_teams = atoi(getenv("FWD_ROW_TEAMS")); #endif /* setting up the barrier */ res.barrier = libxsmm_barrier_create(threads, 1); /* TPP creation */ l_flags = ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ) | LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG; l_tc_flags = LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ); unroll_hint = (res.C/res.bc)/res.fwd_bf; res.gemm_fwd = libxsmm_bsmmdispatch_reducebatch_strd_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &beta, &l_flags, NULL); if ( res.gemm_fwd == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd failed. Bailing...!\n"); exit(-1); } res.gemm_fwd2 = libxsmm_bmmdispatch_reducebatch_strd_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &beta, &l_flags, NULL); if ( res.gemm_fwd2 == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd2 failed. Bailing...!\n"); exit(-1); } res.gemm_fwd3 = libxsmm_bmmdispatch_reducebatch_strd_unroll(res.bk, res.bn, res.bc, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL); if ( res.gemm_fwd3 == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_fwd3 failed. Bailing...!\n"); exit(-1); } /* Also JIT eltwise TPPs... */ res.fwd_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_unary(res.bk, res.bn, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY); if ( res.fwd_cvtfp32bf16_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_cvtfp32bf16_kernel failed. Bailing...!\n"); exit(-1); } res.fwd_cvtfp32bf16_relu_kernel = libxsmm_dispatch_meltw_unary(res.bk, res.bn, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT, LIBXSMM_MELTW_TYPE_UNARY_RELU); if ( res.fwd_cvtfp32bf16_relu_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_cvtfp32bf16_relu_kernel failed. Bailing...!\n"); exit(-1); } res.fwd_sigmoid_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_unary(res.bk, res.bn, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_SIGMOID); if ( res.fwd_sigmoid_cvtfp32bf16_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_sigmoid_cvtfp32bf16_kernel failed. Bailing...!\n"); exit(-1); } res.fwd_zero_kernel = libxsmm_dispatch_meltw_unary(bn*bk, 1, &ld_zero, &ld_zero, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR); if ( res.fwd_zero_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_zero_kernel failed. Bailing...!\n"); exit(-1); } res.fwd_colbcast_bf16fp32_copy_kernel = libxsmm_dispatch_meltw_unary(bk, bn, &ldc, &ldc, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_BCAST_COL, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY ); if ( res.fwd_colbcast_bf16fp32_copy_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_colbcast_bf16fp32_copy_kernel failed. Bailing...!\n"); exit(-1); } res.fwd_colbcast_bf16bf16_copy_kernel = libxsmm_dispatch_meltw_unary(bk, bn, &ldc, &ldc, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_BCAST_COL, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY); if ( res.fwd_colbcast_bf16bf16_copy_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_colbcast_bf16bf16_copy_kernel failed. Bailing...!\n"); exit(-1); } res.fwd_relu_kernel = libxsmm_dispatch_meltw_unary(res.bc, res.bn, &ldb, &ldb, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT, LIBXSMM_MELTW_TYPE_UNARY_RELU); if ( res.fwd_relu_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_relu_kernel failed. Bailing...!\n"); exit(-1); } res.fwd_copy_bf16fp32_kernel = libxsmm_dispatch_meltw_unary(K, 1, &ld_upconvert, &ld_upconvert, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY); if ( res.fwd_copy_bf16fp32_kernel == NULL ) { fprintf( stderr, "JIT for TPP fwd_copy_bf16fp32_kernel failed. Bailing...!\n"); exit(-1); } /* init scratch */ res.scratch_size = sizeof(float) * LIBXSMM_MAX(res.K * res.N, res.threads * LIBXSMM_MAX(res.bk * res.bn, res.K)); return res; } my_fc_bwd_config setup_my_fc_bwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint K, libxsmm_blasint bn, libxsmm_blasint bc, libxsmm_blasint bk, libxsmm_blasint threads, my_eltwise_fuse fuse_type) { my_fc_bwd_config res; libxsmm_blasint lda = bk; libxsmm_blasint ldb = bc; libxsmm_blasint ldc = bk; libxsmm_blasint ld_zero_bwd = bc*bn; libxsmm_blasint ld_zero_upd = bk; libxsmm_blasint delbias_K = K; libxsmm_blasint delbias_N = N; float alpha = 1.0f; float beta = 1.0f; float zerobeta = 0.0f; libxsmm_blasint updM; libxsmm_blasint updN; int l_flags, l_tc_flags; int l_tr_flags = LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ); libxsmm_blasint unroll_hint; size_t size_bwd_scratch; size_t size_upd_scratch; libxsmm_blasint bbk; libxsmm_blasint bbc; libxsmm_blasint ldaT = bc; libxsmm_blasint ldb_orig= bc; /* setting up some handle values */ res.N = N; res.C = C; res.K = K; res.bn = bn; res.bc = bc; res.bk = bk; res.threads = threads; res.fuse_type = fuse_type; /* setup parallelization strategy */ res.bwd_M_hyperpartitions = 1; res.upd_M_hyperpartitions = 1; res.bwd_N_hyperpartitions = 1; res.upd_N_hyperpartitions = 1; if (threads == 16) { res.bwd_bf = 1; res.bwd_2d_blocking = 1; res.bwd_col_teams = 2; res.bwd_row_teams = 8; res.upd_bf = 1; res.upd_2d_blocking = 1; res.upd_col_teams = 2; res.upd_row_teams = 8; res.ifm_subtasks = 1; res.ofm_subtasks = 1; } else if (threads == 14) { res.bwd_bf = 1; res.bwd_2d_blocking = 1; res.bwd_col_teams = 2; res.bwd_row_teams = 7; res.upd_bf = 1; res.upd_2d_blocking = 1; res.upd_col_teams = 2; res.upd_row_teams = 7; res.ifm_subtasks = 1; res.ofm_subtasks = 1; } else if (threads == 56) { res.bwd_bf = 1; res.bwd_2d_blocking = 1; res.bwd_col_teams = 1; res.bwd_row_teams = 14; res.bwd_M_hyperpartitions = 1; res.bwd_N_hyperpartitions = 4; res.upd_bf = 1; res.upd_2d_blocking = 1; res.upd_col_teams = 1; res.upd_row_teams = 14; res.upd_M_hyperpartitions = 1; res.upd_N_hyperpartitions = 4; res.ifm_subtasks = 1; res.ofm_subtasks = 1; } else if (threads == 1) { res.bwd_bf = 1; res.bwd_2d_blocking = 1; res.bwd_col_teams = 1; res.bwd_row_teams = 1; res.bwd_M_hyperpartitions = 1; res.bwd_N_hyperpartitions = 1; res.upd_bf = 1; res.upd_2d_blocking = 1; res.upd_col_teams = 1; res.upd_row_teams = 1; res.upd_M_hyperpartitions = 1; res.upd_N_hyperpartitions = 1; res.ifm_subtasks = 1; res.ofm_subtasks = 1; } else { res.bwd_bf = 1; res.bwd_2d_blocking = 0; res.bwd_col_teams = 1; res.bwd_row_teams = 1; res.upd_bf = 1; res.upd_2d_blocking = 0; res.upd_col_teams = 1; res.upd_row_teams = 1; res.ifm_subtasks = 1; res.ofm_subtasks = 1; } bbk = (res.upd_2d_blocking == 1) ? bk : bk/res.ofm_subtasks; bbc = (res.upd_2d_blocking == 1) ? bc : bc/res.ifm_subtasks; #if 0 res.bwd_bf = atoi(getenv("BWD_BF")); res.bwd_2d_blocking = atoi(getenv("BWD_2D_BLOCKING")); res.bwd_col_teams = atoi(getenv("BWD_COL_TEAMS")); res.bwd_row_teams = atoi(getenv("BWD_ROW_TEAMS")); res.upd_bf = atoi(getenv("UPD_BF")); res.upd_2d_blocking = atoi(getenv("UPD_2D_BLOCKING")); res.upd_col_teams = atoi(getenv("UPD_COL_TEAMS")); res.upd_row_teams = atoi(getenv("UPD_ROW_TEAMS")); res.ifm_subtasks = atoi(getenv("IFM_SUBTASKS")); res.ofm_subtasks = atoi(getenv("OFM_SUBTASKS")); #endif /* setting up the barrier */ res.barrier = libxsmm_barrier_create(threads, 1); /* TPP creation */ /* BWD GEMM */ l_flags = ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ) | LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG; l_tc_flags = LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ); unroll_hint = (res.K/res.bk)/res.bwd_bf; res.gemm_bwd = libxsmm_bsmmdispatch_reducebatch_strd_unroll(res.bc, res.bn, res.bk, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bk*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &ldb, &lda, &ldb, &alpha, &beta, &l_flags, NULL); if ( res.gemm_bwd == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_bwd failed. Bailing...!\n"); exit(-1); } res.gemm_bwd2 = libxsmm_bsmmdispatch_reducebatch_strd_unroll(res.bc, res.bn, res.bk, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bk*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &ldb, &lda, &ldb, &alpha, &zerobeta, &l_flags, NULL); if ( res.gemm_bwd2 == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_bwd2 failed. Bailing...!\n"); exit(-1); } res.gemm_bwd3 = libxsmm_bmmdispatch_reducebatch_strd_unroll(res.bc, res.bn, res.bk, res.bk*res.bc*sizeof(libxsmm_bfloat16), res.bk*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &ldb, &lda, &ldb, &alpha, &zerobeta, &l_flags, NULL); if ( res.gemm_bwd3 == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_bwd3 failed. Bailing...!\n"); exit(-1); } /* Also JIT eltwise TPPs... */ res.bwd_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_unary(res.bc, res.bn, &ldb, &ldb, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY); if ( res.bwd_cvtfp32bf16_kernel == NULL ) { fprintf( stderr, "JIT for TPP bwd_cvtfp32bf16_kernel failed. Bailing...!\n"); exit(-1); } res.bwd_relu_kernel = libxsmm_dispatch_meltw_unary(res.bc, res.bn,&ldb, &ldb, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_BITMASK_2BYTEMULT, LIBXSMM_MELTW_TYPE_UNARY_RELU_INV); if ( res.bwd_relu_kernel == NULL ) { fprintf( stderr, "JIT for TPP bwd_relu_kernel failed. Bailing...!\n"); exit(-1); } res.bwd_zero_kernel = libxsmm_dispatch_meltw_unary(bn*bc, 1, &ld_zero_bwd, &ld_zero_bwd, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR); if ( res.bwd_zero_kernel == NULL ) { fprintf( stderr, "JIT for TPP bwd_zero_kernel failed. Bailing...!\n"); exit(-1); } /* JITing the tranpose kernel */ res.vnni_to_vnniT_kernel = libxsmm_dispatch_meltw_unary(bk, bc, &lda, &ldaT, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_VNNI_TO_VNNIT); if ( res.vnni_to_vnniT_kernel == NULL ) { fprintf( stderr, "JIT for TPP vnni_to_vnniT_kernel failed. Bailing...!\n"); exit(-1); } /* UPD GEMM */ lda = res.bk; ldb = res.bn; ldc = res.bk; updM = res.bk/res.ofm_subtasks; updN = res.bc/res.ifm_subtasks; l_flags = ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ) | LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | LIBXSMM_GEMM_FLAG_NO_SETUP_TILECONFIG; l_tc_flags = LIBXSMM_GEMM_FLAG_NO_RESET_TILECONFIG | ( LIBXSMM_GEMM_VNNI_FLAGS('N', 'N', 'V', 'N') ); unroll_hint = (res.N/res.bn)/res.upd_bf; res.gemm_upd = libxsmm_bsmmdispatch_reducebatch_strd_unroll(updM, updN, res.bn, res.bk*res.bn*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &beta, &l_flags, NULL); if ( res.gemm_upd == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_upd failed. Bailing...!\n"); exit(-1); } res.gemm_upd3 = libxsmm_bmmdispatch_reducebatch_strd_unroll(updM, updN, res.bn, res.bk*res.bn*sizeof(libxsmm_bfloat16), res.bc*res.bn*sizeof(libxsmm_bfloat16), unroll_hint, &lda, &ldb, &ldc, &alpha, &zerobeta, &l_flags, NULL); if ( res.gemm_upd3 == NULL ) { fprintf( stderr, "JIT for BRGEMM TPP gemm_upd3 failed. Bailing...!\n"); exit(-1); } /* Also JIT eltwise TPPs... */ res.upd_cvtfp32bf16_kernel = libxsmm_dispatch_meltw_unary(bbk, bbc, &ldc, &ldc, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY); if ( res.upd_cvtfp32bf16_kernel == NULL ) { fprintf( stderr, "JIT for TPP upd_cvtfp32bf16_kernel failed. Bailing...!\n"); exit(-1); } res.upd_zero_kernel = libxsmm_dispatch_meltw_unary(bbk, bbc, &ld_zero_upd, &ld_zero_upd, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR); if ( res.upd_zero_kernel == NULL ) { fprintf( stderr, "JIT for TPP upd_zero_kernel failed. Bailing...!\n"); exit(-1); } res.delbias_reduce_kernel = libxsmm_dispatch_meltw_unary(bk, bn, &delbias_K, &delbias_N, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_REDUCE_COLS, LIBXSMM_MELTW_TYPE_UNARY_REDUCE_X_OP_ADD_NCNC_FORMAT); if ( res.delbias_reduce_kernel == NULL ) { fprintf( stderr, "JIT for TPP delbias_reduce_kernel failed. Bailing...!\n"); exit(-1); } /* JITing the tranpose kernels */ res.norm_to_vnni_kernel = libxsmm_dispatch_meltw_unary(bk, bn, &lda, &lda, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI); if ( res.norm_to_vnni_kernel == NULL ) { fprintf( stderr, "JIT for TPP norm_to_vnni_kernel failed. Bailing...!\n"); exit(-1); } res.upd_norm_to_vnni_kernel = libxsmm_dispatch_meltw_unary(bk, bc, &lda, &lda, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI); if ( res.upd_norm_to_vnni_kernel == NULL ) { fprintf( stderr, "JIT for TPP upd_norm_to_vnni_kernel failed. Bailing...!\n"); exit(-1); } res.norm_to_vnni_kernel_wt = libxsmm_dispatch_meltw_unary(bbk, bbc, &ldc, &ldc, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI); if ( res.norm_to_vnni_kernel_wt == NULL ) { fprintf( stderr, "JIT for TPP norm_to_vnni_kernel failed. Bailing...!\n"); exit(-1); } res.norm_to_normT_kernel = libxsmm_dispatch_meltw_unary(bc, bn, &ldb, &ldb_orig, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT); if ( res.norm_to_normT_kernel == NULL ) { fprintf( stderr, "JIT for TPP norm_to_normT_kernel failed. Bailing...!\n"); exit(-1); } /* init scratch */ size_bwd_scratch = sizeof(float) * LIBXSMM_MAX(res.C * res.N, res.threads * res.bc * res.bn) + sizeof(libxsmm_bfloat16) * res.C * res.K; size_upd_scratch = sizeof(float) * LIBXSMM_MAX(res.C * res.K, res.threads * res.bc * res.bk) + sizeof(libxsmm_bfloat16) * res.threads * res.bk * res.bc + sizeof(libxsmm_bfloat16) * (res.N * (res.C + res.K)); #ifdef OVERWRITE_DOUTPUT_BWDUPD res.scratch_size = LIBXSMM_MAX(size_bwd_scratch, size_upd_scratch) + sizeof(libxsmm_bfloat16) * res.N * res.K; #else res.scratch_size = LIBXSMM_MAX(size_bwd_scratch, size_upd_scratch) + 2 * sizeof(libxsmm_bfloat16) * res.N * res.K; #endif res.doutput_scratch_mark = LIBXSMM_MAX(size_bwd_scratch, size_upd_scratch) ; return res; } my_opt_config setup_my_opt(libxsmm_blasint C, libxsmm_blasint K, libxsmm_blasint bc, libxsmm_blasint bk, libxsmm_blasint threads, float lr) { my_opt_config res; /* setting up some handle values */ res.C = C; res.K = K; res.bc = bc; res.bk = bk; res.threads = threads; res.lr = lr; /* setting up the barrier */ res.barrier = libxsmm_barrier_create(threads, 1); /* init scratch */ res.scratch_size = 0; return res; } my_smax_fwd_config setup_my_smax_fwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint bn, libxsmm_blasint bc, libxsmm_blasint threads) { my_smax_fwd_config res; /* setting up some handle values */ res.C = C; res.N = N; res.bc = bc; res.bn = bn; res.threads = threads; /* setting up the barrier */ res.barrier = libxsmm_barrier_create(threads, 1); /* init scratch */ res.scratch_size = (sizeof(float)*res.C*res.N*2);; return res; } my_smax_bwd_config setup_my_smax_bwd(libxsmm_blasint N, libxsmm_blasint C, libxsmm_blasint bn, libxsmm_blasint bc, libxsmm_blasint threads, float loss_weight) { my_smax_bwd_config res; /* setting up some handle values */ res.C = C; res.N = N; res.bc = bc; res.bn = bn; res.threads = threads; res.loss_weight = loss_weight; /* setting up the barrier */ res.barrier = libxsmm_barrier_create(threads, 1); /* init scratch */ res.scratch_size = (sizeof(float)*res.C*res.N*2); return res; } void my_fc_fwd_exec( my_fc_fwd_config cfg, const libxsmm_bfloat16* wt_ptr, const libxsmm_bfloat16* in_act_ptr, libxsmm_bfloat16* out_act_ptr, const libxsmm_bfloat16* bias_ptr, unsigned char* relu_ptr, int start_tid, int my_tid, void* scratch ) { const libxsmm_blasint nBlocksIFm = cfg.C / cfg.bc; const libxsmm_blasint nBlocksOFm = cfg.K / cfg.bk; const libxsmm_blasint nBlocksMB = cfg.N / cfg.bn; const libxsmm_blasint bn = cfg.bn; const libxsmm_blasint bk = cfg.bk; const libxsmm_blasint lpb = 2; const libxsmm_blasint bc_lp = cfg.bc/lpb; /* const libxsmm_blasint bc = cfg.bc;*/ libxsmm_blasint use_2d_blocking = cfg.fwd_2d_blocking; /* computing first logical thread */ const libxsmm_blasint ltid = my_tid - start_tid; /* number of tasks that could be run in parallel */ const libxsmm_blasint work = nBlocksOFm * nBlocksMB; /* compute chunk size */ const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work; const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work; /* loop variables */ libxsmm_blasint mb1ofm1 = 0, mb1 = 0, ofm1 = 0, ifm1 = 0; libxsmm_blasint N_tasks_per_thread = 0, M_tasks_per_thread = 0, my_M_start = 0, my_M_end = 0, my_N_start = 0, my_N_end = 0, my_col_id = 0, my_row_id = 0, col_teams = 0, row_teams = 0; LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, output, out_act_ptr, nBlocksOFm, cfg.bn, cfg.bk); LIBXSMM_VLA_DECL(4, const libxsmm_bfloat16, input, in_act_ptr, nBlocksIFm, cfg.bn, cfg.bc); LIBXSMM_VLA_DECL(5, const libxsmm_bfloat16, filter, wt_ptr, nBlocksIFm, bc_lp, cfg.bk, lpb); LIBXSMM_VLA_DECL(4, float, output_f32, (float*)scratch, nBlocksOFm, bn, bk); libxsmm_meltw_gemm_param gemm_eltwise_params; float* fp32_bias_scratch = ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) ? (float*)scratch + ltid * cfg.K : NULL; LIBXSMM_VLA_DECL(2, const libxsmm_bfloat16, bias, ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) ? (libxsmm_bfloat16*) bias_ptr : NULL, cfg.bk); LIBXSMM_VLA_DECL(4, __mmask32, relubitmask, ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) ? (__mmask32*)relu_ptr : NULL, nBlocksOFm, cfg.bn, cfg.bk/32); libxsmm_meltwfunction_unary eltwise_kernel_act = cfg.fwd_cvtfp32bf16_relu_kernel; libxsmm_meltw_unary_param eltwise_params_act; libxsmm_meltwfunction_unary eltwise_kernel = cfg.fwd_cvtfp32bf16_kernel; libxsmm_meltw_unary_param eltwise_params; libxsmm_meltw_unary_param copy_params; libxsmm_meltw_unary_param relu_params; libxsmm_meltwfunction_unary relu_kernel = cfg.fwd_relu_kernel; libxsmm_bmmfunction_reducebatch_strd gemm_kernel = ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) ? cfg.gemm_fwd2 : cfg.gemm_fwd3; unsigned long long blocks = nBlocksIFm; libxsmm_blasint CB_BLOCKS = nBlocksIFm, BF = 1; BF = cfg.fwd_bf; CB_BLOCKS = nBlocksIFm/BF; blocks = CB_BLOCKS; if (use_2d_blocking == 1) { int _ltid, M_hyperpartition_id, N_hyperpartition_id, _nBlocksOFm, _nBlocksMB, hyperteam_id; col_teams = cfg.fwd_col_teams; row_teams = cfg.fwd_row_teams; hyperteam_id = ltid/(col_teams*row_teams); _nBlocksOFm = nBlocksOFm/cfg.fwd_M_hyperpartitions; _nBlocksMB = nBlocksMB/cfg.fwd_N_hyperpartitions; _ltid = ltid % (col_teams * row_teams); M_hyperpartition_id = hyperteam_id % cfg.fwd_M_hyperpartitions; N_hyperpartition_id = hyperteam_id / cfg.fwd_M_hyperpartitions; my_row_id = _ltid % row_teams; my_col_id = _ltid / row_teams; N_tasks_per_thread = (_nBlocksMB + col_teams-1)/col_teams; M_tasks_per_thread = (_nBlocksOFm + row_teams-1)/row_teams; my_N_start = N_hyperpartition_id * _nBlocksMB + LIBXSMM_MIN( my_col_id * N_tasks_per_thread, _nBlocksMB); my_N_end = N_hyperpartition_id * _nBlocksMB + LIBXSMM_MIN( (my_col_id+1) * N_tasks_per_thread, _nBlocksMB); my_M_start = M_hyperpartition_id * _nBlocksOFm + LIBXSMM_MIN( my_row_id * M_tasks_per_thread, _nBlocksOFm); my_M_end = M_hyperpartition_id * _nBlocksOFm + LIBXSMM_MIN( (my_row_id+1) * M_tasks_per_thread, _nBlocksOFm); } /* lazy barrier init */ libxsmm_barrier_init(cfg.barrier, ltid); if (use_2d_blocking == 1) { if (BF > 1) { for ( ifm1 = 0; ifm1 < BF; ++ifm1 ) { for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) { for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) { if ( ifm1 == 0 ) { if ( (cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS ) { copy_params.in.primary = (void*) &LIBXSMM_VLA_ACCESS(2, bias, ofm1, 0,cfg.bk); copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm,cfg.bn,cfg.bk); cfg.fwd_colbcast_bf16fp32_copy_kernel(&copy_params); } else { copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); cfg.fwd_zero_kernel(&copy_params); } } cfg.gemm_fwd( &LIBXSMM_VLA_ACCESS(5, filter, ofm1, ifm1*CB_BLOCKS, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb), &LIBXSMM_VLA_ACCESS(4, input, mb1, ifm1*CB_BLOCKS, 0, 0, nBlocksIFm, cfg.bn, cfg.bc), &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk), &blocks); if ( ifm1 == BF-1 ) { if ( (cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU ) { eltwise_params_act.in.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_params_act.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_params_act.out.secondary = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32); eltwise_kernel_act(&eltwise_params_act); } else { eltwise_params.in.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_kernel(&eltwise_params); } } } } } } else { for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) { for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) { if ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) { copy_params.in.primary = (void*) &LIBXSMM_VLA_ACCESS(2, bias, ofm1, 0,cfg.bk); copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk); cfg.fwd_colbcast_bf16bf16_copy_kernel(&copy_params); } gemm_kernel( &LIBXSMM_VLA_ACCESS(5, filter, ofm1, 0, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb), &LIBXSMM_VLA_ACCESS(4, input, mb1, 0, 0, 0, nBlocksIFm, cfg.bn, cfg.bc), &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk), &blocks); if ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) { relu_params.in.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); relu_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); relu_params.out.secondary = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32); relu_kernel(&relu_params); } } } } } else { if (BF > 1) { for ( ifm1 = 0; ifm1 < BF; ++ifm1 ) { for ( mb1ofm1 = thr_begin; mb1ofm1 < thr_end; ++mb1ofm1 ) { mb1 = mb1ofm1%nBlocksMB; ofm1 = mb1ofm1/nBlocksMB; /* Initialize libxsmm_blasintermediate f32 tensor */ if ( ifm1 == 0 ) { if ( (cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS ) { copy_params.in.primary = (void*) &LIBXSMM_VLA_ACCESS(2, bias, ofm1, 0,cfg.bk); copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm,cfg.bn,cfg.bk); cfg.fwd_colbcast_bf16fp32_copy_kernel(&copy_params); } else { copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); cfg.fwd_zero_kernel(&copy_params); } } cfg.gemm_fwd( &LIBXSMM_VLA_ACCESS(5, filter, ofm1, ifm1*CB_BLOCKS, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb), &LIBXSMM_VLA_ACCESS(4, input, mb1, ifm1*CB_BLOCKS, 0, 0, nBlocksIFm, cfg.bn, cfg.bc), &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk), &blocks); if ( ifm1 == BF-1 ) { if ( (cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU ) { eltwise_params_act.in.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_params_act.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_params_act.out.secondary = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32); eltwise_kernel_act(&eltwise_params_act); } else { eltwise_params.in.primary = &LIBXSMM_VLA_ACCESS(4, output_f32, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); eltwise_kernel(&eltwise_params); } } } } } else { for ( mb1ofm1 = thr_begin; mb1ofm1 < thr_end; ++mb1ofm1 ) { mb1 = mb1ofm1%nBlocksMB; ofm1 = mb1ofm1/nBlocksMB; if ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) { copy_params.in.primary = (void*) &LIBXSMM_VLA_ACCESS(2, bias, ofm1, 0,cfg.bk); copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk); cfg.fwd_colbcast_bf16bf16_copy_kernel(&copy_params); } gemm_kernel( &LIBXSMM_VLA_ACCESS(5, filter, ofm1, 0, 0, 0, 0, nBlocksIFm, bc_lp, cfg.bk, lpb), &LIBXSMM_VLA_ACCESS(4, input, mb1, 0, 0, 0, nBlocksIFm, cfg.bn, cfg.bc), &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk), &blocks); if ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) { relu_params.in.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); relu_params.out.primary = &LIBXSMM_VLA_ACCESS(4, output, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); relu_params.out.secondary = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32); relu_kernel(&relu_params); } } } } libxsmm_barrier_wait(cfg.barrier, ltid); } void my_fc_bwd_exec( my_fc_bwd_config cfg, const libxsmm_bfloat16* wt_ptr, libxsmm_bfloat16* din_act_ptr, const libxsmm_bfloat16* dout_act_ptr, libxsmm_bfloat16* dwt_ptr, const libxsmm_bfloat16* in_act_ptr, libxsmm_bfloat16* dbias_ptr, const unsigned char* relu_ptr, my_pass pass, int start_tid, int my_tid, void* scratch ) { /* size variables, all const */ /* here we assume that input and output blocking is similar */ const libxsmm_blasint bn = cfg.bn; const libxsmm_blasint bk = cfg.bk; const libxsmm_blasint bc = cfg.bc; libxsmm_blasint lpb = 2; const libxsmm_blasint bc_lp = bc/lpb; const libxsmm_blasint bk_lp = bk/lpb; const libxsmm_blasint bn_lp = bn/lpb; const libxsmm_blasint nBlocksIFm = cfg.C / cfg.bc; const libxsmm_blasint nBlocksOFm = cfg.K / cfg.bk; const libxsmm_blasint nBlocksMB = cfg.N / cfg.bn; libxsmm_blasint mb1ofm1 = 0, mb1 = 0, ofm1 = 0, ofm2 = 0; libxsmm_blasint performed_doutput_transpose = 0; libxsmm_meltw_unary_param trans_param; /* computing first logical thread */ const libxsmm_blasint ltid = my_tid - start_tid; /* number of tasks for transpose that could be run in parallel */ const libxsmm_blasint eltwise_work = nBlocksOFm * nBlocksMB; /* compute chunk size */ const libxsmm_blasint eltwise_chunksize = (eltwise_work % cfg.threads == 0) ? (eltwise_work / cfg.threads) : ((eltwise_work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint eltwise_thr_begin = (ltid * eltwise_chunksize < eltwise_work) ? (ltid * eltwise_chunksize) : eltwise_work; const libxsmm_blasint eltwise_thr_end = ((ltid + 1) * eltwise_chunksize < eltwise_work) ? ((ltid + 1) * eltwise_chunksize) : eltwise_work; /* number of tasks for transpose that could be run in parallel */ const libxsmm_blasint dbias_work = nBlocksOFm; /* compute chunk size */ const libxsmm_blasint dbias_chunksize = (dbias_work % cfg.threads == 0) ? (dbias_work / cfg.threads) : ((dbias_work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint dbias_thr_begin = (ltid * dbias_chunksize < dbias_work) ? (ltid * dbias_chunksize) : dbias_work; const libxsmm_blasint dbias_thr_end = ((ltid + 1) * dbias_chunksize < dbias_work) ? ((ltid + 1) * dbias_chunksize) : dbias_work; LIBXSMM_VLA_DECL(2, libxsmm_bfloat16, dbias, ((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS) ? (libxsmm_bfloat16*) dbias_ptr : NULL, cfg.bk); LIBXSMM_VLA_DECL(4, __mmask32, relubitmask, ((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU) ? (__mmask32*)relu_ptr : NULL, nBlocksOFm, cfg.bn, cfg.bk/32); #ifdef OVERWRITE_DOUTPUT_BWDUPD libxsmm_bfloat16 *grad_output_ptr = (libxsmm_bfloat16*)dout_act_ptr; libxsmm_bfloat16 *tr_doutput_ptr = (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) ? (libxsmm_bfloat16*)((char*)scratch + cfg.doutput_scratch_mark) : (libxsmm_bfloat16*)scratch; #else libxsmm_bfloat16 *grad_output_ptr = (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) ? (libxsmm_bfloat16*)((char*)scratch + cfg.doutput_scratch_mark) : (libxsmm_bfloat16*)dout_act_ptr; libxsmm_bfloat16 *tr_doutput_ptr = (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) ? (libxsmm_bfloat16*)grad_output_ptr + cfg.N * cfg.K : (libxsmm_bfloat16*)scratch; #endif LIBXSMM_VLA_DECL(4, const libxsmm_bfloat16, doutput_orig, (libxsmm_bfloat16*)dout_act_ptr, nBlocksOFm, bn, bk); libxsmm_meltw_unary_param relu_params; libxsmm_meltwfunction_unary relu_kernel = cfg.bwd_relu_kernel; LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, doutput, grad_output_ptr, nBlocksOFm, bn, bk); LIBXSMM_VLA_DECL(5, libxsmm_bfloat16, doutput_tr, tr_doutput_ptr, nBlocksMB, bn_lp, bk, lpb); libxsmm_meltwfunction_unary eltwise_kernel = cfg.bwd_cvtfp32bf16_kernel; libxsmm_meltwfunction_unary eltwise_kernel2 = cfg.upd_cvtfp32bf16_kernel; libxsmm_meltw_unary_param eltwise_params; libxsmm_meltw_unary_param copy_params; libxsmm_meltw_unary_param delbias_params; /* lazy barrier init */ libxsmm_barrier_init(cfg.barrier, ltid); /* Apply to doutput potential fusions */ if (((cfg.fuse_type & MY_ELTWISE_FUSE_RELU) == MY_ELTWISE_FUSE_RELU)) { for ( mb1ofm1 = eltwise_thr_begin; mb1ofm1 < eltwise_thr_end; ++mb1ofm1 ) { mb1 = mb1ofm1/nBlocksOFm; ofm1 = mb1ofm1%nBlocksOFm; relu_params.in.primary =(void*) &LIBXSMM_VLA_ACCESS(4, doutput_orig, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); relu_params.out.primary = &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); relu_params.in.secondary = &LIBXSMM_VLA_ACCESS(4, relubitmask, mb1, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk/32); relu_kernel(&relu_params); /* If in UPD pass, also perform transpose of doutput */ if ( (pass & MY_PASS_BWD_W) == MY_PASS_BWD_W ) { trans_param.in.primary = &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk); trans_param.out.primary = &LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, mb1, 0, 0, 0, nBlocksMB, bn_lp, bk, lpb); cfg.norm_to_vnni_kernel(&trans_param); } } if ( (pass & MY_PASS_BWD_W) == MY_PASS_BWD_W ) { performed_doutput_transpose = 1; } libxsmm_barrier_wait(cfg.barrier, ltid); } /* Accumulation of bias happens in f32 */ if (((cfg.fuse_type & MY_ELTWISE_FUSE_BIAS) == MY_ELTWISE_FUSE_BIAS)) { for ( ofm1 = dbias_thr_begin; ofm1 < dbias_thr_end; ++ofm1 ) { delbias_params.in.primary = &LIBXSMM_VLA_ACCESS(4, doutput, 0, ofm1, 0, 0, nBlocksOFm, cfg.bn, cfg.bk); delbias_params.out.primary = &LIBXSMM_VLA_ACCESS(2, dbias, ofm1, 0, cfg.bk); cfg.delbias_reduce_kernel(&delbias_params); } /* wait for eltwise to finish */ libxsmm_barrier_wait(cfg.barrier, ltid); } if ( (pass & MY_PASS_BWD_D) == MY_PASS_BWD_D ){ libxsmm_blasint use_2d_blocking = cfg.bwd_2d_blocking; /* number of tasks that could be run in parallel */ const libxsmm_blasint work = nBlocksIFm * nBlocksMB; /* compute chunk size */ const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work; const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work; /* number of tasks for transpose that could be run in parallel */ const libxsmm_blasint transpose_work = nBlocksIFm * nBlocksOFm; /* compute chunk size */ const libxsmm_blasint transpose_chunksize = (transpose_work % cfg.threads == 0) ? (transpose_work / cfg.threads) : ((transpose_work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint transpose_thr_begin = (ltid * transpose_chunksize < transpose_work) ? (ltid * transpose_chunksize) : transpose_work; const libxsmm_blasint transpose_thr_end = ((ltid + 1) * transpose_chunksize < transpose_work) ? ((ltid + 1) * transpose_chunksize) : transpose_work; /* loop variables */ libxsmm_blasint ifm1 = 0, ifm1ofm1 = 0, mb1ifm1 = 0; libxsmm_blasint N_tasks_per_thread = 0, M_tasks_per_thread = 0, my_M_start = 0, my_M_end = 0, my_N_start = 0, my_N_end = 0, my_col_id = 0, my_row_id = 0, col_teams = 0, row_teams = 0; LIBXSMM_VLA_DECL(5, const libxsmm_bfloat16, filter, (libxsmm_bfloat16*)wt_ptr, nBlocksIFm, bc_lp, bk, lpb); LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, dinput, (libxsmm_bfloat16* )din_act_ptr, nBlocksIFm, bn, bc); LIBXSMM_VLA_DECL(5, libxsmm_bfloat16, filter_tr, (libxsmm_bfloat16*)scratch, nBlocksOFm, bk_lp, bc, lpb); float* temp_output = (float*)scratch + (cfg.C * cfg.K)/2; LIBXSMM_VLA_DECL(4, float, dinput_f32, (float*) temp_output, nBlocksIFm, bn, bc); unsigned long long blocks = nBlocksOFm; libxsmm_blasint KB_BLOCKS = nBlocksOFm, BF = 1; BF = cfg.bwd_bf; KB_BLOCKS = nBlocksOFm/BF; blocks = KB_BLOCKS; if (use_2d_blocking == 1) { int _ltid, M_hyperpartition_id, N_hyperpartition_id, _nBlocksIFm, _nBlocksMB, hyperteam_id; col_teams = cfg.bwd_col_teams; row_teams = cfg.bwd_row_teams; hyperteam_id = ltid/(col_teams*row_teams); _nBlocksIFm = nBlocksIFm/cfg.bwd_M_hyperpartitions; _nBlocksMB = nBlocksMB/cfg.bwd_N_hyperpartitions; _ltid = ltid % (col_teams * row_teams); M_hyperpartition_id = hyperteam_id % cfg.bwd_M_hyperpartitions; N_hyperpartition_id = hyperteam_id / cfg.bwd_M_hyperpartitions; my_row_id = _ltid % row_teams; my_col_id = _ltid / row_teams; N_tasks_per_thread = (_nBlocksMB + col_teams-1)/col_teams; M_tasks_per_thread = (_nBlocksIFm + row_teams-1)/row_teams; my_N_start = N_hyperpartition_id * _nBlocksMB + LIBXSMM_MIN( my_col_id * N_tasks_per_thread, _nBlocksMB); my_N_end = N_hyperpartition_id * _nBlocksMB + LIBXSMM_MIN( (my_col_id+1) * N_tasks_per_thread, _nBlocksMB); my_M_start = M_hyperpartition_id * _nBlocksIFm + LIBXSMM_MIN( my_row_id * M_tasks_per_thread, _nBlocksIFm); my_M_end = M_hyperpartition_id * _nBlocksIFm + LIBXSMM_MIN( (my_row_id+1) * M_tasks_per_thread, _nBlocksIFm); } /* transpose weight */ for (ifm1ofm1 = transpose_thr_begin; ifm1ofm1 < transpose_thr_end; ++ifm1ofm1) { ofm1 = ifm1ofm1 / nBlocksIFm; ifm1 = ifm1ofm1 % nBlocksIFm; trans_param.in.primary = (void*)&LIBXSMM_VLA_ACCESS(5, filter, ofm1, ifm1, 0, 0, 0, nBlocksIFm, bc_lp, bk, lpb); trans_param.out.primary = &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, ofm1, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb); cfg.vnni_to_vnniT_kernel(&trans_param); } /* wait for transpose to finish */ libxsmm_barrier_wait(cfg.barrier, ltid); if (use_2d_blocking == 1) { if (BF > 1) { for ( ofm1 = 0; ofm1 < BF; ++ofm1 ) { for (ifm1 = my_M_start; ifm1 < my_M_end; ++ifm1) { for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) { /* Initialize libxsmm_blasintermediate f32 tensor */ if ( ofm1 == 0 ) { copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc); cfg.bwd_zero_kernel(&copy_params); } cfg.gemm_bwd( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, ofm1*KB_BLOCKS, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb), &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1*KB_BLOCKS, 0, 0, nBlocksOFm, bn, bk), &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks); /* downconvert libxsmm_blasintermediate f32 tensor to bf 16 and store to final C */ if ( ofm1 == BF-1 ) { eltwise_params.in.primary = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc); eltwise_params.out.primary = &LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc); eltwise_kernel(&eltwise_params); } } } } } else { for (ifm1 = my_M_start; ifm1 < my_M_end; ++ifm1) { for (mb1 = my_N_start; mb1 < my_N_end; ++mb1) { cfg.gemm_bwd3( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, 0, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb), &LIBXSMM_VLA_ACCESS(4, doutput, mb1, 0, 0, 0, nBlocksOFm, bn, bk), &LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks); } } } } else { if (BF > 1) { for ( ofm1 = 0; ofm1 < BF; ++ofm1 ) { for ( mb1ifm1 = thr_begin; mb1ifm1 < thr_end; ++mb1ifm1 ) { mb1 = mb1ifm1%nBlocksMB; ifm1 = mb1ifm1/nBlocksMB; /* Initialize libxsmm_blasintermediate f32 tensor */ if ( ofm1 == 0 ) { copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc); cfg.bwd_zero_kernel(&copy_params); } cfg.gemm_bwd( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, ofm1*KB_BLOCKS, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb), &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1*KB_BLOCKS, 0, 0, nBlocksOFm, bn, bk), &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks); /* downconvert libxsmm_blasintermediate f32 tensor to bf 16 and store to final C */ if ( ofm1 == BF-1 ) { eltwise_params.in.primary = &LIBXSMM_VLA_ACCESS(4, dinput_f32, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc); eltwise_params.out.primary = &LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc); eltwise_kernel(&eltwise_params); } } } } else { for ( mb1ifm1 = thr_begin; mb1ifm1 < thr_end; ++mb1ifm1 ) { mb1 = mb1ifm1%nBlocksMB; ifm1 = mb1ifm1/nBlocksMB; cfg.gemm_bwd3( &LIBXSMM_VLA_ACCESS(5, filter_tr, ifm1, 0, 0, 0, 0, nBlocksOFm, bk_lp, bc, lpb), &LIBXSMM_VLA_ACCESS(4, doutput, mb1, 0, 0, 0, nBlocksOFm, bn, bk), &LIBXSMM_VLA_ACCESS(4, dinput, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc), &blocks); } } } libxsmm_barrier_wait(cfg.barrier, ltid); } if ( (pass & MY_PASS_BWD_W) == MY_PASS_BWD_W ) { /* number of tasks that could be run in parallel */ const libxsmm_blasint ofm_subtasks = (cfg.upd_2d_blocking == 1) ? 1 : cfg.ofm_subtasks; const libxsmm_blasint ifm_subtasks = (cfg.upd_2d_blocking == 1) ? 1 : cfg.ifm_subtasks; const libxsmm_blasint bbk = (cfg.upd_2d_blocking == 1) ? bk : bk/ofm_subtasks; const libxsmm_blasint bbc = (cfg.upd_2d_blocking == 1) ? bc : bc/ifm_subtasks; const libxsmm_blasint work = nBlocksIFm * ifm_subtasks * nBlocksOFm * ofm_subtasks; const libxsmm_blasint Cck_work = nBlocksIFm * ifm_subtasks * ofm_subtasks; const libxsmm_blasint Cc_work = nBlocksIFm * ifm_subtasks; /* 2D blocking parameters */ libxsmm_blasint use_2d_blocking = cfg.upd_2d_blocking; libxsmm_blasint N_tasks_per_thread = 0, M_tasks_per_thread = 0, my_M_start = 0, my_M_end = 0, my_N_start = 0, my_N_end = 0, my_col_id = 0, my_row_id = 0, col_teams = 0, row_teams = 0; /* compute chunk size */ const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work; const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work; libxsmm_blasint BF = cfg.upd_bf; /* loop variables */ libxsmm_blasint ifm1ofm1 = 0, ifm1 = 0, ifm2 = 0, bfn = 0, mb1ifm1 = 0; /* Batch reduce related variables */ unsigned long long blocks = nBlocksMB/BF; LIBXSMM_VLA_DECL(4, const libxsmm_bfloat16, input, (libxsmm_bfloat16* )in_act_ptr, nBlocksIFm, bn, bc); LIBXSMM_VLA_DECL(5, libxsmm_bfloat16, dfilter, (libxsmm_bfloat16*)dwt_ptr, nBlocksIFm, bc_lp, bk, lpb); /* Set up tensors for transposing/scratch before vnni reformatting dfilter */ libxsmm_bfloat16 *tr_inp_ptr = (libxsmm_bfloat16*) ((libxsmm_bfloat16*)scratch + cfg.N * cfg.K); float *dfilter_f32_ptr = (float*) ((libxsmm_bfloat16*)tr_inp_ptr + cfg.N * cfg.C); LIBXSMM_VLA_DECL(4, libxsmm_bfloat16, input_tr, (libxsmm_bfloat16*)tr_inp_ptr, nBlocksMB, bc, bn); LIBXSMM_VLA_DECL(4, float, dfilter_f32, (float*)dfilter_f32_ptr, nBlocksIFm, bc, bk); libxsmm_bfloat16 _tmp[bc*bk]; const libxsmm_blasint tr_out_work = nBlocksMB * nBlocksOFm; const libxsmm_blasint tr_out_chunksize = (tr_out_work % cfg.threads == 0) ? (tr_out_work / cfg.threads) : ((tr_out_work / cfg.threads) + 1); const libxsmm_blasint tr_out_thr_begin = (ltid * tr_out_chunksize < tr_out_work) ? (ltid * tr_out_chunksize) : tr_out_work; const libxsmm_blasint tr_out_thr_end = ((ltid + 1) * tr_out_chunksize < tr_out_work) ? ((ltid + 1) * tr_out_chunksize) : tr_out_work; const libxsmm_blasint tr_inp_work = nBlocksMB * nBlocksIFm; const libxsmm_blasint tr_inp_chunksize = (tr_inp_work % cfg.threads == 0) ? (tr_inp_work / cfg.threads) : ((tr_inp_work / cfg.threads) + 1); const libxsmm_blasint tr_inp_thr_begin = (ltid * tr_inp_chunksize < tr_inp_work) ? (ltid * tr_inp_chunksize) : tr_inp_work; const libxsmm_blasint tr_inp_thr_end = ((ltid + 1) * tr_inp_chunksize < tr_inp_work) ? ((ltid + 1) * tr_inp_chunksize) : tr_inp_work; if (use_2d_blocking == 1) { int _ltid, M_hyperpartition_id, N_hyperpartition_id, _nBlocksOFm, _nBlocksIFm, hyperteam_id; col_teams = cfg.upd_col_teams; row_teams = cfg.upd_row_teams; hyperteam_id = ltid/(col_teams*row_teams); _nBlocksOFm = nBlocksOFm/cfg.upd_M_hyperpartitions; _nBlocksIFm = nBlocksIFm/cfg.upd_N_hyperpartitions; _ltid = ltid % (col_teams * row_teams); M_hyperpartition_id = hyperteam_id % cfg.upd_M_hyperpartitions; N_hyperpartition_id = hyperteam_id / cfg.upd_M_hyperpartitions; my_row_id = _ltid % row_teams; my_col_id = _ltid / row_teams; N_tasks_per_thread = (_nBlocksIFm + col_teams-1)/col_teams; M_tasks_per_thread = (_nBlocksOFm + row_teams-1)/row_teams; my_N_start = N_hyperpartition_id * _nBlocksIFm + LIBXSMM_MIN( my_col_id * N_tasks_per_thread, _nBlocksIFm); my_N_end = N_hyperpartition_id * _nBlocksIFm + LIBXSMM_MIN( (my_col_id+1) * N_tasks_per_thread, _nBlocksIFm); my_M_start = M_hyperpartition_id * _nBlocksOFm + LIBXSMM_MIN( my_row_id * M_tasks_per_thread, _nBlocksOFm); my_M_end = M_hyperpartition_id * _nBlocksOFm + LIBXSMM_MIN( (my_row_id+1) * M_tasks_per_thread, _nBlocksOFm); } /* Required upfront tranposes */ for (mb1ifm1 = tr_inp_thr_begin; mb1ifm1 < tr_inp_thr_end; mb1ifm1++) { mb1 = mb1ifm1%nBlocksMB; ifm1 = mb1ifm1/nBlocksMB; trans_param.in.primary = (void*)&LIBXSMM_VLA_ACCESS(4, input, mb1, ifm1, 0, 0, nBlocksIFm, bn, bc); trans_param.out.primary = &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, mb1, 0, 0, nBlocksMB, bc, bn); cfg.norm_to_normT_kernel(&trans_param); } if (performed_doutput_transpose == 0) { for (mb1ofm1 = tr_out_thr_begin; mb1ofm1 < tr_out_thr_end; mb1ofm1++) { mb1 = mb1ofm1%nBlocksMB; ofm1 = mb1ofm1/nBlocksMB; trans_param.in.primary = &LIBXSMM_VLA_ACCESS(4, doutput, mb1, ofm1, 0, 0, nBlocksOFm, bn, bk); trans_param.out.primary = &LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, mb1, 0, 0, 0, nBlocksMB, bn_lp, bk, lpb); cfg.norm_to_vnni_kernel(&trans_param); } } libxsmm_barrier_wait(cfg.barrier, ltid); if (use_2d_blocking == 1) { ifm2 = 0; ofm2 = 0; if (BF == 1) { for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) { for (ifm1 = my_N_start; ifm1 < my_N_end; ++ifm1) { cfg.gemm_upd3(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, 0, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, 0, ifm2*bbc, 0, nBlocksMB, bc, bn), _tmp, &blocks); trans_param.in.primary = _tmp; trans_param.out.primary = &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, 0, 0, 0, nBlocksIFm, bc_lp, bk, lpb); cfg.upd_norm_to_vnni_kernel(&trans_param); } } } else { for (bfn = 0; bfn < BF; bfn++) { for (ofm1 = my_M_start; ofm1 < my_M_end; ++ofm1) { for (ifm1 = my_N_start; ifm1 < my_N_end; ++ifm1) { /* initialize current work task to zero */ if (bfn == 0) { copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk); cfg.upd_zero_kernel(&copy_params); } cfg.gemm_upd(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, bfn*blocks, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, bfn*blocks, ifm2*bbc, 0, nBlocksMB, bc, bn), &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk), &blocks); /* Downconvert result to BF16 and vnni format */ if (bfn == BF-1) { LIBXSMM_ALIGNED(libxsmm_bfloat16 tmp_buf[bc][bk], 64); eltwise_params.in.primary = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, 0, 0, nBlocksIFm, bc, bk); eltwise_params.out.primary = tmp_buf; trans_param.in.primary = tmp_buf; trans_param.out.primary = &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, 0, 0, 0, nBlocksIFm, bc_lp, bk, lpb); eltwise_kernel2(&eltwise_params); cfg.norm_to_vnni_kernel_wt(&trans_param); } } } } } } else { if (BF == 1) { for ( ifm1ofm1 = thr_begin; ifm1ofm1 < thr_end; ++ifm1ofm1 ) { ofm1 = ifm1ofm1 / Cck_work; ofm2 = (ifm1ofm1 % Cck_work) / Cc_work; ifm1 = ((ifm1ofm1 % Cck_work) % Cc_work) / ifm_subtasks; ifm2 = ((ifm1ofm1 % Cck_work) % Cc_work) % ifm_subtasks; cfg.gemm_upd3(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, 0, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, 0, ifm2*bbc, 0, nBlocksMB, bc, bn), _tmp, &blocks); trans_param.in.primary = _tmp; trans_param.out.primary = &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, (ifm2*bbc)/lpb, ofm2*bbk, 0, nBlocksIFm, bc_lp, bk, lpb); cfg.upd_norm_to_vnni_kernel(&trans_param); } } else { for (bfn = 0; bfn < BF; bfn++) { for ( ifm1ofm1 = thr_begin; ifm1ofm1 < thr_end; ++ifm1ofm1 ) { ofm1 = ifm1ofm1 / Cck_work; ofm2 = (ifm1ofm1 % Cck_work) / Cc_work; ifm1 = ((ifm1ofm1 % Cck_work) % Cc_work) / ifm_subtasks; ifm2 = ((ifm1ofm1 % Cck_work) % Cc_work) % ifm_subtasks; /* initialize current work task to zero */ if (bfn == 0) { copy_params.out.primary = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk); cfg.upd_zero_kernel(&copy_params); } cfg.gemm_upd(&LIBXSMM_VLA_ACCESS(5, doutput_tr, ofm1, bfn*blocks, 0, ofm2*bbk, 0, nBlocksMB, bn_lp, bk, lpb), &LIBXSMM_VLA_ACCESS(4, input_tr, ifm1, bfn*blocks, ifm2*bbc, 0, nBlocksMB, bc, bn), &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk), &blocks); /* Downconvert result to BF16 and vnni format */ if (bfn == BF-1) { LIBXSMM_ALIGNED(libxsmm_bfloat16 tmp_buf[bc][bk], 64); eltwise_params.in.primary = &LIBXSMM_VLA_ACCESS(4, dfilter_f32, ofm1, ifm1, ifm2*bbc, ofm2*bbk, nBlocksIFm, bc, bk); eltwise_params.out.primary = tmp_buf; trans_param.in.primary = tmp_buf; trans_param.out.primary = &LIBXSMM_VLA_ACCESS(5, dfilter, ofm1, ifm1, (ifm2*bbc)/lpb, ofm2*bbk, 0, nBlocksIFm, bc_lp, bk, lpb); eltwise_kernel2(&eltwise_params); cfg.norm_to_vnni_kernel_wt(&trans_param); } } } } } libxsmm_barrier_wait(cfg.barrier, ltid); } } void my_opt_exec( my_opt_config cfg, libxsmm_bfloat16* wt_ptr, float* master_wt_ptr, const libxsmm_bfloat16* delwt_ptr, int start_tid, int my_tid, void* scratch ) { /* loop counters */ libxsmm_blasint i; /* computing first logical thread */ const libxsmm_blasint ltid = my_tid - start_tid; /* number of tasks that could run in parallel for the filters */ const libxsmm_blasint work = cfg.C * cfg.K; /* compute chunk size */ const libxsmm_blasint chunksize = (work % cfg.threads == 0) ? (work / cfg.threads) : ((work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint thr_begin = (ltid * chunksize < work) ? (ltid * chunksize) : work; const libxsmm_blasint thr_end = ((ltid + 1) * chunksize < work) ? ((ltid + 1) * chunksize) : work; /* lazy barrier init */ libxsmm_barrier_init( cfg.barrier, ltid ); #if 0 /*defined(__AVX512BW__)*/ libxsmm_blasint iv = ( (thr_end-thr_begin)/16 ) * 16; /* compute iterations which are vectorizable */ __m512 vlr = _mm512_set1_ps( cfg.lr ); for ( i = thr_begin; i < thr_begin+iv; i+=16 ) { __m512 newfilter = _mm512_sub_ps( _mm512_loadu_ps( master_wt_ptr+i ), _mm512_mul_ps( vlr, _mm512_load_fil( delwt_ptr + i ) ) ); _mm512_store_fil( wt_ptr+i, newfilter ); _mm512_storeu_ps( master_wt_ptr+i, newfilter ); } for ( i = thr_begin+iv; i < thr_end; ++i ) { libxsmm_bfloat16_hp t1, t2; t1.i[0] =0; t1.i[1] = delwt_ptr[i]; master_wt_ptr[i] = master_wt_ptr[i] - (cfg.lr*t1.f); t2.f = master_wt_ptr[i]; wt_ptr[i] = t2.i[1]; } #else for ( i = thr_begin; i < thr_end; ++i ) { libxsmm_bfloat16_hp t1, t2; t1.i[0] =0; t1.i[1] = delwt_ptr[i]; master_wt_ptr[i] = master_wt_ptr[i] - (cfg.lr*t1.f); t2.f = master_wt_ptr[i]; wt_ptr[i] = t2.i[1]; } #endif libxsmm_barrier_wait( cfg.barrier, ltid ); } void my_smax_fwd_exec( my_smax_fwd_config cfg, const libxsmm_bfloat16* in_act_ptr, libxsmm_bfloat16* out_act_ptr, const int* label_ptr, float* loss, int start_tid, int my_tid, void* scratch ) { libxsmm_blasint bn = cfg.bn; libxsmm_blasint Bn = cfg.N/cfg.bn; libxsmm_blasint bc = cfg.bc; libxsmm_blasint Bc = cfg.C/cfg.bc; /* loop counters */ libxsmm_blasint i = 0; libxsmm_blasint img1, img2, ifm1, ifm2; /* computing first logical thread */ const libxsmm_blasint ltid = my_tid - start_tid; /* number of tasks that could run in parallel for the batch */ const libxsmm_blasint n_work = Bn * bn; /* compute chunk size */ const libxsmm_blasint n_chunksize = (n_work % cfg.threads == 0) ? (n_work / cfg.threads) : ((n_work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint n_thr_begin = (ltid * n_chunksize < n_work) ? (ltid * n_chunksize) : n_work; const libxsmm_blasint n_thr_end = ((ltid + 1) * n_chunksize < n_work) ? ((ltid + 1) * n_chunksize) : n_work; /* number of tasks that could run in parallel for the batch */ const libxsmm_blasint nc_work = Bn * bn * Bc * bc; /* compute chunk size */ const libxsmm_blasint nc_chunksize = (nc_work % cfg.threads == 0) ? (nc_work / cfg.threads) : ((nc_work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint nc_thr_begin = (ltid * nc_chunksize < nc_work) ? (ltid * nc_chunksize) : nc_work; const libxsmm_blasint nc_thr_end = ((ltid + 1) * nc_chunksize < nc_work) ? ((ltid + 1) * nc_chunksize) : nc_work; libxsmm_bfloat16* poutput_bf16 = out_act_ptr; const libxsmm_bfloat16* pinput_bf16 = in_act_ptr; float* poutput_fp32 = (float*)scratch; float* pinput_fp32 = ((float*)scratch)+(cfg.N*cfg.C); LIBXSMM_VLA_DECL(4, float, output, poutput_fp32, Bc, bn, bc); LIBXSMM_VLA_DECL(4, const float, input, pinput_fp32, Bc, bn, bc); LIBXSMM_VLA_DECL(2, const int, label, label_ptr, bn); /* lazy barrier init */ libxsmm_barrier_init( cfg.barrier, ltid ); for ( i = nc_thr_begin; i < nc_thr_end; ++i ) { libxsmm_bfloat16_hp in; in.i[0] = 0; in.i[1] = pinput_bf16[i]; pinput_fp32[i] = in.f; } libxsmm_barrier_wait( cfg.barrier, ltid ); for ( i = n_thr_begin; i < n_thr_end; ++i ) { float max = FLT_MIN; float sum_of_exp = 0.0f; img1 = i/bn; img2 = i%bn; /* set output to input and set compute max per image */ for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) { for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) { LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) = LIBXSMM_VLA_ACCESS( 4, input, img1, ifm1, img2, ifm2, Bc, bn, bc ); if ( LIBXSMM_VLA_ACCESS( 4, input, img1, ifm1, img2, ifm2, Bc, bn, bc ) > max ) { max = LIBXSMM_VLA_ACCESS( 4, input, img1, ifm1, img2, ifm2, Bc, bn, bc ); } } } /* sum exp over outputs */ for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) { for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) { LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) = (float)exp( (double)(LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) - max) ); sum_of_exp += LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ); } } /* scale output */ sum_of_exp = 1.0f/sum_of_exp; for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) { for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) { LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) = LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) * sum_of_exp; } } } libxsmm_barrier_wait( cfg.barrier, ltid ); /* calculate loss single threaded */ if ( ltid == 0 ) { (*loss) = 0.0f; for ( img1 = 0; img1 < Bn; ++img1 ) { for ( img2 = 0; img2 <bn; ++img2 ) { libxsmm_blasint ifm = (libxsmm_blasint)LIBXSMM_VLA_ACCESS( 2, label, img1, img2, bn ); libxsmm_blasint ifm1b = ifm/bc; libxsmm_blasint ifm2b = ifm%bc; float val = ( LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1b, img2, ifm2b, Bc, bn, bc ) > FLT_MIN ) ? LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1b, img2, ifm2b, Bc, bn, bc ) : FLT_MIN; *loss += LIBXSMM_LOGF( val ); } } *loss = ((-1.0f)*(*loss))/cfg.N; } libxsmm_barrier_wait( cfg.barrier, ltid ); for ( i = nc_thr_begin; i < nc_thr_end; ++i ) { libxsmm_bfloat16_hp in; in.f = poutput_fp32[i]; poutput_bf16[i] = in.i[1]; } libxsmm_barrier_wait( cfg.barrier, ltid ); } void my_smax_bwd_exec( my_smax_bwd_config cfg, libxsmm_bfloat16* delin_act_ptr, const libxsmm_bfloat16* out_act_ptr, const int* label_ptr, int start_tid, int my_tid, void* scratch ) { libxsmm_blasint bn = cfg.bn; libxsmm_blasint Bn = cfg.N/cfg.bn; libxsmm_blasint bc = cfg.bc; libxsmm_blasint Bc = cfg.C/cfg.bc; /* loop counters */ libxsmm_blasint i = 0; libxsmm_blasint img1, img2, ifm1, ifm2; float rcp_N = 1.0f/cfg.N; /* computing first logical thread */ const libxsmm_blasint ltid = my_tid - start_tid; /* number of tasks that could run in parallel for the batch */ const libxsmm_blasint n_work = Bn * bn; /* compute chunk size */ const libxsmm_blasint n_chunksize = (n_work % cfg.threads == 0) ? (n_work / cfg.threads) : ((n_work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const libxsmm_blasint n_thr_begin = (ltid * n_chunksize < n_work) ? (ltid * n_chunksize) : n_work; const libxsmm_blasint n_thr_end = ((ltid + 1) * n_chunksize < n_work) ? ((ltid + 1) * n_chunksize) : n_work; /* number of tasks that could run in parallel for the batch */ const libxsmm_blasint nc_work = Bn * bn * Bc * bc; /* compute chunk size */ const int nc_chunksize = (nc_work % cfg.threads == 0) ? (nc_work / cfg.threads) : ((nc_work / cfg.threads) + 1); /* compute thr_begin and thr_end */ const int nc_thr_begin = (ltid * nc_chunksize < nc_work) ? (ltid * nc_chunksize) : nc_work; const int nc_thr_end = ((ltid + 1) * nc_chunksize < nc_work) ? ((ltid + 1) * nc_chunksize) : nc_work; const libxsmm_bfloat16* poutput_bf16 = out_act_ptr; libxsmm_bfloat16* pdinput_bf16 = delin_act_ptr; float* poutput_fp32 = (float*)scratch; float* pdinput_fp32 = ((float*)scratch)+(cfg.N*cfg.C); LIBXSMM_VLA_DECL(4, const float, output, poutput_fp32, Bc, bn, bc); LIBXSMM_VLA_DECL(4, float, dinput, pdinput_fp32, Bc, bn, bc); LIBXSMM_VLA_DECL(2, const int, label, label_ptr, bn); /* lazy barrier init */ libxsmm_barrier_init( cfg.barrier, ltid ); for ( i = nc_thr_begin; i < nc_thr_end; ++i ) { libxsmm_bfloat16_hp out; out.i[0] = 0; out.i[1] = poutput_bf16[i]; poutput_fp32[i] = out.f; } libxsmm_barrier_wait( cfg.barrier, ltid ); for ( i = n_thr_begin; i < n_thr_end; ++i ) { img1 = i/bn; img2 = i%bn; /* set output to input and set compute max per image */ for ( ifm1 = 0; ifm1 < Bc; ++ifm1 ) { for ( ifm2 = 0; ifm2 < bc; ++ifm2 ) { if ( (ifm1*Bc)+ifm2 == (libxsmm_blasint)LIBXSMM_VLA_ACCESS( 2, label, img1, img2, bn ) ) { LIBXSMM_VLA_ACCESS( 4, dinput, img1, ifm1, img2, ifm2, Bc, bn, bc ) = ( LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) - 1.0f ) * rcp_N * cfg.loss_weight; } else { LIBXSMM_VLA_ACCESS( 4, dinput, img1, ifm1, img2, ifm2, Bc, bn, bc ) = LIBXSMM_VLA_ACCESS( 4, output, img1, ifm1, img2, ifm2, Bc, bn, bc ) * rcp_N * cfg.loss_weight; } } } } libxsmm_barrier_wait( cfg.barrier, ltid ); for ( i = nc_thr_begin; i < nc_thr_end; ++i ) { libxsmm_bfloat16_hp in; in.f = pdinput_fp32[i]; pdinput_bf16[i] = in.i[1]; } libxsmm_barrier_wait( cfg.barrier, ltid ); } void init_master_weights( my_opt_config cfg, float* master_wt_ptr, size_t size) { #if 0 if (0/* && cfg.upd_N_hyperpartitions != 1 */) { /* TODO: add hyperpartitions (?) */ /* Spread out weights in a blocked fasion since we partition the MODEL dimenstion */ init_buffer_block_numa((libxsmm_bfloat16*) master_wt_ptr, size/2); } else { /* Init weights in a block-cyclic fashion */ init_buffer_block_cyclic_numa(master_wt_ptr, size); } #endif } void init_weights( my_fc_fwd_config cfg, libxsmm_bfloat16* wt_ptr, size_t size) { if (cfg.fwd_M_hyperpartitions != 1) { /* Spread out weights in a blocked fasion since we partition the MODEL dimenstion */ init_buffer_block_numa(wt_ptr, size); } else { /* Init weights in a block fashion */ init_buffer_block_cyclic_numa(wt_ptr, size); } } void init_dweights( my_fc_bwd_config cfg, libxsmm_bfloat16* dwt_ptr, size_t size) { if (cfg.upd_N_hyperpartitions != 1) { /* Spread out weights */ init_buffer_block_numa(dwt_ptr, size); } else { /* Init weights in a block-cyclic fashion */ init_buffer_block_cyclic_numa(dwt_ptr, size); } } void init_acts( my_fc_fwd_config cfg, libxsmm_bfloat16* act_ptr, size_t size) { if (cfg.fwd_N_hyperpartitions != 1) { /* Spread out weights */ init_buffer_block_numa(act_ptr, size); } else { /* Init weights in a block-cyclic fashion */ init_buffer_block_cyclic_numa(act_ptr, size); } } void init_delacts( my_fc_bwd_config cfg, libxsmm_bfloat16* delact_ptr, size_t size) { if (cfg.bwd_N_hyperpartitions != 1) { /* Spread out weights */ init_buffer_block_numa(delact_ptr, size); } else { /* Init weights in a block-cyclic fashion */ init_buffer_block_cyclic_numa(delact_ptr, size); } } int main(int argc, char* argv[]) { libxsmm_bfloat16 **act_libxsmm, **fil_libxsmm, **delact_libxsmm, **delfil_libxsmm; libxsmm_bfloat16 **bias_libxsmm, **delbias_libxsmm; float **fil_master; unsigned char **relumask_libxsmm; int *label_libxsmm; my_eltwise_fuse my_fuse; my_fc_fwd_config* my_fc_fwd; my_fc_bwd_config* my_fc_bwd; my_opt_config* my_opt; my_smax_fwd_config my_smax_fwd; my_smax_bwd_config my_smax_bwd; void* scratch = NULL; size_t scratch_size = 0; /* some parameters we can overwrite via cli, default is some inner layer of overfeat */ int iters = 10; /* repetitions of benchmark */ int MB = 32; /* mini-batch size, "N" */ int fuse_type = 0; /* 0: nothing fused, 1: relu fused, 2: elementwise fused, 3: relu and elementwise fused */ char type = 'A'; /* 'A': ALL, 'F': FP, 'B': BP */ int bn = 64; int bk = 64; int bc = 64; int *C; /* number of input feature maps, "C" */ int num_layers = 0; const char *const env_check = getenv("CHECK"); const double check = LIBXSMM_ABS(0 == env_check ? 1 : atof(env_check)); #if defined(_OPENMP) int nThreads = omp_get_max_threads(); /* number of threads */ #else int nThreads = 1; /* number of threads */ #endif unsigned long long l_start, l_end; double l_total = 0.0; double gflop = 0.0; int i, j; double act_size = 0.0; double fil_size = 0.0; float lr = 0.1f; float loss_weight = 1.0f; float loss = 0.0; libxsmm_matdiff_info norms_fwd, norms_bwd, norms_upd, diff; libxsmm_matdiff_clear(&norms_fwd); libxsmm_matdiff_clear(&norms_bwd); libxsmm_matdiff_clear(&norms_upd); libxsmm_matdiff_clear(&diff); char* env_threads_per_numa; if (argc > 1 && !strncmp(argv[1], "-h", 3)) { printf("Usage: %s iters MB bn bk bc C1 C2 ... CN\n", argv[0]); return 0; } libxsmm_rng_set_seed(1); /* reading new values from cli */ i = 1; num_layers = argc - 7; if (argc > i) iters = atoi(argv[i++]); if (argc > i) MB = atoi(argv[i++]); if (argc > i) bn = atoi(argv[i++]); if (argc > i) bk = atoi(argv[i++]); if (argc > i) bc = atoi(argv[i++]); /* allocate the number of channles buffer */ if ( num_layers < 1 ) { printf("Usage: %s iters MB fuse_type type bn bk bc C1 C2 ... CN\n", argv[0]); return 0; } C = (int*)malloc((num_layers+2)*sizeof(int)); for (j = 0 ; i < argc; ++i, ++j ) { C[j] = atoi(argv[i]); } /* handle softmax config */ C[num_layers+1] = C[num_layers]; #if defined(__SSE3__) _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST); #endif /* Read env variables */ env_threads_per_numa = getenv("THREADS_PER_NUMA"); if ( 0 == env_threads_per_numa ) { printf("please specify THREADS_PER_NUMA to a non-zero value!\n"); return -1; } else { threads_per_numa = atoi(env_threads_per_numa); } /* print some summary */ printf("##########################################\n"); printf("# Setting Up (Common) #\n"); printf("##########################################\n"); printf("PARAMS: N:%d\n", MB); printf("PARAMS: Layers: %d\n", num_layers); printf("PARAMS: ITERS:%d", iters); if (LIBXSMM_FEQ(0, check)) printf(" Threads:%d\n", nThreads); else printf("\n"); for (i = 0; i < num_layers; ++i ) { if (i == 0) { act_size += (double)(MB*C[i]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0); printf("SIZE Activations %i (%dx%d): %10.2f MiB\n", i, MB, C[i], (double)(MB*C[i]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) ); } act_size += (double)(MB*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0); fil_size += (double)(C[i]*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0); printf("SIZE Filter %i (%dx%d): %10.2f MiB\n", i, C[i], C[i+1], (double)(C[i]*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) ); printf("SIZE Activations %i (%dx%d): %10.2f MiB\n", i+1, MB, C[i+1], (double)(MB*C[i+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) ); } act_size += (double)(MB*C[num_layers+1]*sizeof(float))/(1024.0*1024.0); printf("SIZE Activations softmax (%dx%d): %10.2f MiB\n", MB, C[num_layers+1], (double)(MB*C[num_layers+1]*sizeof(libxsmm_bfloat16))/(1024.0*1024.0) ); printf("\nTOTAL SIZE Activations: %10.2f MiB\n", act_size ); printf("TOTAL SIZE Filter (incl. master): %10.2f MiB\n", 3.0*fil_size ); printf("TOTAL SIZE delActivations: %10.2f MiB\n", act_size ); printf("TOTAL SIZE delFilter: %10.2f MiB\n", fil_size ); printf("TOTAL SIZE MLP: %10.2f MiB\n", (4.0*fil_size) + (2.0*act_size) ); /* allocate data */ act_libxsmm = (libxsmm_bfloat16**)malloc( (num_layers+2)*sizeof(libxsmm_bfloat16*) ); delact_libxsmm = (libxsmm_bfloat16**)malloc( (num_layers+1)*sizeof(libxsmm_bfloat16*) ); for ( i = 0 ; i < num_layers+2; ++i ) { act_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( MB*C[i]*sizeof(libxsmm_bfloat16), 2097152); /* softmax has no incoming gradients */ if ( i < num_layers+1 ) { delact_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( MB*C[i]*sizeof(libxsmm_bfloat16), 2097152); } } fil_master = (float**) malloc( num_layers*sizeof(float*) ); fil_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) ); delfil_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) ); for ( i = 0 ; i < num_layers; ++i ) { fil_master[i] = (float*) libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(float), 2097152); fil_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(libxsmm_bfloat16), 2097152); delfil_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i]*C[i+1]*sizeof(libxsmm_bfloat16), 2097152); } bias_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) ); delbias_libxsmm = (libxsmm_bfloat16**)malloc( num_layers*sizeof(libxsmm_bfloat16*) ); for ( i = 0 ; i < num_layers; ++i ) { bias_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i+1]*sizeof(libxsmm_bfloat16), 2097152); delbias_libxsmm[i] = (libxsmm_bfloat16*)libxsmm_aligned_malloc( C[i+1]*sizeof(libxsmm_bfloat16), 2097152); } relumask_libxsmm = (unsigned char**)malloc( num_layers*sizeof(unsigned char*) ); for ( i = 0 ; i < num_layers; ++i ) { relumask_libxsmm[i] = (unsigned char*)libxsmm_aligned_malloc( MB*C[i+1]*sizeof(unsigned char), 2097152); } label_libxsmm = (int*)libxsmm_aligned_malloc( MB*sizeof(int), 2097152); printf("\n"); printf("##########################################\n"); printf("# Setting Up (custom-Storage) #\n"); printf("##########################################\n"); /* allocating handles */ my_fc_fwd = (my_fc_fwd_config*) malloc( num_layers*sizeof(my_fc_fwd_config) ); my_fc_bwd = (my_fc_bwd_config*) malloc( num_layers*sizeof(my_fc_bwd_config) ); my_opt = (my_opt_config*) malloc( num_layers*sizeof(my_opt_config) ); /* setting up handles + scratch */ size_t max_bwd_scratch_size = 0, max_doutput_scratch_mark = 0; scratch_size = 0; for ( i = 0; i < num_layers; ++i ) { /* MNIST Specific where everywhere we use relu act except the last layer */ if ( i < num_layers -1 ) { my_fuse = MY_ELTWISE_FUSE_RELU; } else { my_fuse = MY_ELTWISE_FUSE_NONE; } my_fc_fwd[i] = setup_my_fc_fwd(MB, C[i], C[i+1], (MB % bn == 0) ? bn : MB, (C[i ] % bc == 0) ? bc : C[i ], (C[i+1] % bk == 0) ? bk : C[i+1], nThreads, my_fuse); my_fc_bwd[i] = setup_my_fc_bwd(MB, C[i], C[i+1], (MB % bn == 0) ? bn : MB, (C[i ] % bc == 0) ? bc : C[i ], (C[i+1] % bk == 0) ? bk : C[i+1], nThreads, my_fuse); my_opt[i] = setup_my_opt( C[i], C[i+1], (C[i ] % bc == 0) ? bc : C[i ], (C[i+1] % bk == 0) ? bk : C[i+1], nThreads, lr ); if (my_fc_bwd[i].scratch_size > 0 && my_fc_bwd[i].scratch_size > max_bwd_scratch_size) { max_bwd_scratch_size = my_fc_bwd[i].scratch_size; } if (my_fc_bwd[i].doutput_scratch_mark > 0 && my_fc_bwd[i].doutput_scratch_mark > max_doutput_scratch_mark) { max_doutput_scratch_mark = my_fc_bwd[i].doutput_scratch_mark; } /* let's allocate and bind scratch */ if ( my_fc_fwd[i].scratch_size > 0 || my_fc_bwd[i].scratch_size > 0 || my_opt[i].scratch_size > 0 ) { size_t alloc_size = LIBXSMM_MAX( LIBXSMM_MAX( my_fc_fwd[i].scratch_size, my_fc_bwd[i].scratch_size), my_opt[i].scratch_size ); if ( alloc_size > scratch_size ) { scratch_size = alloc_size; } } } /* softmax+loss is treated as N+1 layer */ my_smax_fwd = setup_my_smax_fwd( MB, C[num_layers+1], (MB % bn == 0) ? bn : MB, (C[num_layers+1] % bk == 0) ? bk : C[num_layers+1], nThreads ); my_smax_bwd = setup_my_smax_bwd( MB, C[num_layers+1], (MB % bn == 0) ? bn : MB, (C[num_layers+1] % bk == 0) ? bk : C[num_layers+1], nThreads, loss_weight ); if ( my_smax_fwd.scratch_size > 0 || my_smax_bwd.scratch_size > 0 ) { size_t alloc_size = LIBXSMM_MAX( my_smax_fwd.scratch_size, my_smax_bwd.scratch_size ); if ( alloc_size > scratch_size ) { scratch_size = alloc_size; } } scratch = libxsmm_aligned_malloc( scratch_size, 2097152 ); /* init data */ for ( i = 0 ; i < num_layers+2; ++i ) { init_acts(my_fc_fwd[i], act_libxsmm[i], MB*C[i]); } for ( i = 0 ; i < num_layers+1; ++i ) { init_delacts(my_fc_bwd[i], delact_libxsmm[i], MB*C[i]); } for ( i = 0 ; i < num_layers; ++i ) { /*init_master_weights(my_opt[i], fil_master[i], C[i]*C[i+1] );*/ my_init_buf( fil_master[i], C[i]*C[i+1], 0, 0 ); libxsmm_rne_convert_fp32_bf16( fil_master[i], fil_libxsmm[i], C[i]*C[i+1] ); /*init_weights(my_fc_fwd[i], fil_libxsmm[i], C[i]*C[i+1]);*/ init_dweights(my_fc_bwd[i], delfil_libxsmm[i], C[i]*C[i+1]); } for ( i = 0 ; i < num_layers; ++i ) { my_init_buf_bf16( bias_libxsmm[i], C[i+1], 0, 0 ); } for ( i = 0 ; i < num_layers; ++i ) { my_init_buf_bf16( delbias_libxsmm[i], C[i+1], 0, 0 ); } zero_buf_int32( label_libxsmm, MB ); /* Reading in the MNIST dataset */ int n_batches = NUM_TRAIN/MB, batch_id = 0; int n_epochs = iters, epoch_id = 0; libxsmm_bfloat16 *input_acts = (libxsmm_bfloat16*)libxsmm_aligned_malloc( NUM_TRAIN * C[0] * sizeof(libxsmm_bfloat16), 2097152); /* Read in input data */ char *train_image_path = "../mlpdriver/mnist_data/train-images.idx3-ubyte"; char *train_label_path = "../mlpdriver/mnist_data/train-labels.idx1-ubyte"; char *test_image_path = "../mlpdriver/mnist_data/t10k-images.idx3-ubyte"; char *test_label_path = "../mlpdriver/mnist_data/t10k-labels.idx1-ubyte"; load_mnist(train_image_path, train_label_path, test_image_path, test_label_path); /* Format the input layer in NCNC blocked format */ int _i, _j; for (_i = 0; _i < n_batches*MB; _i++) { for (_j = 0; _j < C[0]; _j++) { float val = (_j < 784) ? (float) train_image[_i][_j] : (float)0.0; int batchid = _i/MB; int mb = _i % MB; int _bn = (MB % bn == 0) ? bn : MB; int _bc = (C[0] % bc == 0) ? bc : C[0]; libxsmm_bfloat16 *cur_pos = input_acts + batchid * MB *C[0] + (mb / _bn) * C[0] * _bn + (_j / _bc) * _bn * _bc + (mb % _bn) * _bc + (_j % _bc); libxsmm_rne_convert_fp32_bf16( &val, cur_pos, 1 ); } } printf("###########################################\n"); printf("# Training MNIST with %d training samples #\n", n_batches*MB); printf("###########################################\n"); l_start = libxsmm_timer_tick(); #if defined(_OPENMP) # pragma omp parallel private(i,j,epoch_id,batch_id) #endif { #if defined(_OPENMP) const int tid = omp_get_thread_num(); #else const int tid = 0; #endif for (epoch_id = 0; epoch_id < n_epochs; epoch_id++) { for (batch_id = 0; batch_id < n_batches; batch_id++) { for ( i = 0; i < num_layers; ++i) { libxsmm_bfloat16 *input_act_ptr = (i == 0) ? input_acts + batch_id * MB * C[0] : act_libxsmm[i]; my_fc_fwd_exec( my_fc_fwd[i], fil_libxsmm[i], input_act_ptr, act_libxsmm[i+1], bias_libxsmm[i], relumask_libxsmm[i], 0, tid, scratch ); } my_smax_fwd_exec( my_smax_fwd, act_libxsmm[num_layers], act_libxsmm[num_layers+1], train_label + batch_id * MB, &loss, 0, tid, scratch ); if ((tid == 0) && (batch_id == 0) && (epoch_id % 10 == 0 || epoch_id == n_epochs - 1 )) { printf("Loss for epoch %d batch_id %d is %f\n", epoch_id, batch_id, loss); } my_smax_bwd_exec( my_smax_bwd, delact_libxsmm[num_layers], act_libxsmm[num_layers+1], train_label + batch_id * MB, 0, tid, scratch ); for ( i = num_layers-1; i > 0; --i) { my_fc_bwd_exec( my_fc_bwd[i], fil_libxsmm[i], delact_libxsmm[i], delact_libxsmm[i+1], delfil_libxsmm[i], act_libxsmm[i], delbias_libxsmm[i], relumask_libxsmm[i], MY_PASS_BWD, 0, tid, scratch ); my_opt_exec( my_opt[i], fil_libxsmm[i], fil_master[i], delfil_libxsmm[i], 0, tid, scratch ); } my_fc_bwd_exec( my_fc_bwd[0], fil_libxsmm[0], delact_libxsmm[0], delact_libxsmm[0+1], delfil_libxsmm[0], input_acts + batch_id * MB * C[0], delbias_libxsmm[0], relumask_libxsmm[0], MY_PASS_BWD_W, 0, tid, scratch ); my_opt_exec( my_opt[0], fil_libxsmm[0], fil_master[0], delfil_libxsmm[0], 0, tid, scratch ); } } } l_end = libxsmm_timer_tick(); l_total = libxsmm_timer_duration(l_start, l_end); gflop = 0.0; for ( i = num_layers-1; i > 0; --i) { gflop += (6.0*(double)MB*(double)C[i]*(double)C[i+1]*(double)((double)n_epochs *(double)n_batches)) / (1000.0*1000.0*1000.0); } gflop += (4.0*(double)MB*(double)C[0]*(double)C[1]*(double)((double)n_epochs *(double)n_batches)) / (1000.0*1000.0*1000.0); printf("GFLOP = %.5g\n", gflop/(double)((double)n_epochs *(double)n_batches)); printf("fp time = %.5g\n", ((double)(l_total/((double)n_epochs *(double)n_batches)))); printf("GFLOPS = %.5g\n", gflop/l_total); printf("PERFDUMP,BP,%s,%i,%i,", LIBXSMM_VERSION, nThreads, MB ); for ( i = 0; i < num_layers; ++i ) { printf("%i,", C[i] ); } printf("%f,%f\n", ((double)(l_total/((double)n_epochs *(double)n_batches))), gflop/l_total); #ifdef TEST_ACCURACY /* Test accuracy */ n_batches = NUM_TEST/MB; for (_i = 0; _i < n_batches * MB; _i++) { for (_j = 0; _j < C[0]; _j++) { float val = (_j < 784) ? (float) test_image[_i][_j] : 0.0; int batchid = _i/MB; int mb = _i % MB; int _bn = (MB % bn == 0) ? bn : MB; int _bc = (C[0] % bc == 0) ? bc : C[0]; libxsmm_bfloat16 *cur_pos = input_acts + batchid * MB *C[0] + (mb / _bn) * C[0] * _bn + (_j / _bc) * _bn * _bc + (mb % _bn) * _bc + (_j % _bc); libxsmm_rne_convert_fp32_bf16( &val, cur_pos, 1 ); } } n_batches = NUM_TEST/MB; unsigned int hits = 0; unsigned int samples = 0; #if defined(_OPENMP) # pragma omp parallel private(i,j,batch_id) #endif { #if defined(_OPENMP) const int tid = omp_get_thread_num(); #else const int tid = 0; #endif for (batch_id = 0; batch_id < n_batches; batch_id++) { for ( i = 0; i < num_layers; ++i) { libxsmm_bfloat16 *input_act_ptr = (i == 0) ? input_acts + batch_id * MB * C[0] : act_libxsmm[i]; my_fc_fwd_exec( my_fc_fwd[i], fil_libxsmm[i], input_act_ptr, act_libxsmm[i+1], bias_libxsmm[i], relumask_libxsmm[i], 0, tid, scratch ); } my_smax_fwd_exec( my_smax_fwd, act_libxsmm[num_layers], act_libxsmm[num_layers+1], test_label + batch_id * MB, &loss, 0, tid, scratch ); if (tid == 0) { for (_i = 0; _i < MB; _i++) { int label = *(test_label + batch_id * MB + _i); int max_id = 0; float max_val = 0.0; libxsmm_convert_bf16_f32( act_libxsmm[num_layers+1] + _i * 10, &max_val, 1 ); /* Find predicted label */ for (_j = 1; _j < 10; _j++) { libxsmm_bfloat16 val = *(act_libxsmm[num_layers+1] + _i * 10 + _j); float f32_val; libxsmm_convert_bf16_f32( &val, &f32_val, 1 ); if (f32_val > max_val) { max_id = _j; max_val = f32_val; } } /* Compare with true label */ if (max_id == label) { hits++; } samples++; } } #pragma omp barrier } } printf("Accuracy is %f %% (%d test samples)\n", (1.0*hits)/(1.0*samples)*100.0, samples); #endif /* deallocate data */ if ( scratch != NULL ) { libxsmm_free(scratch); } for ( i = 0; i < num_layers; ++i ) { if ( i == 0 ) { libxsmm_free(act_libxsmm[i]); libxsmm_free(delact_libxsmm[i]); } libxsmm_free(act_libxsmm[i+1]); libxsmm_free(delact_libxsmm[i+1]); libxsmm_free(fil_libxsmm[i]); libxsmm_free(delfil_libxsmm[i]); libxsmm_free(bias_libxsmm[i]); libxsmm_free(delbias_libxsmm[i]); libxsmm_free(relumask_libxsmm[i]); libxsmm_free(fil_master[i]); } libxsmm_free(act_libxsmm[num_layers+1]); libxsmm_free(label_libxsmm); libxsmm_free(input_acts); free( my_opt ); free( my_fc_fwd ); free( my_fc_bwd ); free( act_libxsmm ); free( delact_libxsmm ); free( fil_master ); free( fil_libxsmm ); free( delfil_libxsmm ); free( bias_libxsmm ); free( delbias_libxsmm ); free( relumask_libxsmm ); free( C ); /* some empty lines at the end */ printf("\n\n\n"); return 0; }
SparseProduct.c
#include <stdio.h> #include <stdlib.h> #include <math.h> /// #include "InputOutput.h" #include "ScalarVectors.h" #include "hb_io.h" #include "SparseProduct.h" /*********************************************************************************/ // This routine creates a sparseMatrix from the next parameters // * numR defines the number of rows // * numC defines the number of columns // * numE defines the number of nonzero elements // * msr indicates if the MSR is the format used to the sparse matrix // If msr is actived, numE doesn't include the diagonal elements // The parameter index indicates if 0-indexing or 1-indexing is used. void CreateSparseMatrix (ptr_SparseMatrix p_spr, int index, int numR, int numC, int numE, int msr) { // printf (" index = %d , numR = %d , numC = %d , numE = %d\n", index, numR, numC, numE); // The scalar components of the structure are initiated p_spr->dim1 = numR; p_spr->dim2 = numC; // Only one malloc is made for the vectors of indices CreateInts (&(p_spr->vptr), numE+numR+1); // The first component of the vectors depends on the used format *(p_spr->vptr) = ((msr)? (numR+1): 0) + index; p_spr->vpos = p_spr->vptr + ((msr)? 0: (numR+1)); // The number of nonzero elements depends on the format used CreateDoubles (&(p_spr->vval), numE+(numR+1)*msr); } // This routine liberates the memory related to matrix spr void RemoveSparseMatrix (ptr_SparseMatrix spr) { // First the scalar are initiated spr->dim1 = -1; spr->dim2 = -1; // The vectors are liberated RemoveInts (&(spr->vptr)); RemoveDoubles (&(spr->vval)); } /*********************************************************************************/ // This routine creates de sparse matrix dst from the symmetric matrix spr. // The parameters indexS and indexD indicate, respectivaly, if 0-indexing or 1-indexing is used // to store the sparse matrices. void DesymmetrizeSparseMatrices (SparseMatrix src, int indexS, ptr_SparseMatrix dst, int indexD) { int n = src.dim1, nnz = 0; int *sizes = NULL; int *pp1 = NULL, *pp2 = NULL, *pp3 = NULL, *pp4 = NULL, *pp5 = NULL; int i, j, dim, indexDS = indexD - indexS; double *pd3 = NULL, *pd4 = NULL; // The vector sizes is created and initiated CreateInts (&sizes, n); InitInts (sizes, n, 0, 0); // This loop counts the number of elements in each row pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS; pp2 = pp1 + 1 ; pp4 = sizes - indexS; for (i=indexS; i<(n+indexS); i++) { // The size of the corresponding row is accumulated dim = (*pp2 - *pp1); pp4[i] += dim; // Now each component of the row is analyzed for (j=0; j<dim; j++) { // The nondiagonals elements define another element in the graph if (*pp3 != i) pp4[*pp3]++; pp3++; } pp1 = pp2++; } // Compute the number of nonzeros of the new sparse matrix nnz = AddInts (sizes, n); // Create the new sparse matrix CreateSparseMatrix (dst, indexD, n, n, nnz, 0); // Fill the vector of pointers CopyInts (sizes, (dst->vptr) + 1, n); dst->vptr[0] = indexD; TransformLengthtoHeader (dst->vptr, n); // The vector sizes is initiated with the beginning of each row CopyInts (dst->vptr, sizes, n); // This loop fills the contents of vector vpos pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS; pp2 = pp1 + 1 ; pp4 = dst->vpos - indexD; pp5 = sizes - indexS; pd3 = src.vval + *pp1 - indexS; pd4 = dst->vval - indexD; for (i=indexS; i<(n+indexS); i++) { dim = (*pp2 - *pp1); for (j=0; j<dim; j++) { // The elements in the i-th row pp4[pp5[i] ] = *pp3+indexDS; pd4[pp5[i]++] = *pd3; if (*pp3 != i) { // The nondiagonals elements define another element in the graph pp4[pp5[*pp3] ] = i+indexDS; pd4[pp5[*pp3]++] = *pd3; } pp3++; pd3++; } pp1 = pp2++; } // The memory related to the vector sizes is liberated RemoveInts (&sizes); } /*********************************************************************************/ // This routine creates de sparse matrix dst from the matrix spr. // The parameters indexS and indexD indicate, respectivaly, if 0-indexing or 1-indexing is used // to store the sparse matrices. void TransposeSparseMatrices (SparseMatrix src, int indexS, ptr_SparseMatrix dst, int indexD) { int n = src.dim1, nnz = 0; int *sizes = NULL; int *pp1 = NULL, *pp2 = NULL, *pp3 = NULL, *pp4 = NULL, *pp5 = NULL; int i, j, dim, indexDS = indexD - indexS; double *pd3 = NULL, *pd4 = NULL; // The vector sizes is created and initiated CreateInts (&sizes, n); InitInts (sizes, n, 0, 0); // This loop counts the number of elements in each row pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS; pp2 = pp1 + 1 ; pp4 = sizes - indexS; for (i=indexS; i<(n+indexS); i++) { // The size of the corresponding row is accumulated dim = (*pp2 - *pp1); // Now each component of the row is analyzed for (j=0; j<dim; j++) { pp4[*pp3]++; pp3++; } pp1 = pp2++; } // Compute the number of nonzeros of the new sparse matrix nnz = AddInts (sizes, n); // Create the new sparse matrix CreateSparseMatrix (dst, indexD, n, n, nnz, 0); // Fill the vector of pointers CopyInts (sizes, (dst->vptr) + 1, n); dst->vptr[0] = indexD; TransformLengthtoHeader (dst->vptr, n); // The vector sizes is initiated with the beginning of each row CopyInts (dst->vptr, sizes, n); // This loop fills the contents of vector vpos pp1 = src.vptr; pp3 = src.vpos + *pp1 - indexS; pp2 = pp1 + 1 ; pp4 = dst->vpos - indexD; pp5 = sizes - indexS; pd3 = src.vval + *pp1 - indexS; pd4 = dst->vval - indexD; for (i=indexS; i<(n+indexS); i++) { dim = (*pp2 - *pp1); for (j=0; j<dim; j++) { // The elements in the i-th column pp4[pp5[*pp3] ] = i+indexDS; pd4[pp5[*pp3]++] = *pd3; pp3++; pd3++; } pp1 = pp2++; } // The memory related to the vector sizes is liberated RemoveInts (&sizes); } /*********************************************************************************/ int ReadMatrixHB (char *filename, ptr_SparseMatrix p_spr) { int *colptr = NULL; double *exact = NULL; double *guess = NULL; int indcrd; char *indfmt = NULL; FILE *input; char *key = NULL; char *mxtype = NULL; int ncol; int neltvl; int nnzero; int nrhs; int nrhsix; int nrow; int ptrcrd; char *ptrfmt = NULL; int rhscrd; char *rhsfmt = NULL; int *rhsind = NULL; int *rhsptr = NULL; char *rhstyp = NULL; double *rhsval = NULL; double *rhsvec = NULL; int *rowind = NULL; char *title = NULL; int totcrd; int valcrd; char *valfmt = NULL; double *values = NULL; printf ("\nTEST09\n"); printf (" HB_FILE_READ reads all the data in an HB file.\n"); printf (" HB_FILE_MODULE is the module that stores the data.\n"); input = fopen (filename, "r"); if ( !input ) { printf ("\n TEST09 - Warning!\n Error opening the file %s .\n", filename); return -1; } hb_file_read ( input, &title, &key, &totcrd, &ptrcrd, &indcrd, &valcrd, &rhscrd, &mxtype, &nrow, &ncol, &nnzero, &neltvl, &ptrfmt, &indfmt, &valfmt, &rhsfmt, &rhstyp, &nrhs, &nrhsix, &colptr, &rowind, &values, &rhsval, &rhsptr, &rhsind, &rhsvec, &guess, &exact ); fclose (input); // Conversion Fortran to C CopyShiftInts (colptr, colptr, nrow+1, -1); CopyShiftInts (rowind, rowind, nnzero, -1); // Data assignment p_spr->dim1 = nrow ; p_spr->dim2 = ncol ; p_spr->vptr = colptr; p_spr->vpos = rowind; p_spr->vval = values; // Memory liberation free (exact ); free (guess ); free (indfmt); free (key ); free (mxtype); free (ptrfmt); free (rhsfmt); free (rhsind); free (rhsptr); free (rhstyp); free (rhsval); free (rhsvec); free (title ); free (valfmt); return 0; } /*********************************************************************************/ // This routine computes the product { res += spr * vec }. // The parameter index indicates if 0-indexing or 1-indexing is used, void ProdSparseMatrixVector2 (SparseMatrix spr, int index, double *vec, double *res) { int i, j; int *pp1 = spr.vptr, *pp2 = pp1+1, *pi1 = spr.vpos + *pp1 - index; double aux, *pvec = vec - index, *pd2 = res; double *pd1 = spr.vval + *pp1 - index; // If the MSR format is used, first the diagonal has to be processed if (spr.vptr == spr.vpos) VvecDoubles (1.0, spr.vval, vec, 1.0, res, spr.dim1); for (i=0; i<spr.dim1; i++) { // The dot product between the row i and the vector vec is computed aux = 0.0; for (j=*pp1; j<*pp2; j++) aux += *(pd1++) * pvec[*(pi1++)]; // for (j=spr.vptr[i]; j<spr.vptr[i+1]; j++) // aux += spr.vval[j] * pvec[spr.vpos[j]]; // Accumulate the obtained value on the result *(pd2++) += aux; pp1 = pp2++; } } // This routine computes the product { res += spr * vec }. // The parameter index indicates if 0-indexing or 1-indexing is used, void ProdSparseMatrixVectorByRows (SparseMatrix spr, int index, double *vec, double *res) { int i, j, dim = spr.dim1; int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index; double aux, *pvec = vec + *pp1 - index; double *pd1 = spr.vval + *pp1 - index; // Process all the rows of the matrix for (i=0; i<dim; i++) { // The dot product between the row i and the vector vec is computed aux = 0.0; for (j=pp1[i]; j<pp1[i+1]; j++) aux = fma(pd1[j], pvec[pi1[j]], aux); // Accumulate the obtained value on the result res[i] += aux; } } // This routine computes the product { res += spr * vec }. // The parameter index indicates if 0-indexing or 1-indexing is used, void ProdSparseMatrixVectorByRows_OMP (SparseMatrix spr, int index, double *vec, double *res) { int i, j, dim = spr.dim1; int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index; double aux, *pvec = vec + *pp1 - index; double *pd1 = spr.vval + *pp1 - index; // Process all the rows of the matrix #pragma omp parallel for private(j, aux) for (i=0; i<dim; i++) { // The dot product between the row i and the vector vec is computed aux = 0.0; for (j=pp1[i]; j<pp1[i+1]; j++) aux += pd1[j] * pvec[pi1[j]]; // Accumulate the obtained value on the result res[i] += aux; } } /*void ProdSparseMatrixVectorByRows_OMPTasks (SparseMatrix spr, int index, double *vec, double *res, int bm) { int i, dim = spr.dim1; // Process all the rows of the matrix //#pragma omp taskloop grainsize(bm) for ( i=0; i<dim; i+=bm) { int cs = dim - i; int c = cs < bm ? cs : bm; // for (i=0; i<dim; i++) { #pragma omp task depend(inout:res[i:i+c-1]) //shared(c) { // printf("Task SPMV ---- i: %d, c: %d \n", i, c); int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index; double aux, *pvec = vec + *pp1 - index; double *pd1 = spr.vval + *pp1 - index; // The dot product between the row i and the vector vec is computed aux = 0.0; for(int idx=i; idx < i+c; idx++){ // printf("Task SPMV ---- idx: %d\n", idx); for (int j=pp1[idx]; j<pp1[idx+1]; j++) aux += pd1[j] * pvec[pi1[j]]; // Accumulate the obtained value on the result res[idx] += aux; } } } } */ void ProdSparseMatrixVectorByRows_OMPTasks (SparseMatrix spr, int index, double *vec, double *res, int bm) { int i, j, idx, dim = spr.dim1; int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index; double aux, *pvec = vec + *pp1 - index; double *pd1 = spr.vval + *pp1 - index; // Process all the rows of the matrix #pragma omp taskloop grainsize(bm) for ( i=0; i<dim; i++ ) { // The dot product between the row i and the vector vec is computed aux = 0.0; for (j=pp1[i]; j<pp1[i+1]; j++) aux += pd1[j] * pvec[pi1[j]]; // Accumulate the obtained value on the result res[i] += aux; } } /*********************************************************************************/ // This routine computes the product { res += spr * vec }. // The parameter index indicates if 0-indexing or 1-indexing is used, void ProdSparseMatrixVectorByCols (SparseMatrix spr, int index, double *vec, double *res) { int i, j, dim = spr.dim1; int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index; double aux, *pres = res + *pp1 - index; double *pd1 = spr.vval + *pp1 - index; // Process all the columns of the matrix for (i=0; i<dim; i++) { // The result is scaled by the column i and the scalar vec[i] aux = vec[i]; for (j=pp1[i]; j<pp1[i+1]; j++) pres[pi1[j]] += pd1[j] * aux; } } // This routine computes the product { res += spr * vec }. // The parameter index indicates if 0-indexing or 1-indexing is used, void ProdSparseMatrixVectorByCols_OMP (SparseMatrix spr, int index, double *vec, double *res) { int i, j, dim = spr.dim1; int *pp1 = spr.vptr, *pi1 = spr.vpos + *pp1 - index; double aux, *pres = res + *pp1 - index; double *pd1 = spr.vval + *pp1 - index; // Process all the columns of the matrix #pragma omp parallel for private(j, aux) for (i=0; i<dim; i++) { // The result is scaled by the column i and the scalar vec[i] for (j=pp1[i]; j<pp1[i+1]; j++) { aux = vec[i] * pd1[j]; #pragma omp atomic pres[pi1[j]] += aux; } } } /*********************************************************************************/ void GetDiagonalSparseMatrix2 (SparseMatrix spr, int shft, double *diag, int *posd) { int i, j, dim = (spr.dim1 < spr.dim2) ? spr.dim1 : spr.dim2; int *pp1 = NULL, *pp2 = NULL, *pi1 = NULL, *pi2 = posd; double *pd1 = NULL, *pd2 = diag; if (spr.vptr == spr.vpos) CopyDoubles (spr.vval, diag, spr.dim1); else { pp1 = spr.vptr; pp2 = pp1+1; j = (*pp2-*pp1); pi1 = spr.vpos+*pp1; pd1 = spr.vval+*pp1; for (i=0; i<dim; i++) { while ((j > 0) && (*pi1 < (i+shft))) { pi1++; pd1++; j--; } *(pd2++) = ((j > 0) && (*pi1 == (i+shft))) ? *pd1: 0.0; //*(pi2++) = ((j > 0) && (*pi1 == (i+shft))) ? *pp2-j: -1; pi1 += j; pd1 += j; pp1 = (pp2++); j = (*pp2-*pp1); } } } /*********************************************************************************/
pfor.c
#include <omp.h> #define N 100000 #define CHUNKSIZE 1000 double a[N], b[N], c[N]; int main () { int i, chunk; /* Some initializations */ for (i=0; i < N; i++) a[i] = b[i] = i * 1.0; chunk = CHUNKSIZE; #pragma omp parallel for schedule(static,CHUNKSIZE) private(i) for (i=0; i < N; i++) { int id; c[i] = a[i] + b[i]; id = omp_get_thread_num(); if ( (i % chunk) == 0 ) printf("Iteration #%d in thread #%d\n",i, id); } }
DRB059-lastprivate-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Using lastprivate() to resolve an output dependence. Semantics of lastprivate (x): causes the corresponding original list item to be updated after the end of the region. The compiler/runtime copies the local value back to the shared one within the last iteration. */ #include <stdio.h> void foo() { int i,x; #pragma omp parallel for lastprivate (x) for (i=0;i<100;i++) x=i; printf("x=%d",x); } int main() { foo(); return 0; }
GB_binop__pow_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__pow_uint64 // A.*B function (eWiseMult): GB_AemultB__pow_uint64 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__pow_uint64 // C+=b function (dense accum): GB_Cdense_accumb__pow_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__pow_uint64 // C=scalar+B GB_bind1st__pow_uint64 // C=scalar+B' GB_bind1st_tran__pow_uint64 // C=A+scalar GB_bind2nd__pow_uint64 // C=A'+scalar GB_bind2nd_tran__pow_uint64 // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = GB_pow_uint64 (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) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_pow_uint64 (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_POW || GxB_NO_UINT64 || GxB_NO_POW_UINT64) //------------------------------------------------------------------------------ // 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__pow_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__pow_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__pow_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 //------------------------------------------------------------------------------ #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 uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) 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__pow_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__pow_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__pow_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = Bx [p] ; Cx [p] = GB_pow_uint64 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__pow_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = Ax [p] ; Cx [p] = GB_pow_uint64 (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 = Ax [pA] ; \ Cx [pC] = GB_pow_uint64 (x, aij) ; \ } GrB_Info GB_bind1st_tran__pow_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = GB_pow_uint64 (aij, y) ; \ } GrB_Info GB_bind2nd_tran__pow_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nvector_openmp.c
/* ----------------------------------------------------------------- * Programmer(s): David J. Gardner and Carol S. Woodward @ LLNL * ----------------------------------------------------------------- * Acknowledgements: This NVECTOR module is based on the NVECTOR * Serial module by Scott D. Cohen, Alan C. * Hindmarsh, Radu Serban, and Aaron Collier * @ LLNL * ----------------------------------------------------------------- * LLNS Copyright Start * Copyright (c) 2014, Lawrence Livermore National Security * This work was performed under the auspices of the U.S. Department * of Energy by Lawrence Livermore National Laboratory in part under * Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344. * Produced at the Lawrence Livermore National Laboratory. * All rights reserved. * For details, see the LICENSE file. * LLNS Copyright End * ----------------------------------------------------------------- * This is the implementation file for an OpenMP implementation * of the NVECTOR module. * -----------------------------------------------------------------*/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <nvector/nvector_openmp.h> #include <sundials/sundials_math.h> #define ZERO RCONST(0.0) #define HALF RCONST(0.5) #define ONE RCONST(1.0) #define ONEPT5 RCONST(1.5) /* Private function prototypes */ /* z=x */ static void VCopy_OpenMP(N_Vector x, N_Vector z); /* z=x+y */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x-y */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=-x */ static void VNeg_OpenMP(N_Vector x, N_Vector z); /* z=c(x+y) */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x-y) */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=ax+y */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax-y */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* y <- ax+y */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y); /* x <- ax */ static void VScaleBy_OpenMP(realtype a, N_Vector x); /* * ----------------------------------------------------------------- * exported functions * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------- * Returns vector type ID. Used to identify vector implementation * from abstract N_Vector interface. */ N_Vector_ID N_VGetVectorID_OpenMP(N_Vector v) { return SUNDIALS_NVEC_OPENMP; } /* ---------------------------------------------------------------------------- * Function to create a new empty vector */ N_Vector N_VNewEmpty_OpenMP(sunindextype length, int num_threads) { N_Vector v; N_Vector_Ops ops; N_VectorContent_OpenMP content; /* Create vector */ v = NULL; v = (N_Vector) malloc(sizeof *v); if (v == NULL) return(NULL); /* Create vector operation structure */ ops = NULL; ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops)); if (ops == NULL) { free(v); return(NULL); } ops->nvgetvectorid = N_VGetVectorID_OpenMP; ops->nvclone = N_VClone_OpenMP; ops->nvcloneempty = N_VCloneEmpty_OpenMP; ops->nvdestroy = N_VDestroy_OpenMP; ops->nvspace = N_VSpace_OpenMP; ops->nvgetarraypointer = N_VGetArrayPointer_OpenMP; ops->nvsetarraypointer = N_VSetArrayPointer_OpenMP; ops->nvlinearsum = N_VLinearSum_OpenMP; ops->nvconst = N_VConst_OpenMP; ops->nvprod = N_VProd_OpenMP; ops->nvdiv = N_VDiv_OpenMP; ops->nvscale = N_VScale_OpenMP; ops->nvabs = N_VAbs_OpenMP; ops->nvinv = N_VInv_OpenMP; ops->nvaddconst = N_VAddConst_OpenMP; ops->nvdotprod = N_VDotProd_OpenMP; ops->nvmaxnorm = N_VMaxNorm_OpenMP; ops->nvwrmsnormmask = N_VWrmsNormMask_OpenMP; ops->nvwrmsnorm = N_VWrmsNorm_OpenMP; ops->nvmin = N_VMin_OpenMP; ops->nvwl2norm = N_VWL2Norm_OpenMP; ops->nvl1norm = N_VL1Norm_OpenMP; ops->nvcompare = N_VCompare_OpenMP; ops->nvinvtest = N_VInvTest_OpenMP; ops->nvconstrmask = N_VConstrMask_OpenMP; ops->nvminquotient = N_VMinQuotient_OpenMP; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof(struct _N_VectorContent_OpenMP)); if (content == NULL) { free(ops); free(v); return(NULL); } content->length = length; content->num_threads = num_threads; content->own_data = SUNFALSE; content->data = NULL; /* Attach content and ops */ v->content = content; v->ops = ops; return(v); } /* ---------------------------------------------------------------------------- * Function to create a new vector */ N_Vector N_VNew_OpenMP(sunindextype length, int num_threads) { N_Vector v; realtype *data; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create a vector with user data component */ N_Vector N_VMake_OpenMP(sunindextype length, realtype *v_data, int num_threads) { N_Vector v; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); if (length > 0) { /* Attach data */ NV_OWN_DATA_OMP(v) = SUNFALSE; NV_DATA_OMP(v) = v_data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors. */ N_Vector *N_VCloneVectorArray_OpenMP(int count, N_Vector w) { N_Vector *vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector *) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VClone_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors with NULL data array. */ N_Vector *N_VCloneVectorArrayEmpty_OpenMP(int count, N_Vector w) { N_Vector *vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector *) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VCloneEmpty_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to free an array created with N_VCloneVectorArray_OpenMP */ void N_VDestroyVectorArray_OpenMP(N_Vector *vs, int count) { int j; for (j = 0; j < count; j++) N_VDestroy_OpenMP(vs[j]); free(vs); vs = NULL; return; } /* ---------------------------------------------------------------------------- * Function to return number of vector elements */ sunindextype N_VGetLength_OpenMP(N_Vector v) { return NV_LENGTH_OMP(v); } /* ---------------------------------------------------------------------------- * Function to print a vector to stdout */ void N_VPrint_OpenMP(N_Vector x) { N_VPrintFile_OpenMP(x, stdout); } /* ---------------------------------------------------------------------------- * Function to print a vector to outfile */ void N_VPrintFile_OpenMP(N_Vector x, FILE *outfile) { sunindextype i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); for (i = 0; i < N; i++) { #if defined(SUNDIALS_EXTENDED_PRECISION) STAN_SUNDIALS_FPRINTF(outfile, "%11.8Lg\n", xd[i]); #elif defined(SUNDIALS_DOUBLE_PRECISION) STAN_SUNDIALS_FPRINTF(outfile, "%11.8g\n", xd[i]); #else STAN_SUNDIALS_FPRINTF(outfile, "%11.8g\n", xd[i]); #endif } STAN_SUNDIALS_FPRINTF(outfile, "\n"); return; } /* * ----------------------------------------------------------------- * implementation of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Create new vector from existing vector without attaching data */ N_Vector N_VCloneEmpty_OpenMP(N_Vector w) { N_Vector v; N_Vector_Ops ops; N_VectorContent_OpenMP content; if (w == NULL) return(NULL); /* Create vector */ v = NULL; v = (N_Vector) malloc(sizeof *v); if (v == NULL) return(NULL); /* Create vector operation structure */ ops = NULL; ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops)); if (ops == NULL) { free(v); return(NULL); } ops->nvgetvectorid = w->ops->nvgetvectorid; ops->nvclone = w->ops->nvclone; ops->nvcloneempty = w->ops->nvcloneempty; ops->nvdestroy = w->ops->nvdestroy; ops->nvspace = w->ops->nvspace; ops->nvgetarraypointer = w->ops->nvgetarraypointer; ops->nvsetarraypointer = w->ops->nvsetarraypointer; ops->nvlinearsum = w->ops->nvlinearsum; ops->nvconst = w->ops->nvconst; ops->nvprod = w->ops->nvprod; ops->nvdiv = w->ops->nvdiv; ops->nvscale = w->ops->nvscale; ops->nvabs = w->ops->nvabs; ops->nvinv = w->ops->nvinv; ops->nvaddconst = w->ops->nvaddconst; ops->nvdotprod = w->ops->nvdotprod; ops->nvmaxnorm = w->ops->nvmaxnorm; ops->nvwrmsnormmask = w->ops->nvwrmsnormmask; ops->nvwrmsnorm = w->ops->nvwrmsnorm; ops->nvmin = w->ops->nvmin; ops->nvwl2norm = w->ops->nvwl2norm; ops->nvl1norm = w->ops->nvl1norm; ops->nvcompare = w->ops->nvcompare; ops->nvinvtest = w->ops->nvinvtest; ops->nvconstrmask = w->ops->nvconstrmask; ops->nvminquotient = w->ops->nvminquotient; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof(struct _N_VectorContent_OpenMP)); if (content == NULL) { free(ops); free(v); return(NULL); } content->length = NV_LENGTH_OMP(w); content->num_threads = NV_NUM_THREADS_OMP(w); content->own_data = SUNFALSE; content->data = NULL; /* Attach content and ops */ v->content = content; v->ops = ops; return(v); } /* ---------------------------------------------------------------------------- * Create new vector from existing vector and attach data */ N_Vector N_VClone_OpenMP(N_Vector w) { N_Vector v; realtype *data; sunindextype length; v = NULL; v = N_VCloneEmpty_OpenMP(w); if (v == NULL) return(NULL); length = NV_LENGTH_OMP(w); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Destroy vector and free vector memory */ void N_VDestroy_OpenMP(N_Vector v) { if (NV_OWN_DATA_OMP(v) == SUNTRUE) { free(NV_DATA_OMP(v)); NV_DATA_OMP(v) = NULL; } free(v->content); v->content = NULL; free(v->ops); v->ops = NULL; free(v); v = NULL; return; } /* ---------------------------------------------------------------------------- * Get storage requirement for N_Vector */ void N_VSpace_OpenMP(N_Vector v, sunindextype *lrw, sunindextype *liw) { *lrw = NV_LENGTH_OMP(v); *liw = 1; return; } /* ---------------------------------------------------------------------------- * Get vector data pointer */ realtype *N_VGetArrayPointer_OpenMP(N_Vector v) { return((realtype *) NV_DATA_OMP(v)); } /* ---------------------------------------------------------------------------- * Set vector data pointer */ void N_VSetArrayPointer_OpenMP(realtype *v_data, N_Vector v) { if (NV_LENGTH_OMP(v) > 0) NV_DATA_OMP(v) = v_data; return; } /* ---------------------------------------------------------------------------- * Compute linear combination z[i] = a*x[i]+b*y[i] */ void N_VLinearSum_OpenMP(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z) { sunindextype i, N; realtype c, *xd, *yd, *zd; N_Vector v1, v2; booleantype test; xd = yd = zd = NULL; if ((b == ONE) && (z == y)) { /* BLAS usage: axpy y <- ax+y */ Vaxpy_OpenMP(a,x,y); return; } if ((a == ONE) && (z == x)) { /* BLAS usage: axpy x <- by+x */ Vaxpy_OpenMP(b,y,x); return; } /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) { VSum_OpenMP(x, y, z); return; } /* Cases: (1) a == 1.0, b = -1.0, (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { v1 = test ? y : x; v2 = test ? x : y; VDiff_OpenMP(v2, v1, z); return; } /* Cases: (1) a == 1.0, b == other or 0.0, (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin1_OpenMP(c, v1, v2, z); return; } /* Cases: (1) a == -1.0, b != 1.0, (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin2_OpenMP(c, v1, v2, z); return; } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) { VScaleSum_OpenMP(a, x, y, z); return; } /* Case: a == -b */ if (a == -b) { VScaleDiff_OpenMP(a, x, y, z); return; } /* Do all cases not handled above: (1) a == other, b == 0.0 - user should have called N_VScale (2) a == 0.0, b == other - user should have called N_VScale (3) a,b == other, a !=b, a != -b */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,b,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+(b*yd[i]); return; } /* ---------------------------------------------------------------------------- * Assigns constant value to all vector elements, z[i] = c */ void N_VConst_OpenMP(realtype c, N_Vector z) { sunindextype i, N; realtype *zd; zd = NULL; N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(z)) for (i = 0; i < N; i++) zd[i] = c; return; } /* ---------------------------------------------------------------------------- * Compute componentwise product z[i] = x[i]*y[i] */ void N_VProd_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]*yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise division z[i] = x[i]/y[i] */ void N_VDiv_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]/yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaler multiplication z[i] = c*x[i] */ void N_VScale_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; if (z == x) { /* BLAS usage: scale x <- cx */ VScaleBy_OpenMP(c, x); return; } if (c == ONE) { VCopy_OpenMP(x, z); } else if (c == -ONE) { VNeg_OpenMP(x, z); } else { N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*xd[i]; } return; } /* ---------------------------------------------------------------------------- * Compute absolute value of vector components z[i] = SUNRabs(x[i]) */ void N_VAbs_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = SUNRabs(xd[i]); return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = 1 / x[i] */ void N_VInv_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = ONE/xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise addition of a scaler to a vector z[i] = x[i] + b */ void N_VAddConst_OpenMP(N_Vector x, realtype b, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,b,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+b; return; } /* ---------------------------------------------------------------------------- * Computes the dot product of two vectors, a = sum(x[i]*y[i]) */ realtype N_VDotProd_OpenMP(N_Vector x, N_Vector y) { sunindextype i, N; realtype sum, *xd, *yd; sum = ZERO; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); #pragma omp parallel for default(none) private(i) shared(N,xd,yd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += xd[i]*yd[i]; } return(sum); } /* ---------------------------------------------------------------------------- * Computes max norm of a vector */ realtype N_VMaxNorm_OpenMP(N_Vector x) { sunindextype i, N; realtype tmax, max, *xd; max = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel default(none) private(i,tmax) shared(N,max,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmax = ZERO; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (SUNRabs(xd[i]) > tmax) tmax = SUNRabs(xd[i]); } #pragma omp critical { if (tmax > max) max = tmax; } } return(max); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a vector */ realtype N_VWrmsNorm_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum/N)); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a masked vector */ realtype N_VWrmsNormMask_OpenMP(N_Vector x, N_Vector w, N_Vector id) { sunindextype i, N; realtype sum, *xd, *wd, *idd; sum = ZERO; xd = wd = idd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); idd = NV_DATA_OMP(id); #pragma omp parallel for default(none) private(i) shared(N,xd,wd,idd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (idd[i] > ZERO) { sum += SUNSQR(xd[i]*wd[i]); } } return(SUNRsqrt(sum / N)); } /* ---------------------------------------------------------------------------- * Finds the minimun component of a vector */ realtype N_VMin_OpenMP(N_Vector x) { sunindextype i, N; realtype min, *xd; realtype tmin; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); min = xd[0]; #pragma omp parallel default(none) private(i,tmin) shared(N,min,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmin = xd[0]; #pragma omp for schedule(static) for (i = 1; i < N; i++) { if (xd[i] < tmin) tmin = xd[i]; } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* ---------------------------------------------------------------------------- * Computes weighted L2 norm of a vector */ realtype N_VWL2Norm_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum)); } /* ---------------------------------------------------------------------------- * Computes L1 norm of a vector */ realtype N_VL1Norm_OpenMP(N_Vector x) { sunindextype i, N; realtype sum, *xd; sum = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,xd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i<N; i++) sum += SUNRabs(xd[i]); return(sum); } /* ---------------------------------------------------------------------------- * Compare vector component values to a scaler */ void N_VCompare_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { zd[i] = (SUNRabs(xd[i]) >= c) ? ONE : ZERO; } return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = ONE/x[i] and checks if x[i] == ZERO */ booleantype N_VInvTest_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd, val; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); val = ZERO; #pragma omp parallel for default(none) private(i) shared(N,val,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (xd[i] == ZERO) val = ONE; else zd[i] = ONE/xd[i]; } if (val > ZERO) return (SUNFALSE); else return (SUNTRUE); } /* ---------------------------------------------------------------------------- * Compute constraint mask of a vector */ booleantype N_VConstrMask_OpenMP(N_Vector c, N_Vector x, N_Vector m) { sunindextype i, N; realtype temp; realtype *cd, *xd, *md; cd = xd = md = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); cd = NV_DATA_OMP(c); md = NV_DATA_OMP(m); temp = ONE; #pragma omp parallel for default(none) private(i) shared(N,xd,cd,md,temp) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { md[i] = ZERO; if (cd[i] == ZERO) continue; if (cd[i] > ONEPT5 || cd[i] < -ONEPT5) { if ( xd[i]*cd[i] <= ZERO) { temp = ZERO; md[i] = ONE; } continue; } if ( cd[i] > HALF || cd[i] < -HALF) { if (xd[i]*cd[i] < ZERO ) { temp = ZERO; md[i] = ONE; } } } if (temp == ONE) return (SUNTRUE); else return(SUNFALSE); } /* ---------------------------------------------------------------------------- * Compute minimum componentwise quotient */ realtype N_VMinQuotient_OpenMP(N_Vector num, N_Vector denom) { sunindextype i, N; realtype *nd, *dd, min, tmin, val; nd = dd = NULL; N = NV_LENGTH_OMP(num); nd = NV_DATA_OMP(num); dd = NV_DATA_OMP(denom); min = BIG_REAL; #pragma omp parallel default(none) private(i,tmin,val) shared(N,min,nd,dd) \ num_threads(NV_NUM_THREADS_OMP(num)) { tmin = BIG_REAL; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (dd[i] != ZERO) { val = nd[i]/dd[i]; if (val < tmin) tmin = val; } } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* * ----------------------------------------------------------------- * private functions * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Copy vector components into a second vector */ static void VCopy_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector sum */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute the negative of a vector */ static void VNeg_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = -xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector sum */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]+yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute scaled vector difference */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]-yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute vector sum z[i] = a*x[i]+y[i] */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference z[i] = a*x[i]-y[i] */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute special cases of linear sum */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y) { sunindextype i, N; realtype *xd, *yd; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); if (a == ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += xd[i]; return; } if (a == -ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] -= xd[i]; return; } #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += a*xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector x[i] = a*x[i] */ static void VScaleBy_OpenMP(realtype a, N_Vector x) { sunindextype i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,a,xd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) xd[i] *= a; return; }
DRB098-simd2-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> /* Two-dimension array computation with a vetorization directive collapse(2) makes simd associate with 2 loops. Loop iteration variables should be predetermined as lastprivate. */ int main() { int len=100; double a[len][len], b[len][len], c[len][len]; int i,j; #pragma omp parallel for private(i, j) for (i=0;i<len;i++) #pragma omp parallel for private(j) for (j=0;j<len;j++) { a[i][j]=((double)i)/2.0; b[i][j]=((double)i)/3.0; c[i][j]=((double)i)/7.0; } #pragma omp parallel for private(j) collapse(2) for (i=0;i<len;i++) for (j=0;j<len;j++) c[i][j]=a[i][j]*b[i][j]; printf ("c[50][50]=%f\n",c[50][50]); return 0; }
GB_binop__rminus_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__rminus_int8) // A.*B function (eWiseMult): GB (_AemultB_08__rminus_int8) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_int8) // A.*B function (eWiseMult): GB (_AemultB_04__rminus_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_int8) // A*D function (colscale): GB (_AxD__rminus_int8) // D*A function (rowscale): GB (_DxB__rminus_int8) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_int8) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_int8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_int8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_int8) // C=scalar+B GB (_bind1st__rminus_int8) // C=scalar+B' GB (_bind1st_tran__rminus_int8) // C=A+scalar GB (_bind2nd__rminus_int8) // C=A'+scalar GB (_bind2nd_tran__rminus_int8) // C type: int8_t // A type: int8_t // A pattern? 0 // B type: int8_t // B pattern? 0 // BinaryOp: cij = (bij - aij) #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) // 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) \ int8_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) \ 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 = (y - x) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RMINUS || GxB_NO_INT8 || GxB_NO_RMINUS_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__rminus_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__rminus_int8) ( 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__rminus_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__rminus_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__rminus_int8) ( 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 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__rminus_int8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, 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, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rminus_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 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) ; int8_t alpha_scalar ; int8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int8_t *) alpha_scalar_in)) ; beta_scalar = (*((int8_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__rminus_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_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__rminus_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_04__rminus_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_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__rminus_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__rminus_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] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rminus_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] = (y - aij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_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] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_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
ConvPoolLayer.c
/* * ConvPoolLayer.c * Francesco Conti <f.conti@unibo.it> * * Copyright (C) 2016 ETH Zurich, University of Bologna * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include "linalg.h" #include "tiling.h" #include "ConvPoolLayer.h" #ifdef CCN_HWCE_ACCEL #include "hwce.h" #endif #ifdef CCN_ENCRYPT #include "encryption.h" #endif #ifdef IPC_LINALG #include "perf_monitor.h" #endif #ifndef NULL #define NULL ((void *) 0) #endif #ifndef PULP_CHIP #define PULP_CHIP -1 #endif unsigned int dmaId = -1; #ifdef CCN_TILING_LESSTIME #define _conv_tiling_init(); \ unsigned char (*tile_grid_nof)[layer->ntile_nif][layer->ntile_h][layer->ntile_w] = (unsigned char (*)[layer->ntile_nif][layer->ntile_h][layer->ntile_w]) layer->tile_grid_nof; \ unsigned char (*tile_grid_nif)[layer->ntile_nif][layer->ntile_h][layer->ntile_w] = (unsigned char (*)[layer->ntile_nif][layer->ntile_h][layer->ntile_w]) layer->tile_grid_nif; \ unsigned char (*tile_grid_h) [layer->ntile_nif][layer->ntile_h][layer->ntile_w] = (unsigned char (*)[layer->ntile_nif][layer->ntile_h][layer->ntile_w]) layer->tile_grid_h; \ unsigned char (*tile_grid_w) [layer->ntile_nif][layer->ntile_h][layer->ntile_w] = (unsigned char (*)[layer->ntile_nif][layer->ntile_h][layer->ntile_w]) layer->tile_grid_w; \ int _fs = layer->filter_size; \ int _nof = tile_grid_nof[aa][bb][ii][jj]; \ int _nif = tile_grid_nif[aa][bb][ii][jj]; \ int _h = tile_grid_h [aa][bb][ii][jj]; \ int _w = tile_grid_w [aa][bb][ii][jj]; \ int _oh = _h-_fs+1; \ int _ow = _w-_fs+1; #else /* ~CCN_TILING_LESSTIME */ #define _conv_tiling_init(); \ int _fs = layer->filter_size; \ int _nof = (aa < layer->ntile_full_nof) ? layer->tiling_max_nof : layer->tlast_nof; \ int _nif = (bb < layer->ntile_full_nif) ? layer->tiling_max_nif : layer->tlast_nif; \ int _h = (ii < layer->ntile_full_h ) ? layer->tiling_max_height : layer->tlast_h; \ int _w = (jj < layer->ntile_full_w ) ? layer->tiling_max_width : layer->tlast_w; \ int _oh = _h-_fs+1; \ int _ow = _w-_fs+1; #endif /* ~CCN_TILING_LESSTIME */ #define _conv_notiling_init(); \ int _fs = layer->filter_size; \ int _nof = layer->n_out_feat; \ int _nif = layer->n_in_feat; \ int _h = layer->height; \ int _w = layer->width; \ int _oh = _h-_fs+1; \ int _ow = _w-_fs+1; /** * Allocates a new ConvPoolLayer data structure and its fields (weight, bias, * output feature maps). * * @return a pointer to the new ConvPoolLayer data structure. * * @param n_out_feat * the number of output feature maps. * @param n_in_feat * the number of input feature maps. * @param filter_size * the size of the filters. * @param height * the height of the input feature maps. * @param width * the width of the input feature maps. * @param activation * 1 if activation is tanh, 0 if no activation. * @param *x * a *mandatory* pointer to the input feature maps. * @param *y * an *optional* pointer to the already-allocated output feature maps. If * NULL, ConvPoolLayer_new() will allocate y automatically. */ ConvPoolLayer *ConvPoolLayer_new( #ifdef CCN_NOALLOC ConvPoolLayer *layer, #endif /* CCN_NOALLOC */ const char *name, data_t *w, data_t *b, data_t *x, data_t *y, data_t *loc_x0, data_t *loc_x1, data_t *loc_y0, data_t *loc_y1, data_t *loc_y2, data_t *loc_y3, data_t *loc_w0, data_t *loc_w1, int n_out_feat, int n_in_feat, int height, int width, int filter_size, int activation, int pool_size, int parallel_type, int tiling_max_nof, int tiling_max_nif, int tiling_max_height, int tiling_max_width, unsigned qf ) { #ifndef CCN_NOALLOC // build ConvPoolLayer ConvPoolLayer *layer; layer = ccn_malloc(sizeof(ConvPoolLayer)); #endif /* ifndef CCN_NOALLOC */ layer->name = name; layer->n_in_feat = n_in_feat; layer->n_out_feat = n_out_feat; layer->filter_size = filter_size; layer->height = height; layer->width = width; layer->activation = activation; layer->parallel_type = parallel_type; layer->w = w; layer->b = b; layer->x = x; layer->y = y; layer->qf = qf; layer->pool_size = pool_size; #ifndef CCN_CACHE layer->loc_x0 = loc_x0; layer->loc_y0 = loc_y0; layer->loc_x1 = loc_x1; layer->loc_y1 = loc_y1; layer->loc_y2 = loc_y2; layer->loc_y_tmp = loc_y3; layer->loc_w0 = loc_w0; layer->loc_w1 = loc_w1; layer->loc_b = (data_t *) ccn_malloc(sizeof(data_t)*tiling_max_nof); #endif /* ifndef CCN_CACHE */ layer->tiling_max_nof = tiling_max_nof; layer->tiling_max_nif = tiling_max_nif; layer->tiling_max_height = tiling_max_height; layer->tiling_max_width = tiling_max_width; #ifdef CCN_TILING // define and record the number of tiles int ntile_nof = (n_out_feat % tiling_max_nof ) ? n_out_feat / tiling_max_nof + 1 : n_out_feat / tiling_max_nof; int ntile_nif = (n_in_feat % tiling_max_nif ) ? n_in_feat / tiling_max_nif + 1 : n_in_feat / tiling_max_nif; // a little more complicated for H and W tiles: the last tile counts for (tiling_max_height-_fs+1)+height%(tiling_max_height-_fs+1), // then every other tile only for tiling_max_height-_fs+1 int ntile_h; int ntile_w; int tlast_h; int tlast_w; if(height <= tiling_max_height) { ntile_h = 1; } else { // e.g. tiling_max_height = 7, height = 14, _fs = 5 // e.g. tlast = 3+2 = 5 tlast_h = (tiling_max_height-layer->filter_size+1) + height%(tiling_max_height-layer->filter_size+1); // e.g. ntile = 1 + 9/3 = 1+3 = 4 ntile_h = 1 + (height-tlast_h) / (tiling_max_height-layer->filter_size+1); } if(width <= tiling_max_width) { ntile_w = 1; } else { // e.g. tiling_max_width = 20, width = 32, _fs = 5 // e.g. tlast = 16+0 = 16 tlast_w = (tiling_max_width-layer->filter_size+1) + width%(tiling_max_width-layer->filter_size+1); // e.g. ntile = 1 + 16/16 = 1+1 = 2 ntile_w = 1 + (width-tlast_w) / (tiling_max_width-layer->filter_size+1); } layer->ntile_nof = ntile_nof; layer->ntile_nif = ntile_nif; layer->ntile_h = ntile_h; layer->ntile_w = ntile_w; #ifdef CCN_TILING_LESSMEM layer->tlast_nof = n_out_feat % tiling_max_nof; layer->tlast_nif = n_in_feat % tiling_max_nif; layer->tlast_h = tlast_h; layer->tlast_w = tlast_w; layer->ntile_full_nof = ntile_nof; layer->ntile_full_nif = ntile_nif; layer->ntile_full_h = ntile_h; layer->ntile_full_w = ntile_w; #else /* ~CCN_TILING_LESSMEM */ // allocate the tile grid in a flat fashion layer->tile_grid_nof = ccn_malloc(sizeof(unsigned char)*(ntile_nof+NB_PIPE_STAGE-1)*ntile_nif*ntile_h*ntile_w); layer->tile_grid_nif = ccn_malloc(sizeof(unsigned char)*(ntile_nof+NB_PIPE_STAGE-1)*ntile_nif*ntile_h*ntile_w); layer->tile_grid_h = ccn_malloc(sizeof(unsigned char)*(ntile_nof+NB_PIPE_STAGE-1)*ntile_nif*ntile_h*ntile_w); layer->tile_grid_w = ccn_malloc(sizeof(unsigned char)*(ntile_nof+NB_PIPE_STAGE-1)*ntile_nif*ntile_h*ntile_w); // cast the tile grid to a 4-dimensional array unsigned char (*tile_grid_nof)[ntile_nif][ntile_h][ntile_w] = layer->tile_grid_nof; unsigned char (*tile_grid_nif)[ntile_nif][ntile_h][ntile_w] = layer->tile_grid_nif; unsigned char (*tile_grid_h) [ntile_nif][ntile_h][ntile_w] = layer->tile_grid_h; unsigned char (*tile_grid_w) [ntile_nif][ntile_h][ntile_w] = layer->tile_grid_w; #endif /* ~CCN_TILING_LESSMEM */ // fill in the tile grid int aa, bb, ii, jj; for(aa=0; aa<layer->ntile_nof; aa++) { for(bb=0; bb<layer->ntile_nif; bb++) { for(ii=0; ii<layer->ntile_h; ii++) { for(jj=0; jj<layer->ntile_w; jj++) { #ifdef CCN_TILING_LESSTIME if(jj*(tiling_max_width-layer->filter_size+1) > width-tiling_max_width) { tile_grid_w[aa][bb][ii][jj] = (unsigned char) tlast_w; } else { tile_grid_w[aa][bb][ii][jj] = (unsigned char) tiling_max_width; } if(ii*(tiling_max_height-layer->filter_size+1) > height-tiling_max_height) { tile_grid_h[aa][bb][ii][jj] = (unsigned char) tlast_h; } else { tile_grid_h[aa][bb][ii][jj] = (unsigned char) tiling_max_height; } if(bb*tiling_max_nif > n_in_feat-tiling_max_nif) { tile_grid_nif[aa][bb][ii][jj] = (unsigned char) n_in_feat % tiling_max_nif; } else { tile_grid_nif[aa][bb][ii][jj] = (unsigned char) tiling_max_nif; } if(aa*tiling_max_nof > n_out_feat-tiling_max_nof) { tile_grid_nof[aa][bb][ii][jj] = (unsigned char) n_out_feat % tiling_max_nof; } else { tile_grid_nof[aa][bb][ii][jj] = (unsigned char) tiling_max_nof; } #else /* ~CCN_TILING_LESSTIME */ if(jj*(tiling_max_width-layer->filter_size+1) > width-tiling_max_width) { layer->ntile_full_w = jj; } if(ii*(tiling_max_height-layer->filter_size+1) > height-tiling_max_height) { layer->ntile_full_h = ii; } if(bb*tiling_max_nif > n_in_feat-tiling_max_nif) { layer->ntile_full_nif = bb; } if(aa*tiling_max_nof > n_out_feat-tiling_max_nof) { layer->ntile_full_nof = aa; } #endif /* ~CCN_TILING_LESSTIME */ } } } } #ifdef CCN_TILING_LESSTIME for(aa=layer->ntile_nof; aa<layer->ntile_nof+NB_PIPE_STAGE-1; aa++) { for(bb=0; bb<layer->ntile_nif; bb++) { for(ii=0; ii<layer->ntile_h; ii++) { for(jj=0; jj<layer->ntile_w; jj++) { tile_grid_w [aa][bb][ii][jj] = 0; tile_grid_h [aa][bb][ii][jj] = 0; tile_grid_h [aa][bb][ii][jj] = 0; tile_grid_nif[aa][bb][ii][jj] = 0; tile_grid_nif[aa][bb][ii][jj] = 0; tile_grid_nof[aa][bb][ii][jj] = 0; tile_grid_nof[aa][bb][ii][jj] = 0; } } } } #endif /* CCN_TILING_LESSTIME */ #else /* ~CCN_TILING */ // no tile grid int ntile_nof = n_out_feat; int ntile_nif = n_in_feat; int ntile_h = height; int ntile_w = width; layer->ntile_nof = ntile_nof; layer->ntile_nif = ntile_nif; layer->ntile_h = ntile_h; layer->ntile_w = ntile_w; #endif /* ~CCN_TILING */ #ifdef TILING_DEBUG printf("[ConvPoolLayer %s] NOF grid:\n", layer->name); for(aa=0; aa<layer->ntile_nof; aa++) { for(bb=0; bb<layer->ntile_nif; bb++) { printf("aa=%d bb=%d\n", aa, bb); for(ii=0; ii<layer->ntile_h; ii++) { printf(" "); for(jj=0; jj<layer->ntile_w; jj++) { printf("%d ", tile_grid_nof[aa][bb][ii][jj]); } printf("\n"); } } } printf("[ConvPoolLayer %s] NIF grid:\n", layer->name); for(aa=0; aa<layer->ntile_nof; aa++) { for(bb=0; bb<layer->ntile_nif; bb++) { printf("aa=%d bb=%d\n", aa, bb); for(ii=0; ii<layer->ntile_h; ii++) { printf(" "); for(jj=0; jj<layer->ntile_w; jj++) { printf("%d ", tile_grid_nif[aa][bb][ii][jj]); } printf("\n"); } } } printf("[ConvPoolLayer %s] H grid:\n", layer->name); for(aa=0; aa<layer->ntile_nof; aa++) { for(bb=0; bb<layer->ntile_nif; bb++) { printf("aa=%d bb=%d\n", aa, bb); for(ii=0; ii<layer->ntile_h; ii++) { printf(" "); for(jj=0; jj<layer->ntile_w; jj++) { printf("%d ", tile_grid_h[aa][bb][ii][jj]); } printf("\n"); } } } printf("[ConvPoolLayer %s] W grid:\n", layer->name); for(aa=0; aa<layer->ntile_nof; aa++) { for(bb=0; bb<layer->ntile_nif; bb++) { printf("aa=%d bb=%d\n", aa, bb); for(ii=0; ii<layer->ntile_h; ii++) { printf(" "); for(jj=0; jj<layer->ntile_w; jj++) { printf("%d ", tile_grid_w[aa][bb][ii][jj]); } printf("\n"); } } } #endif /* TILING_DEBUG */ #ifdef CCN_PULP_HWCE #if PULP_CHIP==CHIP_FULMINE hwce_enable(); #endif /* ~CHIP_FULMINE */ #endif /* ~CCN_PULP_HWCE */ #ifdef CCN_HWCE_ACCEL hwce_config_init(); #endif return layer; } void ConvPoolLayer_delete( ConvPoolLayer *layer ) { #ifndef CCN_CACHE ccn_free(layer->loc_w0); ccn_free(layer->loc_w1); ccn_free(layer->loc_b); #endif /* ~CCN_CACHE */ #ifdef CCN_TILING ccn_free(layer->tile_grid_nof); ccn_free(layer->tile_grid_nif); ccn_free(layer->tile_grid_h); ccn_free(layer->tile_grid_w); #endif /* ~CCN_TILING */ ccn_free(layer); } static void ConvPoolLayer_pipe_fe( ConvPoolLayer *layer, int aa, int bb, int ii, int jj ) { #ifdef CCN_CACHE return; #endif // if aa is -1, it means that this is the last tile (and bb, ii, jj also = -1) if(aa==-1) return; #ifdef FETCH_PROFILE perf_enable_all(); perf_reset(); perf_start(); #endif /* FETCH_PROFILE */ { _conv_tiling_init() // x strides are h-fs+1, w-fs+1 due to tile overlap data_t *l2_x = ccn_get_tile_3d( layer->x, bb, ii, jj, layer->tiling_max_nif, layer->tiling_max_height, layer->tiling_max_width, layer->height, layer->width, 0, _fs-1, _fs-1 ); data_t *l2_y = ccn_get_tile_3d( layer->y, aa, ii, jj, layer->tiling_max_nof, layer->tiling_max_height-_fs+1, layer->tiling_max_width-_fs+1, layer->height-_fs+1, layer->width-_fs+1, 0, 0, 0 ); #if PULP_CHIP == CHIP_MIA || PULP_CHIP == CHIP_PULP3 || PULP_CHIP == CHIP_FULMINE || PULP_CHIP == CHIP_HONEY data_t *l2_W = ccn_get_tile_2d( layer->w, aa, bb, layer->tiling_max_nof*MULTIPLE8(_fs*_fs), layer->tiling_max_nif*MULTIPLE8(_fs*_fs), layer->n_in_feat ); #else /* ~CHIP_MIA && ~CHIP_PULP3 && ~CHIP_FULMINE && ~CHIP_HONEY */ data_t *l2_W = ccn_get_tile_2d( layer->w, aa, bb, layer->tiling_max_nof*_fs*_fs, layer->tiling_max_nif*_fs*_fs, layer->n_in_feat ); #endif /* ~CHIP_MIA && ~CHIP_PULP3 && ~CHIP_FULMINE && ~CHIP_HONEY */ #ifdef CCN_TILING_3D /* with no additional assumptions, the tiling grid is three-dimensional */ // X tile copy-in ccn_memcpy_async_3d( layer->loc_x_fe, // pointers l2_x, _nif, // sizes _h, _w*sizeof(data_t), _h, // local strides _w*sizeof(data_t), layer->height, // remote strides layer->width*sizeof(data_t) ); #endif /* CCN_TILING_3D */ #ifdef CCN_TILING_2D /* Assuming that tiles are internally contiguous in the j feature map dimension, the tiling grid is two-dimensional. Moreover, _w=layer->width */ // X tile copy-in ccn_memcpy_async_2d( layer->loc_x_fe, // pointers l2_x, _nif, // sizes _h*_w*sizeof(data_t), _h*_w*sizeof(data_t), // local strides layer->height*layer->width*sizeof(data_t) // remote strides ); #endif /* CCN_TILING_2D */ #ifdef CCN_TILING_1D /* Assuming that tiles are internally contiguous in the i,j feature map dimensions, the tiling grid is one-dimensional. Moreover, _h=layer->height,_w=layer->width */ // X tile copy-in ccn_memcpy_async( layer->loc_x_fe, // pointers l2_x, _nif*_h*_w*sizeof(data_t) ); #endif /* CCN_TILING_1D */ // W copy-in #if PULP_CHIP == CHIP_MIA || PULP_CHIP == CHIP_PULP3 || PULP_CHIP == CHIP_FULMINE || PULP_CHIP == CHIP_HONEY for(int a=0; a<_nof; a++) { for(int b=0; b<_nif; b++) { ccn_memcpy_async( layer->loc_w_fe + a*_nif*MULTIPLE4(_fs*_fs) + b*MULTIPLE4(_fs*_fs), l2_W + a*layer->n_in_feat*MULTIPLE8(_fs*_fs) + b*MULTIPLE8(_fs*_fs), sizeof(data_t)*_fs*_fs ); } } #else /* ~CHIP_MIA && ~CHIP_PULP3 */ if(layer->parallel_type != PARALLEL_HWCE) { for(int a=0; a<_nof; a++) { for(int b=0; b<_nif; b++) { ccn_memcpy_async( layer->loc_w_fe + a*_nif*_fs*_fs + b*_fs*_fs, l2_W + a*layer->n_in_feat*_fs*_fs + b*_fs*_fs, sizeof(data_t)*_fs*_fs ); } } } else { for(int a=0; a<_nof; a++) { for(int b=0; b<_nif; b++) { ccn_memcpy_async( layer->loc_w_fe + a*_nif*MULTIPLE4(_fs*_fs) + b*MULTIPLE4(_fs*_fs), l2_W + a*layer->n_in_feat*_fs*_fs + b*_fs*_fs, sizeof(data_t)*_fs*_fs ); } } } #endif /* ~CHIP_MIA && ~CHIP_PULP3 */ #ifdef FAKEDMA // ccn_memcpy_wait(); #endif /* FAKEDMA */ #ifdef FETCH_CHECKSUM int32_t sum_x = 0; int32_t sum_W = 0; int32_t sum_y = 0; for(int i=0; i<_nif*_h*_w; i++) { sum_x += layer->loc_x_fe[i]; } if(layer->parallel_type == PARALLEL_HWCE) { for(int a=0; a<_nof; a++) { for(int b=0; b<_nif; b++) { for(int i=0; i<_fs*_fs; i++) { sum_W += layer->loc_w_fe[a*_nif*MULTIPLE4(_fs*_fs) + b*MULTIPLE4(_fs*_fs) + i]; } } } } else { for(int i=0; i<_nof*_nif*_fs*_fs; i++) { sum_W += layer->loc_w_fe[i]; } } printf("[ConvPoolLayer %s] Fetch checksum %d,%d,%d,%d: x=%d W=%d\n", layer->name, aa, bb, ii, jj, sum_x, sum_W); #endif /* FETCH_CHECKSUM */ } #ifdef FETCH_PROFILE perf_stop(); int t0 = perf_get_cycles(); printf("[ConvPoolLayer %s] Fetch profiling: %d\n", layer->name, t0); #endif /* FETCH_PROFILE */ } static void ConvPoolLayer_pipe_ex( ConvPoolLayer *layer, int aa, int bb, int ii, int jj ) { // if aa is -1, it means that this is the first tile (and bb, ii, jj also = -1) if(aa==-1) return; #ifdef EXECUTE_PROFILE perf_enable_all(); perf_reset(); perf_start(); #endif /* EXECUTE_PROFILE */ // #pragma omp single nowait { #ifdef INTERM_CHECKSUM int print_flag = 0; #endif #ifdef CCN_TILING _conv_tiling_init() #else /* ~CCN_TILING */ _conv_notiling_init() #endif /* ~CCN_TILING */ #ifndef CCN_CACHE data_t *_x = layer->loc_x_ex; // #define USE_TMP_BUFFER #ifdef USE_TMP_BUFFER data_t *_y; data_t *_y2 = layer->loc_y_ex; if(bb == layer->ntile_nif-1) { _y = layer->loc_y_tmp; } else { _y = layer->loc_y_ex; } #else /* USE_TMP_BUFFER */ data_t *_y = layer->loc_y_ex; #endif /* USE_TMP_BUFFER */ data_t *_W = layer->loc_w_ex; #ifndef CCN_DOUBLEBUF // wait for the end of the fetch stage if not doing double buffering // ccn_memcpy_wait(); // #pragma omp barrier #endif /* ~CCN_DOUBLEBUF */ #else /* CCN_CACHE */ data_t *_x = ccn_get_tile_3d( layer->x, bb, ii, jj, layer->tiling_max_nif, layer->tiling_max_height, layer->tiling_max_width, layer->height, layer->width, 0, _fs-1, _fs-1 ); data_t *_y = ccn_get_tile_3d( layer->y, aa, ii, jj, layer->tiling_max_nof, layer->tiling_max_height-_fs+1, layer->tiling_max_width-_fs+1, layer->height-_fs+1, layer->width-_fs+1, 0, 0, 0 ); // we assume weights to be contiguous data_t *_W = ccn_get_tile_2d( layer->w, aa, bb, layer->tiling_max_nof, layer->tiling_max_nif, layer->n_in_feat*_fs*_fs ) #endif /* CCN_CACHE */ // loop over output features for(int a=0; a<_nof; a++) { // #pragma omp barrier // y_a[i,j] = b_a for every output feature a, pixel (i,j) if(bb == 0) { data_t _b = layer->b[aa*layer->tiling_max_nof+a]; // #pragma omp parallel for for(int i=0; i<_oh*_ow; i++) { _y[a*_oh*_ow+i] = _b; } } // convolution "core" #ifndef NOCOMPUTATION #ifndef CCN_CACHE #ifdef CCN_PULP_HWCE if(layer->parallel_type == PARALLEL_HWCE) linalg_2dconv_hwce(_W, _x, _y, _h, _w, _fs, a, _nif, layer->parallel_type, layer->qf); else linalg_2dconv(_W, _x, _y, _h, _w, _fs, a, _nif, layer->parallel_type, layer->qf); #else /* ~CCN_PULP_HWCE */ linalg_2dconv(_W, _x, _y, _h, _w, _fs, a, _nif, layer->parallel_type, layer->qf); #endif /* ~CCN_PULP_HWCE */ #else /* CCN_CACHE */ linalg_2dconv(_W, _x, _y, layer->height, layer->width, _fs, a, layer->n_in_feat, layer->parallel_type, layer->qf); #endif /* CCN_CACHE */ #endif /* NOCOMPUTATION */ #ifdef DETAILED_DEBUG #pragma omp master { for(int i=0; i<_oh; i++) { for(int j=0; j<_ow; j++) { printf("(%d,%d): %04x\n", i, j, _y[a*_oh*_ow+i*_ow+j] & 0xffff); } } } #pragma omp barrier #endif /* DETAILED_DEBUG */ if(bb == layer->ntile_nif-1) { int _ps = layer->pool_size; int _oph, _opw; if(_ps == 2) { _oph = _oh >> 1; _opw = _ow >> 1; } else if(_ps == 4) { _oph = _oh >> 2; _opw = _ow >> 2; } else { _oph = _oh / _ps; _opw = _ow / _ps; } // #pragma omp parallel \ // firstprivate(_y2,_ps) // { if(layer->activation == ACTIVATION_TANH) { // #pragma omp for \ // collapse(2) for (int i=0; i<_oh; i++) { for (int j=0; j<_ow; j++) { _y[a*_oh*_ow+i*_ow+j] = ccn_tanh(_y[a*_oh*_ow+i*_ow+j]); } } } else if(layer->activation == ACTIVATION_RELU) { // #pragma omp for \ // collapse(2) for (int i=0; i<_oh; i++) { for (int j=0; j<_ow; j++) { _y[a*_oh*_ow+i*_ow+j] = ccn_relu(_y[a*_oh*_ow+i*_ow+j]); } } } // #pragma omp for \ // collapse(2) for(int i=0; i<_oph; i++) { for(int j=0; j<_opw; j++) { data_t max = -DATA_T_MAX; for(int i1=0; i1<_ps; i1++) { for(int j1=0; j1<_ps; j1++) { data_t xtmp = _y[((a*_oh)+(i*_ps+i1))*_ow+(j*_ps+j1)]; if(xtmp > max) max = xtmp; } } #ifdef USE_TMP_BUFFER _y2[a*_oph*_opw+i*_opw+j] = max; #else /* USE_TMP_BUFFER */ _y[a*_oph*_opw+i*_opw+j] = max; #endif /* USE_TMP_BUFFER */ } } // } } #ifdef CCN_ENCRYPT #ifdef CCN_ENCRYPT_HWCRYPT hwcrypt_enable(); ccn_encrypt_aes_xts_hwcrypt_config(); ccn_encrypt_aes_xts_hwcrypt(_y, _y, _nof*_oh*_ow >> 1); // number of 32-bit words #ifdef CCN_HWCE_ACCEL hwce_enable(); #endif /* CCN_HWCE_ACCEL */ #else /* ~CCN_ENCRYPT_HWCRYPT */ ccn_encrypt_aes_xts(_y, _y, _nof*_oh*_ow*sizeof(data_t)); // number of bytes #endif /* ~CCN_ENCRYPT_HWCRYPT */ #endif /* CCN_ENCRYPT */ #ifdef INTERM_CHECKSUM // #pragma omp barrier // #pragma omp master { int i, sum=0; printf("[ConvPoolLayer %s] Intermediate checksum tile %d,%d,%d,%d, a=%d: ", layer->name, aa,bb,ii,jj, print_flag); sum=0; data_t *xt = _x + a*_nif*_h*_w; for(i=0; i<_nif*_h*_w; i++){ sum+=xt[i]; // FIXME: it should be _x, not xt. but if i do it here => WRONG CHECKSUM (BIG MISTERY) } printf("xsum=%d, ", sum); sum=0; data_t *wt = _W + a*_nif*MULTIPLE4(_fs*_fs); for(i=0; i<_nif*_fs*_fs; i++) { sum+=wt[i]; } printf("wsum=%d, ", sum); sum=0; data_t *yt = _y + a*_oh*_ow; for(i=0; i<_oh*_ow; i++) { sum+=yt[i]; } print_flag++; printf("ysum=%d\n", sum); printf(" xptr=%08x, wptr=%08x, yptr=%08x\n", _x, _W, _y); } // #pragma omp barrier #endif #ifdef CCN_CACHE _y += (layer->height-_fs+1)*(layer->width-_fs+1); _W += layer->n_in_feat*_fs*_fs; #endif /* CCN_CACHE */ } /* for(int a=a_start; a<_nof; a++) */ #ifdef TILE_CHECKSUM // #pragma omp barrier // #pragma omp master { int _oph, _opw; int _ps = layer->pool_size; data_t *_y2 = layer->loc_y_ex; if(_ps == 2) { _oph = _oh >> 1; _opw = _ow >> 1; } else if(_ps == 4) { _oph = _oh >> 2; _opw = _ow >> 2; } else { _oph = _oh / _ps; _opw = _ow / _ps; } int i, sum=0; printf("[ConvPoolLayer %s] Tile checksum %d,%d,%d,%d: ", layer->name, aa,bb,ii,jj); sum=0; for(i=0; i<_nif*_h*_w; i++){ sum+=_x[i]; } printf("xsum=%d, ", sum); sum=0; for(i=0; i<_nof*_nif*_fs*_fs; i++) { sum+=_W[i]; } printf("wsum=%d, ", sum); sum=0; for(i=0; i<_nof*_oh*_ow; i++) { sum+=_y[i]; } // print_flag++; printf("ysum=%d\n", sum); sum=0; for(i=0; i<_nof*_oph*_opw; i++) { sum+=_y2[i]; } // print_flag++; printf("y2sum=%d\n", sum); printf(" xptr=%08x, wptr=%08x, yptr=%08x\n", _x, _W, _y); } // #pragma omp barrier #endif } #ifdef EXECUTE_PROFILE perf_stop(); int t0 = perf_get_cycles(); printf("[ConvPoolLayer %s] Execute profiling: %d\n", layer->name, t0); #endif /* EXECUTE_PROFILE */ } static void ConvPoolLayer_pipe_wb( ConvPoolLayer *layer, int aa, int bb, int ii, int jj ) { #ifdef CCN_CACHE return; #endif // if aa is -1, it means that this is the first tile (and bb, ii, jj also = -1) if(aa==-1) return; #ifdef WRITEBACK_PROFILE perf_enable_all(); perf_reset(); perf_start(); #endif /* WRITEBACK_PROFILE */ // #pragma omp single { _conv_tiling_init(); data_t *l2_y; // if last bb tile, then l2_y points to the max-pooled output // if(bb != layer->ntile_nif-1) { // l2_y = ccn_get_tile_3d( // layer->y, // aa, ii, jj, // layer->tiling_max_nof, layer->tiling_max_height-_fs+1, layer->tiling_max_width-_fs+1, // layer->height-_fs+1, layer->width-_fs+1, // 0, 0, 0 // ); // } // else { int _tph, _tpw; int _ph, _pw; int _oph, _opw; if(bb == layer->ntile_nif-1) { int _ps = layer->pool_size; if(_ps == 2) { _tph = (layer->tiling_max_height-_fs+1) >> 1; _tpw = (layer->tiling_max_width-_fs +1) >> 1; _ph = (layer->height-_fs+1) >> 1; _pw = (layer->width-_fs +1) >> 1; _oph = _oh >> 1; _opw = _ow >> 1; } else if(_ps == 4) { _tph = (layer->tiling_max_height-_fs+1) >> 2; _tpw = (layer->tiling_max_width-_fs +1) >> 2; _ph = (layer->height-_fs+1) >> 2; _pw = (layer->width-_fs +1) >> 2; _oph = _oh >> 2; _opw = _ow >> 2; } else { _tph = (layer->tiling_max_height-_fs+1) / _ps; _tpw = (layer->tiling_max_width-_fs +1) / _ps; _ph = (layer->height-_fs+1) / _ps; _pw = (layer->width-_fs +1) / _ps; _oph = _oh / _ps; _opw = _ow / _ps; } l2_y = ccn_get_tile_3d( layer->y, aa, ii, jj, layer->tiling_max_nof, _tph, _tpw, _ph, _pw, 0, 0, 0 ); #ifdef WRITEBACK_CHECKSUM int32_t sum = 0; for(int i=0; i<_nof*_oh*_ow; i++) { sum += layer->loc_y_tmp[i]; } printf("[ConvLayer %s] Writeback checksum %d,%d,%d,%d: %d\n", layer->name, aa, bb, ii, jj, sum); sum = 0; for(int i=0; i<_nof*_oph*_opw; i++) { sum += layer->loc_y_wb[i]; } // printf("[ConvPoolLayer %s] Writeback checksum %d,%d,%d,%d: %d\n", layer->name, aa, bb, ii, jj, sum); #endif /* WRITEBACK_CHECKSUM */ #ifdef WRITEBACK_DEBUG printf("[ConvPoolLayer %s] Writeback debug CONV %d,%d,%d,%d:\n", layer->name, aa, bb, ii, jj); for(int i=0; i<_nof; i++) { for(int j=0; j<_oh; j++) { for(int k=0; k<_ow; k++) { printf(" (%d,%d,%d): %04x\n", i,j,k, layer->loc_y_tmp[i*_oh*_ow+j*_ow+k] & 0xffff); } } } printf("[ConvPoolLayer %s] Writeback debug POOL %d,%d,%d,%d:\n", layer->name, aa, bb, ii, jj); for(int i=0; i<_nof; i++) { for(int j=0; j<_oph; j++) { for(int k=0; k<_opw; k++) { printf(" (%d,%d,%d): %04x\n", i,j,k, layer->loc_y_wb[i*_oph*_opw+j*_opw+k] & 0xffff); } } } #endif /* WRITEBACK_DEBUG */ #ifdef CCN_TILING_3D /* with no additional assumptions, the tiling grid is three-dimensional */ // Y tile copy-out ccn_memcpy_async_3d( l2_y, // pointers layer->loc_y_wb, _nof, // sizes _oph, _opw*sizeof(data_t), _ph, // remote strides _pw*sizeof(data_t), _oph, // local strides _opw*sizeof(data_t) ); #endif /* CCN_TILING_3D */ #ifdef CCN_TILING_2D /* Assuming that tiles are internally contiguous in the j feature map dimension, the tiling grid is two-dimensional. Moreover, _w=layer->width */ // Y tile copy-in ccn_memcpy_async_2d( l2_y, // pointers layer->loc_y_wb, _nof, // sizes _oph*_opw*sizeof(data_t), _ph*_pw*sizeof(data_t), // local strides _oph*_opw*sizeof(data_t) // remote strides ); #endif /* CCN_TILING_2D */ #ifdef CCN_TILING_1D /* Assuming that tiles are internally contiguous in the i,j feature map dimensions, the tiling grid is one-dimensional. Moreover, _h=layer->height,_w=layer->width */ // Y tile copy-in ccn_memcpy_async( l2_y, // pointers layer->loc_y_wb, _nof*_oph*_opw*sizeof(data_t) ); #endif /* CCN_TILING_1D */ } #ifdef FAKEDMA // ccn_memcpy_wait(); #endif /* FAKEDMA */ } #ifdef WRITEBACK_DEBUG #pragma omp barrier #endif #ifdef WRITEBACK_PROFILE perf_stop(); int t0 = perf_get_cycles(); printf("[ConvPoolLayer %s] Writeback profiling: %d\n", layer->name, t0); #endif /* WRITEBACK_PROFILE */ } /** * Executes the given ConvPoolLayer, i.e. computes its outputs given the inputs * defined in the data structure. * The ConvPoolLayer computes the output of a convolutional network layer with * 3d inputs and outputs (an array of 2d feature maps). * * @param *layer * a pointer to the ConvPoolLayer data structure to execute. */ void ConvPoolLayer_exec(ConvPoolLayer *layer) { // ConvPoolLayer_exec is now organized as a pipeline with the following stages // fetch (fe) : DMA in of a tile // execute (ex) : execution of layer // write-back (wb) : DMA out of a tile // all indeces have a fetch, execute and write-back version int aa_pipe,bb_pipe,ii_pipe,jj_pipe; int aa_fe = -1, bb_fe = -1, ii_fe = -1, jj_fe = -1; int aa_ex = -1, bb_ex = -1, ii_ex = -1, jj_ex = -1; int aa_wb = -1, bb_wb = -1, ii_wb = -1, jj_wb = -1; #ifdef CCN_DOUBLEBUF // initialize double buffering in a known state int doublebuf_state_x_fe = 0; int doublebuf_state_y_fe = 0; int doublebuf_state_y_wb = 0; #endif /* CCN_DOUBLEBUF */ #ifndef CCN_CACHE // initialize state of fe local buffer pointers layer->loc_x_fe = layer->loc_x0; layer->loc_w_fe = layer->loc_w0; layer->loc_y_fe = layer->loc_y0; #endif /* ~CCN_CACHE */ // reset the weights! memset(layer->loc_w0, 0, sizeof(data_t)*layer->tiling_max_nof*layer->tiling_max_nif*MULTIPLE4(layer->filter_size*layer->filter_size)); memset(layer->loc_w1, 0, sizeof(data_t)*layer->tiling_max_nof*layer->tiling_max_nif*MULTIPLE4(layer->filter_size*layer->filter_size)); #ifdef CCN_TILING for(aa_pipe=0; aa_pipe<layer->ntile_nof+NB_PIPE_STAGE-1; aa_pipe++) { for(ii_pipe=0; ii_pipe<layer->ntile_h; ii_pipe++) { for(jj_pipe=0; jj_pipe<layer->ntile_w; jj_pipe++) { for(bb_pipe=0; bb_pipe<layer->ntile_nif; bb_pipe++) { // update state of fe indeces if(jj_pipe<layer->ntile_w) { jj_fe = jj_pipe; ii_fe = ii_pipe; bb_fe = bb_pipe; aa_fe = aa_pipe; } else { jj_fe = -1; ii_fe = -1; bb_fe = -1; aa_fe = -1; } #ifndef CCN_CACHE #ifdef CCN_DOUBLEBUF // update state of fe local buffer pointers if (doublebuf_state_x_fe == 0) { layer->loc_x_fe = layer->loc_x0; } else { layer->loc_x_fe = layer->loc_x1; } if (doublebuf_state_x_fe == 0) { layer->loc_w_fe = layer->loc_w0; } else { layer->loc_w_fe = layer->loc_w1; } if (doublebuf_state_y_fe == 0) { layer->loc_y_fe = layer->loc_y0; } else if (doublebuf_state_y_fe == 1) { layer->loc_y_fe = layer->loc_y1; } else { layer->loc_y_fe = layer->loc_y2; } #endif /* CCN_DOUBLEBUF */ #endif /* ~CCN_CACHE */ #ifdef PIPE_DEBUG printf("[ConvPoolLayer %s pipe] aa=%d bb=%d ii=%d jj=%d\n", layer->name, aa_pipe, bb_pipe, ii_pipe, jj_pipe); printf(" fe: aa=%d bb=%d ii=%d jj=%d\n", aa_fe, bb_fe, ii_fe, jj_fe); printf(" ex: aa=%d bb=%d ii=%d jj=%d\n", aa_ex, bb_ex, ii_ex, jj_ex); printf(" wb: aa=%d bb=%d ii=%d jj=%d\n", aa_wb, bb_wb, ii_wb, jj_wb); printf(" doublebuf states: %d %d %d\n", doublebuf_state_x_fe, doublebuf_state_y_fe, doublebuf_state_y_wb); printf("\n"); #endif PIPE_DEBUG #ifdef PIPE_PROFILE reset_timer(); start_timer(); #endif /* PIPE_PROFILE */ #ifndef DISABLE_OPENMP #pragma omp parallel num_threads(3) #endif { // fetch stage #ifndef DISABLE_OPENMP if(omp_get_thread_num() == THREAD_FE) #endif ConvPoolLayer_pipe_fe(layer, aa_fe, bb_fe, ii_fe, jj_fe); // execute stage #ifndef DISABLE_OPENMP if(omp_get_thread_num() == THREAD_EX) #endif ConvPoolLayer_pipe_ex(layer, aa_ex, bb_ex, ii_ex, jj_ex); // write-back stage #ifndef DISABLE_OPENMP if(omp_get_thread_num() == THREAD_WB) #endif ConvPoolLayer_pipe_wb(layer, aa_wb, bb_wb, ii_wb, jj_wb); } #ifdef PIPE_PROFILE stop_timer(); int t0 = get_time(); reset_timer(); printf("[ConvPoolLayer %s] Pipe profiling: %d\n", layer->name, t0); #endif /* PIPE_PROFILE */ // update state of ex,wb indeces jj_wb = jj_ex; jj_ex = jj_fe; ii_wb = ii_ex; ii_ex = ii_fe; bb_wb = bb_ex; bb_ex = bb_fe; aa_wb = aa_ex; aa_ex = aa_fe; // update state of ex,wb local buffers layer->loc_x_ex = layer->loc_x_fe; layer->loc_w_ex = layer->loc_w_fe; layer->loc_y_wb = layer->loc_y_ex; layer->loc_y_ex = layer->loc_y_fe; #ifndef CCN_CACHE #ifdef CCN_DOUBLEBUF // switch double buffering state if (doublebuf_state_x_fe == 0) { doublebuf_state_x_fe = 1; } else { doublebuf_state_x_fe = 0; } if (doublebuf_state_y_fe == 0) { doublebuf_state_y_fe = 1; } else if (doublebuf_state_y_fe == 1) { doublebuf_state_y_fe = 2; } else { doublebuf_state_y_fe = 0; } if (doublebuf_state_y_wb == 0) { doublebuf_state_y_wb = 1; } else if (doublebuf_state_y_wb == 1) { doublebuf_state_y_wb = 2; } else { doublebuf_state_y_wb = 0; } #endif /* CCN_DOUBLEBUF */ #endif /* ~CCN_CACHE */ } } } } #else /* ~CCN_TILING */ // fetch stage ConvPoolLayer_pipe_fe(layer, 0, 0, 0, 0); // execute stage ConvPoolLayer_pipe_ex(layer, 0, 0, 0, 0); // write-back stage ConvPoolLayer_pipe_wb(layer, 0, 0, 0, 0); #endif /* CCN_TILING */ }
GB_binop__isge_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__isge_int32 // A.*B function (eWiseMult): GB_AemultB__isge_int32 // A*D function (colscale): GB_AxD__isge_int32 // D*A function (rowscale): GB_DxB__isge_int32 // C+=B function (dense accum): GB_Cdense_accumB__isge_int32 // C+=b function (dense accum): GB_Cdense_accumb__isge_int32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isge_int32 // C=scalar+B GB_bind1st__isge_int32 // C=scalar+B' GB_bind1st_tran__isge_int32 // C=A+scalar GB_bind2nd__isge_int32 // C=A'+scalar GB_bind2nd_tran__isge_int32 // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x >= y) ; // 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_ISGE || GxB_NO_INT32 || GxB_NO_ISGE_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__isge_int32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__isge_int32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *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__isge_int32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__isge_int32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *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 int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__isge_int32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #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__isge_int32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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__isge_int32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const 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__isge_int32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = Bx [p] ; Cx [p] = (x >= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__isge_int32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = Ax [p] ; Cx [p] = (aij >= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB_bind1st_tran__isge_int32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *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 \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB_bind2nd_tran__isge_int32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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
raytracer.h
#pragma once #include "resource.h" #include <linalg.h> #include <memory> #include <omp.h> #include <random> #include <time.h> using namespace linalg::aliases; namespace cg::renderer { struct ray { ray(float3 position, float3 direction) : position(position) { this->direction = normalize(direction); } float3 position; float3 direction; }; struct payload { float t; float3 bary; cg::color color; }; template<typename VB> struct triangle { triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c); float3 a; float3 b; float3 c; float3 ba; float3 ca; float3 na; float3 nb; float3 nc; float3 ambient; float3 diffuse; float3 emissive; }; template<typename VB> inline triangle<VB>::triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c) { a = float3{ vertex_a.x, vertex_a.y, vertex_a.z }; b = float3{ vertex_b.x, vertex_b.y, vertex_b.z }; c = float3{ vertex_c.x, vertex_c.y, vertex_c.z }; ba = b - a; ca = c - a; na = float3{ vertex_a.nx, vertex_a.ny, vertex_a.nz }; nb = float3{ vertex_b.nx, vertex_b.ny, vertex_b.nz }; nc = float3{ vertex_c.nx, vertex_c.ny, vertex_c.nz }; ambient = { vertex_a.ambient_r, vertex_a.ambient_g, vertex_a.ambient_b, }; diffuse = { vertex_a.diffuse_r, vertex_a.diffuse_g, vertex_a.diffuse_b, }; emissive = { vertex_a.emissive_r, vertex_a.emissive_g, vertex_a.emissive_b, }; } template<typename VB> class aabb { public: void add_triangle(const triangle<VB> triangle); const std::vector<triangle<VB>>& get_triangles() const; bool aabb_test(const ray& ray) const; protected: std::vector<triangle<VB>> triangles; float3 aabb_min; float3 aabb_max; }; struct light { float3 position; float3 color; }; template<typename VB, typename RT> class raytracer { public: raytracer(){}; ~raytracer(){}; void set_render_target(std::shared_ptr<resource<RT>> in_render_target); void clear_render_target(const RT& in_clear_value); void set_viewport(size_t in_width, size_t in_height); void set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer); void build_acceleration_structure(); std::vector<aabb<VB>> acceleration_structures; void ray_generation(float3 position, float3 direction, float3 right, float3 up, float frame_weight = 1.f); payload trace_ray(const ray& ray, size_t depth, float max_t = 1000.f, float min_t = 0.001f) const; payload intersection_shader(const triangle<VB>& triangle, const ray& ray) const; std::function<payload(const ray& ray)> miss_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> closest_hit_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> any_hit_shader = nullptr; protected: std::shared_ptr<cg::resource<RT>> render_target; std::vector<std::shared_ptr<cg::resource<VB>>> per_shape_vertex_buffer; float get_random(const int thread_num, float range = 0.1f) const; size_t width = 1920; size_t height = 1080; }; template<typename VB, typename RT> inline void raytracer<VB, RT>::set_render_target(std::shared_ptr<resource<RT>> in_render_target) { render_target = in_render_target; } template<typename VB, typename RT> inline void raytracer<VB, RT>::clear_render_target(const RT& in_clear_value) { for (size_t i = 0; i < render_target->get_number_of_elements(); i++) { render_target->item(i) = in_clear_value; } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer) { per_shape_vertex_buffer = in_per_shape_vertex_buffer; } template<typename VB, typename RT> inline void raytracer<VB, RT>::build_acceleration_structure() { for (auto& vertex_buffer : per_shape_vertex_buffer) { size_t vertex_id = 0; aabb<VB> aabb; while (vertex_id < vertex_buffer->get_number_of_elements()) { triangle<VB> triangle( vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++)); aabb.add_triangle(triangle); } acceleration_structures.push_back(aabb); } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_viewport(size_t in_width, size_t in_height) { width = in_width; height = in_height; } template<typename VB, typename RT> inline void raytracer<VB, RT>::ray_generation( float3 position, float3 direction, float3 right, float3 up, float frame_weight) { for (int x = 0; x < width; x++) { #pragma omp parallel for for (int y = 0; y < height; y++) { float x_jitter = 0; // get_random(omp_get_thread_num() + clock(), 0.05f); float y_jitter = 0; // get_random(omp_get_thread_num() + clock() + 1, 0.05f); float u = (x * 2.f + x_jitter) / static_cast<float>(width - 1) - 1.f; u *= static_cast<float>(width) / static_cast<float>(height); float v = (y * 2.f + y_jitter) / static_cast<float>(height - 1) - 1.f; float3 ray_direction = direction + u * right - v * up; ray ray(position, ray_direction); payload payload = trace_ray(ray, 1); cg::color accumed = cg::color::from_float3(render_target->item(x, y).to_float3()); cg::color result{ payload.color.r * frame_weight + accumed.r * (1.f - frame_weight), payload.color.g * frame_weight + accumed.g * (1.f - frame_weight), payload.color.b * frame_weight + accumed.b * (1.f - frame_weight)}; render_target->item(x, y) = RT::from_color(result); } } } template<typename VB, typename RT> inline payload raytracer<VB, RT>::trace_ray(const ray& ray, size_t depth, float max_t, float min_t) const { if (depth == 0) { return miss_shader(ray); } depth--; payload closest_hit_payload = {}; closest_hit_payload.t = max_t; const triangle<VB>* closest_triangle = nullptr; for (auto& aabb : acceleration_structures) { if (aabb.aabb_test(ray)) { for (auto& triangle : aabb.get_triangles()) { payload payload = intersection_shader(triangle, ray); if (payload.t > min_t && payload.t < closest_hit_payload.t) { closest_hit_payload = payload; closest_triangle = &triangle; if (any_hit_shader) { return any_hit_shader(ray, payload, triangle); } } } } } if (closest_hit_payload.t < max_t) { if (closest_hit_shader) { return closest_hit_shader(ray, closest_hit_payload, *closest_triangle); } } return miss_shader(ray); } template<typename VB, typename RT> inline payload raytracer<VB, RT>::intersection_shader(const triangle<VB>& triangle, const ray& ray) const { payload payload{}; payload.t = -1.f; float3 pvec = cross(ray.direction, triangle.ca); float det = dot(triangle.ba, pvec); if (det > -1e-8 && det < 1e-8) return payload; float inv_det = 1.f / det; float3 tvec = ray.position - triangle.a; float u = dot(tvec, pvec) * inv_det; if (u < 0.f || u > 1.f) return payload; float3 qvec = cross(tvec, triangle.ba); float v = dot(ray.direction, qvec) * inv_det; if(v < 0.f || u + v > 1.f) return payload; payload.t = dot(triangle.ca, qvec) * inv_det; payload.bary = {1.f - u - v, u, v}; return payload; } template<typename VB, typename RT> inline float raytracer<VB, RT>::get_random(const int thread_num, const float range) const { static std::default_random_engine generator(thread_num); static std::normal_distribution<float> distribution(0.f, range); return distribution(generator); } template<typename VB> inline void aabb<VB>::add_triangle(const triangle<VB> triangle) { if (triangles.empty()) { aabb_min = aabb_max = triangle.a; } aabb_min = min(aabb_min, min(min(triangle.a, triangle.b), triangle.c)); aabb_max = max(aabb_max, max(max(triangle.a, triangle.b), triangle.c)); triangles.push_back(triangle); } template<typename VB> inline const std::vector<triangle<VB>>& aabb<VB>::get_triangles() const { return triangles; } template<typename VB> inline bool aabb<VB>::aabb_test(const ray& ray) const { float3 inv_ray_direction = float3(1.f) / ray.direction; float3 t0 = (aabb_max - ray.position) * inv_ray_direction; float3 t1 = (aabb_min - ray.position) * inv_ray_direction; float3 tmin = min(t0, t1); float3 tmax = max(t0, t1); return maxelem(tmin) <= minelem(tmax); } } // namespace cg::renderer
3d7pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 32; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,4);t1++) { lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8)); ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-7,8)),ceild(8*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(4*t1+Ny+5,32)),floord(8*t2+Ny+4,32)),floord(8*t1-8*t2+Nz+Ny+3,32));t3++) { for (t4=max(max(max(0,ceild(t1-7,8)),ceild(8*t2-Nz-28,32)),ceild(32*t3-Ny-28,32));t4<=min(min(min(min(floord(Nt+Nx-4,32),floord(4*t1+Nx+5,32)),floord(8*t2+Nx+4,32)),floord(32*t3+Nx+28,32)),floord(8*t1-8*t2+Nz+Nx+3,32));t4++) { for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),32*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),32*t3+30),32*t4+30),8*t1-8*t2+Nz+5);t5++) { for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) { lbv=max(32*t4,t5+1); ubv=min(32*t4+31,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
GB_binop__islt_int16.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__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_08__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_02__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_04__islt_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_int16) // A*D function (colscale): GB (_AxD__islt_int16) // D*A function (rowscale): GB (_DxB__islt_int16) // C+=B function (dense accum): GB (_Cdense_accumB__islt_int16) // C+=b function (dense accum): GB (_Cdense_accumb__islt_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_int16) // C=scalar+B GB (_bind1st__islt_int16) // C=scalar+B' GB (_bind1st_tran__islt_int16) // C=A+scalar GB (_bind2nd__islt_int16) // C=A'+scalar GB (_bind2nd_tran__islt_int16) // C type: int16_t // A type: int16_t // A pattern? 0 // B type: int16_t // B pattern? 0 // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_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) \ int16_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) \ int16_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_ISLT || GxB_NO_INT16 || GxB_NO_ISLT_INT16) //------------------------------------------------------------------------------ // 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__islt_int16) ( 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 int16_t *restrict Cx = (int16_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__islt_int16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_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__islt_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; int16_t alpha_scalar ; int16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int16_t *) alpha_scalar_in)) ; beta_scalar = (*((int16_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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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__islt_int16) ( 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 int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_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__islt_int16) ( 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 ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = 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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB (_bind1st_tran__islt_int16) ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB (_bind2nd_tran__islt_int16) ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convolution_bf16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convolution_bf16s(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_bf16, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { unsigned short* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float sum = 0.f; if (bias_data_ptr) { sum = bias_data_ptr[p]; } const unsigned short* kptr = (const unsigned short*)weight_data_bf16 + maxk * channels * p; // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const unsigned short* sptr = m.row<unsigned short>(i * stride_h) + j * stride_w; for (int k = 0; k < maxk; k++) { float val = bfloat16_to_float32(sptr[space_ofs[k]]); float wt = bfloat16_to_float32(kptr[k]); sum += val * wt; } kptr += maxk; } if (activation_type == 1) { sum = std::max(sum, 0.f); } else if (activation_type == 2) { float slope = activation_params[0]; sum = sum > 0.f ? sum : sum * slope; } else if (activation_type == 3) { float min = activation_params[0]; float max = activation_params[1]; if (sum < min) sum = min; if (sum > max) sum = max; } else if (activation_type == 4) { sum = static_cast<float>(1.f / (1.f + exp(-sum))); } else if (activation_type == 5) { sum = static_cast<float>(sum * tanh(log(exp(sum) + 1.f))); } outptr[j] = float32_to_bfloat16(sum); } outptr += outw; } } }
core32.c
#undef DT32 #define DT32 //<- This should be the ONLY difference between core32 and core64! #ifdef DT32 #define flt float #define DT_CALC DT_FLOAT32 #define epsilon FLT_EPSILON #else #define flt double #define DT_CALC DT_FLOAT64 #define epsilon DBL_EPSILON #endif #define SIMD #ifdef SIMD //explicitly vectorize (SSE,AVX,Neon) #ifdef __x86_64__ #include <immintrin.h> #ifdef DT32 #define kSSE32 4 //128-bit SSE handles 4 32-bit floats per instruction #else #define kSSE64 2 //128-bit SSE handles 2 64-bit floats per instruction #endif //#define myUseAVX //#define kAVX32 8 //256-bit AVX handles 8 32-bit floats per instruction //#define kAVX64 4 //256-bit AVX handles 4 64-bit floats per instruction #else #ifdef DT32 #include "sse2neon.h" #define kSSE32 4 //128-bit SSE handles 4 32-bit floats per instruction #else #undef SIMD #endif //#undef myUseAVX #endif #endif #include <float.h> //FLT_EPSILON #include <nifti2_io.h> #include <stdio.h> #include <stdlib.h> #ifdef __aarch64__ #include "arm_malloc.h" #else #include <immintrin.h> #endif #include <limits.h> #include <math.h> #if defined(_OPENMP) #include <omp.h> #endif #include "core.h" #define bandpass #ifdef bandpass #include "bw.h" #endif //#define slicetimer //tensor_decomp support is optional #ifdef slicetimer #include "afni.h" #endif #define tensor_decomp //tensor_decomp support is optional #ifdef tensor_decomp #include "tensor.h" #endif //#define TFCE //formerly we used Christian Gaser's tfce, new bespoke code handles connectivity //#ifdef TFCE //we now use in-built tfce function // #include "tfce_pthread.h" //#endif #ifdef SIMD #ifdef DT32 static void nifti_sqrt(flt *v, size_t n) { flt *vin = v; //#pragma omp parallel for for (size_t i = 0; i <= (n - kSSE32); i += kSSE32) { __m128 v4 = _mm_loadu_ps(vin); __m128 ma = _mm_sqrt_ps(v4); _mm_storeu_ps(vin, ma); vin += kSSE32; } int tail = (n % kSSE32); while (tail > 0) { v[n - tail] = sqrt(v[n - tail]); tail--; } } // nifti_sqrt() static void nifti_mul(flt *v, size_t n, flt slope1) { flt *vin = v; __m128 slope = _mm_set1_ps(slope1); //#pragma omp parallel for for (size_t i = 0; i <= (n - kSSE32); i += kSSE32) { __m128 v4 = _mm_loadu_ps(vin); __m128 m = _mm_mul_ps(v4, slope); _mm_storeu_ps(vin, m); vin += kSSE32; } int tail = (n % kSSE32); while (tail > 0) { v[n - tail] *= slope1; tail--; } } //nifti_mul() static void nifti_add(flt *v, int64_t n, flt intercept1) { //add, out = in + intercept if (intercept1 == 0.0f) return; flt *vin = v; __m128 intercept = _mm_set1_ps(intercept1); //#pragma omp parallel for for (int64_t i = 0; i <= (n - kSSE32); i += kSSE32) { __m128 v4 = _mm_loadu_ps(vin); __m128 ma = _mm_add_ps(v4, intercept); _mm_storeu_ps(vin, ma); vin += kSSE32; } int tail = (n % kSSE32); while (tail > 0) { v[n - tail] = v[n - tail] + intercept1; tail--; } } //nifti_add() static void nifti_fma(flt *v, int64_t n, flt slope1, flt intercept1) { //multiply+add, out = in * slope + intercept if ((slope1 == 1.0f) && (intercept1 == 0.0f)) return; flt *vin = v; __m128 intercept = _mm_set1_ps(intercept1); __m128 slope = _mm_set1_ps(slope1); //#pragma omp parallel for for (int64_t i = 0; i <= (n - kSSE32); i += kSSE32) { __m128 v4 = _mm_loadu_ps(vin); __m128 m = _mm_mul_ps(v4, slope); __m128 ma = _mm_add_ps(m, intercept); _mm_storeu_ps(vin, ma); vin += kSSE32; } int tail = (n % kSSE32); while (tail > 0) { v[n - tail] = (v[n - tail] * slope1) + intercept1; tail--; } } //nifti_fma() #else //if SIMD32 else SIMD64 static void nifti_sqrt(flt *v, size_t n) { flt *vin = v; //#pragma omp parallel for for (size_t i = 0; i <= (n - kSSE64); i += kSSE64) { __m128d v2 = _mm_loadu_pd(vin); __m128d ma = _mm_sqrt_pd(v2); _mm_storeu_pd(vin, ma); vin += kSSE64; } int tail = (n % kSSE64); while (tail > 0) { v[n - tail] = sqrt(v[n - tail]); tail--; } } // nifti_sqrt() static void nifti_mul(flt *v, size_t n, flt slope1) { flt *vin = v; __m128d slope = _mm_set1_pd(slope1); //#pragma omp parallel for for (size_t i = 0; i <= (n - kSSE64); i += kSSE64) { __m128d v2 = _mm_loadu_pd(vin); __m128d m = _mm_mul_pd(v2, slope); _mm_storeu_pd(vin, m); vin += kSSE64; } int tail = (n % kSSE64); while (tail > 0) { v[n - tail] *= slope1; tail--; } } //nifti_mul() static void nifti_add(flt *v, int64_t n, flt intercept1) { //add, out = in + intercept if (intercept1 == 0.0f) return; flt *vin = v; __m128d intercept = _mm_set1_pd(intercept1); //#pragma omp parallel for for (int64_t i = 0; i <= (n - kSSE64); i += kSSE64) { __m128d v2 = _mm_loadu_pd(vin); __m128d ma = _mm_add_pd(v2, intercept); _mm_storeu_pd(vin, ma); vin += kSSE64; } int tail = (n % kSSE64); while (tail > 0) { v[n - tail] = v[n - tail] + intercept1; tail--; } } //nifti_add() static void nifti_fma(flt *v, int64_t n, flt slope1, flt intercept1) { //multiply+add, out = in * slope + intercept if ((slope1 == 1.0f) && (intercept1 == 0.0f)) return; flt *vin = v; __m128d intercept = _mm_set1_pd(intercept1); __m128d slope = _mm_set1_pd(slope1); //#pragma omp parallel for for (int64_t i = 0; i <= (n - kSSE64); i += kSSE64) { __m128d v2 = _mm_loadu_pd(vin); __m128d m = _mm_mul_pd(v2, slope); __m128d ma = _mm_add_pd(m, intercept); _mm_storeu_pd(vin, ma); vin += kSSE64; } int tail = (n % kSSE64); while (tail > 0) { v[n - tail] = (v[n - tail] * slope1) + intercept1; tail--; } } //nifti_fma() #endif //end SIMD64 #else //if SIMD vectorized, else scalar static void nifti_sqrt(flt *v, size_t n) { //#pragma omp parallel for for (size_t i = 0; i < n; i++) v[i] = sqrt(v[i]); } //nifti_sqrt() static void nifti_mul(flt *v, size_t n, flt slope1) { //#pragma omp parallel for for (size_t i = 0; i < n; i++) v[i] *= slope1; } //nifti_mul() static void nifti_add(flt *v, size_t n, flt intercept1) { //#pragma omp parallel for for (size_t i = 0; i < n; i++) v[i] += intercept1; } //nifti_add() static void nifti_fma(flt *v, size_t n, flt slope1, flt intercept1) { //#pragma omp parallel for for (size_t i = 0; i < n; i++) v[i] = (v[i] * slope1) + intercept1; } //nifti_fma #endif //if vector SIMD else scalar static int show_helpx(void) { printf("Fatal: show_help shown by wrapper function\n"); exit(1); } static flt vx(flt *f, int p, int q) { flt ret = ((f[q] + q * q) - (f[p] + p * p)) / (2.0 * q - 2.0 * p); if (isnan(ret)) ret = INFINITY; return ret; } inline void transposeXY( flt *img3Din, flt *img3Dout, int *nxp, int *nyp, int nz) { //transpose X and Y dimensions: rows <-> columns //Note: in future we could use SIMD to transpose values in tiles // https://stackoverflow.com/questions/16737298/what-is-the-fastest-way-to-transpose-a-matrix-in-c int nx = *nxp; int ny = *nyp; size_t vi = 0; //volume offset for (int z = 0; z < nz; z++) { int zo = z * nx * ny; for (int y = 0; y < ny; y++) { int xo = 0; for (int x = 0; x < nx; x++) { img3Dout[zo + xo + y] = img3Din[vi]; xo += ny; vi += 1; } } } *nxp = ny; *nyp = nx; } inline void transposeXZ( flt *img3Din, flt *img3Dout, int *nxp, int ny, int *nzp) { //transpose X and Z dimensions: slices <-> columns int nx = *nxp; int nz = *nzp; int nyz = ny * nz; size_t vi = 0; //volume offset for (int z = 0; z < nz; z++) { for (int y = 0; y < ny; y++) { int yo = y * nz; int zo = 0; for (int x = 0; x < nx; x++) { img3Dout[z + yo + zo] = img3Din[vi]; zo += nyz; vi += 1; } } } *nxp = nz; *nzp = nx; } static void edt(flt *f, int n) { int q, p, k; flt s, dx; flt *d = (flt *)_mm_malloc((n+2) * sizeof(flt), 64); flt *z = (flt *)_mm_malloc((n+2) * sizeof(flt), 64); int *v = (int *)_mm_malloc((n+2) * sizeof(int), 64); /*# Find the lower envelope of a sequence of parabolas. # f...source data (returns the Y of the parabola vertex at X) # d...destination data (final distance values are written here) # z...temporary used to store X coords of parabola intersections # v...temporary used to store X coords of parabola vertices # i...resulting X coords of parabola vertices # n...number of pixels in "f" to process # Always add the first pixel to the enveloping set since it is # obviously lower than all parabolas processed so far.*/ k = 0; v[0] = 0; z[0] = -INFINITY; z[1] = INFINITY; for (q = 1; q < n; q++) { /* If the new parabola is lower than the right-most parabola in # the envelope, remove it from the envelope. To make this # determination, find the X coordinate of the intersection (s) # between the parabolas with vertices at (q,f[q]) and (p,f[p]).*/ p = v[k]; s = vx(f, p, q); //while (s <= z[k]) { while ((s <= z[k]) && (k > 0)) { k = k - 1; p = v[k]; s = vx(f, p, q); } //# Add the new parabola to the envelope. k = k + 1; v[k] = q; z[k] = s; z[k + 1] = INFINITY; } /*# Go back through the parabolas in the envelope and evaluate them # in order to populate the distance values at each X coordinate.*/ k = 0; for (q = 0; q < n; q++) { while (z[k + 1] < q) k = k + 1; dx = (q - v[k]); d[q] = dx * dx + f[v[k]]; } for (q = 0; q < n; q++) f[q] = d[q]; _mm_free(d); _mm_free(z); _mm_free(v); } static void edt1(flt *df, int n) { //first dimension is simple int q, prevX; flt prevY, v; prevX = 0; prevY = INFINITY; //forward for (q = 0; q < n; q++) { if (df[q] == 0) { prevX = q; prevY = 0; } else df[q] = sqr(q - prevX) + prevY; } //reverse prevX = n; prevY = INFINITY; for (q = (n - 1); q >= 0; q--) { v = sqr(q - prevX) + prevY; if (df[q] < v) { prevX = q; prevY = df[q]; } else df[q] = v; } } static int nifti_edt(nifti_image *nim) { //https://github.com/neurolabusc/DistanceFields if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2) || (nim->nz < 1)) return 1; if (nim->datatype != DT_CALC) return 1; flt *img = (flt *)nim->data; int nvox3D = nim->nx * nim->ny * MAX(nim->nz, 1); int nVol = nim->nvox / nvox3D; if ((nvox3D * nVol) != nim->nvox) return 1; int nx = nim->nx; int ny = nim->ny; int nz = nim->nz; flt threshold = 0.0; for (size_t i = 0; i < nim->nvox; i++) { if (img[i] > threshold) img[i] = INFINITY; else img[i] = 0; } size_t nRow = 1; for (int i = 2; i < 8; i++) nRow *= MAX(nim->dim[i], 1); //EDT in left-right direction flt *imgRow = img; for (int r = 0; r < nRow; r++) edt1(imgRow += nx, nx); //EDT in anterior-posterior direction nRow = nim->nx * nim->nz; //transpose XYZ to YXZ and blur Y columns with XZ Rows for (int v = 0; v < nVol; v++) { //transpose each volume separately flt *img3D = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64); //alloc for each volume to allow openmp size_t vo = v * nvox3D; //volume offset transposeXY(&img[vo], img3D, &nx, &ny, nz); //perform EDT for all "rows" flt *imgRow = img3D; for (int r = 0; r < nRow; r++) edt(imgRow += nx, nx); transposeXY(img3D, &img[vo], &nx, &ny, nz); _mm_free(img3D); } //for each volume //EDT in head-foot direction nRow = nim->nx * nim->ny; //transpose XYZ to ZXY and blur Z columns with XY Rows #pragma omp parallel for for (int v = 0; v < nVol; v++) { //transpose each volume separately flt *img3D = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64); //alloc for each volume to allow openmp size_t vo = v * nvox3D; //volume offset transposeXZ(&img[vo], img3D, &nx, ny, &nz); //perform EDT for all "rows" flt *imgRow = img3D; for (int r = 0; r < nRow; r++) edt(imgRow += nx, nx); transposeXZ(img3D, &img[vo], &nx, ny, &nz); _mm_free(img3D); } //for each volume return 0; } //kernelWid influences width of kernel, use negative values for round, positive for ceil // kenrnelWid of 2.5 means the kernel will be (2 * ceil(2.5 * sigma))+1 voxels wide // kenrnelWid of -6.0 means the kernel will be (2 * round(6.0 * sigma))+1 voxels wide // 2.5 AFNI ceil(2.5) https://github.com/afni/afni/blob/25e77d564f2c67ff480fa99a7b8e48ec2d9a89fc/src/edt_blur.c#L1391 // -6 SPM round(6) https://github.com/spm/spm12/blob/3085dac00ac804adb190a7e82c6ef11866c8af02/spm_smooth.m#L97 // -6 FSL round(6) (estimated) // -3 opencv round(3) or round(4) depending on datatype https://github.com/opencv/opencv/blob/9c23f2f1a682faa9f0b2c2223a857c7d93ba65a6/modules/imgproc/src/smooth.cpp#L3782 //bioimagesuite floor(1.5) https://github.com/bioimagesuiteweb/bisweb/blob/210d678c92fd404287fe5766136379ec94750eb2/js/utilities/bis_imagesmoothreslice.js#L133 //Gaussian blur, both serial and parallel variants, https://github.com/neurolabusc/niiSmooth static void blurS(flt *img, int nx, int ny, flt xmm, flt Sigmamm, flt kernelWid) { //serial blur //make kernels if ((xmm == 0) || (nx < 2) || (ny < 1) || (Sigmamm <= 0.0)) return; //flt sigma = (FWHMmm/xmm)/sqrt(8*log(2)); flt sigma = (Sigmamm / xmm); //mm to vox //round(6*sigma), ceil(4*sigma) seems spot on larger than fslmaths //int cutoffvox = round(6*sigma); //filter width to 6 sigma: faster but lower precision AFNI_BLUR_FIRFAC = 2.5 int cutoffvox; if (kernelWid < 0) cutoffvox = round(fabs(kernelWid) * sigma); //filter width to 6 sigma: faster but lower precision AFNI_BLUR_FIRFAC = 2.5 else cutoffvox = ceil(kernelWid * sigma); //filter width to 6 sigma: faster but lower precision AFNI_BLUR_FIRFAC = 2.5 //printf(".Blur Cutoff (%g) %d\n", 4*sigma, cutoffvox); //validated on SPM12's 1.5mm isotropic mask_ICV.nii (discrete jump in number of non-zero voxels) //fslmaths mask -s 2.26 f6.nii //Blur Cutoff (6.02667) 7 //fslmaths mask -s 2.24 f4.nii //Blur Cutoff (5.97333) 6 cutoffvox = MAX(cutoffvox, 1); flt *k = (flt *)_mm_malloc((cutoffvox + 1) * sizeof(flt), 64); //FIR Gaussian flt expd = 2 * sigma * sigma; for (int i = 0; i <= cutoffvox; i++) k[i] = exp(-1.0f * (i * i) / expd); //calculate start, end for each voxel in int *kStart = (int *)_mm_malloc(nx * sizeof(int), 64); //-cutoff except left left columns, e.g. 0, -1, -2... cutoffvox int *kEnd = (int *)_mm_malloc(nx * sizeof(int), 64); //+cutoff except right columns flt *kWeight = (flt *)_mm_malloc(nx * sizeof(flt), 64); //ensure sum of kernel = 1.0 for (int i = 0; i < nx; i++) { kStart[i] = MAX(-cutoffvox, -i); //do not read below 0 kEnd[i] = MIN(cutoffvox, nx - i - 1); //do not read beyond final columnn if ((i > 0) && (kStart[i] == (kStart[i - 1])) && (kEnd[i] == (kEnd[i - 1]))) { //reuse weight kWeight[i] = kWeight[i - 1]; continue; } flt wt = 0.0f; for (int j = kStart[i]; j <= kEnd[i]; j++) wt += k[abs(j)]; kWeight[i] = 1 / wt; //printf("%d %d->%d %g\n", i, kStart[i], kEnd[i], kWeight[i]); } //apply kernel to each row flt *tmp = _mm_malloc(nx * sizeof(flt), 64); //input values prior to blur for (int y = 0; y < ny; y++) { //printf("-+ %d:%d\n", y, ny); memcpy(tmp, img, nx * sizeof(flt)); for (int x = 0; x < nx; x++) { flt sum = 0; for (int i = kStart[x]; i <= kEnd[x]; i++) sum += tmp[x + i] * k[abs(i)]; img[x] = sum * kWeight[x]; } img += nx; } //blurX //free kernel _mm_free(tmp); _mm_free(k); _mm_free(kStart); _mm_free(kEnd); _mm_free(kWeight); } #if defined(_OPENMP) static void blurP(flt *img, int nx, int ny, flt xmm, flt FWHMmm, flt kernelWid) { //parallel blur //make kernels if ((xmm == 0) || (nx < 2) || (ny < 1) || (FWHMmm <= 0.0)) return; //flt sigma = (FWHMmm/xmm)/sqrt(8*log(2)); flt sigma = (FWHMmm / xmm); //mm to vox int cutoffvox; if (kernelWid < 0) cutoffvox = round(fabs(kernelWid) * sigma); //filter width to 6 sigma: faster but lower precision AFNI_BLUR_FIRFAC = 2.5 else cutoffvox = ceil(kernelWid * sigma); //filter width to 6 sigma: faster but lower precision AFNI_BLUR_FIRFAC = 2.5 cutoffvox = MAX(cutoffvox, 1); flt *k = (flt *)_mm_malloc((cutoffvox + 1) * sizeof(flt), 64); //FIR Gaussian flt expd = 2 * sigma * sigma; for (int i = 0; i <= cutoffvox; i++) k[i] = exp(-1.0f * (i * i) / expd); //calculate start, end for each voxel in int *kStart = (int *)_mm_malloc(nx * sizeof(int), 64); //-cutoff except left left columns, e.g. 0, -1, -2... cutoffvox int *kEnd = (int *)_mm_malloc(nx * sizeof(int), 64); //+cutoff except right columns flt *kWeight = (flt *)_mm_malloc(nx * sizeof(flt), 64); //ensure sum of kernel = 1.0 for (int i = 0; i < nx; i++) { kStart[i] = MAX(-cutoffvox, -i); //do not read below 0 kEnd[i] = MIN(cutoffvox, nx - i - 1); //do not read beyond final columnn if ((i > 0) && (kStart[i] == (kStart[i - 1])) && (kEnd[i] == (kEnd[i - 1]))) { //reuse weight kWeight[i] = kWeight[i - 1]; continue; } flt wt = 0.0f; for (int j = kStart[i]; j <= kEnd[i]; j++) wt += k[abs(j)]; kWeight[i] = 1 / wt; //printf("%d %d->%d %g\n", i, kStart[i], kEnd[i], kWeight[i]); } //apply kernel to each row #pragma omp parallel for for (int y = 0; y < ny; y++) { flt *tmp = _mm_malloc(nx * sizeof(flt), 64); //input values prior to blur flt *imgx = img; imgx += (nx * y); memcpy(tmp, imgx, nx * sizeof(flt)); for (int x = 0; x < nx; x++) { flt sum = 0; for (int i = kStart[x]; i <= kEnd[x]; i++) sum += tmp[x + i] * k[abs(i)]; imgx[x] = sum * kWeight[x]; } _mm_free(tmp); } //free kernel _mm_free(k); _mm_free(kStart); _mm_free(kEnd); _mm_free(kWeight); } //blurP #endif static int nifti_smooth_gauss(nifti_image *nim, flt SigmammX, flt SigmammY, flt SigmammZ, flt kernelWid) { //https://github.com/afni/afni/blob/699775eba3c58c816d13947b81cf3a800cec606f/src/edt_blur.c if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2) || (nim->nz < 1)) return 1; if (nim->datatype != DT_CALC) return 1; if ((SigmammX == 0) && (SigmammY == 0) && (SigmammZ == 0)) return 0; //all done: no smoothing, e.g. small kernel for difference of Gaussian if (SigmammX < 0) //negative values for voxels, not mm SigmammX = -SigmammX * nim->dx; if (SigmammY < 0) //negative values for voxels, not mm SigmammY = -SigmammY * nim->dy; if (SigmammZ < 0) //negative values for voxels, not mm SigmammZ = -SigmammZ * nim->dz; flt *img = (flt *)nim->data; int nvox3D = nim->nx * nim->ny * MAX(nim->nz, 1); int nVol = nim->nvox / nvox3D; if ((nvox3D * nVol) != nim->nvox) return 1; int nx = nim->nx; int ny = nim->ny; int nz = nim->nz; if (SigmammX <= 0.0) goto DO_Y_BLUR; //BLUR X int nRow = 1; for (int i = 2; i < 8; i++) nRow *= MAX(nim->dim[i], 1); #if defined(_OPENMP) if (omp_get_max_threads() > 1) blurP(img, nim->nx, nRow, nim->dx, SigmammX, kernelWid); else blurS(img, nim->nx, nRow, nim->dx, SigmammX, kernelWid); #else blurS(img, nim->nx, nRow, nim->dx, SigmammX, kernelWid); #endif //blurX(img, nim->nx, nRow, nim->dx, SigmammX); DO_Y_BLUR: //BLUR Y if (SigmammY <= 0.0) goto DO_Z_BLUR; nRow = nim->nx * nim->nz; //transpose XYZ to YXZ and blur Y columns with XZ Rows #pragma omp parallel for for (int v = 0; v < nVol; v++) { //transpose each volume separately flt *img3D = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64); //alloc for each volume to allow openmp size_t vo = v * nvox3D; //volume offset transposeXY(&img[vo], img3D, &nx, &ny, nz); blurS(img3D, nim->ny, nRow, nim->dy, SigmammY, kernelWid); transposeXY(img3D, &img[vo], &nx, &ny, nz); _mm_free(img3D); } //for each volume DO_Z_BLUR: //BLUR Z: if ((SigmammZ <= 0.0) || (nim->nz < 2)) return 0; //all done! nRow = nim->nx * nim->ny; //transpose XYZ to ZXY and blur Z columns with XY Rows #pragma omp parallel for for (int v = 0; v < nVol; v++) { //transpose each volume separately //printf("volume %d uses thread %d\n", v, omp_get_thread_num()); flt *img3D = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64); //alloc for each volume to allow openmp size_t vo = v * nvox3D; //volume offset transposeXZ(&img[vo], img3D, &nx, ny, &nz); blurS(img3D, nim->nz, nRow, nim->dz, SigmammZ, kernelWid); transposeXZ(img3D, &img[vo], &nx, ny, &nz); _mm_free(img3D); } //for each volume return 0; } // nifti_smooth_gauss() static int nifti_smooth_gauss_vox(nifti_image *nim, flt SigmaVox) { flt SigmammX = SigmaVox * nim->dx; flt SigmammY = SigmaVox * nim->dy; flt SigmammZ = SigmaVox * nim->dz; return nifti_smooth_gauss(nim, SigmammX, SigmammY, SigmammZ, -6.0); } // nifti_smooth_gauss_vox() static int nifti_dog(nifti_image *nim, flt SigmammPos, flt SigmammNeg, int isEdge) { //Difference of Gaussians (DoG): difference ratio of 1.6 approximates a Laplacian of Gaussian // https://homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm flt kKernelWid = 2.5; //ceil(2.5) if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2) || (nim->nz < 1) || (nim->datatype != DT_CALC)) return 1; if (SigmammPos == SigmammNeg) { fprintf(stderr, "Difference of Gaussian requires two different sigma values.\n"); return 1; } if ((SigmammPos < 0) || (SigmammNeg < 0)) { fprintf(stderr, "Difference of Gaussian requires positive values of sigma.\n"); return 1; } flt sigmaMn = MIN(SigmammNeg, SigmammPos); flt sigmaMx = MAX(SigmammNeg, SigmammPos); //Optimization: use results from narrow blur (sigmaMn) as inputs for wide blur (sigmaMx) //consider desired blurs of 2mm and 3.2mm, we can instead compute 2mm and 2.5mmm //only about 10% faster for difference ratio of 2.0, but also removes one copy //https://computergraphics.stackexchange.com/questions/256/is-doing-multiple-gaussian-blurs-the-same-as-doing-one-larger-blur sigmaMx = sqrt((sigmaMx*sigmaMx) - (sigmaMn*sigmaMn)); flt *inimg = (flt *)nim->data; int nvox3D = nim->nx * nim->ny * MAX(nim->nz, 1); int nVol = nim->nvox / nvox3D; int64_t nvox4D = nvox3D * nVol; int ret = nifti_smooth_gauss(nim, sigmaMn, sigmaMn, sigmaMn, kKernelWid); if (ret != 0) return ret; flt *imgMn = (flt *)_mm_malloc(nvox4D * sizeof(flt), 64); //alloc for each volume to allow openmp for (int64_t i = 0; i < nvox4D; i++) imgMn[i] = inimg[i]; ret = nifti_smooth_gauss(nim, sigmaMx, sigmaMx, sigmaMx, kKernelWid); if (SigmammPos > SigmammNeg) { for (int64_t i = 0; i < nvox4D; i++) inimg[i] = inimg[i] - imgMn[i]; } else { for (int64_t i = 0; i < nvox4D; i++) inimg[i] = imgMn[i] - inimg[i]; } if (!isEdge) { _mm_free(imgMn); return ret; //return continuous values } //we will define edges as voxels with zero crossings for (int64_t i = 0; i < nvox4D; i++) imgMn[i] = 0.0; int nx = nim->nx; int nxy = nx * nim->ny; int nxyz = nxy * nim->nz; for (int v = 0; v < nVol; v++) for (int z = 1; z < (nim->nz -1); z++) for (int y = 1; y < (nim->ny - 1); y++) for (size_t x = 1; x < (nim->nx - 1); x++) { int64_t i = x + (y * nx) + (z * nxy) + (v * nxyz); flt val = inimg[i]; if ((isEdge == 1) && (val <= 0.0)) continue; //one sided edge if (val == 0.0) continue; //masked images will have a lot of zeros! //logic: pos*neg = neg; pos*pos=pos; neg*neg=neg //check six neighbors that share a face if (val * inimg[i-1] < 0) { imgMn[i] = 1.0; continue;} if (val * inimg[i+1] < 0) { imgMn[i] = 1.0; continue;} if (val * inimg[i-nx] < 0) { imgMn[i] = 1.0; continue;} if (val * inimg[i+nx] < 0) { imgMn[i] = 1.0; continue;} if (val * inimg[i-nxy] < 0) { imgMn[i] = 1.0; continue;} if (val * inimg[i+nxy] < 0) { imgMn[i] = 1.0; continue;} if (isEdge == 1) continue; //dog1 is binary //check 12 neighbors that share an edge if (val * inimg[i-1-nxy] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i+1-nxy] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i-nx-nxy] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i+nx-nxy] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i-1-nx] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i+1-nx] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i-1+nx] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i+1+nx] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i-1+nxy] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i+1+nxy] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i-nx+nxy] < 0) { imgMn[i] = 0.5; continue;} if (val * inimg[i+nx+nxy] < 0) { imgMn[i] = 0.5; continue;} //check 8 neighbors that share a corner if (val * inimg[i-1-nx-nxy] < 0) { imgMn[i] = 0.25; continue;} if (val * inimg[i+1-nx-nxy] < 0) { imgMn[i] = 0.25; continue;} if (val * inimg[i-1+nx-nxy] < 0) { imgMn[i] = 0.25; continue;} if (val * inimg[i+1+nx-nxy] < 0) { imgMn[i] = 0.25; continue;} if (val * inimg[i-1-nx+nxy] < 0) { imgMn[i] = 0.25; continue;} if (val * inimg[i+1-nx+nxy] < 0) { imgMn[i] = 0.25; continue;} if (val * inimg[i-1+nx+nxy] < 0) { imgMn[i] = 0.25; continue;} if (val * inimg[i+1+nx+nxy] < 0) { imgMn[i] = 0.25; continue;} } for (int64_t i = 0; i < nvox4D; i++) inimg[i] = imgMn[i]; nim->scl_inter = 0.0; nim->scl_slope = 1.0; nim->cal_min = 0.0; nim->cal_max = 1.0; _mm_free(imgMn); return ret; } // nifti_dog() static int nifti_otsu(nifti_image *nim, int ignoreZeroVoxels) { //binarize image using Otsu's method if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2) || (nim->nz < 1)) return 1; if (nim->datatype != DT_CALC) return 1; flt *inimg = (flt *)nim->data; flt mn = INFINITY; //better that inimg[0] in case NaN flt mx = -INFINITY; for (int i = 0; i < nim->nvox; i++) { mn = MIN(mn, inimg[i]); mx = MAX(mx, inimg[i]); } if (mn >= mx) return 0; //no variability #define nBins 1001 flt scl = (nBins - 1) / (mx - mn); int hist[nBins]; for (int i = 0; i < nBins; i++) hist[i] = 0; if (ignoreZeroVoxels) { for (int i = 0; i < nim->nvox; i++) { if (isnan(inimg[i])) continue; if (inimg[i] == 0.0) continue; hist[(int)round((inimg[i] - mn) * scl)]++; } } else { for (int i = 0; i < nim->nvox; i++) { if (isnan(inimg[i])) continue; hist[(int)round((inimg[i] - mn) * scl)]++; } } //https://en.wikipedia.org/wiki/Otsu%27s_method size_t total = 0; for (int i = 0; i < nBins; i++) total += hist[i]; int top = nBins - 1; int level = 0; double sumB = 0; double wB = 0; double maximum = 0.0; double sum1 = 0.0; for (int i = 0; i < nBins; i++) sum1 += (i * hist[i]); for (int ii = 0; ii < nBins; ii++) { double wF = total - wB; if ((wB > 0) && (wF > 0)) { double mF = (sum1 - sumB) / wF; double val = wB * wF * ((sumB / wB) - mF) * ((sumB / wB) - mF); if (val >= maximum) { level = ii; maximum = val; } } wB = wB + hist[ii]; sumB = sumB + (ii - 1) * hist[ii]; } double threshold = (level / scl) + mn; if (ignoreZeroVoxels) { for (int i = 0; i < nim->nvox; i++) { if (inimg[i] == 0.0) continue; inimg[i] = (inimg[i] < threshold) ? 0.0 : 1.0; } } else { for (int i = 0; i < nim->nvox; i++) inimg[i] = (inimg[i] < threshold) ? 0.0 : 1.0; } //fprintf(stderr,"range %g..%g threshold %g bin %d\n", mn, mx, threshold, level); return 0; } // nifti_otsu() static int nifti_unsharp(nifti_image *nim, flt SigmammX, flt SigmammY, flt SigmammZ, flt amount) { //https://github.com/afni/afni/blob/699775eba3c58c816d13947b81cf3a800cec606f/src/edt_blur.c if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2) || (nim->nz < 1)) return 1; if (nim->datatype != DT_CALC) return 1; if (amount == 0.0) return 0; flt *inimg = (flt *)nim->data; void *indat = (void *)nim->data; flt mn = INFINITY; //better that inimg[0] in case NaN flt mx = -INFINITY; for (int i = 0; i < nim->nvox; i++) { mn = MIN(mn, inimg[i]); mx = MAX(mx, inimg[i]); } if (mn >= mx) return 0; //no variability size_t nvox3D = nim->nx * nim->ny * MAX(nim->nz, 1); size_t nVol = nim->nvox / nvox3D; if ((nvox3D * nVol) != nim->nvox) return 1; //process each 3D volume independently: reduce memory pressure nim->nvox = nvox3D; void *sdat = (void *)calloc(1, nim->nvox * sizeof(flt)); nim->data = sdat; flt *simg = (flt *)sdat; for (int v = 0; v < nVol; v++) { memcpy(simg, inimg, nim->nvox * sizeof(flt)); nifti_smooth_gauss(nim, SigmammX, SigmammY, SigmammZ, 2.5); //2.5: a relatively narrow kernel for speed for (int i = 0; i < nim->nvox; i++) { //sharpened = original + (original - blurred) * amount inimg[i] += (inimg[i] - simg[i]) * amount; //keep in original range inimg[i] = MAX(inimg[i], mn); inimg[i] = MIN(inimg[i], mx); } inimg += nim->nvox; } free(sdat); //return original data nim->data = indat; nim->nvox = nvox3D * nVol; return 0; } //nifti_unsharp() static int nifti_crop(nifti_image *nim, int tmin, int tsize) { if (tsize == 0) { fprintf(stderr, "tsize must not be 0\n"); return 1; } if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; int nvox3D = nim->nx * nim->ny * MAX(nim->nz, 1); if ((nvox3D < 1) || ((nim->nvox % nvox3D) != 0)) return 1; int nvol = (nim->nvox / nvox3D); //in if (nvol < 2) { fprintf(stderr, "crop only appropriate for 4D volumes"); return 1; } if (tmin >= nvol) { fprintf(stderr, "tmin must be from 0..%d, not %d\n", nvol - 1, tmin); return 1; } int tminVol = MAX(0, tmin); int tFinalVol = tminVol + tsize - 1; //e.g. if tmin=0 and tsize=1, tFinal=0 if (tsize < 0) { tFinalVol = INT_MAX; } tFinalVol = MIN(tFinalVol, nvol - 1); if ((tminVol == 0) && (tFinalVol == (nvol - 1))) return 0; int nvolOut = tFinalVol - tminVol + 1; flt *imgIn = (flt *)nim->data; nim->nvox = nvox3D * nvolOut; void *dat = (void *)calloc(1, nim->nvox * sizeof(flt)); flt *imgOut = (flt *)dat; imgIn += tminVol * nvox3D; memcpy(imgOut, imgIn, nim->nvox * sizeof(flt)); free(nim->data); nim->data = dat; if (nvolOut == 1) nim->dim[0] = 3; else nim->dim[0] = 4; nim->ndim = nim->dim[0]; nim->dim[4] = nvolOut; nim->nt = nvolOut; nim->nu = 1; nim->nv = 1; nim->nw = 1; for (int i = 5; i < 8; i++) nim->dim[i] = 1; return 0; } static int nifti_rescale(nifti_image *nim, double scale, double intercept) { //linear transform of data if (nim->nvox < 1) return 1; if (nim->datatype == DT_CALC) { flt scl = scale; flt inter = intercept; flt *f32 = (flt *)nim->data; if (intercept == 0.0) { if (scale == 1.0) return 0; //nothing to do nifti_mul(f32, nim->nvox, scl); return 0; } else if (scale == 1.0) { nifti_mul(f32, nim->nvox, intercept); return 0; } nifti_fma(f32, nim->nvox, scl, inter); //for (size_t i = 0; i < nim->nvox; i++ ) // f32[i] = (f32[i] * scl) + inter; return 0; } fprintf(stderr, "nifti_rescale: Unsupported datatype %d\n", nim->datatype); return 1; } static int nifti_tfceS(nifti_image *nim, double H, double E, int c, int x, int y, int z, double tfce_thresh) { if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; if ((x < 0) || (x >= nim->dim[1]) || (y < 0) || (y >= nim->dim[2]) || (z < 0) || (z >= nim->dim[3])) { fprintf(stderr, "tfceS x/y/z must be in range 0..%" PRId64 "/0..%" PRId64 "/0..%" PRId64 "\n", nim->dim[1] - 1, nim->dim[2] - 1, nim->dim[3] - 1); } if (!neg_determ(nim)) x = nim->dim[1] - x - 1; int seed = x + (y * nim->dim[1]) + (z * nim->dim[1] * nim->dim[2]); flt *inimg = (flt *)nim->data; if (inimg[seed] < H) { fprintf(stderr, "it doesn't reach to specified threshold\n"); return 1; } size_t nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; if (nim->nvox > nvox3D) { fprintf(stderr, "tfceS not suitable for 4D data.\n"); return 1; } //printf("peak %g\n", inimg[seed]); int numk = c; if ((c != 6) && (c != 18) && (c != 26)) { fprintf(stderr, "suitable values for c are 6, 18 or 26\n"); numk = 6; } //set up kernel to search for neighbors. Since we already included sides, we do not worry about A<->P and L<->R wrap int32_t *k = (int32_t *)_mm_malloc(3 * numk * sizeof(int32_t), 64); //kernel: offset, x, y int mxDx = 1; //connectivity 6: faces only if (numk == 18) mxDx = 2; //connectivity 18: faces+edges if (numk == 26) mxDx = 3; //connectivity 26: faces+edges+corners int j = 0; for (int z = -1; z <= 1; z++) for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { int dx = abs(x) + abs(y) + abs(z); if ((dx > mxDx) || (dx == 0)) continue; k[j] = x + (y * nim->nx) + (z * nim->nx * nim->ny); k[j + numk] = x; //avoid left-right wrap k[j + numk + numk] = x; //avoid anterior-posterior wrap j++; } //for x flt mx = (inimg[0]); for (size_t i = 0; i < nvox3D; i++) mx = MAX((inimg[i]), mx); double dh = mx / 100.0; flt *outimg = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64); //output image int32_t *q = (int32_t *)_mm_malloc(nvox3D * sizeof(int32_t), 64); //queue with untested seed uint8_t *vxs = (uint8_t *)_mm_malloc(nvox3D * sizeof(uint8_t), 64); for (int i = 0; i < nvox3D; i++) outimg[i] = 0.0; int n_steps = (int)ceil(mx / dh); //for (int step=0; step<n_steps; step++) { for (int step = n_steps - 1; step >= 0; step--) { flt thresh = (step + 1) * dh; memset(vxs, 0, nvox3D * sizeof(uint8_t)); for (int i = 0; i < nvox3D; i++) if (inimg[i] >= thresh) vxs[i] = 1; //survives, unclustered int qlo = 0; int qhi = 0; q[qhi] = seed; //add starting voxel as seed in queue vxs[seed] = 0; //do not find again! while (qhi >= qlo) { //first in, first out queue //retire one seed, add 0..6, 0..18 or 0..26 new ones (depending on connectivity) for (int j = 0; j < numk; j++) { int jj = q[qlo] + k[j]; if ((jj < 0) || (jj >= nvox3D)) continue; //voxel in volume if (vxs[jj] == 0) continue; //already found or did not survive threshold int dx = x + k[j + numk]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + k[j + numk + numk]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior //add new seed: vxs[jj] = 0; //do not find again! qhi++; q[qhi] = jj; } qlo++; } //while qhi >= qlo: continue until all seeds tested flt valToAdd = pow(qhi + 1, E) * pow(thresh, H); //"supporting section", Dark Gray in Figure 1 for (int j = 0; j <= qhi; j++) outimg[q[j]] += valToAdd; //printf("step %d thresh %g\n", step, outimg[seed]); if (outimg[seed] >= tfce_thresh) break; } //for each step if (outimg[seed] < tfce_thresh) fprintf(stderr, "it doesn't reach to specified threshold (%g < %g)\n", outimg[seed], tfce_thresh); for (size_t i = 0; i < nvox3D; i++) if (outimg[i] == 0.0) inimg[i] = 0.0; _mm_free(q); _mm_free(vxs); _mm_free(outimg); _mm_free(k); return 0; } static int nifti_tfce(nifti_image *nim, double H, double E, int c) { //https://www.fmrib.ox.ac.uk/datasets/techrep/tr08ss1/tr08ss1.pdf if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nim->nvox / nvox3D; int numk = c; if ((c != 6) && (c != 18) && (c != 26)) { fprintf(stderr, "suitable values for c are 6, 18 or 26\n"); numk = 6; } //set up kernel to search for neighbors. Since we already included sides, we do not worry about A<->P and L<->R wrap int32_t *k = (int32_t *)_mm_malloc(3 * numk * sizeof(int32_t), 64); //kernel: offset, x, y int mxDx = 1; //connectivity 6: faces only if (numk == 18) mxDx = 2; //connectivity 18: faces+edges if (numk == 26) mxDx = 3; //connectivity 26: faces+edges+corners int j = 0; for (int z = -1; z <= 1; z++) for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { int dx = abs(x) + abs(y) + abs(z); if ((dx > mxDx) || (dx == 0)) continue; k[j] = x + (y * nim->nx) + (z * nim->nx * nim->ny); k[j + numk] = x; //avoid left-right wrap k[j + numk + numk] = x; //avoid anterior-posterior wrap j++; } //for x //omp notes: here we compute each volume independently. // Christian Gaser computes the step loop in parallel, which accelerates 3D cases // This code is very quick on 3D, so this does not seem crucial, and avoids critical sections #pragma omp parallel for for (int vol = 0; vol < nvol; vol++) { //identify clusters flt *inimg = (flt *)nim->data; inimg += vol * nvox3D; flt mx = (inimg[0]); for (size_t i = 0; i < nvox3D; i++) mx = MAX((inimg[i]), mx); double dh = mx / 100.0; flt *outimg = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64);//output image int32_t *q = (int32_t *)_mm_malloc(nvox3D * sizeof(int32_t), 64); //queue with untested seed uint8_t *vxs = (uint8_t *)_mm_malloc(nvox3D * sizeof(uint8_t), 64); for (int i = 0; i < nvox3D; i++) outimg[i] = 0.0; int n_steps = (int)ceil(mx / dh); for (int step = 0; step < n_steps; step++) { flt thresh = (step + 1) * dh; memset(vxs, 0, nvox3D * sizeof(uint8_t)); for (int i = 0; i < nvox3D; i++) if (inimg[i] >= thresh) vxs[i] = 1; //survives, unclustered int i = 0; for (int z = 0; z < nim->nz; z++) for (int y = 0; y < nim->ny; y++) for (int x = 0; x < nim->nx; x++) { if (vxs[i] == 0) { i++; continue; } //voxel did not survive or already clustered int qlo = 0; int qhi = 0; q[qhi] = i; //add starting voxel as seed in queue vxs[i] = 0; //do not find again! while (qhi >= qlo) { //first in, first out queue //retire one seed, add 0..6, 0..18 or 0..26 new ones (depending on connectivity) for (int j = 0; j < numk; j++) { int jj = q[qlo] + k[j]; if ((jj < 0) || (jj >= nvox3D)) continue; //voxel in volume if (vxs[jj] == 0) continue; //already found or did not survive threshold int dx = x + k[j + numk]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + k[j + numk + numk]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior //add new seed: vxs[jj] = 0; //do not find again! qhi++; q[qhi] = jj; } qlo++; } //while qhi >= qlo: continue until all seeds tested flt valToAdd = pow(qhi + 1, E) * pow(thresh, H); //"supporting section", Dark Gray in Figure 1 for (int j = 0; j <= qhi; j++) outimg[q[j]] += valToAdd; i++; } //for each voxel } //for each step for (int i = 0; i < nvox3D; i++) inimg[i] = outimg[i]; _mm_free(q); _mm_free(vxs); _mm_free(outimg); } _mm_free(k); return 0; } //nifti_tfce() static int nifti_grid(nifti_image *nim, double v, int spacing) { if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2)) return 1; if (nim->datatype != DT_CALC) return 1; size_t nxy = (nim->nx * nim->ny); size_t nzt = nim->nvox / nxy; flt *f32 = (flt *)nim->data; flt fv = v; #pragma omp parallel for for (size_t i = 0; i < nzt; i++) { //for each 2D slices size_t so = i * nxy; //slice offset int z = (i % nim->nz); if ((nim->nz > 1) && ((z % spacing) == 0)) { //whole slice is grid for (size_t j = 0; j < nxy; j++) f32[so++] = fv; continue; } for (size_t y = 0; y < nim->ny; y++) for (size_t x = 0; x < nim->nx; x++) { if ((x % spacing) == 0) f32[so] = fv; so++; } so = i * nxy; //slice offset for (size_t y = 0; y < nim->ny; y++) for (size_t x = 0; x < nim->nx; x++) { if ((y % spacing) == 0) f32[so] = fv; so++; } } //for i: each 2D slice return 0; } static int nifti_rem(nifti_image *nim, double v, int isFrac) { //remainder (modulo) : fslmaths /*fmod(0.45, 2) = 0.45 : 0 fmod(0.9, 2) = 0.9 : 0 fmod(1.35, 2) = 1.35 : 1 fmod(1.8, 2) = 1.8 : 1 fmod(-0.45, 2) = -0.45 : 0 fmod(-0.9, 2) = -0.9 : 0 fmod(-1.35, 2) = -1.35 : -1 fmod(-1.8, 2) = -1.8 : -1 */ if (nim->datatype != DT_CALC) return 1; if (nim->nvox < 1) return 1; if (v == 0.0) { fprintf(stderr, "Exception: '-rem 0' does not make sense\n"); return 1; } flt fv = v; flt *f32 = (flt *)nim->data; if (isFrac) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = fmod(f32[i], fv); } else { for (size_t i = 0; i < nim->nvox; i++) { //printf("fmod(%g, %g) = %g : %g\n", f32[i], fv, fmod(f32[i],fv), trunc(fmod(f32[i],fv)) ); f32[i] = trunc(fmod(f32[i], fv)); } } return 0; } static int nifti_thr(nifti_image *nim, double v, int modifyBrightVoxels, float newIntensity) { if (nim->nvox < 1) return 1; if (nim->datatype == DT_CALC) { flt fv = v; flt *f32 = (flt *)nim->data; if (modifyBrightVoxels) { for (size_t i = 0; i < nim->nvox; i++) if (f32[i] > fv) f32[i] = newIntensity; } else { for (size_t i = 0; i < nim->nvox; i++) if (f32[i] < fv) f32[i] = newIntensity; } return 0; } fprintf(stderr, "nifti_thr: Unsupported datatype %d\n", nim->datatype); return 1; } // nifti_thr() static int nifti_max(nifti_image *nim, double v, int useMin) { if (nim->nvox < 1) return 1; if (nim->datatype == DT_CALC) { flt fv = v; flt *f32 = (flt *)nim->data; if (useMin) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = fmin(f32[i], fv); } else { for (size_t i = 0; i < nim->nvox; i++) f32[i] = fmax(f32[i], fv); } return 0; } fprintf(stderr, "nifti_max: Unsupported datatype %d\n", nim->datatype); return 1; } // nifti_max() static int nifti_inm(nifti_image *nim, double M) { //https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=fsl;bf9d21d2.1610 //With '-inm <value>', every voxel in the input volume is multiplied by <value> / M // where M is the mean across all voxels. //n.b.: regardless of description, mean appears to only include voxels > 0 if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; int nvox3D = nim->nx * nim->ny * MAX(nim->nz, 1); if ((nvox3D < 1) || ((nim->nvox % nvox3D) != 0)) return 1; int nvol = nim->nvox / nvox3D; flt *f32 = (flt *)nim->data; #pragma omp parallel for for (int v = 0; v < nvol; v++) { size_t vi = v * nvox3D; double sum = 0.0; #define gt0 #ifdef gt0 int n = 0; for (size_t i = 0; i < nvox3D; i++) { if (f32[vi + i] > 0.0f) { n++; sum += f32[vi + i]; } } if (sum == 0.0) continue; double ave = sum / n; #else for (int i = 0; i < nvox3D; i++) sum += f32[vi + i]; if (sum == 0.0) continue; double ave = sum / nvox3D; #endif //printf("%g %g\n", ave, M); flt scale = M / ave; for (int i = 0; i < nvox3D; i++) f32[vi + i] *= scale; } return 0; } // nifti_inm() static int nifti_ing(nifti_image *nim, double M) { //https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=fsl;bf9d21d2.1610 //With '-inm <value>', every voxel in the input volume is multiplied by <value> / M // where M is the mean across all voxels. //n.b.: regardless of description, mean appears to only include voxels > 0 if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; flt *f32 = (flt *)nim->data; double sum = 0.0; int n = 0; for (size_t i = 0; i < nim->nvox; i++) { if (f32[i] > 0.0f) { n++; sum += f32[i]; } } if (sum == 0) return 0; double ave = sum / n; flt scale = M / ave; #pragma omp parallel for for (int i = 0; i < nim->nvox; i++) f32[i] *= scale; return 0; } //nifti_ing() static int nifti_robust_range(nifti_image *nim, flt *pct2, flt *pct98, int ignoreZeroVoxels) { //https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=fsl;31f309c1.1307 // robust range is essentially the 2nd and 98th percentiles // "but ensuring that the majority of the intensity range is captured, even for binary images." // fsl uses 1000 bins, also limits for volumes less than 100 voxels taylor.hanayik@ndcn.ox.ac.uk 20190107 //fslstats trick -r // 0.000000 1129.141968 //niimath >fslstats trick -R // 0.000000 2734.000000 *pct2 = 0.0; *pct98 = 1.0; if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; flt *f32 = (flt *)nim->data; flt mn = INFINITY; flt mx = -INFINITY; size_t nZero = 0; size_t nNan = 0; for (size_t i = 0; i < nim->nvox; i++) { if (isnan(f32[i])) { nNan++; continue; } if (f32[i] == 0.0) { nZero++; if (ignoreZeroVoxels) continue; } mn = fmin(f32[i], mn); mx = fmax(f32[i], mx); } if ((nZero > 0) && (mn > 0.0) && (!ignoreZeroVoxels)) mn = 0.0; if (mn > mx) return 0; //all NaN if (mn == mx) { *pct2 = mn; *pct98 = mx; return 0; } if (!ignoreZeroVoxels) nZero = 0; nZero += nNan; size_t n2pct = round((nim->nvox - nZero) * 0.02); if ((n2pct < 1) || (mn == mx) || ((nim->nvox - nZero) < 100)) { //T Hanayik mentioned issue with very small volumes *pct2 = mn; *pct98 = mx; return 0; } #define nBins 1001 flt scl = (nBins - 1) / (mx - mn); int hist[nBins]; for (int i = 0; i < nBins; i++) hist[i] = 0; if (ignoreZeroVoxels) { for (int i = 0; i < nim->nvox; i++) { if (isnan(f32[i])) continue; if (f32[i] == 0.0) continue; hist[(int)round((f32[i] - mn) * scl)]++; } } else { for (int i = 0; i < nim->nvox; i++) { if (isnan(f32[i])) continue; hist[(int)round((f32[i] - mn) * scl)]++; } } size_t n = 0; size_t lo = 0; while (n < n2pct) { n += hist[lo]; //if (lo < 10) // printf("%zu %zu %zu %d\n",lo, n, n2pct, ignoreZeroVoxels); lo++; } lo--; //remove final increment n = 0; int hi = nBins; while (n < n2pct) { hi--; n += hist[hi]; } /*if ((lo+1) < hi) { size_t nGray = 0; for (int i = lo+1; i < hi; i++ ) { nGray += hist[i]; //printf("%d %d\n", i, hist[i]); } float fracGray = (float)nGray/(float)(nim->nvox - nZero); printf("histogram[%d..%d] = %zu %g\n", lo, hi, nGray, fracGray); }*/ if (lo == hi) { //MAJORITY are not black or white int ok = -1; while (ok != 0) { if (lo > 0) { lo--; if (hist[lo] > 0) ok = 0; } if ((ok != 0) && (hi < (nBins - 1))) { hi++; if (hist[hi] > 0) ok = 0; } if ((lo == 0) && (hi == (nBins - 1))) ok = 0; } //while not ok }//if lo == hi *pct2 = (lo) / scl + mn; *pct98 = (hi) / scl + mn; printf("full range %g..%g (voxels 0 or NaN =%zu) robust range %g..%g\n", mn, mx, nZero, *pct2, *pct98); return 0; } enum eDimReduceOp { Tmean, Tstd, Tmax, Tmaxn, Tmin, Tmedian, Tperc, Tar1 }; static int compare(const void *a, const void *b) { flt fa = *(const flt *)a; flt fb = *(const flt *)b; return (fa > fb) - (fa < fb); } static void dtrend(flt *xx, int npt, int pt0) { //linear detrend, first point is set to zero // if pt0=0 then mean is zero, pt0=1 then first point is zero, if pt0=2 final point is zero double t1, t3, t10, x0, x1; int ii; if (npt < 2 || xx == NULL) return; x0 = xx[0]; x1 = 0.0; for (ii = 1; ii < npt; ii++) { x0 += xx[ii]; x1 += xx[ii] * ii; } t1 = npt * x0; t3 = 1.0 / npt; t10 = npt * npt; double f0 = (double)(2.0 / (npt + 1.0) * t3 * (2.0 * t1 - 3.0 * x1 - x0)); double f1 = (double)(-6.0 / (t10 - 1.0) * t3 * (-x0 - 2.0 * x1 + t1)); //printf("%.8g %.8g %g\n", f0, f1, xx[0]); if (pt0 == 1) f0 = xx[0]; if (pt0 == 2) f0 = xx[npt - 1] - (f1 * (npt - 1)); for (ii = 0; ii < npt; ii++) xx[ii] -= (f0 + f1 * ii); } static int nifti_detrend_linear(nifti_image *nim) { if (nim->datatype != DT_CALC) return 1; size_t nvox3D = nim->nx * nim->ny * MAX(1, nim->nz); if (nvox3D < 1) return 1; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol < 2) { fprintf(stderr, "detrend requires a 4D image with at least three volumes\n"); return 1; } flt *img = (flt *)nim->data; #pragma omp parallel for for (size_t i = 0; i < nvox3D; i++) { flt *data = (flt *)_mm_malloc(nvol * sizeof(flt), 64); //load one voxel across all timepoints int j = 0; for (size_t v = i; v < nim->nvox; v += nvox3D) { data[j] = img[v]; j++; } //detrend dtrend(data, nvol, 0); //save one voxel across all timepoints j = 0; for (size_t v = i; v < nim->nvox; v += nvox3D) { img[v] = data[j]; j++; } _mm_free(data); } return 0; } #ifdef bandpass //https://github.com/QtSignalProcessing/QtSignalProcessing/blob/master/src/iir.cpp //https://github.com/rkuchumov/day_plot_diagrams/blob/8df48af431dc76b1656a627f1965d83e8693ddd7/data.c //https://scipy-cookbook.readthedocs.io/items/ButterworthBandpass.html // Sample rate and desired cutoff frequencies (in Hz). // double highcut = 1250; // double lowcut = 500; // double samp_rate = 5000; //[b,a] = butter(2, [0.009, 0.08]); //https://afni.nimh.nih.gov/afni/community/board/read.php?1,84373,137180#msg-137180 //Power 2011, Satterthwaite 2013, Carp 2011, Power's reply to Carp 2012 // https://github.com/lindenmp/rs-fMRI/blob/master/func/ButterFilt.m //https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.filtfilt.html /* The function butterworth_filter() emulates Jan Simon's FiltFiltM it uses Gustafsson’s method and padding to reduce ringing at start/end https://www.mathworks.com/matlabcentral/fileexchange/32261-filterm?focused=5193423&tab=function Copyright (c) 2011, Jan Simon All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ static int butterworth_filter(flt *img, int nvox3D, int nvol, double fs, double highcut, double lowcut) { //sample rate, low cut and high cut are all in Hz //this attempts to emulate performance of https://www.mathworks.com/matlabcentral/fileexchange/32261-filterm // specifically, prior to the forward and reverse pass the coefficients are estimated by a forward and reverse pass int order = 2; if (order <= 0) return 1; if ((highcut <= 0.0) && (lowcut <= 0.0)) return 1; if (fs <= 0.0) return 1; if ((lowcut > 0.0) && (highcut > 0.0)) printf("butter bandpass lowcut=%g highcut=%g fs=%g order=%d (effectively %d due to filtfilt)\n", lowcut, highcut, fs, order, 2 * order); else if (highcut > 0.0) printf("butter lowpass highcut=%g fs=%g order=%d (effectively %d due to filtfilt)\n", highcut, fs, order, 2 * order); else if (lowcut > 0.0) printf("butter highpass lowcut=%g fs=%g order=%d (effectively %d due to filtfilt)\n", lowcut, fs, order, 2 * order); else { printf("Butterworth parameters do not make sense\n"); return 1; } double *a; double *b; double *IC; int nX = nvol; int nA = 0; nA = butter_design(order, 2.0 * lowcut / fs, 2.0 * highcut / fs, &a, &b, &IC); int nEdge = 3 * (nA - 1); if ((nA < 1) || (nX <= nEdge)) { printf("filter requires at least %d samples\n", nEdge); _mm_free(a); _mm_free(b); _mm_free(IC); return 1; } #pragma omp parallel for for (int vx = 0; vx < nvox3D; vx++) { double *X = (double *)_mm_malloc(nX * sizeof(double), 64); size_t vo = vx; flt mn = INFINITY; flt mx = -INFINITY; for (int j = 0; j < nX; j++) { X[j] = img[vo]; mn = MIN(mn, X[j]); mx = MAX(mx, X[j]); vo += nvox3D; } if (mn < mx) { //some variability double *Xi = (double *)_mm_malloc(nEdge * sizeof(double), 64); for (int i = 0; i < nEdge; i++) Xi[nEdge - i - 1] = X[0] - (X[i + 1] - X[0]); double *CC = (double *)_mm_malloc((nA - 1) * sizeof(double), 64); for (int i = 0; i < (nA - 1); i++) CC[i] = IC[i] * Xi[0]; double *Xf = (double *)_mm_malloc(nEdge * sizeof(double), 64); for (int i = 0; i < nEdge; i++) Xf[i] = X[nX - 1] - (X[nX - 2 - i] - X[nX - 1]); Filt(Xi, nEdge, a, b, nA - 1, CC); //filter head Filt(X, nX, a, b, nA - 1, CC); //filter array Filt(Xf, nEdge, a, b, nA - 1, CC); //filter tail //reverse for (int i = 0; i < (nA - 1); i++) CC[i] = IC[i] * Xf[nEdge - 1]; FiltRev(Xf, nEdge, a, b, nA - 1, CC); //filter tail FiltRev(X, nX, a, b, nA - 1, CC); //filter array _mm_free(Xi); _mm_free(Xf); _mm_free(CC); } else { //else no variability: set all voxels to zero for (int j = 0; j < nX; j++) X[j] = 0; } //save data to 4D array vo = vx; for (int j = 0; j < nX; j++) { img[vo] = X[j]; vo += nvox3D; } _mm_free(X); } //for vx _mm_free(b); _mm_free(a); _mm_free(IC); return 0; } static int nifti_bandpass(nifti_image *nim, double hp_hz, double lp_hz, double TRsec) { if (nim->datatype != DT_CALC) return 1; size_t nvox3D = nim->nx * nim->ny * MAX(1, nim->nz); if (TRsec <= 0.0) TRsec = nim->pixdim[4]; if (TRsec <= 0) { fprintf(stderr, "Unable to determine sample rate\n"); return 1; } if (nvox3D < 1) return 1; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol < 1) { fprintf(stderr, "bandpass requires 4D datasets\n"); return 1; } return butterworth_filter((flt *)nim->data, nvox3D, nvol, 1 / TRsec, hp_hz, lp_hz); } #endif //#define DEBUG_ENABLED #ifdef DEBUG_ENABLED static int xyzt2txyz(nifti_image *nim) { size_t nxyz = nim->nx * nim->ny * nim->nz; size_t nt = nim->nt; if ((nim->nvox < 1) || (nim->nx < 1) || (nim->ny < 1) || (nim->nz < 1) || (nt < 2)) return 1; if (nim->datatype != DT_CALC) return 1; flt *img = (flt *)nim->data; flt *inimg = (flt *)_mm_malloc(nxyz * nt * sizeof(flt), 64); //alloc for each volume to allow openmp memcpy(inimg, img, nim->nvox * sizeof(flt)); size_t i = 0; #pragma omp parallel for for (size_t x = 0; x < nxyz; x++) { for (size_t t = 0; t < nt; t++) { img[i] = inimg[x + t * nxyz]; i++; } } _mm_free(inimg); return 0; } static int txyz2xyzt(nifti_image *nim) { size_t nxyz = nim->nx * nim->ny * nim->nz; size_t nt = nim->nt; if ((nim->nvox < 1) || (nim->nx < 1) || (nim->ny < 1) || (nim->nz < 1) || (nt < 2)) return 1; if (nim->datatype != DT_CALC) return 1; flt *img = (flt *)nim->data; flt *inimg = (flt *)_mm_malloc(nxyz * nt * sizeof(flt), 64); //alloc for each volume to allow openmp memcpy(inimg, img, nim->nvox * sizeof(flt)); size_t i = 0; #pragma omp parallel for for (size_t x = 0; x < nxyz; x++) { for (size_t t = 0; t < nt; t++) { img[x + t * nxyz] = inimg[i]; i++; } } _mm_free(inimg); return 0; } static int nifti_bptf(nifti_image *nim, double hp_sigma, double lp_sigma, int demean) { //Spielberg Matlab code: https://cpb-us-w2.wpmucdn.com/sites.udel.edu/dist/7/4542/files/2016/09/fsl_temporal_filt-15sywxn.m //5.0.7 highpass temporal filter removes the mean component https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/WhatsNew#anchor1 // http://www.fast.u-psud.fr/ezyfit/html/ezfit.html //gauss fitting functions: y = a*exp(-(x-x0)^2/(2*s^2)) // regression formula (https://www.mathsisfun.com/data/least-squares-regression.html) modulated by weight if (nim->datatype != DT_CALC) return 1; if ((hp_sigma <= 0) && (lp_sigma <= 0)) return 0; size_t nvox3D = nim->nx * nim->ny * MAX(1, nim->nz); if (nvox3D < 1) return 1; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol < 1) { fprintf(stderr, "bptf requires 4D datasets\n"); return 1; } int *hpStart, *hpEnd; double *hpSumX, *hpDenom, *hpSumWt, *hp, *hp0; if (hp_sigma > 0) { //initialize high-pass reusables //Spielberg's code uses 8*sigma, does not match current fslmaths: //tested with fslmaths freq4d -bptf 10 -1 nhp //cutoff ~3: most difference: 4->0.0128902 3->2.98023e-08 2->-0.0455322 1->0.379412 int cutoffhp = ceil(3 * hp_sigma); //to do: check this! ~3 hp = (double *)_mm_malloc((cutoffhp + 1 + cutoffhp) * sizeof(double), 64); //-cutoffhp..+cutoffhp hp0 = hp + cutoffhp; //convert from 0..(2*cutoffhp) to -cutoffhp..+cutoffhp for (int k = -cutoffhp; k <= cutoffhp; k++) //for each index in kernel hp0[k] = exp(-sqr(k) / (2 * sqr(hp_sigma))); hpStart = (int *)_mm_malloc(nvol * sizeof(int), 64); hpEnd = (int *)_mm_malloc(nvol * sizeof(int), 64); hpSumX = (double *)_mm_malloc(nvol * sizeof(double), 64); // hpDenom = (double *)_mm_malloc(nvol * sizeof(double), 64); // N*Sum(x^2) - (Sum(x))^2 hpSumWt = (double *)_mm_malloc(nvol * sizeof(double), 64); //sum of weight, N for (int v = 0; v < nvol; v++) { //linear regression with "gauss" fitting hpStart[v] = MAX(0, v - cutoffhp); hpEnd[v] = MIN(nvol - 1, v + cutoffhp); double sumX = 0.0; double sumX2 = 0.0; double sumWt = 0.0; for (int k = hpStart[v]; k <= hpEnd[v]; k++) { //for each index in kernel int x = k - v; double wt = hp0[x]; //kernel weight sumX += wt * x; sumX2 += wt * x * x; sumWt += wt; } hpSumX[v] = sumX; hpDenom[v] = (sumWt * sumX2) - sqr(sumX); // N*Sum(x^2) - (Sum(x))^2 if (hpDenom[v] == 0.0) hpDenom[v] = 1.0; //should never happen, x is known index hpDenom[v] = 1.0 / hpDenom[v]; //use reciprocal so we can use faster multiplication later hpSumWt[v] = sumWt; } //for each volume } //high-pass reusables //low-pass AFTER high-pass: fslmaths freq4d -bptf 45 5 fbp int *lpStart, *lpEnd; double *lpSumWt, *lp, *lp0; if (lp_sigma > 0) { //initialize low-pass reusables //simple Gaussian blur in time domain //freq4d -bptf -1 5 flp // fslmaths rest -bptf -1 5 flp // 3->0.00154053 4->3.5204e-05 5->2.98023e-07, 6->identical // Spielberg's code uses 8*sigma, so we will use that, even though precision seems excessive int cutofflp = ceil(8 * lp_sigma); //to do: check this! at least 6 lp = (double *)_mm_malloc((cutofflp + 1 + cutofflp) * sizeof(double), 64); //-cutofflp..+cutofflp lp0 = lp + cutofflp; //convert from 0..(2*cutofflp) to -cutofflp..+cutofflp for (int k = -cutofflp; k <= cutofflp; k++) //for each index in kernel lp0[k] = exp(-sqr(k) / (2 * sqr(lp_sigma))); lpStart = (int *)_mm_malloc(nvol * sizeof(int), 64); lpEnd = (int *)_mm_malloc(nvol * sizeof(int), 64); lpSumWt = (double *)_mm_malloc(nvol * sizeof(double), 64); //sum of weight, N for (int v = 0; v < nvol; v++) { lpStart[v] = MAX(0, v - cutofflp); lpEnd[v] = MIN(nvol - 1, v + cutofflp); double sumWt = 0.0; for (int k = lpStart[v]; k <= lpEnd[v]; k++) //for each index in kernel sumWt += lp0[k - v]; //kernel weight if (sumWt == 0.0) sumWt = 1.0; //will never happen lpSumWt[v] = 1.0 / sumWt; //use reciprocal so we can use faster multiplication later } //for each volume } //low-pass reusables //https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=FSL;5b8cace9.0902 //if TR=2s and 100 second cutoff is requested choose "-bptf 50 -1" //The 'cutoff' is defined as the FWHM of the filter, so if you ask for //100s that means 50 Trs, so the sigma, or HWHM, is 25 TRs. // -bptf <hp_sigma> <lp_sigma> xyzt2txyz(nim); flt *img = (flt *)nim->data; #pragma omp parallel for for (size_t i = 0; i < nvox3D; i++) { //read input data flt *imgIn = (flt *)_mm_malloc((nvol) * sizeof(flt), 64); flt *imgOut = img + (i * nvol); memcpy(imgIn, imgOut, nvol * sizeof(flt)); if (hp_sigma > 0) { double sumOut = 0.0; for (int v = 0; v < nvol; v++) { //each volume double sumY = 0.0; double sumXY = 0.0; for (int k = hpStart[v]; k <= hpEnd[v]; k++) { //for each index in kernel int x = k - v; double wt = hp0[x]; flt y = imgIn[k]; sumY += wt * y; sumXY += wt * x * y; } double n = hpSumWt[v]; double m = ((n * sumXY) - (hpSumX[v] * sumY)) * hpDenom[v]; //slope double b = (sumY - (m * hpSumX[v])) / n; //intercept imgOut[v] = imgIn[v] - b; sumOut += imgOut[v]; } //for each volume //"fslmaths -bptf removes timeseries mean (for FSL 5.0.7 onward)" n.b. except low-pass double mean = sumOut / (double)nvol; //de-mean AFTER high-pass if (demean) { for (int v = 0; v < nvol; v++) //each volume imgOut[v] -= mean; } } //hp_sigma > 0 if (lp_sigma > 0) { //low pass does not de-mean data //if BOTH low-pass and high-pass, apply low pass AFTER high pass: // fslmaths freq4d -bptf 45 5 fbp // difference 1.86265e-08 //still room for improvement: // fslmaths /Users/chris/src/rest -bptf 45 5 fbp // r=1.0 identical voxels 73% max difference 0.000488281 if (hp_sigma > 0) memcpy(imgIn, imgOut, nvol * sizeof(flt)); for (int v = 0; v < nvol; v++) { //each volume double sum = 0.0; for (int k = lpStart[v]; k <= lpEnd[v]; k++) //for each index in kernel sum += imgIn[k] * lp0[k - v]; imgOut[v] = sum * lpSumWt[v]; } // for each volume } //lp_sigma > 0 _mm_free(imgIn); } txyz2xyzt(nim); if (hp_sigma > 0) { //initialize high-pass reuseables _mm_free(hp); _mm_free(hpStart); _mm_free(hpEnd); _mm_free(hpSumX); _mm_free(hpDenom); _mm_free(hpSumWt); } if (lp_sigma > 0) { //initialize high-pass reuseables _mm_free(lp); _mm_free(lpStart); _mm_free(lpEnd); _mm_free(lpSumWt); } return 0; } // nifti_bptf() #else static int nifti_bptf(nifti_image *nim, double hp_sigma, double lp_sigma, int demean) { //Spielberg Matlab code: https://cpb-us-w2.wpmucdn.com/sites.udel.edu/dist/7/4542/files/2016/09/fsl_temporal_filt-15sywxn.m //5.0.7 highpass temporal filter removes the mean component https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/WhatsNew#anchor1 // http://www.fast.u-psud.fr/ezyfit/html/ezfit.html //gauss fitting functions: y = a*exp(-(x-x0)^2/(2*s^2)) // regression formula (https://www.mathsisfun.com/data/least-squares-regression.html) modulated by weight if (nim->datatype != DT_CALC) return 1; if ((hp_sigma <= 0) && (lp_sigma <= 0)) return 0; size_t nvox3D = nim->nx * nim->ny * MAX(1, nim->nz); if (nvox3D < 1) return 1; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol < 1) { fprintf(stderr, "bptf requires 4D datasets\n"); return 1; } int *hpStart, *hpEnd; double *hpSumX, *hpDenom, *hpSumWt, *hp, *hp0; if (hp_sigma > 0) { //initialize high-pass reusables //Spielberg's code uses 8*sigma, does not match current fslmaths: //tested with fslmaths freq4d -bptf 10 -1 nhp //cutoff ~3: most difference: 4->0.0128902 3->2.98023e-08 2->-0.0455322 1->0.379412 int cutoffhp = ceil(3 * hp_sigma); //to do: check this! ~3 hp = (double *)_mm_malloc((cutoffhp + 1 + cutoffhp) * sizeof(double), 64); //-cutoffhp..+cutoffhp hp0 = hp + cutoffhp; //convert from 0..(2*cutoffhp) to -cutoffhp..+cutoffhp for (int k = -cutoffhp; k <= cutoffhp; k++) //for each index in kernel hp0[k] = exp(-sqr(k) / (2 * sqr(hp_sigma))); hpStart = (int *)_mm_malloc(nvol * sizeof(int), 64); hpEnd = (int *)_mm_malloc(nvol * sizeof(int), 64); hpSumX = (double *)_mm_malloc(nvol * sizeof(double), 64);// hpDenom = (double *)_mm_malloc(nvol * sizeof(double), 64); // N*Sum(x^2) - (Sum(x))^2 hpSumWt = (double *)_mm_malloc(nvol * sizeof(double), 64); //sum of weight, N for (int v = 0; v < nvol; v++) { //linear regression with "gauss" fitting hpStart[v] = MAX(0, v - cutoffhp); hpEnd[v] = MIN(nvol - 1, v + cutoffhp); double sumX = 0.0; double sumX2 = 0.0; double sumWt = 0.0; for (int k = hpStart[v]; k <= hpEnd[v]; k++) { //for each index in kernel int x = k - v; double wt = hp0[x]; //kernel weight sumX += wt * x; sumX2 += wt * x * x; sumWt += wt; } hpSumX[v] = sumX; hpDenom[v] = (sumWt * sumX2) - sqr(sumX); // N*Sum(x^2) - (Sum(x))^2 if (hpDenom[v] == 0.0) hpDenom[v] = 1.0; //should never happen, x is known index hpDenom[v] = 1.0 / hpDenom[v]; //use reciprocal so we can use faster multiplication later hpSumWt[v] = sumWt; } //for each volume } //high-pass reusables //low-pass AFTER high-pass: fslmaths freq4d -bptf 45 5 fbp int *lpStart, *lpEnd; double *lpSumWt, *lp, *lp0; if (lp_sigma > 0) { //initialize low-pass reusables //simple Gaussian blur in time domain //freq4d -bptf -1 5 flp // fslmaths rest -bptf -1 5 flp // 3->0.00154053 4->3.5204e-05 5->2.98023e-07, 6->identical // Spielberg's code uses 8*sigma, so we will use that, even though precision seems excessive int cutofflp = ceil(8 * lp_sigma); //to do: check this! at least 6 lp = (double *)_mm_malloc((cutofflp + 1 + cutofflp) * sizeof(double), 64); //-cutofflp..+cutofflp lp0 = lp + cutofflp; //convert from 0..(2*cutofflp) to -cutofflp..+cutofflp for (int k = -cutofflp; k <= cutofflp; k++) //for each index in kernel lp0[k] = exp(-sqr(k) / (2 * sqr(lp_sigma))); lpStart = (int *)_mm_malloc(nvol * sizeof(int), 64); lpEnd = (int *)_mm_malloc(nvol * sizeof(int), 64); lpSumWt = (double *)_mm_malloc(nvol * sizeof(double), 64); //sum of weight, N for (int v = 0; v < nvol; v++) { lpStart[v] = MAX(0, v - cutofflp); lpEnd[v] = MIN(nvol - 1, v + cutofflp); double sumWt = 0.0; for (int k = lpStart[v]; k <= lpEnd[v]; k++) //for each index in kernel sumWt += lp0[k - v]; //kernel weight if (sumWt == 0.0) sumWt = 1.0; //will never happen lpSumWt[v] = 1.0 / sumWt; //use reciprocal so we can use faster multiplication later } //for each volume } //low-pass reusables //https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=FSL;5b8cace9.0902 //if TR=2s and 100 second cutoff is requested choose "-bptf 50 -1" //The 'cutoff' is defined as the FWHM of the filter, so if you ask for //100s that means 50 Trs, so the sigma, or HWHM, is 25 TRs. // -bptf <hp_sigma> <lp_sigma> flt *img = (flt *)nim->data; #pragma omp parallel for for (size_t i = 0; i < nvox3D; i++) { //read input data flt *imgIn = (flt *)_mm_malloc((nvol) * sizeof(flt), 64); flt *imgOut = (flt *)_mm_malloc((nvol) * sizeof(flt), 64); int j = 0; for (size_t v = i; v < nim->nvox; v += nvox3D) { imgIn[j] = img[v]; j++; } if (hp_sigma > 0) { double sumOut = 0.0; for (int v = 0; v < nvol; v++) { //each volume double sumY = 0.0; double sumXY = 0.0; for (int k = hpStart[v]; k <= hpEnd[v]; k++) { //for each index in kernel int x = k - v; double wt = hp0[x]; flt y = imgIn[k]; sumY += wt * y; sumXY += wt * x * y; } double n = hpSumWt[v]; double m = ((n * sumXY) - (hpSumX[v] * sumY)) * hpDenom[v]; //slope double b = (sumY - (m * hpSumX[v])) / n; //intercept imgOut[v] = imgIn[v] - b; sumOut += imgOut[v]; } //for each volume //"fslmaths -bptf removes timeseries mean (for FSL 5.0.7 onward)" n.b. except low-pass double mean = sumOut / (double)nvol; //de-mean AFTER high-pass if (demean) { for (int v = 0; v < nvol; v++) //each volume imgOut[v] -= mean; } } //hp_sigma > 0 if (lp_sigma > 0) { //low pass does not de-mean data //if BOTH low-pass and high-pass, apply low pass AFTER high pass: // fslmaths freq4d -bptf 45 5 fbp // difference 1.86265e-08 //still room for improvement: // fslmaths /Users/chris/src/rest -bptf 45 5 fbp // r=1.0 identical voxels 73% max difference 0.000488281 if (hp_sigma > 0) memcpy(imgIn, imgOut, nvol * sizeof(flt)); for (int v = 0; v < nvol; v++) { //each volume double sum = 0.0; for (int k = lpStart[v]; k <= lpEnd[v]; k++) //for each index in kernel sum += imgIn[k] * lp0[k - v]; imgOut[v] = sum * lpSumWt[v]; } // for each volume } //lp_sigma > 0 //write filtered data j = 0; for (size_t v = i; v < nim->nvox; v += nvox3D) { img[v] = imgOut[j]; j++; } _mm_free(imgIn); _mm_free(imgOut); } if (hp_sigma > 0) { //initialize high-pass reuseables _mm_free(hp); _mm_free(hpStart); _mm_free(hpEnd); _mm_free(hpSumX); _mm_free(hpDenom); _mm_free(hpSumWt); } if (lp_sigma > 0) { //initialize high-pass reuseables _mm_free(lp); _mm_free(lpStart); _mm_free(lpEnd); _mm_free(lpSumWt); } return 0; } // nifti_bptf() #endif static int nifti_demean(nifti_image *nim) { if (nim->datatype != DT_CALC) return 1; size_t nvox3D = nim->nx * nim->ny * MAX(1, nim->nz); if (nvox3D < 1) return 1; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol < 1) { fprintf(stderr, "demean requires 4D datasets\n"); return 1; } flt *img = (flt *)nim->data; #pragma omp parallel for for (size_t i = 0; i < nvox3D; i++) { double sum = 0.0; for (size_t v = i; v < nim->nvox; v += nvox3D) sum += img[v]; double mean = sum / nvol; for (size_t v = i; v < nim->nvox; v += nvox3D) img[v] -= mean; } return 0; } static int nifti_dim_reduce(nifti_image *nim, enum eDimReduceOp op, int dim, int percentage) { //e.g. nifti_dim_reduce(nim, Tmean, 4) reduces 4th dimension, saving mean int nReduce = nim->dim[dim]; if ((nReduce <= 1) || (dim < 1) || (dim > 4)) return 0; //nothing to reduce, fslmaths does not generate an error if ((nim->nvox < 1) || (nim->nx < 1) || (nim->ny < 1) || (nim->nz < 1)) return 1; //size_t nvox3D = nim->nx * nim->ny * nim->nz; //int nvol = nim->nvox / nvox3D; //if ((nvox3D * nvol) != nim->nvox) return 1; if (nim->datatype != DT_CALC) return 1; if (nim->dim[0] > 4) fprintf(stderr, "dimension reduction collapsing %" PRId64 "D into to 4D\n", nim->dim[0]); int dims[8], indims[8]; for (int i = 0; i < 4; i++) dims[i] = MAX(nim->dim[i], 1); //XYZT limits to 4 dimensions, so collapse dims [4,5,6,7] dims[4] = nim->nvox / (dims[1] * dims[2] * dims[3]); for (int i = 5; i < 8; i++) dims[i] = 1; for (int i = 0; i < 8; i++) indims[i] = dims[i]; if ((dims[1] * dims[2] * dims[3] * dims[4]) != nim->nvox) return 1; //e.g. data in dim 5..7! dims[dim] = 1; if (dim == 4) dims[0] = 3; //reduce 4D to 3D size_t nvox = dims[1] * dims[2] * dims[3] * dims[4]; flt *i32 = (flt *)nim->data; void *dat = (void *)calloc(1, nim->nvox * sizeof(flt)); flt *o32 = (flt *)dat; int collapseStep; //e.g. if we collapse 4th dimension, we will collapse across voxels separated by X*Y*Z if (dim == 1) collapseStep = 1; //collapse by columns else if (dim == 2) collapseStep = indims[1]; //collapse by rows else if (dim == 3) collapseStep = indims[1] * indims[2]; //collapse by slices else collapseStep = indims[1] * indims[2] * indims[3]; //collapse by volumes int xy = dims[1] * dims[2]; int xyz = xy * dims[3]; if ((op == Tmedian) || (op == Tstd) || (op == Tperc) || (op == Tar1)) { //for even number of items, two options for median, consider 4 volumes ranked // meam of 2nd and 3rd: problem one can return values not in data // 2nd value. Representative //here we use the latter approach //int itm = ((nReduce-1) * 0.5); int itm = (nReduce * 0.5); //seems correct tested with odd and even number of volumes if (op == Tperc) { double frac = ((double)percentage) / 100.0; //itm = ((nReduce-1) * frac); itm = ((nReduce)*frac); itm = MAX(itm, 0); itm = MIN(itm, nReduce - 1); } #pragma omp parallel for for (size_t i = 0; i < nvox; i++) { flt *vxls = (flt *)_mm_malloc((nReduce) * sizeof(flt), 64); size_t inPos = i; if (dim < 4) { //i is in output space, convert to input space, allows single loop for OpenMP int T = (i / xyz); //volume int r = i % (xyz); int Z = (r / xy); //slice r = r % (xy); int Y = (r / dims[1]); //row int X = r % dims[1]; inPos = X + (Y * indims[1]) + (Z * indims[1] * indims[2]) + (T * indims[1] * indims[2] * indims[3]); } for (int v = 0; v < nReduce; v++) { vxls[v] = i32[inPos]; inPos += collapseStep; } if ((op == Tstd) || (op == Tar1)) { //computed in cache, far fewer operations than Welford //note 64-bit double precision even if 32-bit DT_CALC //neither precision gives identical results // double precision attenuates catastrophic cancellation double sum = 0.0; for (int v = 0; v < nReduce; v++) sum += vxls[v]; double mean = sum / nReduce; double sumSqr = 0.0; for (int v = 0; v < nReduce; v++) sumSqr += sqr(vxls[v] - mean); if (op == Tstd) o32[i] = sqrt(sumSqr / (nReduce - 1)); else { //Tar1 if (sumSqr == 0.0) { o32[i] = 0.0; continue; } for (int v = 0; v < nReduce; v++) vxls[v] = vxls[v] - mean; //demean double r = 0.0; for (int v = 1; v < nReduce; v++) r += (vxls[v] * vxls[v - 1]) / sumSqr; o32[i] = r; } } else { //Tperc or Tmedian qsort(vxls, nReduce, sizeof(flt), compare); o32[i] = vxls[itm]; } _mm_free(vxls); } //for i: each voxel } else { #pragma omp parallel for for (size_t i = 0; i < nvox; i++) { size_t inPos = i; //ok if dim==4 if (dim < 4) { //i is in output space, convert to input space, allows single loop for OpenMP int T = (i / xyz); //volume int r = i % (xyz); int Z = (r / xy); //slice r = r % (xy); int Y = (r / dims[1]); //row int X = r % dims[1]; inPos = X + (Y * indims[1]) + (Z * indims[1] * indims[2]) + (T * indims[1] * indims[2] * indims[3]); } double sum = 0.0; flt mx = i32[inPos]; flt mn = mx; int mxn = 0; //flt sd = 0.0; //flt mean = 0.0; for (int v = 0; v < nReduce; v++) { flt f = i32[inPos]; sum += f; if (f > mx) { mx = f; mxn = v; } mn = MIN(mn, f); //Welford https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance // 2-pass method faster //flt delta = f - mean; //mean = mean + delta / (v+1); //sd = sd + delta*(f- mean); inPos += collapseStep; } if (op == Tmean) o32[i] = sum / nReduce; //mean else if (op == Tmax) o32[i] = mx; //max else if (op == Tmaxn) o32[i] = mxn; //maxn else if (op == Tmin) o32[i] = mn; //min } } //if opel nim->nvox = nvox; for (int i = 0; i < 4; i++) nim->dim[i] = dims[i]; nim->ndim = dims[0]; nim->nx = dims[1]; nim->ny = dims[2]; nim->nz = dims[3]; nim->nt = dims[4]; nim->nu = dims[5]; nim->nv = dims[6]; nim->nw = dims[7]; free(nim->data); nim->data = dat; return 0; } //Tar1 enum eOp { unknown, add, sub, mul, divX, rem, mod, mas, thr, thrp, thrP, uthr, uthrp, uthrP, clamp, uclamp, max, min, power, seed, inm, ing, smth, exp1, floor1, round1, trunc1, ceil1, log1, sin1, cos1, tan1, asin1, acos1, atan1, sqr1, sqrt1, recip1, abs1, bin1, binv1, edge1, index1, nan1, nanm1, rand1, randn1, range1, rank1, ranknorm1, pval1, pval01, cpval1, ztop1, ptoz1, dilMk, dilDk, dilFk, dilallk, erok, eroFk, fmediank, fmeank, fmeanuk, subsamp2, subsamp2offc }; static int *make_kernel_gauss(nifti_image *nim, int *nkernel, double sigmamm) { sigmamm = fabs(sigmamm); if (sigmamm == 0.0) return NULL; double mmCutoff = sigmamm * 6.0; //maximum extent int x = (2 * floor(mmCutoff / nim->dx)) + 1; int y = (2 * floor(mmCutoff / nim->dy)) + 1; int z = (2 * floor(mmCutoff / nim->dz)) + 1; int xlo = (int)(-x / 2); int ylo = (int)(-y / 2); int zlo = (int)(-z / 2); //betterthanfsl // fsl computes gaussian for all values in cube // from first principles, a spherical filter has less bias // since weighting is very low at these edge voxels, it has little impact on // "-fmean", however with other filters like "dilM", fsl's solution works like // a "box" filter, not a "sphere" filter // default is to clone fsl #ifdef betterthanfsl //true sphere at cutouff //first pass: determine number of surviving voxels (n) int n = 0; for (int zi = zlo; zi < (zlo + z); zi++) for (int yi = ylo; yi < (ylo + y); yi++) for (int xi = xlo; xi < (xlo + x); xi++) { flt dx = (xi * nim->dx); flt dy = (yi * nim->dy); flt dz = (zi * nim->dz); flt dist = sqrt(dx * dx + dy * dy + dz * dz); if (dist > mmCutoff) continue; n++; } *nkernel = n; int kernelWeight = (int)((double)INT_MAX / (double)n); //requires <limits.h> int *kernel = (int *)_mm_malloc((n * 4) * sizeof(int), 64); //4 values: offset, xpos, ypos, weight double *wt = (double *)_mm_malloc((n) * sizeof(double), 64); //precess weight: temporary //second pass: fill surviving voxels int i = 0; double expd = 2.0 * sigmamm * sigmamm; for (int zi = zlo; zi < (zlo + z); zi++) for (int yi = ylo; yi < (ylo + y); yi++) for (int xi = xlo; xi < (xlo + x); xi++) { flt dx = (xi * nim->dx); flt dy = (yi * nim->dy); flt dz = (zi * nim->dz); flt dist = sqrt(dx * dx + dy * dy + dz * dz); if (dist > mmCutoff) continue; kernel[i] = xi + (yi * nim->nx) + (zi * nim->nx * nim->ny); kernel[i + n] = xi; //left-right wrap detection kernel[i + n + n] = yi; //anterior-posterior wrap detection //kernel[i+n+n+n] = kernelWeight; //kernel height wt[i] = exp(-1.0 * (dist * dist) / expd); i++; } #else int n = x * y * z; *nkernel = n; int *kernel = (int *)_mm_malloc((n * 4) * sizeof(int), 64); //4 values: offset, xpos, ypos, weight double *wt = (double *)_mm_malloc((n) * sizeof(double), 64); //precess weight: temporary int i = 0; double expd = 2.0 * sigmamm * sigmamm; for (int zi = zlo; zi < (zlo + z); zi++) for (int yi = ylo; yi < (ylo + y); yi++) for (int xi = xlo; xi < (xlo + x); xi++) { flt dx = (xi * nim->dx); flt dy = (yi * nim->dy); flt dz = (zi * nim->dz); flt dist = sqrt(dx * dx + dy * dy + dz * dz); //if (dist > mmCutoff) continue; //<- fsl fills all kernel[i] = xi + (yi * nim->nx) + (zi * nim->nx * nim->ny); kernel[i + n] = xi; //left-right wrap detection kernel[i + n + n] = yi; //anterior-posterior wrap detection //kernel[i+n+n+n] = kernelWeight; //kernel height wt[i] = exp(-1.0 * (dist * dist) / expd); i++; } #endif double sum = 0.0; for (int i = 0; i < n; i++) sum += wt[i]; //sum of entire gaussian is 1 double scale = 1.0 / sum; scale *= (double)INT_MAX; //we use integer scaling: in future faster to typecast integer as flt (if int=32bit) or double (if int=64bit) for (int i = 0; i < n; i++) kernel[i + n + n + n] = wt[i] * scale; _mm_free(wt); return kernel; } //make_kernel_gauss() static flt calmax(nifti_image *nim) { if ((nim->nvox < 1) || (nim->datatype != DT_CALC)) return 0.0; flt *in32 = (flt *)nim->data; flt mx = in32[0]; for (size_t i = 0; i < nim->nvox; i++) mx = MAX(mx, in32[i]); return mx; } static flt calmin(nifti_image *nim) { if ((nim->nvox < 1) || (nim->datatype != DT_CALC)) return 0.0; flt *in32 = (flt *)nim->data; flt mn = in32[0]; for (size_t i = 0; i < nim->nvox; i++) mn = MIN(mn, in32[i]); return mn; } static int nifti_tensor_2(nifti_image *nim, int lower2upper) { int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; if ((nim->datatype != DT_CALC) || (nvox3D < 1)) return 1; int nVol = (int)(nim->nvox / nvox3D); if (nVol != 6) { fprintf(stderr, "nifti_tensor_2: input must have precisely 6 volumes (not %d)\n", nVol); return 1; } //3dAFNItoNIFTI does not set intent_code to NIFTI_INTENT_SYMMATRIX, so check dimensions if ((lower2upper) && (nim->dim[4] == 6)) fprintf(stderr, "nifti_tensor_2: check images (header suggests already in upper triangle format)\n"); if ((!lower2upper) && (nim->dim[4] == 6)) fprintf(stderr, "nifti_tensor_2: check images (header suggests already in lower triangle format)\n"); //lower xx xy yy xz yz zz //upper xx xy xz yy yz zz //swap volumes 3 and 4 flt *in32 = (flt *)nim->data; flt *tmp = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64); flt *v3 = in32 + (2 * nvox3D); flt *v4 = in32 + (3 * nvox3D); memcpy(tmp, v4, nvox3D * sizeof(flt)); memcpy(v4, v3, nvox3D * sizeof(flt)); memcpy(v3, tmp, nvox3D * sizeof(flt)); _mm_free(tmp); if (lower2upper) { //FSL uses non-standard upper triangle nim->dim[0] = 4; for (int i = 4; i < 8; i++) nim->dim[i] = 1; nim->dim[4] = 6; nim->ndim = 4; nim->nt = 6; nim->nu = 1; nim->nv = 1; nim->nw = 1; } else { //upper2lower //lower is NIfTI default, used by AFNI, Camino, ANTS nim->intent_code = NIFTI_INTENT_SYMMATRIX; /*! To store an NxN symmetric matrix at each voxel: - dataset must have a 5th dimension - intent_code must be NIFTI_INTENT_SYMMATRIX - dim[5] must be N*(N+1)/2 - intent_p1 must be N (in float format) - the matrix values A[i][[j] are stored in row-order: - A[0][0] - A[1][0] A[1][1] - A[2][0] A[2][1] A[2][2] - etc.: row-by-row*/ nim->dim[0] = 5; for (int i = 4; i < 8; i++) nim->dim[i] = 1; nim->dim[5] = 6; nim->ndim = 5; nim->nt = 1; nim->nu = 6; nim->nv = 1; nim->nw = 1; } return 0; } static int nifti_tensor_decomp(nifti_image *nim, int isUpperTriangle) { // MD= (Dxx+Dyy+Dzz)/3 //https://github.com/ANTsX/ANTs/wiki/Importing-diffusion-tensor-data-from-other-software // dtifit produces upper-triangular order: xx xy xz yy yz zz //MD = 1/3*(Dxx+Dyy+Dzz) //FA= sqrt(3/2)*sqrt(((Dx-MD)^2+(Dy-MD)^2+(Dz-MD^2))/(Dx^2+Dy^2+Dz^2)) //fslmaths tensor.nii -tensor_decomp bork.nii // 3dDTeig -uddata -sep_dsets -prefix AFNIdwi.nii tensor.nii //3dDTeig expects LOWER diagonal order unless -uddata // Dxx,Dxy,Dyy,Dxz,Dyz,Dzz // https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dDTeig.html //dxx, dxy, dyy, dxz, dyz, dzz // 3dDTeig -uddata -prefix AFNIdwi.nii tensor.nii // fslmaths tensor.nii -tensor_decomp bork.nii // Creates 5*3D and 3*4D files for a total of 14 volumes L1,L2,L3,V1(3),V2(3),V3(3),FA,MD #ifdef tensor_decomp if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2) || (nim->nz < 1)) return 1; if (nim->datatype != DT_CALC) return 1; int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nVol = (int)(nim->nvox / nvox3D); if (nVol != 6) { fprintf(stderr, "nifti_tensor_decomp: input must have precisely 6 volumes (not %d)\n", nVol); return 1; } flt *in32 = (flt *)nim->data; //detect if data is upper or lower triangle // The "YY" component should be brighter (strongly positive) than the off axis XZ #define detectUpperOrLower #ifdef detectUpperOrLower double sumV3 = 0.0; //3rd volume, YY for lower, XZ for upper double sumV4 = 0.0; //4th volume, XZ for lower, YY for upper flt *v32 = in32 + (nvox3D * 2); //offset to 3rd volume for (size_t i = 0; i < nvox3D; i++) sumV3 += v32[i]; v32 = in32 + (nvox3D * 3); //offset to 4th volume for (size_t i = 0; i < nvox3D; i++) sumV4 += v32[i]; if ((sumV4 > sumV3) && (!isUpperTriangle)) fprintf(stderr, "nifti_tensor_decomp: check results, input looks like UPPER triangle.\n"); if ((sumV4 < sumV3) && (isUpperTriangle)) fprintf(stderr, "nifti_tensor_decomp: check results, input looks like LOWER triangle.\n"); #endif flt *out32 = (flt *)_mm_malloc(14 * nvox3D * sizeof(flt), 64); for (size_t i = 0; i < nvox3D; i++) { //n.b. in6 and out14 are ALWAYS float regradless of DT32, e.g. single even if DT=double float *in6 = (float *)_mm_malloc(6 * sizeof(float), 64); float *out14 = (float *)_mm_malloc(14 * sizeof(float), 64); size_t iv = i; for (int v = 0; v < 6; v++) { in6[v] = in32[iv]; iv += nvox3D; } EIG_tsfunc(0.0, 0.0, 0, in6, 0.0, 0.0, NULL, 0, out14, isUpperTriangle); size_t ov = i; for (int v = 0; v < 14; v++) { out32[ov] = out14[v]; ov += nvox3D; } _mm_free(out14); _mm_free(in6); } free(nim->data); // Creates 5*3D and 3*4D files for a total of 14 volumes L1(0),L2(1),L3(2),V1(3,4,5),V2(6,7,8),V3(9,10,11),FA(12),MD(13) flt *outv; //save 4D images nim->cal_min = -1; nim->cal_max = 1; nim->nvox = nvox3D * 3; nim->ndim = 4; nim->nt = 3; nim->nu = 1; nim->nv = 1; nim->nw = 1; nim->dim[0] = 4; nim->dim[4] = 3; for (int i = 5; i < 8; i++) nim->dim[i] = 1; //void * dat = (void *)calloc(1, 3*nvox3D * sizeof(flt)) ; //nim->data = dat; //flt * fa32 = (flt *) dat; //save V1 outv = out32 + (nvox3D * 3); nim->data = (void *)outv; nifti_save(nim, "_V1"); //save V2 outv = out32 + (nvox3D * 6); //memcpy(fa32, outv, 3*nvox3D*sizeof(flt)); nim->data = (void *)outv; nifti_save(nim, "_V2"); //save V3 outv = out32 + (nvox3D * 9); //memcpy(fa32, outv, 3*nvox3D*sizeof(flt)); nim->data = (void *)outv; nifti_save(nim, "_V3"); //release 4D memory //free(dat); //save 3D images nim->cal_min = 0; nim->cal_max = 0; nim->nvox = nvox3D * 1; nim->ndim = 3; nim->nt = 1; nim->dim[0] = 3; nim->dim[4] = 1; //save L1 outv = out32; //memcpy(fa32, outv, nvox3D*sizeof(flt)); nim->data = (void *)outv; nim->cal_max = calmax(nim); nifti_save(nim, "_L1"); //save L2 outv = out32 + (nvox3D * 1); //memcpy(fa32, outv, nvox3D*sizeof(flt)); nim->data = (void *)outv; nim->cal_max = calmax(nim); nifti_save(nim, "_L2"); //save L3 outv = out32 + (nvox3D * 2); //memcpy(fa32, outv, nvox3D*sizeof(flt)); nim->data = (void *)outv; nim->cal_max = calmax(nim); nifti_save(nim, "_L3"); //save MD outv = out32 + (nvox3D * 13); //memcpy(fa32, outv, nvox3D*sizeof(flt)); nim->data = (void *)outv; nim->cal_min = calmin(nim); nim->cal_max = calmax(nim); nifti_save(nim, "_MD"); //single volume data void *dat = (void *)calloc(1, nvox3D * sizeof(flt)); nim->data = dat; flt *fa32 = (flt *)dat; //save MO //MODE https://www.jiscmail.ac.uk/cgi-bin/webadmin?A2=FSL;4fbed3d1.1103 // compute MO (MODE) from L1, L2, L3, MD //e1=l1-MD, e2=l2-MD, e3=l3-MD; //n = (e1 + e2 - 2*e3)*(2*e1 - e2 - e3)*(e1 - 2*e2 + e3); //d = (e1*e1 + e2*e2 + e3*e3 - e1*e2 - e2*e3 - e1*e3); //d = 2*d*d*d; //mode = n/d; //something is wrong with this formula. // a. Ennis 2006 includes a sqrt that can not be factored out // b. results differ from fslmaths nim->cal_min = -1; nim->cal_max = 1; flt *L1 = out32; flt *L2 = out32 + (nvox3D * 1); flt *L3 = out32 + (nvox3D * 2); flt *MD = out32 + (nvox3D * 13); for (size_t i = 0; i < nvox3D; i++) { flt e1 = L1[i] - MD[i]; flt e2 = L2[i] - MD[i]; flt e3 = L3[i] - MD[i]; flt n = (e1 + e2 - 2 * e3) * (2 * e1 - e2 - e3) * (e1 - 2 * e2 + e3); flt d = (e1 * e1 + e2 * e2 + e3 * e3 - e1 * e2 - e2 * e3 - e1 * e3); d = sqrt(d); //Correlation r = 0.999746 d = 2 * d * d * d; //d = sqrt(d); //Correlation r = 0.990319 if (d != 0) d = n / d; //mode d = MIN(d, 1.0); d = MAX(d, -1.0); fa32[i] = d; } nifti_save(nim, "_MO"); //save FA outv = out32 + (nvox3D * 12); memcpy(fa32, outv, nvox3D * sizeof(flt)); nim->cal_min = 0; nim->cal_max = 1; nifti_save(nim, "_FA"); //keep FA in memory nim->cal_max = 0; _mm_free(out32); return 0; #else fprintf(stderr, "not compiled to support tensor_decomp\n"); return 1; #endif } //nifti_tensor_decomp() static void kernel3D_dilall(nifti_image *nim, int *kernel, int nkernel, int vol) { int nVox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; flt *f32 = (flt *)nim->data; f32 += (nVox3D * vol); flt *inf32 = (flt *)_mm_malloc(nVox3D * sizeof(flt), 64); memcpy(inf32, f32, nVox3D * sizeof(flt)); int nxy = nim->nx * nim->ny; size_t nZero = 1; while (nZero > 0) { nZero = 0; for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; if (f32[i] != 0.0) continue; int nNot0 = 0; flt sum = 0.0f; for (size_t k = 0; k < nkernel; k++) { size_t vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D) || (inf32[vx] == 0.0)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior nNot0++; sum += inf32[vx]; } //for k if (nNot0 > 0) f32[i] = sum / nNot0; nZero++; } //for x } //for y } //for z memcpy(inf32, f32, nVox3D * sizeof(flt)); //printf("n=0: %zu\n", nZero); } //nZero > 0 _mm_free(inf32); } //kernel3D_dilall() static int kernel3D(nifti_image *nim, enum eOp op, int *kernel, int nkernel, int vol) { int nVox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; flt *f32 = (flt *)nim->data; f32 += (nVox3D * vol); flt *inf32 = (flt *)_mm_malloc(nVox3D * sizeof(flt), 64); memcpy(inf32, f32, nVox3D * sizeof(flt)); int nxy = nim->nx * nim->ny; if (op == fmediank) { flt *vxls = (flt *)_mm_malloc((nkernel) * sizeof(flt), 64); for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; int nOK = 0; for (size_t k = 0; k < nkernel; k++) { size_t vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior vxls[nOK] = inf32[vx]; nOK++; } //for k qsort(vxls, nOK, sizeof(flt), compare); int itm = (nOK * 0.5); f32[i] = vxls[itm]; } //for x } //for y } //for z _mm_free(vxls); } else if (op == dilMk) { for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; if (f32[i] != 0.0) continue; int nNot0 = 0; flt sum = 0.0f; for (size_t k = 0; k < nkernel; k++) { size_t vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D) || (inf32[vx] == 0.0)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior nNot0++; sum += inf32[vx]; } //for k if (nNot0 > 0) f32[i] = sum / nNot0; } //for x } //for y } //for z } else if (op == dilDk) { //maximum - fslmaths 6.0.1 emulation, note really MODE, max non-zero for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; if (f32[i] != 0.0) continue; //flt mx = -INFINITY; flt mx = NAN; for (int k = 0; k < nkernel; k++) { int vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior flt v = inf32[vx]; if (v == 0.0) continue; mx = MAX(mx, inf32[vx]); //with dilD a input voxel of 0 } //for k //https://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c // f != f will be true only if f is NaN if (!(mx != mx)) f32[i] = mx; } //for x } //for y } //for z } else if (op == dilFk) { //maximum - fslmaths 6.0.1 appears to use "dilF" when the user requests "dilD" for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; flt mx = f32[i]; for (int k = 0; k < nkernel; k++) { int vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D) || (inf32[vx] <= mx)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior mx = MAX(mx, inf32[vx]); //if (mx < 0) continue; //with dilF, do not make a zero voxel darker than 0 } //for k f32[i] = mx; } //for x } //for y } //for z } else if (op == dilallk) { // -dilall : Apply -dilM repeatedly until the entire FOV is covered"); kernel3D_dilall(nim, kernel, nkernel, vol); } else if (op == eroFk) { //Minimum filtering of all voxels for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; for (int k = 0; k < nkernel; k++) { int vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior f32[i] = MIN(f32[i], inf32[vx]); } //for k } //for x } //for y } //for z } else if (op == fmeank) { flt *kwt = (flt *)_mm_malloc(nkernel * sizeof(flt), 64); for (int k = 0; k < nkernel; k++) kwt[k] = ((double)kernel[k + nkernel + nkernel + nkernel] / (double)INT_MAX); for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; flt sum = 0.0f; flt wt = 0.0f; for (int k = 0; k < nkernel; k++) { int vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior sum += (inf32[vx] * kwt[k]); wt += kwt[k]; } //for k f32[i] = sum / wt; } //for x } //for y } //for z _mm_free(kwt); } else if (op == fmeanuk) { flt *kwt = (flt *)_mm_malloc(nkernel * sizeof(flt), 64); for (int k = 0; k < nkernel; k++) kwt[k] = ((double)kernel[k + nkernel + nkernel + nkernel] / (double)INT_MAX); for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; flt sum = 0.0f; //flt wt = 0.0f; for (int k = 0; k < nkernel; k++) { int vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior sum += (inf32[vx] * kwt[k]); //wt += kwt[k]; } //for k //f32[i] = sum / wt; f32[i] = sum; } //for x } //for y } //for z _mm_free(kwt); } else if (op == erok) { for (int z = 0; z < nim->nz; z++) { int i = (z * nxy) - 1; //offset for (int y = 0; y < nim->ny; y++) { for (int x = 0; x < nim->nx; x++) { i++; if (f32[i] == 0.0) continue; for (int k = 0; k < nkernel; k++) { int vx = i + kernel[k]; if ((vx < 0) || (vx >= nVox3D) || (inf32[vx] != 0.0)) continue; //next handle edge cases int dx = x + kernel[k + nkernel]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kernel[k + nkernel + nkernel]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior f32[i] = 0.0; } //for k } //for x } //for y } //for z } else { fprintf(stderr, "kernel3D: Unsupported operation\n"); _mm_free(inf32); return 1; } _mm_free(inf32); return 0; } //kernel3D static int nifti_kernel(nifti_image *nim, enum eOp op, int *kernel, int nkernel) { if ((nim->nvox < 1) || (nim->nx < 2) || (nim->ny < 2) || (nim->nz < 1)) return 1; if (nim->datatype != DT_CALC) return 1; int nVox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nVol = (int)(nim->nvox / nVox3D); if (nVol < 1) return 1; if ((nkernel < 1) || (kernel == NULL)) return 1; for (int v = 0; v < nVol; v++) { int ok = kernel3D(nim, op, kernel, nkernel, v); if (ok != 0) return ok; } return 0; } static int nifti_roi(nifti_image *nim, int xmin, int xsize, int ymin, int ysize, int zmin, int zsize, int tmin, int tsize) { // "fslmaths LAS -roi 3 32 0 40 0 40 0 5 f " int nt = nim->nvox / (nim->nx * nim->ny * nim->nz); if ((nim->nvox < 1) || (nt < 1)) return 1; if (nim->datatype != DT_CALC) return 1; flt *f32 = (flt *)nim->data; //if (neg_determ(nim)) // do something profound; //determinants do not seem to influence "-roi"? int xmax = xmin + xsize - 1; int ymax = ymin + ysize - 1; int zmax = zmin + zsize - 1; int tmax = tmin + tsize - 1; //printf("%d..%d", zmin, zmax); size_t i = 0; for (int t = 0; t < nt; t++) { int tOK = 1; if ((t < tmin) || (t > tmax)) tOK = 0; for (int z = 0; z < nim->nz; z++) { int zOK = 1; if ((z < zmin) || (z > zmax)) zOK = 0; for (int y = 0; y < nim->ny; y++) { int yOK = 1; if ((y < ymin) || (y > ymax)) yOK = 0; for (int x = 0; x < nim->nx; x++) { int xOK = 1; if ((x < xmin) || (x > xmax)) xOK = 0; if ((xOK == 0) || (yOK == 0) || (zOK == 0) || (tOK == 0)) f32[i] = 0.0; i++; } //x } //y } //z } //t return 0; } static int nifti_sobel(nifti_image *nim, int offc, int isBinary) { //sobel is simply one kernel pass per dimension. // this could be achieved with successive passes of "-kernel" // here it is done in a single pass for cache efficiency // https://en.wikipedia.org/wiki/Sobel_operator int vox3D = nim->nx * nim->ny * MAX(nim->nz, 1); if (nim->datatype != DT_CALC) return 1; int nvol = nim->nvox / vox3D; int numk = 6; //center voxel and all its neighbors int *kx = (int *)_mm_malloc((numk * 4) * sizeof(int), 64); //4 values: offset, xpos, ypos, weight int *ky = (int *)_mm_malloc((numk * 4) * sizeof(int), 64); //4 values: offset, xpos, ypos, weight int *kz = (int *)_mm_malloc((numk * 4) * sizeof(int), 64); //4 values: offset, xpos, ypos, weight int i = 0; for (int x = 0; x <= 1; x++) for (int y = -1; y <= 1; y++) { int sgn = (2 * x) - 1; //-1 or +1 int weight = sgn * (2 - abs(y)); //kx compare left and right kx[i + numk] = (2 * x) - 1; //left/right wrap kx[i + numk + numk] = y; //anterior/posterior wrap kx[i] = kx[i + numk] + (kx[i + numk + numk] * (nim->nx)); //voxel offset kx[i + numk + numk + numk] = weight; //weight //ky compare anterior and posterior ky[i + numk] = y; //left/right wrap ky[i + numk + numk] = (2 * x) - 1; //anterior/posterior wrap ky[i] = ky[i + numk] + (ky[i + numk + numk] * (nim->nx)); //voxel offset ky[i + numk + numk + numk] = weight; //weight //kz superior/inferior kz[i + numk] = y; //left/right wrap kz[i + numk + numk] = 0; //anterior/posterior wrap kz[i] = y + (((2 * x) - 1) * nim->nx * nim->ny); //voxel offset kz[i + numk + numk + numk] = weight; //weight //printf("x%d y%d wt%d\n", kx[i+numk], kx[i+numk+numk], kx[i+numk+numk+numk]); //printf("x%d y%d wt%d\n", ky[i+numk], ky[i+numk+numk], ky[i+numk+numk+numk]); i++; } //for y flt *i32 = (flt *)nim->data; //input volumes #pragma omp parallel for for (int v = 0; v < nvol; v++) { flt *iv32 = i32 + (v * vox3D); flt *imgin = _mm_malloc(vox3D * sizeof(flt), 64); //input values prior to blur //edge information: flt mx = 0.0; uint8_t *imgdir = _mm_malloc(vox3D * sizeof(uint8_t), 64); //image direction if (isBinary) memset(imgdir, 0, vox3D * sizeof(uint8_t)); memcpy(imgin, iv32, vox3D * sizeof(flt)); int i = 0; for (int z = 0; z < nim->nz; z++) for (int y = 0; y < nim->ny; y++) for (size_t x = 0; x < nim->nx; x++) { //compute z gradient flt gx = 0.0f; for (size_t k = 0; k < numk; k++) { size_t vx = i + kx[k]; if ((vx < 0) || (vx >= vox3D)) continue; //next handle edge cases int dx = x + kx[k + numk]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kx[k + numk + numk]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior gx += imgin[vx] * kx[k + numk + numk + numk]; } //for k //compute y gradient flt gy = 0.0f; for (size_t k = 0; k < numk; k++) { size_t vx = i + ky[k]; if ((vx < 0) || (vx >= vox3D)) continue; //next handle edge cases int dx = x + ky[k + numk]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + ky[k + numk + numk]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior gy += imgin[vx] * ky[k + numk + numk + numk]; } //for k //compute z gradient flt gz = 0.0f; //always 0 for 2D, we could add conditional to skip but optimize for 3D for (size_t k = 0; k < numk; k++) { size_t vx = i + kz[k]; if ((vx < 0) || (vx >= vox3D)) continue; //next handle edge cases int dx = x + kz[k + numk]; if ((dx < 0) || (dx >= nim->nx)) continue; //wrapped left-right int dy = y + kz[k + numk + numk]; if ((dy < 0) || (dy >= nim->ny)) continue; //wrapped anterior-posterior gz += imgin[vx] * kz[k + numk + numk + numk]; } //for k gx = sqr(gx); gy = sqr(gy); gz = sqr(gz); iv32[i] = sqrt(gx + gy + gz); if (isBinary) { mx = MAX(mx, iv32[i]); if ((gx > gy) && (gx > gz)) imgdir[i] = 1; //left/right gradient is strongest else if (gy > gz) imgdir[i] = 2; //anterior/posterior gradient is strongest else imgdir[i] = 3; //superior/inferior gradient is strongest (or tie) } i++; } //for x if (isBinary) { //magnitude in range 0..1, zero voxels below threshold float scale = 1.0; if (mx > 0.0) scale = 1.0 / mx; float thresh = 0.1; for (int vx = 0; vx < vox3D; vx++) { imgin[vx] = iv32[vx] * scale; if (imgin[vx] < thresh) { imgin[vx] = 0.0; continue; } } //zero output: we will not set border voxels memset(iv32, 0, vox3D * sizeof(flt)); // int nx = nim->nx; int nxy = nx * nim->ny; for (int z = 1; z < (nim->nz -1); z++) for (int y = 1; y < (nim->ny - 1); y++) for (size_t x = 1; x < (nim->nx - 1); x++) { int vx = x + (y * nx) + (z * nxy); float val = imgin[vx]; if (val == 0.0) continue; float mxX = MAX(imgin[vx-1],imgin[vx+1]); float mxY = MAX(imgin[vx-nx],imgin[vx+nx]); float mxZ = MAX(imgin[vx-nxy],imgin[vx+nxy]); if ((imgdir[vx] == 1) && (val > mxX) && ((mxY > 0.0) || (mxZ > 0.0)) ) //left/right gradient iv32[vx] = 1.0; else if ((imgdir[vx] == 2) && (val > mxY) && ((mxX > 0.0) || (mxZ > 0.0)) ) //anterior/posterior gradient iv32[vx] = 1.0; else if ((val > mxZ) && ((mxX > 0.0) || (mxY > 0.0)))//head/foot gradient iv32[vx] = 1.0; } nim->scl_inter = 0.0; nim->scl_slope = 1.0; nim->cal_min = 0.0; nim->cal_max = 1.0; } //if isBinary _mm_free(imgdir); _mm_free(imgin); } //for each volume _mm_free(kx); _mm_free(ky); _mm_free(kz); return 0; } //nifti_sobel() static int nifti_subsamp2(nifti_image *nim, int offc) { //naive downsampling: this is provided purely to mimic the behavior of fslmaths // see https://nbviewer.jupyter.org/urls/dl.dropbox.com/s/s0nw827nc4kcnaa/Aliasing.ipynb // no anti-aliasing filter https://en.wikipedia.org/wiki/Image_scaling int invox3D = nim->nx * nim->ny * MAX(nim->nz, 1); int indim[5]; for (int i = 1; i < 5; i++) indim[i] = MAX(nim->dim[i], 1); int nvol = nim->nvox / invox3D; int x_odd = indim[1] % 2; if ((nim->nvox < 1) || (nvol < 1)) return 1; if (nim->datatype != DT_CALC) return 1; int nx = ceil(nim->nx * 0.5); int ny = ceil(nim->ny * 0.5); int nz = ceil(nim->nz * 0.5); if ((nx == nim->nx) && (ny == nim->ny) && (nz == nim->nz)) return 0; int nvox3D = nx * ny * nz; flt *i32 = (flt *)nim->data; void *dat = (void *)calloc(1, nvox3D * nvol * sizeof(flt)); flt *o32 = (flt *)dat; int x_flip = 0; if (!neg_determ(nim)) x_flip = 1; if (offc) { int *wt = _mm_malloc(nvox3D * nvol * sizeof(int), 64); //weight, just for edges for (int i = 0; i < (nvox3D * nvol); i++) { wt[i] = 0; o32[i] = 0.0; } int boost = 0; if ((x_odd) && (x_flip)) boost = 1; size_t i = 0; for (int v = 0; v < indim[4]; v++) { size_t vo = v * nvox3D; //volumes do not get reduced for (int z = 0; z < indim[3]; z++) { size_t zo = vo + ((z / 2) * ny * nx); for (int y = 0; y < indim[2]; y++) { size_t yo = zo + ((y / 2) * nx); for (int x = 0; x < indim[1]; x++) { size_t xo = yo + ((x + boost) / 2); wt[xo]++; o32[xo] += i32[i]; i++; } //x } //y } //z } //vol for (int i = 0; i < (nvox3D * nvol); i++) if (wt[i] > 0) o32[i] /= wt[i]; _mm_free(wt); } else { //if subsamp2offc else subsamp2 int numk = 27; //center voxel and all its neighbors int *kernel = (int *)_mm_malloc((numk * 4) * sizeof(int), 64); //4 values: offset, xpos, ypos, weight int i = 0; for (int z = -1; z <= 1; z++) for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { kernel[i] = x + (y * indim[1]) + (z * indim[1] * indim[2]); kernel[i + numk] = x; //left-right wrap detection kernel[i + numk + numk] = y;//anterior-posterior wrap detection kernel[i + numk + numk + numk] = 8 / (pow(2, sqr(x) + sqr(y) + sqr(z))); //kernel weight i++; } int boost = 0; //if ((xflip == 1) && (odd == 0)) boost = 1; if ((x_flip == 1) && (x_odd == 0)) boost = 1; //printf("boost %d\n", boost); size_t nvox3Din = indim[1] * indim[2] * indim[3]; size_t o = 0; for (int v = 0; v < nvol; v++) { size_t vi = v * nvox3Din; for (int z = 0; z < nz; z++) { int zi = (2 * z * indim[1] * indim[2]); //printf("%zu \n", zi); for (int y = 0; y < ny; y++) { int yy = y + y; //y*2 input y int yi = zi + (yy * indim[1]); for (int x = 0; x < nx; x++) { //int xx = x+x+xflip; //x*2 input x int xx = x + x + boost; //x*2 input x int xi = yi + xx; //flt sum = 0.0; //flt wt = 0.0; double sum = 0.0; double wt = 0.0; for (int k = 0; k < numk; k++) { if ((xi + kernel[k]) < 0) continue; //position would be less than 0 - outside volume, avoid negative values in size_t size_t pos = xi + kernel[k]; //offset if (pos >= nvox3Din) continue; //position outside volume, e.g. slice above top of volume int xin = xx + kernel[k + numk]; if ((xin < 0) || (xin >= indim[1])) continue; //wrap left or right int yin = yy + kernel[k + numk + numk]; if ((yin < 0) || (yin >= indim[2])) continue; //wrap anterior or posterior flt w = kernel[k + numk + numk + numk]; wt += w; sum += i32[vi + pos] * w; } //if (wt > 0.0) //no need to check: every voxel has at least one contributor (itself) o32[o] = sum / wt; //else { // o32[o] = 666.6; o++; } //x } //y } //z } //vol _mm_free(kernel); } //if subsamp2offc else subsamp2 nim->nvox = nvox3D * nvol; nim->nx = nx; nim->ny = ny; nim->nz = nz; nim->dim[1] = nx; nim->dim[2] = ny; nim->dim[3] = nz; nim->dx *= 2; nim->dy *= 2; nim->dz *= 2; nim->pixdim[1] *= 2; nim->pixdim[2] *= 2; nim->pixdim[3] *= 2; //adjust origin mat44 m = xform(nim); vec4 vx = setVec4(0, 0, 0); vec4 pos = nifti_vect44mat44_mul(vx, m); //vx = setVec4(0.5,0.5,0.5); //vx = setVec4(1.0,0.0,0.0); if (offc) { //printf("%d flip odd %d\n", x_flip, x_odd); if ((x_odd) && (x_flip)) vx = setVec4(-0.5, -0.5, -0.5); //subsamp2offc else vx = setVec4(0.5, 0.5, 0.5); //subsamp2offc //if (!xflip) { // vx = setVec4(0.5,0.5,0.5); // printf("y\n"); //} } else { if (x_odd) vx = setVec4(0, 0, 0); //subsamp2 else vx = setVec4(1, 0, 0); //subsamp2 if (!x_flip) vx = setVec4(0, 0, 0); } vec4 pos1 = nifti_vect44mat44_mul(vx, m); vx = setVec4(pos1.v[0] - pos.v[0], pos1.v[1] - pos.v[1], pos1.v[2] - pos.v[2]); m.m[0][3] += vx.v[0]; m.m[1][3] += vx.v[1]; m.m[2][3] += vx.v[2]; //scale spatial transform for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m.m[i][j] *= 2; //apply to both sform and qform in case VTK user for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { nim->sto_xyz.m[i][j] = m.m[i][j]; nim->qto_xyz.m[i][j] = m.m[i][j]; } free(nim->data); nim->data = dat; return 0; } static int nifti_resize(nifti_image *nim, flt zx, flt zy, flt zz, int interp_method) { //see AFNI's 3dresample //better than fslmaths: fslmaths can not resample 4D data // time 3dresample -dxyz 4.8 4.8 4.8 -rmode Linear -prefix afni.nii -input rest.nii // time ./sm rest.nii -subsamp2 out.nii //However, aliasing artifacts // time 3dresample -dxyz 4.8 4.8 4.8 -rmode Linear -prefix afni2.nii -input zoneplate3d_129.nii int invox3D = nim->nx * nim->ny * nim->nz; int nvol = nim->nvox / invox3D; if ((nim->nvox < 1) || (nvol < 1)) return 1; if (nim->datatype != DT_CALC) return 1; int nx = ceil(nim->nx * zx); int ny = ceil(nim->ny * zy); int nz = ceil(nim->nz * zz); if ((nx == nim->nx) && (ny == nim->ny) && (nz == nim->nz)) return 0; int nvox3D = nx * ny * nz; flt *i32 = (flt *)nim->data; void *dat = (void *)calloc(1, nvox3D * nvol * sizeof(flt)); flt *o32 = (flt *)dat; #pragma omp parallel for for (int v = 0; v < nvol; v++) { flt *iv32 = i32 + (v * invox3D); //reduce in X: half the width: 1/2 input file size flt *imgx = _mm_malloc(nx * nim->ny * nim->nz * sizeof(flt), 64); //input values prior to blur if (nx == nim->nx) //no change in x dimension memcpy(imgx, iv32, nx * nim->ny * nim->nz * sizeof(flt)); else { CLIST *contrib = createFilter(nim->nx, nx, interp_method); size_t i = 0; for (size_t y = 0; y < (nim->ny * nim->nz); y++) { for (int x = 0; x < nx; x++) { flt weight = 0.0; for (int j = 0; j < contrib[x].n; j++) weight += iv32[contrib[x].p[j].pixel] * contrib[x].p[j].weight; imgx[i++] = weight; } iv32 += nim->nx; } //for y for (i = 0; i < nx; i++) free(contrib[i].p); free(contrib); } //reduce in Y: half the height: 1/4 input size flt *imgy = _mm_malloc(nx * ny * nim->nz * sizeof(flt), 64); //input values prior to blur if (ny == nim->ny) //no change in y dimension memcpy(imgy, imgx, nx * ny * nim->nz * sizeof(flt)); else { CLIST *contrib = createFilter(nim->ny, ny, interp_method); flt *iny = _mm_malloc(nim->ny * sizeof(flt), 64); //input values prior to resize for (int z = 0; z < nim->nz; z++) { for (int x = 0; x < nx; x++) { int yo = (z * nx * ny) + x; //output int yi = (z * nx * nim->ny) + x; //input for (int j = 0; j < nim->ny; j++) { //iny[j] = imgx[yi+(j*nx)]; iny[j] = imgx[yi]; yi += nx; } for (int y = 0; y < ny; y++) { flt weight = 0.0; for (int j = 0; j < contrib[y].n; j++) weight += iny[contrib[y].p[j].pixel] * contrib[y].p[j].weight; //weight = y; imgy[yo] = weight; yo += nx; } //y } //x } //z _mm_free(iny); for (int i = 0; i < ny; i++) free(contrib[i].p); free(contrib); } _mm_free(imgx); //reduce in Z flt *ov32 = o32 + (v * nvox3D); if (nz == nim->nz) //no change in x dimension memcpy(ov32, imgy, nx * ny * nz * sizeof(flt)); else { CLIST *contrib = createFilter(nim->nz, nz, interp_method); flt *inz = _mm_malloc(nim->nz * sizeof(flt), 64); //input values prior to resize int nxy = nx * ny; for (int y = 0; y < ny; y++) { for (int x = 0; x < nx; x++) { int zo = x + (y * nx); //output offset int zi = x + (y * nx); //input offset for (int j = 0; j < nim->nz; j++) { inz[j] = imgy[zi]; zi += nxy; } for (int z = 0; z < nz; z++) { //for (int j = 0; j < nim->nz; j++) // inz[j] = imgy[zi+(j*nx*ny)]; flt weight = 0.0; for (int j = 0; j < contrib[z].n; j++) weight += inz[contrib[z].p[j].pixel] * contrib[z].p[j].weight; //weight = y; ov32[zo] = weight; zo += nx * ny; } //for z } //for x } //for y _mm_free(inz); for (int i = 0; i < nz; i++) free(contrib[i].p); free(contrib); } _mm_free(imgy); } //for v nim->nvox = nvox3D * nvol; nim->nx = nx; nim->ny = ny; nim->nz = nz; nim->dim[1] = nx; nim->dim[2] = ny; nim->dim[3] = nz; nim->dx /= zx; nim->dy /= zy; nim->dz /= zz; nim->pixdim[1] /= zx; nim->pixdim[2] /= zy; nim->pixdim[3] /= zz; //adjust origin - again, just like fslmaths mat44 m = xform(nim); m.m[0][0] /= zx; m.m[1][0] /= zx; m.m[2][0] /= zx; m.m[0][1] /= zy; m.m[1][1] /= zy; m.m[2][1] /= zy; m.m[0][2] /= zz; m.m[1][2] /= zz; m.m[2][2] /= zz; for (int i = 0; i < 4; i++) //transform BOTH sform and qform (e.g. ANTs/ITK user) for (int j = 0; j < 4; j++) { nim->sto_xyz.m[i][j] = m.m[i][j]; nim->qto_xyz.m[i][j] = m.m[i][j]; } free(nim->data); nim->data = dat; return 0; } static int essentiallyEqual(float a, float b) { if (isnan(a) && isnan(b)) return 1; //surprisingly, with C nan != nan return fabs(a - b) <= ((fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon); } static void nifti_compare(nifti_image *nim, char *fin) { if (nim->nvox < 1) exit(1); if (nim->datatype != DT_CALC) { fprintf(stderr, "nifti_compare: Unsupported datatype %d\n", nim->datatype); exit(1); } nifti_image *nim2 = nifti_image_read2(fin, 1); if (!nim2) { fprintf(stderr, "** failed to read NIfTI image from '%s'\n", fin); exit(2); } if ((nim->nx != nim2->nx) || (nim->ny != nim2->ny) || (nim->nz != nim2->nz)) { fprintf(stderr, "** Attempted to process images of different sizes %" PRId64 "x%" PRId64 "x%" PRId64 "vs %" PRId64 "x%" PRId64 "x%" PRId64 "\n", nim->nx, nim->ny, nim->nz, nim2->nx, nim2->ny, nim2->nz); nifti_image_free(nim2); exit(1); } if (nim->nvox != nim2->nvox) { fprintf(stderr, " Number of volumes differ\n"); nifti_image_free(nim2); exit(1); } if (max_displacement_mm(nim, nim2) > 0.5) { //fslmaths appears to use mm not voxel difference to determine alignment, threshold ~0.5mm fprintf(stderr, "WARNING:: Inconsistent orientations for individual images in pipeline! (%gmm)\n", max_displacement_mm(nim, nim2)); fprintf(stderr, " Will use voxel-based orientation which is probably incorrect - *PLEASE CHECK*!\n"); } in_hdr ihdr = set_input_hdr(nim2); if (nifti_image_change_datatype(nim2, nim->datatype, &ihdr) != 0) { nifti_image_free(nim2); exit(1); } flt *img = (flt *)nim->data; flt *img2 = (flt *)nim2->data; size_t differentVox = nim->nvox; double sum = 0.0; double sum2 = 0.0; double maxDiff = 0.0; size_t nNotNan = 0; size_t nDifferent = 0; for (size_t i = 0; i < nim->nvox; i++) { if (!essentiallyEqual(img[i], img2[i])) { if (fabs(img[i] - img2[i]) > maxDiff) { differentVox = i; maxDiff = fabs(img[i] - img2[i]); } nDifferent++; } if (isnan(img[i]) || isnan(img[i])) continue; nNotNan++; sum += img[i]; sum2 += img2[i]; } if (differentVox >= nim->nvox) { //fprintf(stderr,"Images essentially equal\n"); */ nifti_image_free(nim2); exit(0); } //second pass - one pass correlation is inaccurate or slow nNotNan = MAX(1, nNotNan); flt mn = INFINITY; //do not set to item 1, in case it is nan flt mx = -INFINITY; flt sd = 0.0; flt ave = sum / nNotNan; flt mn2 = INFINITY; flt mx2 = -INFINITY; flt sd2 = 0.0; flt ave2 = sum2 / nNotNan; //for i := 0 to (n - 1) do // sd := sd + sqr(y[i] - mn); //sd := sqrt(sd / (n - 1)); double sumDx = 0.0; for (size_t i = 0; i < nim->nvox; i++) { if (isnan(img[i]) || isnan(img[i])) continue; mn = MIN(mn, img[i]); mx = MAX(mx, img[i]); sd += sqr(img[i] - ave); mn2 = MIN(mn2, img2[i]); mx2 = MAX(mx2, img2[i]); sd2 += sqr(img2[i] - ave2); sumDx += (img[i] - ave) * (img2[i] - ave2); } double r = 0.0; nNotNan = MAX(2, nNotNan); if (nim->nvox < 2) { sd = 0.0; sd2 = 0.0; } else { sd = sqrt(sd / (nNotNan - 1)); //if (sd != 0.0) sd = 1.0/sd; sd2 = sqrt(sd2 / (nNotNan - 1)); //if (sd2 != 0.0) sd2 = 1.0/sd2; if ((sd * sd2) != 0.0) r = sumDx / (sd * sd2 * (nNotNan - 1)); //r = r / (nim->nvox - 1); } r = MIN(r, 1.0); r = MAX(r, -1.0); fprintf(stderr, "Images Differ: Correlation r = %g, identical voxels %d%%\n", r, (int)floor(100.0 * (1.0 - (double)nDifferent / (double)nim->nvox))); if (nNotNan < nim->nvox) { fprintf(stderr, " %" PRId64 " voxels have a NaN in at least one image.\n", nim->nvox - nNotNan); fprintf(stderr, " Descriptives consider voxels that are numeric in both images.\n"); } fprintf(stderr, " Most different voxel %g vs %g (difference %g)\n", img[differentVox], img2[differentVox], maxDiff); int nvox3D = nim->nx * nim->ny * MAX(nim->nz, 1); int nVol = nim->nvox / nvox3D; size_t vx[4]; vx[3] = differentVox / nvox3D; vx[2] = (differentVox / (nim->nx * nim->ny)) % nim->nz; vx[1] = (differentVox / nim->nx) % nim->ny; vx[0] = differentVox % nim->nx; fprintf(stderr, " Most different voxel location %zux%zux%zu volume %zu\n", vx[0], vx[1], vx[2], vx[3]); fprintf(stderr, "Image 1 Descriptives\n"); fprintf(stderr, " Range: %g..%g Mean %g StDev %g\n", mn, mx, ave, sd); fprintf(stderr, "Image 2 Descriptives\n"); fprintf(stderr, " Range: %g..%g Mean %g StDev %g\n", mn2, mx2, ave2, sd2); //V1 comparison - EXIT_SUCCESS if all vectors are parallel (for DWI up vector [1 0 0] has same direction as down [-1 0 0]) if (nVol != 3) { nifti_image_free(nim2); exit(1); } int allParallel = 1; //niimath ft_V1 -compare nt_V1 for (size_t i = 0; i < nvox3D; i++) { //check angle of two vectors... assume unit vectors flt v[3]; //vector, image 1 v[0] = img[i]; v[1] = img[i + nvox3D]; v[2] = img[i + nvox3D + nvox3D]; flt v2[3]; //vector, image 2 v2[0] = img2[i]; v2[1] = img2[i + nvox3D]; v2[2] = img2[i + nvox3D + nvox3D]; flt x[3]; //cross product x[0] = (v[1] * v2[2]) - (v[2] * v2[1]); x[1] = (v[2] * v2[0]) - (v[0] * v2[2]); x[2] = (v[0] * v2[1]) - (v[1] * v2[0]); flt len = sqrt((x[0] * x[0]) + (x[1] * x[1]) + (x[2] * x[2])); if (len > 0.01) { allParallel = 0; //fprintf(stderr,"[%g %g %g] vs [%g %g %g]\n", v[0],v[1], v[2], v2[0], v2[1], v2[2]); break; } } if (allParallel) { fprintf(stderr, "Despite polarity differences, all vectors are parallel.\n"); nifti_image_free(nim2); exit(0); } nifti_image_free(nim2); exit(1); } //nifti_compare() static int nifti_binary_power(nifti_image *nim, double v) { //clone operations from ANTS ImageMath: power //https://manpages.debian.org/jessie/ants/ImageMath.1.en.html if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; flt fv = v; flt *f32 = (flt *)nim->data; for (size_t i = 0; i < nim->nvox; i++) f32[i] = pow(f32[i], v); return 0; } static int nifti_binary(nifti_image *nim, char *fin, enum eOp op) { if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) { fprintf(stderr, "nifti_binary: Unsupported datatype %d\n", nim->datatype); return 1; } nifti_image *nim2 = nifti_image_read2(fin, 1); if (!nim2) { fprintf(stderr, "** failed to read NIfTI image from '%s'\n", fin); return 2; } if ((nim->nx != nim2->nx) || (nim->ny != nim2->ny) || (nim->nz != nim2->nz)) { fprintf(stderr, "** Attempted to process images of different sizes %" PRId64 "x%" PRId64 "x%" PRId64 " vs %" PRId64 "x%" PRId64 "x%" PRId64 "\n", nim->nx, nim->ny, nim->nz, nim2->nx, nim2->ny, nim2->nz); nifti_image_free(nim2); return 1; } if (max_displacement_mm(nim, nim2) > 0.5) { //fslmaths appears to use mm not voxel difference to determine alignment, threshold ~0.5mm fprintf(stderr, "WARNING:: Inconsistent orientations for individual images in pipeline! (%gmm)\n", max_displacement_mm(nim, nim2)); fprintf(stderr, " Will use voxel-based orientation which is probably incorrect - *PLEASE CHECK*!\n"); } in_hdr ihdr = set_input_hdr(nim2); if (nifti_image_change_datatype(nim2, nim->datatype, &ihdr) != 0) { nifti_image_free(nim2); return 1; } flt *imga = (flt *)nim->data; flt *imgb = (flt *)nim2->data; int nvox3D = nim->nx * nim->ny * nim->nz; int nvola = nim->nvox / nvox3D; int nvolb = nim2->nvox / nvox3D; int rem0 = 0; int swap4D = 0; //if 1: input nim was 3D, but nim2 is 4D: output will be 4D if ((nvolb > 1) && (nim->nvox != nim2->nvox) && ((op == uthr) || (op == thr))) { //"niimath 3D -uthr 4D out" only uses 1st volume of 4D, only one volume out nvolb = 1; //fslmaths printf("threshold operation expects 3D mask\n"); //fslmaths makes not modification to image if (op == uthr) //strictly for fslmaths compatibility - makes no sense for (size_t i = 0; i < nim->nvox; i++) imga[i] = 0; nifti_image_free(nim2); return 0; } else if (nim->nvox != nim2->nvox) { //situation where one input is 3D and the other is 4D if ((nvola != 1) && ((nvolb != 1))) { fprintf(stderr, "nifti_binary: both images must have the same number of volumes, or one must have a single volume (%d and %d)\n", nvola, nvolb); nifti_image_free(nim2); return 1; } if (nvola == 1) { imgb = (flt *)nim->data; imga = (flt *)nim2->data; swap4D = 1; nvolb = nim->nvox / nvox3D; nvola = nim2->nvox / nvox3D; } } //make it so imga/novla >= imgb/nvolb for (int v = 0; v < nvola; v++) { // int va = v * nvox3D; //start of volume for image A int vb = (v % nvolb) * nvox3D; //start of volume for image B if (op == add) { for (int i = 0; i < nvox3D; i++) imga[va + i] += imgb[vb + i]; } else if (op == sub) { if (swap4D) { for (int i = 0; i < nvox3D; i++) { imga[va + i] = imgb[vb + i] - imga[va + i]; //printf(">>[%d]/[%d] %g/%g = %g\n",vb+i, va+i, imgb[vb+i], x, imga[va+i]); } } else { for (int i = 0; i < nvox3D; i++) { //printf("[%d]/[%d] %g/%g\n", va+i, vb+i, imga[va+i], imga[vb+i]); imga[va + i] = imga[va + i] - imgb[vb + i]; } } } else if (op == mul) { for (int i = 0; i < nvox3D; i++) imga[va + i] *= imgb[vb + i]; } else if (op == max) { for (int i = 0; i < nvox3D; i++) imga[va + i] = MAX(imga[va + i], imgb[vb + i]); } else if (op == min) { for (int i = 0; i < nvox3D; i++) imga[va + i] = MIN(imga[va + i], imgb[vb + i]); } else if (op == thr) { //thr : use following number to threshold current image (zero anything below the number) for (int i = 0; i < nvox3D; i++) if (imga[va + i] < imgb[vb + i]) imga[va + i] = 0; } else if (op == uthr) { //uthr : use following number to upper-threshold current image (zero anything above the number) for (int i = 0; i < nvox3D; i++) if (imga[va + i] > imgb[vb + i]) imga[va + i] = 0; } else if (op == mas) { if (swap4D) { for (int i = 0; i < nvox3D; i++) { if (imga[va + i] > 0) imga[va + i] = imgb[vb + i]; else imga[va + i] = 0; } } else { for (int i = 0; i < nvox3D; i++) if (imgb[vb + i] <= 0) imga[va + i] = 0; } } else if (op == divX) { if (swap4D) { for (int i = 0; i < nvox3D; i++) { //flt x = imga[va+i]; if (imga[va + i] != 0.0f) imga[va + i] = imgb[vb + i] / imga[va + i]; //printf(">>[%d]/[%d] %g/%g = %g\n",vb+i, va+i, imgb[vb+i], x, imga[va+i]); } } else { for (int i = 0; i < nvox3D; i++) { //printf("[%d]/[%d] %g/%g\n", va+i, vb+i, imga[va+i], imga[vb+i]); if (imgb[vb + i] == 0.0f) imga[va + i] = 0.0f; else imga[va + i] = imga[va + i] / imgb[vb + i]; } } } else if (op == mod) { //afni mod function, divide by zero yields 0 (unlike Matlab, see remtest.m) //fractional remainder: if (swap4D) { for (int i = 0; i < nvox3D; i++) { //printf("!>[%d]/[%d] %g/%g = %g\n",vb+i, va+i, imgb[vb+i], imga[va+i], fmod(trunc(imgb[vb+i]), trunc(imga[va+i])) ); if (imga[va + i] != 0.0f) imga[va + i] = fmod(imgb[vb + i], imga[va + i]); else { rem0 = 1; imga[va + i] = 0; //imgb[vb+i]; } } } else { for (int i = 0; i < nvox3D; i++) { //printf("?>[%d]/[%d] %g/%g = %g : %g\n", va+i, vb+i, imga[va+i], imgb[vb+i], fmod(imga[va+i], imgb[vb+i]), fmod(trunc(imga[va+i]), trunc(imgb[vb+i])) ); if (imgb[vb + i] != 0.0f) //imga[va+i] = round(fmod(imga[va+i], imgb[vb+i])); imga[va + i] = fmod(imga[va + i], imgb[vb + i]); else { rem0 = 1; imga[va + i] = 0; } } } } else if (op == rem) { //fmod _rem //fractional remainder: if (swap4D) { for (int i = 0; i < nvox3D; i++) { //printf("!>[%d]/[%d] %g/%g = %g\n",vb+i, va+i, imgb[vb+i], imga[va+i], fmod(trunc(imgb[vb+i]), trunc(imga[va+i])) ); if (trunc(imga[va + i]) != 0.0f) imga[va + i] = fmod(trunc(imgb[vb + i]), trunc(imga[va + i])); else { rem0 = 1; imga[va + i] = imgb[vb + i]; } } } else { for (int i = 0; i < nvox3D; i++) { //printf("?>[%d]/[%d] %g/%g = %g : %g\n", va+i, vb+i, imga[va+i], imgb[vb+i], fmod(imga[va+i], imgb[vb+i]), fmod(trunc(imga[va+i]), trunc(imgb[vb+i])) ); if (trunc(imgb[vb + i]) != 0.0f) //imga[va+i] = round(fmod(imga[va+i], imgb[vb+i])); imga[va + i] = fmod(trunc(imga[va + i]), trunc(imgb[vb + i])); else rem0 = 1; } } } else { fprintf(stderr, "nifti_binary: unsupported operation %d\n", op); nifti_image_free(nim2); return 1; } } if (swap4D) { //if 1: input nim was 3D, but nim2 is 4D: output will be 4D nim->nvox = nim2->nvox; nim->ndim = nim2->ndim; nim->nt = nim2->nt; nim->nu = nim2->nu; nim->nv = nim2->nv; nim->nw = nim2->nw; for (int i = 4; i < 8; i++) { nim->dim[i] = nim2->dim[i]; nim->pixdim[i] = nim2->pixdim[i]; } nim->dt = nim2->dt; nim->du = nim2->du; nim->dv = nim2->dv; nim->dw = nim2->dw; free(nim->data); nim->data = nim2->data; nim2->data = NULL; } nifti_image_free(nim2); if (rem0) { fprintf(stderr, "Warning -rem image included zeros (fslmaths exception)\n"); return 0; } return 0; } // nifti_binary() struct sortIdx { flt val; int idx; }; static int nifti_roc(nifti_image *nim, double fpThresh, const char *foutfile, const char *fnoise, const char *ftruth) { if (nim->datatype != DT_CALC) return 1; //(nim, thresh, argv[outfile], fnoise, argv[truth]); //fslmaths appears to ignore voxels on edge of image, and will crash with small images: // error: sort(): given object has non-finite elements //therefore, there is a margin ("border") around the volume int border = 5; //in voxels int mindim = border + border + 1; //e.g. minimum size has one voxel surrounded by border on each side if ((nim->nx < mindim) || (nim->ny < mindim) || (nim->nz < mindim)) { fprintf(stderr, "volume too small for ROC analyses\n"); return 1; } if (nim->nvox > (nim->nx * nim->ny * nim->nz)) { fprintf(stderr, "ROC input should be 3D image (not 4D)\n"); //fslmaths seg faults return 1; } if ((fpThresh <= 0.0) || (fpThresh >= 1.0)) { fprintf(stderr, "ROC false-positive threshold should be between 0 and 1, not '%g'\n", fpThresh); return 1; } nifti_image *nimTrue = nifti_image_read2(ftruth, 1); if (!nimTrue) { fprintf(stderr, "** failed to read NIfTI image from '%s'\n", ftruth); exit(2); } if ((nim->nx != nimTrue->nx) || (nim->ny != nimTrue->ny) || (nim->nz != nimTrue->nz)) { fprintf(stderr, "** Truth image is the wrong size %" PRId64 "x%" PRId64 "x%" PRId64 " vs %" PRId64 "x%" PRId64 "x%" PRId64 "\n", nim->nx, nim->ny, nim->nz, nimTrue->nx, nimTrue->ny, nimTrue->nz); nifti_image_free(nimTrue); exit(1); } if (nimTrue->nvox > (nimTrue->nx * nimTrue->ny * nimTrue->nz)) { fprintf(stderr, "ROC truth should be 3D image (not 4D)\n"); //fslmaths seg faults return 1; } nifti_image *nimNoise = NULL; //count number of tests //If the truth image contains negative voxels these get excluded from all calculations int nTest = 0; int nTrue = 0; size_t i = 0; flt *imgTrue = (flt *)nimTrue->data; flt *imgObs = (flt *)nim->data; for (int z = 0; z < nim->nz; z++) for (int y = 0; y < nim->ny; y++) for (int x = 0; x < nim->nx; x++) { if ((imgTrue[i] >= 0) && (x >= border) && (y >= border) && (z >= border) && (x < (nim->nx - border)) && (y < (nim->ny - border)) && (z < (nim->nz - border))) { nTest++; if (imgTrue[i] > 0) nTrue++; } i++; } if (nTest < 1) { fprintf(stderr, "** All truth voxels inside border are negative\n"); exit(1); } //printf("%d %d = %d\n", nTrue, nFalse, nTest); if (nTest == nTrue) fprintf(stderr, "Warning: All truth voxels inside border are the same (all true or all false)\n"); struct sortIdx *k = (struct sortIdx *)_mm_malloc(nTest * sizeof(struct sortIdx), 64); //load the data nTest = 0; i = 0; for (int z = 0; z < nim->nz; z++) for (int y = 0; y < nim->ny; y++) for (int x = 0; x < nim->nx; x++) { if ((imgTrue[i] >= 0) && (x >= border) && (y >= border) && (z >= border) && (x < (nim->nx - border)) && (y < (nim->ny - border)) && (z < (nim->nz - border))) { k[nTest].val = imgObs[i]; k[nTest].idx = imgTrue[i] > 0; nTest++; } i++; } qsort(k, nTest, sizeof(struct sortIdx), compare); //for (int v = 0; v < nvol; v++ ) // f32[ k[v].idx ] = v + 1; //printf("%d tests, intensity range %g..%g\n", nTest, k[0].val, k[nTest-1].val); FILE *txt = fopen(foutfile, "w+"); flt threshold = k[nTest - 1].val; //maximum observed intensity int bins = 1000; //step size: how often are results reported flt step = (threshold - k[0].val) / bins; //[max-min]/bins int fp = 0; int tp = 0; if (fnoise != NULL) { nimNoise = nifti_image_read2(fnoise, 1); if ((nim->nx != nimNoise->nx) || (nim->ny != nimNoise->ny) || (nim->nz != nimNoise->nz)) { fprintf(stderr, "** Noise image is the wrong size %" PRId64 "x%" PRId64 "x%" PRId64 " vs %" PRId64 "x%" PRId64 "x%" PRId64 "\n", nim->nx, nim->ny, nim->nz, nimNoise->nx, nimNoise->ny, nimNoise->nz); nifti_image_free(nimTrue); nifti_image_free(nimNoise); exit(1); } //Matlab script roc.m generates samples you can process with fslmaths.\ // The fslmaths text file includes two additional columns of output not described by the help documentation // Appears to find maximum signal in each noise volume, regardless of whether it is a hit or false alarm. int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nimNoise->nvox / nvox3D; if (nvol < 10) fprintf(stderr, "Warning: Noise images should include many volumes for estimating familywise error/\n"); flt *imgNoise = (flt *)nimNoise->data; flt *mxVox = (flt *)_mm_malloc(nvol * sizeof(flt), 64); for (int v = 0; v < nvol; v++) { //for each volume mxVox[v] = -INFINITY; size_t vo = v * nvox3D; size_t vi = 0; for (int z = 0; z < nim->nz; z++) for (int y = 0; y < nim->ny; y++) for (int x = 0; x < nim->nx; x++) { if ((imgTrue[vi] >= 0) && (x >= border) && (y >= border) && (z >= border) && (x < (nim->nx - border)) && (y < (nim->ny - border)) && (z < (nim->nz - border))) mxVox[v] = MAX(mxVox[v], imgNoise[vo + vi]); vi++; } } //for each volume nifti_image_free(nimNoise); qsort(mxVox, nvol, sizeof(flt), compare); int idx = nTest - 1; flt mxNoise = mxVox[nvol - 1]; while ((idx >= 1) && (k[idx].val > mxNoise)) { tp++; idx--; if ((k[idx].val != k[idx - 1].val) && (k[idx].val <= threshold)) { fprintf(txt, "%g %g %g\n", (double)fp / (double)nvol, (double)tp / (double)nTrue, threshold); threshold = threshold - step; //delay next report } } //more significant than any noise... int fpThreshInt = round(fpThresh * nvol); //stop when number of false positives exceed this for (int i = nvol - 1; i >= 1; i--) { fp++; //false alarm while ((idx >= 1) && (k[idx].val >= mxVox[i])) { tp++; idx--; if ((k[idx].val != k[idx - 1].val) && (k[idx].val <= threshold)) { fprintf(txt, "%g %g %g\n", (double)fp / (double)nvol, (double)tp / (double)nTrue, threshold); threshold = threshold - step; //delay next report } } //at least as significant as current noise if ((fp > fpThreshInt) || ((k[i].val != k[i - 1].val) && (k[i].val <= threshold))) { //printf("%g %g %g\n", (double)fp/(double)nFalse, (double)tp/(double)nTrue, threshold); fprintf(txt, "%g %g %g\n", (double)fp / (double)nvol, (double)tp / (double)nTrue, threshold); threshold = threshold - step; //delay next report } if (fp > fpThreshInt) break; } //inspect all tests... _mm_free(mxVox); exit(1); } else { //if noise image else infer FP/TP from input image int nFalse = nTest - nTrue; int fpThreshInt = ceil(fpThresh * nFalse); //stop when number of false positives exceed this for (int i = nTest - 1; i >= 1; i--) { if (k[i].idx == 0) fp++; //false alarm else tp++; //hit if ((fp > fpThreshInt) || ((k[i].val != k[i - 1].val) && (k[i].val <= threshold))) { //printf("%g %g %g\n", (double)fp/(double)nFalse, (double)tp/(double)nTrue, threshold); fprintf(txt, "%g %g %g\n", (double)fp / (double)nFalse, (double)tp / (double)nTrue, threshold); threshold = threshold - step; //delay next report } if (fp > fpThreshInt) break; } //inspect all tests... } //if noise else... fclose(txt); _mm_free(k); nifti_image_free(nimTrue); return 0; } static int nifti_fillh(nifti_image *nim, int is26) { if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) return 1; int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nim->nvox / nvox3D; //size_t nxy = nim->nx * nim->ny; //slice increment uint8_t *vx = (uint8_t *)_mm_malloc(nim->nvox * sizeof(uint8_t), 64); memset(vx, 0, nim->nvox * sizeof(uint8_t)); size_t n1 = 0; flt *f32 = (flt *)nim->data; for (size_t i = 0; i < nim->nvox; i++) if (f32[i] > 0.0) { n1++; vx[i] = 1; } if ((n1 < 1) || (nim->nx < 3) || (nim->ny < 3) || (nim->nz < 3)) { //if fewer than 3 rows, columns or slices all voxels touch edge. //only a binary threshold, not a flood fill for (size_t i = 0; i < nim->nvox; i++) f32[i] = vx[i]; _mm_free(vx); return 1; } //set up kernel to search for neighbors. Since we already included sides, we do not worry about A<->P and L<->R wrap int numk = 6; if (is26) numk = 26; int32_t *k = (int32_t *)_mm_malloc(numk * sizeof(int32_t), 64); //queue with untested seed if (is26) { int j = 0; for (int z = -1; z <= 1; z++) for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) { k[j] = x + (y * nim->nx) + (z * nim->nx * nim->ny); j++; } //for x } else { //if 26 neighbors else 6.. k[0] = nim->nx * nim->ny; //up k[1] = -k[0]; //down k[2] = nim->nx; //anterior k[3] = -k[2]; //posterior k[4] = 1; //left k[5] = -1; } //https://en.wikipedia.org/wiki/Flood_fill #pragma omp parallel for for (int v = 0; v < nvol; v++) { uint8_t *vxv = vx; vxv += (v * nvox3D); uint8_t *vxs = (uint8_t *)_mm_malloc(nim->nvox * sizeof(uint8_t), 64); memcpy(vxs, vxv, nvox3D * sizeof(uint8_t)); //dst, src int32_t *q = (int32_t *)_mm_malloc(nvox3D * sizeof(int32_t), 64); //queue with untested seed int qlo = 0; int qhi = -1; //ints always signed in C! //load edges size_t i = 0; for (int z = 0; z < nim->nz; z++) { int zedge = 0; if ((z == 0) || (z == (nim->nz - 1))) zedge = 1; for (int y = 0; y < nim->ny; y++) { int yedge = 0; if ((y == 0) || (y == (nim->ny - 1))) yedge = 1; for (int x = 0; x < nim->nx; x++) { if ((vxs[i] == 0) && (zedge || yedge || (x == 0) || (x == (nim->nx - 1)))) { //found new seed vxs[i] = 1; //do not find again qhi++; q[qhi] = i; } // new seed i++; } //for x } //y } //z //printf("seeds %d kernel %d\n", qhi+1, numk); //run a 'first in, first out' queue while (qhi >= qlo) { //retire one seed, add 0..6 new ones (fillh) or 0..26 new ones (fillh26) for (int j = 0; j < numk; j++) { int jj = q[qlo] + k[j]; if ((jj < 0) || (jj >= nvox3D)) continue; if (vxs[jj] != 0) continue; //add new seed; vxs[jj] = 1; qhi++; q[qhi] = jj; } qlo++; } //while qhi >= qlo: continue until all seeds tested for (size_t i = 0; i < nvox3D; i++) if (vxs[i] == 0) vxv[i] = 1; //hidden internal voxel not found from the fill _mm_free(vxs); _mm_free(q); } //for each volume for (size_t i = 0; i < nim->nvox; i++) f32[i] = vx[i]; _mm_free(vx); _mm_free(k); return 0; } static void rand_test() { //https://www.phoronix.com/scan.php?page=news_item&px=Linux-RdRand-Sanity-Check int r0 = rand(); for (int i = 0; i < 7; i++) if (rand() != r0) return; fprintf(stderr, "RDRAND gives funky output: update firmware\n"); } static int nifti_unary(nifti_image *nim, enum eOp op) { if (nim->nvox < 1) return 1; if (nim->datatype != DT_CALC) { fprintf(stderr, "nifti_unary: Unsupported datatype %d\n", nim->datatype); return 1; } flt *f32 = (flt *)nim->data; if (op == exp1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = exp(f32[i]); } else if (op == log1) { for (size_t i = 0; i < nim->nvox; i++) { if (f32[i] <= 0.0) f32[i] = 0.0; else f32[i] = log(f32[i]); } } else if (op == floor1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = floor(f32[i]); } else if (op == round1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = round(f32[i]); } else if (op == ceil1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = ceil(f32[i]); } else if (op == trunc1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = trunc(f32[i]); } else if (op == sin1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = sin(f32[i]); } else if (op == cos1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = cos(f32[i]); } else if (op == tan1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = tan(f32[i]); } else if (op == asin1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = asin(f32[i]); } else if (op == acos1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = acos(f32[i]); } else if (op == atan1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = atan(f32[i]); } else if (op == sqr1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = f32[i] * f32[i]; //<- pow(a,x) uses flt for x } else if (op == sqrt1) { nifti_sqrt(f32, nim->nvox); } else if (op == recip1) { //https://stackoverflow.com/questions/10606483/sse-reciprocal-if-not-zero for (size_t i = 0; i < nim->nvox; i++) { if (f32[i] == 0.0f) continue; f32[i] = 1.0 / f32[i]; } } else if (op == abs1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = fabs(f32[i]); } else if (op == bin1) { for (size_t i = 0; i < nim->nvox; i++) { if (f32[i] > 0) f32[i] = 1.0f; else f32[i] = 0.0f; } } else if (op == binv1) { for (size_t i = 0; i < nim->nvox; i++) { if (f32[i] > 0) f32[i] = 0.0f; else f32[i] = 1.0f; } } else if (op == edge1) { if ((nim->dx == 0.0) || (nim->dy == 0.0) || (nim->dz == 0.0)) { fprintf(stderr, "edge requires non-zero pixdim1/pixdim2/pixdim3\n"); return 1; } flt xscl = 1.0 / (sqr(nim->dx)); flt yscl = 1.0 / (sqr(nim->dy)); flt zscl = 1.0 / (sqr(nim->dz)); flt xyzscl = 1.0 / (2.0 * sqrt(xscl + yscl + zscl)); if (nim->dim[3] < 2) { //no slices 'above' or 'below' for 2D size_t nxy = nim->nx * nim->ny; //slice increment int nvol = nim->nvox / nxy; if ((nvol * nxy) != nim->nvox) return 1; #pragma omp parallel for for (int v = 0; v < nvol; v++) { //find maximum for each entire volume (excepted observed volume 0) flt *inp = (flt *)_mm_malloc(nxy * sizeof(flt), 64); flt *o32 = (flt *)f32; o32 += v * nxy; memcpy(inp, o32, nxy * sizeof(flt)); //dst, src for (int y = 1; (y < (nim->ny - 1)); y++) { size_t yo = y * nim->nx; for (int x = 1; (x < (nim->nx - 1)); x++) { size_t vx = yo + x; flt xv = sqr(inp[vx + 1] - inp[vx - 1]) * xscl; flt yv = sqr(inp[vx + nim->nx] - inp[vx - nim->nx]) * yscl; o32[vx] = sqrt(xv + yv) * xyzscl; } //x } //y _mm_free(inp); } //for v return 1; } //edge for 2D volume(s) int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; size_t nxy = nim->nx * nim->ny; //slice increment #pragma omp parallel for for (int v = 0; v < nvol; v++) { //find maximum for each entire volume (excepted observed volume 0) flt *inp = (flt *)_mm_malloc(nvox3D * sizeof(flt), 64); flt *o32 = (flt *)f32; o32 += v * nvox3D; memcpy(inp, o32, nvox3D * sizeof(flt)); //dst, src for (int z = 1; (z < (nim->nz - 1)); z++) { size_t zo = z * nxy; for (int y = 1; (y < (nim->ny - 1)); y++) { size_t yo = y * nim->nx; for (int x = 1; (x < (nim->nx - 1)); x++) { size_t vx = zo + yo + x; flt xv = sqr(inp[vx + 1] - inp[vx - 1]) * xscl; flt yv = sqr(inp[vx + nim->nx] - inp[vx - nim->nx]) * yscl; flt zv = sqr(inp[vx + nxy] - inp[vx - nxy]) * zscl; o32[vx] = sqrt(xv + yv + zv) * xyzscl; } //x } //y } //z _mm_free(inp); } //for v return 1; //edge for 3D volume(s) } else if (op == index1) { //nb FSLmaths flips dim[1] depending on determinant size_t idx = 0; if (!neg_determ(nim)) { //flip x size_t nyzt = nim->nvox / nim->nx; if ((nyzt * nim->nx) != nim->nvox) return 1; for (size_t i = 0; i < nyzt; i++) { size_t row = i * nim->nx; ; int x = nim->nx; while (x > 0) { x--; if (f32[row + x] != 0) f32[row + x] = idx++; } //for each column (x) } //for each row (yzt) } else //don't flip x for (size_t i = 0; i < nim->nvox; i++) if (f32[i] != 0) f32[i] = idx++; } else if (op == nan1) { for (size_t i = 0; i < nim->nvox; i++) if (isnan(f32[i])) f32[i] = 0.0; } else if (op == nanm1) { for (size_t i = 0; i < nim->nvox; i++) if (isnan(f32[i])) f32[i] = 1.0; else f32[i] = 0.0; } else if (op == rand1) { rand_test(); flt scl = (1.0 / RAND_MAX); for (size_t i = 0; i < nim->nvox; i++) f32[i] += rand() * scl; } else if (op == randn1) { rand_test(); //https://en.wikipedia.org/wiki/Box–Muller_transform //for SIMD see https://github.com/miloyip/normaldist-benchmark static const flt sigma = 1.0f; static const flt mu = 0.0; //static const flt epsilon = FLT_EPSILON; static const flt two_pi = 2.0 * 3.14159265358979323846; static const flt scl = (1.0 / RAND_MAX); //fill pairs for (size_t i = 0; i < (nim->nvox - 1); i += 2) { flt u1, u2; do { u1 = rand() * scl; u2 = rand() * scl; } while (u1 <= epsilon); flt su1 = sqrt(-2.0 * log(u1)); flt z0 = su1 * cos(two_pi * u2); flt z1 = su1 * sin(two_pi * u2); f32[i] += z0 * sigma + mu; f32[i + 1] += z1 * sigma + mu; } //if odd, fill final voxel if (nim->nvox % 2 != 0) { flt u1, u2; do { u1 = rand() * scl; u2 = rand() * scl; } while (u1 <= epsilon); flt z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2); f32[nim->nvox - 1] += z0 * sigma + mu; } } else if (op == range1) { flt mn = f32[0]; flt mx = mn; for (size_t i = 0; i < nim->nvox; i++) { mn = fmin(f32[i], mn); mx = fmax(f32[i], mx); } nim->cal_min = mn; nim->cal_max = mx; } else if (op == rank1) { int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol <= 1) { //you are always first if you are the only one to show up... for (size_t i = 0; i < nim->nvox; i++) f32[i] = 1; } else { #pragma omp parallel for for (int i = 0; i < nvox3D; i++) { //how do we handle ties? struct sortIdx *k = (struct sortIdx *)_mm_malloc(nvol * sizeof(struct sortIdx), 64); size_t j = i; for (int v = 0; v < nvol; v++) { k[v].val = f32[j]; k[v].idx = j; j += nvox3D; } int varies = 0; for (int v = 0; v < nvol; v++) { if (k[v].val != k[0].val) { varies = 1; break; } } if (varies) { qsort(k, nvol, sizeof(struct sortIdx), compare); for (int v = 0; v < nvol; v++) f32[k[v].idx] = v + 1; } else { j = i; for (int v = 0; v < nvol; v++) { f32[j] = v + 1; j += nvox3D; } } _mm_free(k); } //for i } //nvol > 1 } else if ((op == rank1) || (op == ranknorm1)) { int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol <= 1) { //you are always first if you are the only one to show up... for (int i = 0; i < nim->nvox; i++) f32[i] = 0; } else { #pragma omp parallel for for (int i = 0; i < nvox3D; i++) { struct sortIdx *k = (struct sortIdx *)_mm_malloc(nvol * sizeof(struct sortIdx), 64); size_t j = i; double sum = 0.0; for (int v = 0; v < nvol; v++) { k[v].val = f32[j]; sum += k[v].val; k[v].idx = j; j += nvox3D; } double mean = sum / nvol; double sumSqr = 0.0; for (int v = 0; v < nvol; v++) sumSqr += sqr(k[v].val - mean); double stdev = sqrt(sumSqr / (nvol - 1)); qsort(k, nvol, sizeof(struct sortIdx), compare); //strange formula, but replicates fslmaths, consider nvol=3 rank[2,0,1] will be pval [2.5/3, 1.5/3, 0.5/3] for (int v = 0; v < nvol; v++) f32[k[v].idx] = (stdev * -qginv((double)(v + 0.5) / (double)nvol)) + mean; _mm_free(k); } //for i } //nvol > 1 //double qginv( double p ) } else if (op == ztop1) { for (size_t i = 0; i < nim->nvox; i++) f32[i] = qg(f32[i]); } else if (op == ptoz1) { //given p, return x such that Q(x)=p, for 0 < p < 1 // #ifdef DT32 const flt kNaN = NAN; //const flt kNaN = 0.0 / 0.0; for (size_t i = 0; i < nim->nvox; i++) { if ((f32[i] < 0.0) || (f32[i] > 1.0)) f32[i] = kNaN; else f32[i] = qginv(f32[i]); } } else if ((op == pval1) || (op == pval01)) { int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol <= 1) { fprintf(stderr, "permutation tests require 4D datasets.\n"); return 1; } void *dat = (void *)calloc(1, nvox3D * sizeof(flt)); flt *o32 = (flt *)dat; #pragma omp parallel for for (int i = 0; i < nvox3D; i++) { size_t vi = i; flt obs = f32[vi]; //observed value - see if it is extreme relative to permutations int nNotZero = 0; int nGreater = 0; int nEqual = 0; //observation in first volume flt f32v0 = f32[vi]; for (int v = 0; v < nvol; v++) { if (f32[vi] != 0) nNotZero++; if (f32[vi] == f32v0) nEqual++; if (f32[vi] >= obs) nGreater++; vi += nvox3D; } if (op == pval1) { //if (nEqual == nvol) // o32[i] = 0.0; //else o32[i] = (double)nGreater / (double)nvol; } else { if (nEqual == nvol) o32[i] = 0.0; else if (obs == 0) o32[i] = 1.0; else //nZero must be at least 1: the observed data is not zero o32[i] = (double)nGreater / (double)(nNotZero); } } //for i nim->nvox = nvox3D; nim->ndim = 3; nim->nt = 1; nim->dim[0] = 3; nim->dim[4] = 1; free(nim->data); nim->data = dat; } else if (op == cpval1) { int nvox3D = nim->dim[1] * nim->dim[2] * nim->dim[3]; int nvol = nim->nvox / nvox3D; if ((nvox3D * nvol) != nim->nvox) return 1; if (nvol <= 1) { fprintf(stderr, "permutation tests require 4D datasets.\n"); return 1; } void *dat = (void *)calloc(1, nvox3D * sizeof(flt)); flt *o32 = (flt *)dat; flt *vmax = (flt *)_mm_malloc(nvol * sizeof(flt), 64); #pragma omp parallel for for (int v = 1; v < nvol; v++) { //find maximum for each entire volume (excepted observed volume 0) size_t vo = v * nvox3D; flt mx = f32[vo]; for (int i = 0; i < nvox3D; i++) mx = MAX(mx, f32[vo + i]); vmax[v] = mx; //printf("%d %g\n", v, mx); } #pragma omp parallel for for (int i = 0; i < nvox3D; i++) { flt obs = f32[i]; //observed value - see if it is extreme relative to permutations int nGreater = 1; //count observation for (int v = 1; v < nvol; v++) if (vmax[v] >= obs) nGreater++; o32[i] = (double)nGreater / (double)nvol; } //for i _mm_free(vmax); nim->nvox = nvox3D; nim->ndim = 3; nim->nt = 1; nim->dim[0] = 3; nim->dim[4] = 1; free(nim->data); nim->data = dat; } else { fprintf(stderr, "nifti_unary: Unsupported operation\n"); return 1; } return 0; } //nifti_unary() static int nifti_thrp(nifti_image *nim, double v, enum eOp op) { // -thrp: use following percentage (0-100) of ROBUST RANGE to threshold current image (zero anything below the number) // -thrP: use following percentage (0-100) of ROBUST RANGE of non-zero voxels and threshold below // -uthrp : use following percentage (0-100) of ROBUST RANGE to upper-threshold current image (zero anything above the number) // -uthrP : use following percentage (0-100) of ROBUST RANGE of non-zero voxels and threshold above if ((v < 0.0) || (v > 100.0)) { fprintf(stderr, "nifti_thrp: threshold should be between 0..100\n"); return 1; } flt pct2, pct98; int ignoreZeroVoxels = 0; if ((op == thrP) || (op == uthrP)) ignoreZeroVoxels = 1; if (nifti_robust_range(nim, &pct2, &pct98, ignoreZeroVoxels) != 0) return 1; flt thresh = pct2 + ((v / 100.0) * (pct98 - pct2)); int modifyBrightVoxels = 0; flt newIntensity = 0.0; if ((op == clamp) || (op == uclamp)) newIntensity = thresh; if ((op == uthrp) || (op == uthrP) || (op == uclamp)) modifyBrightVoxels = 1; nifti_thr(nim, thresh, modifyBrightVoxels, newIntensity); return 0; } //nifti_thrp() #ifdef DT32 int main32(int argc, char *argv[]) { #else int main64(int argc, char *argv[]) { printf("beta: Using 64-bit calc\n"); #endif char *fin = NULL, *fout = NULL; //fslmaths in.nii out.nii changes datatype to flt, here we retain (similar to earlier versions of fslmaths) //fslmsths in.nii -rem 10 out.nii uses integer modulus not fmod //fslmaths robust range not fully described, this emulation is close //fslmaths ing/inm are listed as "unary" but should be listed as binary if (argc < 3) return show_helpx(); //minimal command has input and output: "niimath in.nii out.nii" int dtCalc = DT_FLOAT32; //data type for calculation int dtOut = DT_FLOAT32; //data type for calculation int ac = 1; // '-dt' sets datatype for calculations if (!strcmp(argv[ac], "-dt")) { if (!strcmp(argv[ac + 1], "double")) { dtCalc = DT_FLOAT64; } else if (strcmp(argv[ac + 1], "float")) { fprintf(stderr, "'-dt' error: only float or double calculations supported\n"); return 1; } ac += 2; if (argc < (ac + 2)) return 1; //insufficient arguments remain } //special case: pass through // no calculation, simple pass through copy, e.g. "niimaths in.nii out.nii.gz" // note fslmaths would save as flt type... but lossless conversion in native format is faster // note here we use nifti_image_read not nifti_image_read2 to preserve cal_min, cal_max if (ac + 2 == argc) { fin = argv[ac]; // no string copy, just pointer assignment ac++; nifti_image *nim = nifti_image_read(fin, 1); fout = argv[ac]; // no string copy, just pointer assignment ac++; if (nifti_set_filenames(nim, fout, 0, 1)) return 1; nifti_save(nim, ""); //nifti_image_write( nim ); nifti_image_free(nim); return 0; } //end pass through // next argument is input file fin = argv[ac]; // no string copy, just pointer assignment ac++; //clock_t startTime = clock(); nifti_image *nim = nifti_image_read2(fin, 1); if (!nim) { fprintf(stderr, "** failed to read NIfTI image from '%s'\n", fin); return 2; } //printf("read time: %ld ms\n", timediff(startTime, clock())); in_hdr ihdr = set_input_hdr(nim); int nkernel = 0; //number of voxels in kernel int *kernel = make_kernel(nim, &nkernel, 3, 3, 3); //check for "-odt" must be last couplet if (!strcmp(argv[argc - 2], "-odt")) { if (!strcmp(argv[argc - 1], "double")) { dtOut = DT_FLOAT64; } else if (!strcmp(argv[argc - 1], "flt")) { dtOut = DT_FLOAT32; } else if (!strcmp(argv[argc - 1], "int")) { dtOut = DT_INT32; } else if (!strcmp(argv[argc - 1], "short")) { dtOut = DT_INT16; } else if (!strcmp(argv[argc - 1], "ushort")) { dtOut = DT_UINT16; } else if (!strcmp(argv[argc - 1], "char")) { dtOut = DT_UINT8; } else if (!strcmp(argv[argc - 1], "input")) { dtOut = nim->datatype; //ihdr.datatype; //! } else { fprintf(stderr, "Error: Unknown datatype '%s' - Possible datatypes are: char short ushort int flt double input\n", argv[argc - 1]); return 2; } argc = argc - 2; } //odt //convert data to calculation type (-dt) if (nifti_image_change_datatype(nim, dtCalc, &ihdr) != 0) return 1; //check output filename, e.g does file exist fout = argv[argc - 1]; // no string copy, just pointer assignment if (nifti_set_filenames(nim, fout, 0, 1)) return 1; argc = argc - 1; #if defined(_OPENMP) const int maxNumThreads = omp_get_max_threads(); const char *key = "AFNI_COMPRESSOR"; char *value; value = getenv(key); //export AFNI_COMPRESSOR=PIGZ char pigzKey[5] = "PIGZ"; if ((value != NULL) && (strstr(value, pigzKey))) { omp_set_num_threads(maxNumThreads); fprintf(stderr, "Using %d threads\n", maxNumThreads); } else { omp_set_num_threads(1); fprintf(stderr, "Single threaded\n"); } #endif //read operations char *end; int ok = 0; while (ac < argc) { enum eOp op = unknown; if (!strcmp(argv[ac], "-add")) op = add; if (!strcmp(argv[ac], "-sub")) op = sub; if (!strcmp(argv[ac], "-mul")) op = mul; if (!strcmp(argv[ac], "-div")) op = divX; if (!strcmp(argv[ac], "-rem")) op = rem; if (!strcmp(argv[ac], "-mod")) op = mod; if (!strcmp(argv[ac], "-mas")) op = mas; if (!strcmp(argv[ac], "-thr")) op = thr; if (!strcmp(argv[ac], "-thrp")) op = thrp; if (!strcmp(argv[ac], "-thrP")) op = thrP; if (!strcmp(argv[ac], "-uthr")) op = uthr; if (!strcmp(argv[ac], "-uthrp")) op = uthrp; if (!strcmp(argv[ac], "-uthrP")) op = uthrP; if (!strcmp(argv[ac], "-clamp")) op = clamp; if (!strcmp(argv[ac], "-uclamp")) op = uclamp; if (!strcmp(argv[ac], "-max")) op = max; if (!strcmp(argv[ac], "-min")) op = min; if (!strcmp(argv[ac], "-max")) op = max; //if ( ! strcmp(argv[ac], "-addtozero") ) op = addtozero; //variation of mas //if ( ! strcmp(argv[ac], "-overadd") ) op = overadd; //variation of mas if (!strcmp(argv[ac], "power")) op = power; if (!strcmp(argv[ac], "-seed")) op = seed; //if ( ! strcmp(argv[ac], "-restart") ) op = restart; //if ( ! strcmp(argv[ac], "-save") ) op = save; if (!strcmp(argv[ac], "-inm")) op = inm; if (!strcmp(argv[ac], "-ing")) op = ing; if (!strcmp(argv[ac], "-s")) op = smth; if (!strcmp(argv[ac], "-exp")) op = exp1; if (!strcmp(argv[ac], "-ceil")) op = ceil1; if (!strcmp(argv[ac], "-round")) op = ceil1; if (!strcmp(argv[ac], "-floor")) op = floor1; if (!strcmp(argv[ac], "-trunc")) op = trunc1; if (!strcmp(argv[ac], "-log")) op = log1; if (!strcmp(argv[ac], "-sin")) op = sin1; if (!strcmp(argv[ac], "-cos")) op = cos1; if (!strcmp(argv[ac], "-tan")) op = tan1; if (!strcmp(argv[ac], "-asin")) op = asin1; if (!strcmp(argv[ac], "-acos")) op = acos1; if (!strcmp(argv[ac], "-atan")) op = atan1; if (!strcmp(argv[ac], "-sqr")) op = sqr1; if (!strcmp(argv[ac], "-sqrt")) op = sqrt1; if (!strcmp(argv[ac], "-recip")) op = recip1; if (!strcmp(argv[ac], "-abs")) op = abs1; if (!strcmp(argv[ac], "-bin")) op = bin1; if (!strcmp(argv[ac], "-binv")) op = binv1; if (!strcmp(argv[ac], "-edge")) op = edge1; if (!strcmp(argv[ac], "-index")) op = index1; if (!strcmp(argv[ac], "-nan")) op = nan1; if (!strcmp(argv[ac], "-nanm")) op = nanm1; if (!strcmp(argv[ac], "-rand")) op = rand1; if (!strcmp(argv[ac], "-randn")) op = randn1; if (!strcmp(argv[ac], "-range")) op = range1; if (!strcmp(argv[ac], "-rank")) op = rank1; if (!strcmp(argv[ac], "-ranknorm")) op = ranknorm1; if (!strcmp(argv[ac], "-ztop")) op = ztop1; if (!strcmp(argv[ac], "-ptoz")) op = ptoz1; if (!strcmp(argv[ac], "-pval")) op = pval1; if (!strcmp(argv[ac], "-pval0")) op = pval01; if (!strcmp(argv[ac], "-cpval")) op = cpval1; //kernel operations if (!strcmp(argv[ac], "-dilM")) op = dilMk; if (!strcmp(argv[ac], "-dilD")) op = dilDk; if (!strcmp(argv[ac], "-dilF")) op = dilFk; if (!strcmp(argv[ac], "-dilall")) op = dilallk; if (!strcmp(argv[ac], "-ero")) op = erok; if (!strcmp(argv[ac], "-eroF")) op = eroFk; if (!strcmp(argv[ac], "-fmedian")) op = fmediank; if (!strcmp(argv[ac], "-fmean")) op = fmeank; if (!strcmp(argv[ac], "-fmeanu")) op = fmeanuk; if (!strcmp(argv[ac], "-p")) { ac++; #if defined(_OPENMP) int nProcessors = atoi(argv[ac]); if (nProcessors < 1) { omp_set_num_threads(maxNumThreads); fprintf(stderr, "Using %d threads\n", maxNumThreads); } else { omp_set_num_threads(nProcessors); printf("Using %d threads\n", nProcessors); } #else fprintf(stderr, "Warning: not compiled for OpenMP: '-p' ignored\n"); #endif } else //All Dimensionality reduction operations names begin with Capital letter, no other commands do! if ((strlen(argv[ac]) > 4) && (argv[ac][0] == '-') && (isupper(argv[ac][1]))) { //isupper int dim = 0; switch (argv[ac][1]) { case 'X': // dim = 1; break; case 'Y': // code to be executed if n = 2; dim = 2; break; case 'Z': // dim = 3; break; case 'T': // code to be executed if n = 2; dim = 4; break; } if (dim == 0) { fprintf(stderr, "Error: unknown dimensionality reduction operation: %s\n", argv[ac]); goto fail; } if (strstr(argv[ac], "mean")) ok = nifti_dim_reduce(nim, Tmean, dim, 0); else if (strstr(argv[ac], "std")) ok = nifti_dim_reduce(nim, Tstd, dim, 0); else if (strstr(argv[ac], "maxn")) ok = nifti_dim_reduce(nim, Tmaxn, dim, 0); //test maxn BEFORE max else if (strstr(argv[ac], "max")) ok = nifti_dim_reduce(nim, Tmax, dim, 0); else if (strstr(argv[ac], "min")) ok = nifti_dim_reduce(nim, Tmin, dim, 0); else if (strstr(argv[ac], "median")) ok = nifti_dim_reduce(nim, Tmedian, dim, 0); else if (strstr(argv[ac], "perc")) { ac++; int pct = atoi(argv[ac]); ok = nifti_dim_reduce(nim, Tperc, dim, pct); } else if (strstr(argv[ac], "ar1")) ok = nifti_dim_reduce(nim, Tar1, dim, 0); else { fprintf(stderr, "Error unknown dimensionality reduction operation: %s\n", argv[ac]); ok = 1; } } else if (!strcmp(argv[ac], "-roi")) { //int , int , int , int , int , int , int , int ) if ((argc - ac) < 8) { fprintf(stderr, "not enough arguments for '-roi'\n"); //start.size for 4 dimensions: user might forget volumes goto fail; } ac++; int xmin = atoi(argv[ac]); ac++; int xsize = atoi(argv[ac]); ac++; int ymin = atoi(argv[ac]); ac++; int ysize = atoi(argv[ac]); ac++; int zmin = atoi(argv[ac]); ac++; int zsize = atoi(argv[ac]); ac++; int tmin = atoi(argv[ac]); ac++; int tsize = atoi(argv[ac]); nifti_roi(nim, xmin, xsize, ymin, ysize, zmin, zsize, tmin, tsize); } else if (!strcmp(argv[ac], "-bptfm")) { ac++; double hp_sigma = strtod(argv[ac], &end); ac++; double lp_sigma = strtod(argv[ac], &end); ok = nifti_bptf(nim, hp_sigma, lp_sigma, 0); } else if (!strcmp(argv[ac], "-bptf")) { ac++; double hp_sigma = strtod(argv[ac], &end); ac++; double lp_sigma = strtod(argv[ac], &end); //ok = nifti_bptf(nim, hp_sigma, lp_sigma); ok = nifti_bptf(nim, hp_sigma, lp_sigma, 1); #ifdef bandpass } else if (!strcmp(argv[ac], "-bandpass")) { // niimath test4D -bandpass 0.08 0.008 0 c ac++; double lp_hz = strtod(argv[ac], &end); ac++; double hp_hz = strtod(argv[ac], &end); ac++; double TRsec = strtod(argv[ac], &end); ok = nifti_bandpass(nim, lp_hz, hp_hz, TRsec); #endif } else if (!strcmp(argv[ac], "-roc")) { //-roc <AROC-thresh> <outfile> [4Dnoiseonly] <truth> //-roc <AROC-thresh> <outfile> [4Dnoiseonly] <truth> ac++; double thresh = strtod(argv[ac], &end); ac++; int outfile = ac; char *fnoise = NULL; if (thresh > 0.0) { ac++; fnoise = argv[ac]; } ac++; int truth = ac; //ok = nifti_bptf(nim, hp_sigma, lp_sigma); ok = nifti_roc(nim, fabs(thresh), argv[outfile], fnoise, argv[truth]); if (ac >= argc) { fprintf(stderr, "Error: no output filename specified!\n"); //e.g. volume size might differ goto fail; } } else if (!strcmp(argv[ac], "-unsharp")) { ac++; double sigma = strtod(argv[ac], &end); ac++; double amount = strtod(argv[ac], &end); nifti_unsharp(nim, sigma, sigma, sigma, amount); } else if (!strcmp(argv[ac], "-otsu")) ok = nifti_otsu(nim, 0); else if (!strcmp(argv[ac], "-otsu0")) ok = nifti_otsu(nim, 1); else if (!strcmp(argv[ac], "-subsamp2")) ok = nifti_subsamp2(nim, 0); else if (!strcmp(argv[ac], "-subsamp2offc")) ok = nifti_subsamp2(nim, 1); else if (!strcmp(argv[ac], "-sobel_binary")) ok = nifti_sobel(nim, 1, 1); else if (!strcmp(argv[ac], "-sobel")) ok = nifti_sobel(nim, 1, 0); else if (!strcmp(argv[ac], "-demean")) ok = nifti_demean(nim); else if (!strcmp(argv[ac], "-detrend")) ok = nifti_detrend_linear(nim); else if (!strcmp(argv[ac], "-resize")) { ac++; double X = strtod(argv[ac], &end); ac++; double Y = strtod(argv[ac], &end); ac++; double Z = strtod(argv[ac], &end); ac++; int interp_method = atoi(argv[ac]); ok = nifti_resize(nim, X, Y, Z, interp_method); } else if (!strcmp(argv[ac], "-crop")) { ac++; int tmin = atoi(argv[ac]); ac++; int tsize = atoi(argv[ac]); ok = nifti_crop(nim, tmin, tsize); } else if (!strcmp(argv[ac], "--compare")) { //--function terminates without saving image ac++; nifti_compare(nim, argv[ac]); //always terminates } else if (!strcmp(argv[ac], "-edt")) ok = nifti_edt(nim); else if (!strcmp(argv[ac], "-fillh")) ok = nifti_fillh(nim, 0); else if (!strcmp(argv[ac], "-fillh26")) ok = nifti_fillh(nim, 1); else if (!strcmp(argv[ac], "-kernel")) { ac++; if (kernel != NULL) _mm_free(kernel); kernel = NULL; if (!strcmp(argv[ac], "3D")) kernel = make_kernel(nim, &nkernel, 3, 3, 3); if (!strcmp(argv[ac], "2D")) kernel = make_kernel(nim, &nkernel, 3, 3, 1); if (!strcmp(argv[ac], "boxv")) { ac++; int vx = atoi(argv[ac]); kernel = make_kernel(nim, &nkernel, vx, vx, vx); } if (!strcmp(argv[ac], "sphere")) { ac++; double mm = strtod(argv[ac], &end); kernel = make_kernel_sphere(nim, &nkernel, mm); } if (!strcmp(argv[ac], "file")) { ac++; kernel = make_kernel_file(nim, &nkernel, argv[ac]); } if (!strcmp(argv[ac], "gauss")) { ac++; double mm = strtod(argv[ac], &end); kernel = make_kernel_gauss(nim, &nkernel, mm); } if (!strcmp(argv[ac], "box")) { //all voxels in a cube of width <size> mm centered on target voxel"); ac++; double mm = strtod(argv[ac], &end); int vx = (2 * floor(mm / nim->dx)) + 1; int vy = (2 * floor(mm / nim->dy)) + 1; int vz = (2 * floor(mm / nim->dz)) + 1; kernel = make_kernel(nim, &nkernel, vx, vy, vz); } if (!strcmp(argv[ac], "boxv3")) { ac++; int vx = atoi(argv[ac]); ac++; int vy = atoi(argv[ac]); ac++; int vz = atoi(argv[ac]); kernel = make_kernel(nim, &nkernel, vx, vy, vz); } if (kernel == NULL) { fprintf(stderr, "Error: '-kernel' option failed.\n"); //e.g. volume size might differ ok = 1; } } else if (!strcmp(argv[ac], "-tensor_2lower")) { ok = nifti_tensor_2(nim, 0); } else if (!strcmp(argv[ac], "-tensor_2upper")) { ok = nifti_tensor_2(nim, 1); } else if (!strcmp(argv[ac], "-tensor_decomp")) { ok = nifti_tensor_decomp(nim, 1); } else if (!strcmp(argv[ac], "-tensor_decomp_lower")) { ok = nifti_tensor_decomp(nim, 0); } else if (!strcmp(argv[ac], "-slicetimer")) { #ifdef slicetimer ok = nifti_slicetimer(nim); #else fprintf(stderr, "Recompile to support slice timer\n"); //e.g. volume size might differ ok = 1; #endif } else if (!strcmp(argv[ac], "-save")) { ac++; char *fout2 = argv[ac]; if (nifti_set_filenames(nim, fout2, 1, 1)) ok = 1; else { nifti_save(nim, ""); //nifti_image_write( nim ); nifti_set_filenames(nim, fout, 1, 1); } } else if (!strcmp(argv[ac], "-restart")) { if (kernel != NULL) fprintf(stderr, "Warning: 'restart' resets the kernel\n"); //e.g. volume size might differ nifti_image_free(nim); if (kernel != NULL) _mm_free(kernel); kernel = make_kernel(nim, &nkernel, 3, 3, 3); ac++; nim = nifti_image_read(argv[ac], 1); if (!nim) ok = 1; //error } else if (!strcmp(argv[ac], "-grid")) { ac++; double v = strtod(argv[ac], &end); ac++; int s = atoi(argv[ac]); ok = nifti_grid(nim, v, s); } else if (!strcmp(argv[ac], "-dog1")) { ac++; double pos = strtod(argv[ac], &end); ac++; double neg = strtod(argv[ac], &end); ok = nifti_dog(nim, pos, neg, 1); } else if (!strcmp(argv[ac], "-dog2")) { ac++; double pos = strtod(argv[ac], &end); ac++; double neg = strtod(argv[ac], &end); ok = nifti_dog(nim, pos, neg, 2); } else if (!strcmp(argv[ac], "-dog")) { ac++; double pos = strtod(argv[ac], &end); ac++; double neg = strtod(argv[ac], &end); ok = nifti_dog(nim, pos, neg, 0); } else if (!strcmp(argv[ac], "-tfce")) { ac++; double H = strtod(argv[ac], &end); ac++; double E = strtod(argv[ac], &end); ac++; int c = atoi(argv[ac]); ok = nifti_tfce(nim, H, E, c); } else if (!strcmp(argv[ac], "-tfceS")) { ac++; double H = strtod(argv[ac], &end); ac++; double E = strtod(argv[ac], &end); ac++; int c = atoi(argv[ac]); ac++; int x = atoi(argv[ac]); ac++; int y = atoi(argv[ac]); ac++; int z = atoi(argv[ac]); ac++; double tfce_thresh = strtod(argv[ac], &end); ok = nifti_tfceS(nim, H, E, c, x, y, z, tfce_thresh); } else if (op == unknown) { fprintf(stderr, "!!Error: unsupported operation '%s'\n", argv[ac]); goto fail; } if ((op >= dilMk) && (op <= fmeanuk)) ok = nifti_kernel(nim, op, kernel, nkernel); if ((op >= exp1) && (op <= ptoz1)) nifti_unary(nim, op); if ((op >= add) && (op < exp1)) { //binary operations ac++; double v = strtod(argv[ac], &end); //if (end == argv[ac]) { if (strlen(argv[ac]) != (end - argv[ac])) { // "4d" will return numeric "4" if ((op == power) || (op == clamp) || (op == uclamp) || (op == thrp) || (op == thrP) || (op == uthrp) || (op == uthrP) || (op == seed)) { fprintf(stderr, "Error: '%s' expects numeric value\n", argv[ac - 1]); goto fail; } else ok = nifti_binary(nim, argv[ac], op); } else { if (op == add) ok = nifti_rescale(nim, 1.0, v); if (op == sub) ok = nifti_rescale(nim, 1.0, -v); if (op == mul) ok = nifti_rescale(nim, v, 0.0); if (op == divX) ok = nifti_rescale(nim, 1.0 / v, 0.0); if (op == mod) ok = nifti_rem(nim, v, 1); if (op == rem) ok = nifti_rem(nim, v, 0); if (op == mas) { fprintf(stderr, "Error: -mas expects image not number\n"); goto fail; } if (op == power) ok = nifti_binary_power(nim, v); if (op == thr) ok = nifti_thr(nim, v, 0, 0.0); if ((op == clamp) || (op == uclamp) || (op == thrp) || (op == thrP) || (op == uthrp) || (op == uthrP)) ok = nifti_thrp(nim, v, op); if (op == uthr) ok = nifti_thr(nim, v, 1, 0.0); if (op == max) ok = nifti_max(nim, v, 0); if (op == min) ok = nifti_max(nim, v, 1); if (op == inm) ok = nifti_inm(nim, v); if (op == ing) ok = nifti_ing(nim, v); if (op == smth) ok = nifti_smooth_gauss(nim, v, v, v, -6.0); if (op == seed) { if ((v > 0) && (v < 1)) v *= RAND_MAX; srand((unsigned)fabs(v)); } } } //binary operations if (ok != 0) goto fail; ac++; } //convert data to output type (-odt) if (nifti_image_change_datatype(nim, dtOut, &ihdr) != 0) return 1; // if we get here, write the output dataset //startTime = clock(); nifti_save(nim, ""); //nifti_image_write( nim ); //printf("write time: %ld ms\n", timediff(startTime, clock())); // and clean up memory nifti_image_free(nim); if (kernel != NULL) _mm_free(kernel); return 0; fail: nifti_image_free(nim); if (kernel != NULL) _mm_free(kernel); return 1; } //main()
opencl_7z_fmt_plug.c
/* * This software is Copyright (c) 2015 magnum * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_sevenzip; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_sevenzip); #else #include <string.h> #include "aes.h" #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "common.h" #include "misc.h" #include "common-opencl.h" #include "options.h" #include "crc32.h" #include "stdint.h" #include "unicode.h" #include "dyna_salt.h" #include "memdbg.h" #define FORMAT_LABEL "7z-opencl" #define FORMAT_NAME "7-Zip" #define FORMAT_TAG "$7z$" #define TAG_LENGTH (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "SHA256 OPENCL AES" #define BENCHMARK_COMMENT " (512K iterations)" #define BENCHMARK_LENGTH 0 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define PLAINTEXT_LENGTH ((55-8)/2) // 23, rar3 uses 22 #define UNICODE_LENGTH (2 * PLAINTEXT_LENGTH) #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define SALT_SIZE sizeof(struct custom_salt*) #define SALT_ALIGN sizeof(struct custom_salt*) typedef struct { uint32_t length; uint16_t v[PLAINTEXT_LENGTH]; } sevenzip_password; typedef struct { uint round; uint8_t key[32]; } sevenzip_hash; typedef struct { uint32_t length; uint32_t iterations; uint8_t salt[16]; } sevenzip_salt; typedef struct { cl_uint total[2]; cl_uint state[8]; cl_uchar buffer[64]; } SHA256_CTX; typedef struct { cl_ulong t; SHA256_CTX ctx; cl_uint len; cl_ushort buffer[PLAINTEXT_LENGTH]; } sevenzip_state; static int *cracked; static int any_cracked; static int new_keys; static struct custom_salt { dyna_salt dsalt; size_t length; /* used in decryption */ size_t unpacksize; /* used in CRC calculation */ int NumCyclesPower; int SaltSize; int ivSize; int type; unsigned char iv[16]; unsigned char salt[16]; unsigned int crc; unsigned char data[1]; } *cur_salt; static struct fmt_tests sevenzip_tests[] = { /* CRC checks passes for these hashes */ {"$7z$0$19$0$1122$8$d1f50227759415890000000000000000$1412385885$112$112$5e5b8b734adf52a64c541a5a5369023d7cccb78bd910c0092535dfb013a5df84ac692c5311d2e7bbdc580f5b867f7b5dd43830f7b4f37e41c7277e228fb92a6dd854a31646ad117654182253706dae0c069d3f4ce46121d52b6f20741a0bb39fc61113ce14d22f9184adafd6b5333fb1", "password"}, {"$7z$0$19$0$1122$8$a264c94f2cd72bec0000000000000000$725883103$112$108$64749c0963e20c74602379ca740165b9511204619859d1914819bc427b7e5f0f8fc67f53a0b53c114f6fcf4542a28e4a9d3914b4bc76baaa616d6a7ec9efc3f051cb330b682691193e6fa48159208329460c3025fb273232b82450645f2c12a9ea38b53a2331a1d0858813c8bf25a831", "openwall"}, /* padding check passes for these hashes */ {"$7z$0$19$0$1122$8$732b59fd26896e410000000000000000$2955316379$192$183$7544a3a7ec3eb99a33d80e57907e28fb8d0e140ec85123cf90740900429136dcc8ba0692b7e356a4d4e30062da546a66b92ec04c64c0e85b22e3c9a823abef0b57e8d7b8564760611442ecceb2ca723033766d9f7c848e5d234ca6c7863a2683f38d4605322320765938049305655f7fb0ad44d8781fec1bf7a2cb3843f269c6aca757e509577b5592b60b8977577c20aef4f990d2cb665de948004f16da9bf5507bf27b60805f16a9fcc4983208297d3affc4455ca44f9947221216f58c337f", "password"}, /* not supported hashes, will require validFolder check */ // {"$7z$0$19$0$1122$8$5fdbec1569ff58060000000000000000$2465353234$112$112$58ba7606aafc7918e3db7f6e0920f410f61f01e9c1533c40850992fee4c5e5215bc6b4ea145313d0ac065b8ec5b47d9fb895bb7f97609be46107d71e219544cfd24b52c2ecd65477f72c466915dcd71b80782b1ac46678ab7f437fd9f7b8e9d9fad54281d252de2a7ae386a65fc69eda", "password"}, #if DEBUG {"$7z$0$19$0$1122$8$94fb9024fdd3e6c40000000000000000$3965424295$112$99$1127828817ff126bc45ff3c5225d9d0c5d00a52094909674e6ed3dc431546d9a672738f2fa07556340d604d2efd2901b9d2ac2c0686c25af9c520c137b16c50c54df8703fd0b0606fa721ad70aafb9c4e3b288ef49864e6034021969b4ce11e3b8e269a92090ccf593c6a0da06262116", ""}, {"$7z$0$19$0$1122$8$6fd059d516d5490f0000000000000000$460747259$112$99$af163eb5532c557efca78fbb448aa04f348cd258c94233e6669f4e5025f220274c244d4f2347a7512571d9b6015a1e1a90e281983b743da957437b33092eddb55a5bc76f3ab6c7dbabb001578d1043285f5fa791fd94dd9779b461e44cbfe869f891007335b766774ccee3813ec8cd57", "&"}, {"$7z$0$19$0$1122$8$6d4a12af68d83bfe0000000000000000$993697592$112$99$7c308faa36b667599ee4418435ab621884c5c115ee3b70be454fe99236422f4f2d5cd9c8fcfbe6b6b0805ee602ce8488a08f7ea14a4f5c0c060fc685bff187720a402b23a5cfe3c9c5a5ae07f91209031b8f9804ac10459e15a0158031f6c58e507401ec6e1e6de8f64d94201159432b", "&'"}, {"$7z$0$19$0$1122$8$7527d758a59181830000000000000000$3917710544$112$99$61a9ca9e835bd0f2dc474b34d5d89bcf8cd1bb071a984ee1dcf224174a60bcee140fcf2fde8927fe4f3f4eb4a2cc39faff73f1898ae25cc92bd02939f4317ebb173bf3b6f01eef183163ddd533ad5c076f87341bd8b86d8460c68fc390aa8df89fc4076bdfd24e157f6c07e105c07612", "&'("}, {"$7z$0$19$0$1122$8$68928bade860a2b80000000000000000$3235890186$112$99$4b685a569c3aed78d217bae9ec64fa06b614df55c1cb0d160563d87efe38813accb38dd7037f86cebc91751c2488769c7398dfefaf491c024f2d640dcb388a56404cd5ac475ba16b5f8206fa45d5923b3a0c8dd0f24460ccee0d93bea03ad58b8a8db502a55ba1775560b3d194f342f7", "&'()"}, {"$7z$0$19$0$1122$8$81931b9ba0b069820000000000000000$3094344848$112$99$fdbb2622143d25b13992b1467ce9edce4e3df8ca07535735b76e8abcb0791e384a1d5547483e19c3bd6e5a0742d29c403cfc8b3a003b285e80b350ea9157600eb91c49b329903de9ec9b17d1c95b0e136b579e165a6e80550464fa99830bfd9ee58fc14516b614ff9f84ec80e6880a36", "&'()*"}, {"$7z$0$19$0$1122$8$ccf696913989510d0000000000000000$1238556212$112$99$647264fbc665e73ecfe3ef7055fef0d91cb86833d6df08b2f7a3c1c89cf7cdaa09a802c8bfb2e5c6b55143a315df74d841b349fc8b43613d0f87cc90325fd56fc17ee08df7ce76cdc9cda61bd4d5632e20af3db16e921c755174f291c0aa6581844def4547380e2dd4a574435d17e1e8", "&'()*+"}, {"$7z$0$19$0$1122$8$d618bd3ec8bafd800000000000000000$1349785$112$99$6514e2e7468e6f0ed63796cfc0588ac2d75f024c4a0fa03778bd252d316d03e48a08ffcc0011725ad4f867e9a9666630dff4f352c59bcbadb94b9d0e2c42d653b80f480005ce868a0b1a075b2e00abd743de0867d69cdc8b56c7f9770537d50e6bb11eb0d2d7d8b6af5dd8ecb50ab553", "&'()*+,"}, {"$7z$0$19$0$1122$8$1c1586d191f190890000000000000000$642253888$112$99$f55cf9ab802b10a83471abe9319711ae79906cd6921365167c389470a3a8a72b0d877379daae2c24ea2258e8586f12d5036aff9ddc8e26861467b0843ffb72e4410c2be76ec111d37f875c81b244ed172f1f4765a220d830a9615787e9d07f8582146556e9c566b64897a47d18a82b36", "&'()*+,-"}, {"$7z$0$19$0$1122$8$0df03cbdbc73e22a0000000000000000$3194757927$112$99$df53e9d8b4e02cf2962ad87912021508a36910c399a7abc4a3a5423fa2184816af7172418eb4763924ec8b099b7ca95abdc6faac9aaa6e181ffa60b7e8bdb2bf576536ca69152e3b6b97302c796bbc9dec78db6ba7a4a58e68f8ee28f27dea26bd4f848dc3a3315e97e1463b5c171ce5", "&'()*+,-."}, {"$7z$0$19$0$1122$8$7785351cf9fe5dfa0000000000000000$1304801610$112$99$7b35280384726da8521fee0786ef43e0aa621394a6f015b65cbd7f1329f43c4543b8a451a0007c03a3ce3f61e639c54ede3e580600b113777822b6d562390d14ed236e5bac3d3af63ae23015148a95e7ccbc9eea653b52c606ca09ec51fd2b0c4cfc2b760fccc1fe0ccdd9ee3fcb8129", "&'()*+,-./"}, {"$7z$0$19$0$1122$8$70eb7f4b821cf5310000000000000000$3381356868$112$99$c26db2cb89df1237f323d92044726d03cfc7ba83115e789243c3b2570ae674d8356a23e004b103638b1ea9fe6ff5db844a1ddcaaed8a71a8d8e343f73868b4acafd34d493345439b0e0be87d2cf52eb4cceaafcff0dfaf9cf25080693ede267460320e1282b869a5f0b6c8789e769640", "&'()*+,-./0"}, {"$7z$0$19$0$1122$8$2ac0f1307794d8e10000000000000000$2871514580$112$99$4783d91fa72c377310654e961120e71ecdd27ec2e67366e83291daefcea03514ca9ecea031fcbd25c0759c1f242219e673cee093ef361664f18dacf85ca0620fd7092477ceeff7c548df0a475ce93278a564fe4ddb4ee2e4695cbe417a792e822204390ca5a530208a8ed51bc01f79e6", "&'()*+,-./01"}, {"$7z$0$19$0$1122$8$5bc4988c71cba8b70000000000000000$2815498089$112$99$0e4368dde66925e2bfac9a450291f8f817beaa891f08c4d2735d20b3147df581e2f3c53abfe2b0971186ac39280eb354ca5989f9043ad0288302d0ac59a3c8fa99d26c9619b81d22996f24eec1dba361afdd5e50060c2599a40a00c83c4ee0bc4ebe6e3126a64a743af95d9b22ee5867", "&'()*+,-./012"}, {"$7z$0$19$0$1122$8$33ab0ad513b7d6910000000000000000$107430285$112$99$f9f1195a4210eadc5b23f046f81c8cfaec3b90d8b6b67893f10bd9bedd0d859d0695bca5ce315cecbc2910dce27e4c1a1416675d841901c8d84846360b1919ebcba91143713c6b755758d3db64d39344da18222341818220cc43f3ee3a91cbc288f1aafe377b53def310d3b83d32aee3", "&'()*+,-./0123"}, {"$7z$0$19$0$1122$8$dd490a165c1b90f90000000000000000$2897354864$112$99$51efe41b67875503acebe2e199cb542a279520b468a61ba67b54612e317a84e95879a34eaad82124798f32c19f9c0786e8faaac768da5f6b2c91e3ba9f97a03a992c18b5b9b21a5f2b67ae9daeef37ec115f44bfb8b10ac3cb7862b6c024413a2ee801aa674df05e8b56bd8654f279f5", "&'()*+,-./01234"}, {"$7z$0$19$0$1122$8$9077cb191a5969b40000000000000000$3637063426$112$99$1e74746c59bdfe6b3f3d957493c9d5b92ba358f97e19d30e20443cb2fbac0501e07a162344ac7cf7cfa727c70a2bcf52593accc5c2c070c2331863ac76da5ad2f5de374292a87c6af67ab561f9cf71ae472ed1267d481c250f5b4d82d0ec0b2b8531db1fe4637c3f4e3a08de1b9b5418", "&'()*+,-./012345"}, {"$7z$0$19$0$1122$8$adc090d27b0343d30000000000000000$1147570982$112$99$ac14b9dc3751cfe6c1c719ceef3d73946fff2b0f924e06cd3177883df770e5505551bcf5598277801f46584a4f41530f50007c776d2bb91fd160148042275dfe4e420ff72244409f59c687a5bb2d0fc1bb29138689094fe40bb0f22785c63c631cd05abf4f7f3c9b6832e192e103d2f1", "&'()*+,-./0123456"}, {"$7z$0$19$0$1122$8$8dee69dc35517a2a0000000000000000$87427823$112$99$ea36cf8b577a0b5f31115f8550987f05f174b347a8a6433a08c013ecd816c8ecaad163c62db9bae6c57ace3c2a6ce0b36f78ad4723328cc022906400eed55e0e3685a5e8e6b369df780ee72f3d25ccd49d7f40d013052e080723dd4c0b1c75302c884ea956e3b6fd27261eb8c49dea51", "&'()*+,-./01234567"}, {"$7z$0$19$0$1122$8$200ce603d6f355f10000000000000000$3012105149$112$99$0ae42342f52172ad921178a25df3666e34e5a217d0afb3655088806f821d374bf522c197e59b131dbc574d4c936472f59f8892f69e47724ea52ecc5dc7d3ed734c557c9698a6f01519039714c065ad25008003c93cb7f694ee07267d5fcdebab5d149d5404023a0112faec2264d33ff6", "&'()*+,-./012345678"}, {"$7z$0$19$0$1122$8$a5007fc77fa5cc0b0000000000000000$1082728565$112$99$32c404c9633e9c61b76556e169695248008c51ca8f7f0f79c4a271ac6eb1d905a2622132f2f6988f9f3f5e375c592ec63d92d7b183b5801b149595ed440b23a083633de9f1cb5b6ac3238b7523b23141e686e6cbe9d4d3a28fc6489e902c17aeff6cd4cb516bef5cd5c6def78cb88ad4", "&'()*+,-./0123456789"}, {"$7z$0$19$0$1122$8$fd531c4e580be9a60000000000000000$1843420503$112$99$704289830b1add1c8ee6fd622ecf5b8da01988580bdb52f6269cc61c21838849d3a04299eaee15e0cae0eff9f6c3c82f71e434b3aa1c0ca824b90438c1c983130218acd128d9186e5dc2d19a8db602a0382cb60dadb4641b46fe532b799d29a4b882beaa9217f48ddccc99578617f8a0", "&'()*+,-./0123456789:"}, {"$7z$0$19$0$1122$8$7f94a95f71c1b0df0000000000000000$141406606$112$99$1a510a6fda9788b4f4b2274ea929044c00b61b23946bc417ead90ad64dcc9a55378f9ab74f7d693a5dcf455c00f82f6c2a885b664f4ab10c9969026714ce2773030f1c5872ca3948cd612e21b321826c2a561104d57a3ba2055f03aa9cc264821544ec4bccc41f4ac76aab97accb8f9c", "&'()*+,-./0123456789:;"}, {"$7z$0$19$0$1122$8$e24e93c7a9ebde080000000000000000$718561925$112$99$580bf36388526c932c22e3227b51774b6963a9c5b96fc8e2ac70a4302864fa88f50e7c00d9a79e0bca0f07a236e51200dc23435b7680e6fa99b19d790ac093af615a972f8b232686c21279234a2582f9714c5a1a2d326084158eba3e81b4f8ad40784d84baa8ddbed19f1c6603156d2c", "&'()*+,-./0123456789:;<"}, #if PLAINTEXT_LENGTH > 23 {"$7z$0$19$0$1122$8$6fbd519735b131710000000000000000$1248418560$112$99$cc9e3c97073d7fd37f04d4e6983b386e3ac00f6292dedb0f566dccf22cdbbb55fee8669edade383e96aa0a740e2b42aa7fddbe5831cac10828c624ee03a1a256c6e777c3d714c55296cb815c509a252b9426fe8d4566c944efe3fac5ea94910e55a390aef2c729a031e832c406049810", "&'()*+,-./0123456789:;<="}, {"$7z$0$19$0$1122$8$3ce1b899fc03d9c30000000000000000$1452122600$112$99$d4be60d5ab390713c7189f0dd808227c01f15f71fcf4bbccce6cb9238d6418c115eff59784d96ff8944575710a5799c7bcb761e8f1bfb7646a0e8fac3728ba4cca44fb82e5dd9f87bb26828566af64374b512fa094d35af8d743bded88b6257ec98a99b50dd225d4608b283bf035ac08", "&'()*+,-./0123456789:;<=>"}, {"$7z$0$19$0$1122$8$656e2285aabed25b0000000000000000$3885982465$112$99$77f2871e556e7f5278a9e896e91cd386ca8935128957d31fdce0603ea0e71c08b908a4c2d9f2d279757ced848be9482067c9d7935c88e5233aaa94a101d29908f7f015646758029d2078d25d0886bb9f0cdc0dd5136d72e90ceeea678564b199866dd8c9e5fe927102ee2dcf1cd4167f", "&'()*+,-./0123456789:;<=>?"}, {"$7z$0$19$0$1122$8$44ffefa48fa5a5b00000000000000000$1011653568$112$99$5d2504a1eb819218b9ad552e377d37e811ffccb64a554f404d982d209edfafb893b679cc881bbcbc606e67ffa055f712d7f140b554769511bc00321765830ea7c5db810fa2000ae7f4250b74aa61d881db66ae6f30e4c8e71887960c117b268d9934b8b5d52d4abdcb42b0e4ff40b805", "&'()*+,-./0123456789:;<=>?@"}, {"$7z$0$19$0$1122$8$b6e089dd0c52b6b80000000000000000$1229766981$112$99$49a8334d64d9cc7d710fe3b9c35f5d7cb0ec44d5db8a90966fbee93f85fdeeeca859c55519addb20c4628c9204dd24d1169b34dc53a2a685440fae7ed6748c172a8e9dcc42c8dffe60196818ad17a6f9314fcfd4d97cab3c18cf279df344e00fd04eaff32f29cbfcdb6832cfb69fe351", "&'()*+,-./0123456789:;<=>?@A"}, #endif /* PLAINTEXT_LENGTH > 23 */ #endif /* DEBUG */ {NULL} }; static sevenzip_password *inbuffer; static sevenzip_hash *outbuffer; static sevenzip_salt currentsalt; static cl_mem mem_in, mem_out, mem_salt; static cl_kernel sevenzip_init, sevenzip_final; #define insize (sizeof(sevenzip_password) * global_work_size) #define outsize (sizeof(sevenzip_hash) * global_work_size) #define statesize (sizeof(sevenzip_state) * global_work_size) #define saltsize (sizeof(sevenzip_salt)) #define cracked_size (sizeof(*cracked) * global_work_size) static struct fmt_main *self; #define HASH_LOOPS 0x4000 #define LOOP_COUNT ((1 << currentsalt.iterations) / HASH_LOOPS) #define STEP 0 #define SEED 16 static int split_events[] = { 2, -1, -1 }; static const char *warn[] = { "xfer: ", ", init: ", ", crypt: ", ", final: ", ", xfer: " }; // This file contains auto-tuning routine(s). It has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { size_t s; s = autotune_get_task_max_work_group_size(FALSE, 0, sevenzip_init); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel)); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, sevenzip_final)); return s; } static void create_clobj(size_t global_work_size, struct fmt_main *self) { cl_int cl_error; inbuffer = (sevenzip_password*) mem_calloc(1, insize); outbuffer = (sevenzip_hash*) mem_alloc(outsize); cracked = mem_calloc(1, cracked_size); // Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, saltsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem salt"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(sevenzip_init, 0, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(sevenzip_final, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(sevenzip_final, 1, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(sevenzip_final, 2, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); } static void release_clobj(void) { if (cracked) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_salt), "Release mem salt"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(cracked); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(sevenzip_init), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(sevenzip_final), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { CRC32_t crc; self = _self; opencl_prepare_dev(gpu_id); CRC32_Init(&crc); if (options.target_enc == UTF_8) self->params.plaintext_length = MIN(125, 3 * PLAINTEXT_LENGTH); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; cl_int cl_error; snprintf(build_opts, sizeof(build_opts), "-DPLAINTEXT_LENGTH=%d -DHASH_LOOPS=%d", PLAINTEXT_LENGTH, HASH_LOOPS); opencl_init("$JOHN/kernels/7z_kernel.cl", gpu_id, build_opts); sevenzip_init = clCreateKernel(program[gpu_id], "sevenzip_init", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); crypt_kernel = clCreateKernel(program[gpu_id], "sevenzip_loop", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); sevenzip_final = clCreateKernel(program[gpu_id], "sevenzip_final", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, HASH_LOOPS, split_events, warn, 2, self, create_clobj, release_clobj, sizeof(sevenzip_state), 0, db); // Auto tune execution from shared/included code. autotune_run(self, 1 << 19, 0, 15000000000ULL); } } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr, *p; int len, NumCyclesPower; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += TAG_LENGTH; if ((p = strtokm(ctcopy, "$")) == NULL) goto err; if (strlen(p) > 1 || '0' != *p) /* p must be "0" */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* NumCyclesPower */ goto err; if (strlen(p) > 2) goto err; if (!isdec(p)) goto err; NumCyclesPower = atoi(p); if (NumCyclesPower > 24 || NumCyclesPower < 1) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* salt length */ goto err; if (!isdec(p)) goto err; len = atoi(p); if (len > 16) /* salt length */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* salt */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* iv length */ goto err; if (strlen(p) > 2) goto err; if (!isdec(p)) goto err; len = atoi(p); if (len > 16) /* iv length */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* iv */ goto err; if (!ishexlc(p)) goto err; if (strlen(p) / 2 > len && strcmp(p+len*2, "0000000000000000")) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* crc */ goto err; if (!isdecu(p)) goto err; if ((p = strtokm(NULL, "$")) == NULL) /* data length */ goto err; if(!isdec(p)) goto err; len = atoi(p); if ((p = strtokm(NULL, "$")) == NULL) /* unpacksize */ goto err; if (!isdec(p)) /* no way to validate, other than atoi() works for it */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* data */ goto err; if (strlen(p) / 2 != len) /* validates data_len atoi() */ goto err; if (!ishexlc(p)) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { struct custom_salt cs; struct custom_salt *psalt; static void *ptr; char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; if (!ptr) ptr = mem_alloc_tiny(sizeof(struct custom_salt*), sizeof(struct custom_salt*)); memset(&cs, 0, sizeof(cs)); ctcopy += TAG_LENGTH; p = strtokm(ctcopy, "$"); cs.type = atoi(p); p = strtokm(NULL, "$"); cs.NumCyclesPower = atoi(p); p = strtokm(NULL, "$"); cs.SaltSize = atoi(p); p = strtokm(NULL, "$"); /* salt */ p = strtokm(NULL, "$"); cs.ivSize = atoi(p); p = strtokm(NULL, "$"); /* iv */ for (i = 0; i < cs.ivSize; i++) cs.iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); /* crc */ cs.crc = atou(p); /* unsigned function */ p = strtokm(NULL, "$"); cs.length = atoll(p); psalt = malloc(sizeof(struct custom_salt) + cs.length - 1); memcpy(psalt, &cs, sizeof(cs)); p = strtokm(NULL, "$"); psalt->unpacksize = atoll(p); p = strtokm(NULL, "$"); /* data */ for (i = 0; i < psalt->length; i++) psalt->data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); psalt->dsalt.salt_cmp_offset = SALT_CMP_OFF(struct custom_salt, length); psalt->dsalt.salt_cmp_size = SALT_CMP_SIZE(struct custom_salt, length, data, psalt->length); psalt->dsalt.salt_alloc_needs_free = 1; memcpy(ptr, &psalt, sizeof(void*)); return ptr; } static void set_salt(void *salt) { cur_salt = *((struct custom_salt **)salt); memcpy((char*)currentsalt.salt, cur_salt->salt, cur_salt->SaltSize); if (currentsalt.iterations != cur_salt->NumCyclesPower) new_keys = 1; currentsalt.length = cur_salt->SaltSize; currentsalt.iterations = cur_salt->NumCyclesPower; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, saltsize, &currentsalt, 0, NULL, NULL), "Transfer salt to gpu"); } static void clear_keys(void) { memset(inbuffer, 0, insize); } static void sevenzip_set_key(char *key, int index) { UTF16 c_key[PLAINTEXT_LENGTH + 1]; int length = strlen(key); /* Convert password to utf-16-le format (--encoding aware) */ length = enc_to_utf16(c_key, PLAINTEXT_LENGTH, (UTF8*)key, length); if (length <= 0) length = strlen16(c_key); length *= 2; inbuffer[index].length = length; memcpy(inbuffer[index].v, c_key, length); new_keys = 1; } static char *get_key(int index) { UTF16 c_key[PLAINTEXT_LENGTH + 1]; int length = inbuffer[index].length; memcpy(c_key, inbuffer[index].v, length); c_key[length / 2] = 0; return (char*)utf16_to_enc(c_key); } static int salt_compare(const void *x, const void *y) { int c; const struct custom_salt *s1 = *((struct custom_salt**)x); const struct custom_salt *s2 = *((struct custom_salt**)y); // we had to make the salt order deterministic, so that intersalt-restore works if (s1->NumCyclesPower != s2->NumCyclesPower) return (s1->NumCyclesPower - s2->NumCyclesPower); c = memcmp(s1->salt, s2->salt, 16); if (c) return c; return memcmp(s1->iv, s2->iv, 16); } // XXX port Python code to C *OR* use code from LZMA SDK static int validFolder(unsigned char *data) { // int numcoders = self._read64Bit(file) return 0; } static int sevenzip_decrypt(unsigned char *derived_key, unsigned char *data) { unsigned char out[cur_salt->length]; AES_KEY akey; unsigned char iv[16]; union { unsigned char crcc[4]; unsigned int crci; } _crc_out; unsigned char *crc_out = _crc_out.crcc; unsigned int ccrc; CRC32_t crc; int i; int nbytes, margin; memcpy(iv, cur_salt->iv, 16); if(AES_set_decrypt_key(derived_key, 256, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n"); } AES_cbc_encrypt(cur_salt->data, out, cur_salt->length, &akey, iv, AES_DECRYPT); /* various verifications tests */ // test 0, padding check, bad hack :-( margin = nbytes = cur_salt->length - cur_salt->unpacksize; i = cur_salt->length - 1; while (nbytes > 0) { if (out[i] != 0) return -1; nbytes--; i--; } if (margin > 7) { // printf("valid padding test ;-)\n"); // print_hex(out, cur_salt->length); return 0; } // test 1, CRC test CRC32_Init(&crc); CRC32_Update(&crc, out, cur_salt->unpacksize); CRC32_Final(crc_out, crc); ccrc = _crc_out.crci; // computed CRC if (ccrc == cur_salt->crc) return 0; // XXX don't be too eager! // XXX test 2, "well-formed folder" test if (validFolder(out)) { printf("validFolder check ;-)\n"); return 0; } return -1; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; //fprintf(stderr, "%s(%d) lws %zu gws %zu\n", __FUNCTION__, count, local_work_size, global_work_size); if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } if (ocl_autotune_running || new_keys) { int i; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); // Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); // Run 1st kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], sevenzip_init, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run init kernel"); // Run loop kernel for (i = 0; i < (ocl_autotune_running ? 1 : LOOP_COUNT); i++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[2]), "Run loop kernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } // Run final kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], sevenzip_final, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[3]), "Run final kernel"); // Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[4]), "Copy result back"); } new_keys = 0; if (!ocl_autotune_running) { #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { /* decrypt and check */ if(sevenzip_decrypt(outbuffer[index].key, cur_salt->data) == 0) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } } return count; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int)(1 << my_salt->NumCyclesPower); } struct fmt_main fmt_opencl_sevenzip = { { 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_NOT_EXACT | FMT_UNICODE | FMT_UTF8 | FMT_DYNA_SALT, { "iteration count", }, { FORMAT_TAG }, sevenzip_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, salt_compare, set_salt, sevenzip_set_key, get_key, clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
GB_binop__band_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__band_int16) // A.*B function (eWiseMult): GB (_AemultB_08__band_int16) // A.*B function (eWiseMult): GB (_AemultB_02__band_int16) // A.*B function (eWiseMult): GB (_AemultB_04__band_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__band_int16) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__band_int16) // C+=b function (dense accum): GB (_Cdense_accumb__band_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_int16) // C=scalar+B GB (_bind1st__band_int16) // C=scalar+B' GB (_bind1st_tran__band_int16) // C=A+scalar GB (_bind2nd__band_int16) // C=A'+scalar GB (_bind2nd_tran__band_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x) & (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BAND || GxB_NO_INT16 || GxB_NO_BAND_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__band_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__band_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__band_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__band_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__band_int16) ( 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__band_int16) ( 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__band_int16) ( 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__band_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__band_int16) ( 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 int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__band_int16) ( 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 ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = 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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB (_bind1st_tran__band_int16) ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB (_bind2nd_tran__band_int16) ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
sample_ordered.c
/* Andre Augusto Giannotti Scota (https://sites.google.com/view/a2gs/) */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> #include "openmp_util.h" int main(int argc, char *argv[]) { /* #pragma omp parallel num_threads(3) */ /* omp_set_num_threads(2); */ dumpEnviroment(); #pragma omp parallel for ordered for(int i = 0; i < 20; ++i){ #pragma omp ordered { if(i % 2 == 0) sleep(2); printf("Thread Id: [%d] - i: [%d]\n",omp_get_thread_num(), i); } } return(0); }
GB_binop__min_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_01__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__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 // B,b type: uint32_t // 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) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ 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 //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__min_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__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, 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 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, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, 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 or 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 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__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_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__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_03__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_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__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
deprecate.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD EEEEE PPPP RRRR EEEEE CCCC AAA TTTTT EEEEE % % D D E P P R R E C A A T E % % D D EEE PPPPP RRRR EEE C AAAAA T EEE % % D D E P R R E C A A T E % % DDDD EEEEE P R R EEEEE CCCC A A T EEEEE % % % % % % MagickCore Deprecated Methods % % % % Software Design % % John Cristy % % October 2002 % % % % % % Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/property.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/fx.h" #include "magick/geometry.h" #include "magick/identify.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/magick.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/morphology.h" #include "magick/paint.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/segment.h" #include "magick/splay-tree.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/utility.h" #if !defined(MAGICKCORE_EXCLUDE_DEPRECATED) /* Global declarations. */ static MonitorHandler monitor_handler = (MonitorHandler) NULL; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e C a c h e V i e w I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCacheViewIndexes() returns the indexes associated with the specified % view. % % Deprecated, replace with: % % GetCacheViewVirtualIndexQueue(cache_view); % % The format of the AcquireCacheViewIndexes method is: % % const IndexPacket *AcquireCacheViewIndexes(const CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % */ MagickExport const IndexPacket *AcquireCacheViewIndexes( const CacheView *cache_view) { return(GetCacheViewVirtualIndexQueue(cache_view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireCacheViewPixels() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % GetCacheViewVirtualPixels(cache_view,x,y,columns,rows,exception); % % The format of the AcquireCacheViewPixels method is: % % const PixelPacket *AcquireCacheViewPixels(const CacheView *cache_view, % const ssize_t x,const ssize_t y,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const PixelPacket *AcquireCacheViewPixels( const CacheView *cache_view,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { return(GetCacheViewVirtualPixels(cache_view,x,y,columns,rows,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireImagePixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in RAM, or in a memory-mapped file. The % returned pointer should *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to access % the black color component or to obtain the colormap indexes (of type % IndexPacket) corresponding to the region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the AcquireImagePixels() and GetAuthenticPixels() methods are not % thread-safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % Deprecated, replace with: % % GetVirtualPixels(image,x,y,columns,rows,exception); % % The format of the AcquireImagePixels() method is: % % const PixelPacket *AcquireImagePixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const PixelPacket *AcquireImagePixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns, const size_t rows,ExceptionInfo *exception) { return(GetVirtualPixels(image,x,y,columns,rows,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireIndexes() returns the black channel or the colormap indexes % associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % Deprecated, replace with: % % GetVirtualIndexQueue(image); % % The format of the AcquireIndexes() method is: % % const IndexPacket *AcquireIndexes(const Image *image) % % A description of each parameter follows: % % o indexes: AcquireIndexes() returns the indexes associated with the last % call to QueueAuthenticPixels() or GetVirtualPixels(). % % o image: the image. % */ MagickExport const IndexPacket *AcquireIndexes(const Image *image) { return(GetVirtualIndexQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireMemory() returns a pointer to a block of memory at least size bytes % suitably aligned for any use. % % The format of the AcquireMemory method is: % % void *AcquireMemory(const size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *AcquireMemory(const size_t size) { void *allocation; assert(size != 0); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); allocation=malloc(size); return(allocation); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e C a c h e V i e w P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneCacheViewPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneCacheViewAuthenticPixel() instead. % % Deprecated, replace with: % % GetOneCacheViewVirtualPixel(cache_view,x,y,pixel,exception); % % The format of the AcquireOneCacheViewPixel method is: % % MagickBooleanType AcquireOneCacheViewPixel(const CacheView *cache_view, % const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y: These values define the offset of the pixel. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AcquireOneCacheViewPixel( const CacheView *cache_view,const ssize_t x,const ssize_t y,PixelPacket *pixel, ExceptionInfo *exception) { return(GetOneCacheViewVirtualPixel(cache_view,x,y,pixel,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e C a c h e V i e w V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneCacheViewVirtualPixel() returns a single pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneCacheViewAuthenticPixel() instead. % % Deprecated, replace with: % % GetOneCacheViewVirtualMethodPixel(cache_view,virtual_pixel_method, % x,y,pixel,exception); % % The format of the AcquireOneCacheViewPixel method is: % % MagickBooleanType AcquireOneCacheViewVirtualPixel( % const CacheView *cache_view, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_view: the cache view. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the offset of the pixel. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AcquireOneCacheViewVirtualPixel( const CacheView *cache_view,const VirtualPixelMethod virtual_pixel_method, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { MagickBooleanType status; status=GetOneCacheViewVirtualMethodPixel(cache_view,virtual_pixel_method, x,y,pixel,exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e M a g i c k P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneMagickPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOnePixel() instead. % % Deprecated, replace with: % % MagickPixelPacket pixel; % GetOneVirtualMagickPixel(image,x,y,&pixel,exception); % % The format of the AcquireOneMagickPixel() method is: % % MagickPixelPacket AcquireOneMagickPixel(const Image image,const ssize_t x, % const ssize_t y,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickPixelPacket AcquireOneMagickPixel(const Image *image, const ssize_t x,const ssize_t y,ExceptionInfo *exception) { MagickPixelPacket pixel; (void) GetOneVirtualMagickPixel(image,x,y,&pixel,exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOnePixel() returns a single pixel at the specified (x,y) location. % The image background color is returned if an error occurs. If you plan to % modify the pixel, use GetOnePixel() instead. % % Deprecated, replace with: % % PixelPacket pixel; % GetOneVirtualPixel(image,x,y,&pixel,exception); % % The format of the AcquireOnePixel() method is: % % PixelPacket AcquireOnePixel(const Image image,const ssize_t x, % const ssize_t y,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket AcquireOnePixel(const Image *image,const ssize_t x, const ssize_t y,ExceptionInfo *exception) { PixelPacket pixel; (void) GetOneVirtualPixel(image,x,y,&pixel,exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireOneVirtualPixel() returns a single pixel at the specified (x,y) % location as defined by specified pixel method. The image background color % is returned if an error occurs. If you plan to modify the pixel, use % GetOnePixel() instead. % % Deprecated, replace with: % % PixelPacket pixel; % GetOneVirtualMethodPixel(image,virtual_pixel_method,x,y,&pixel,exception); % % The format of the AcquireOneVirtualPixel() method is: % % PixelPacket AcquireOneVirtualPixel(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,ExceptionInfo exception) % % A description of each parameter follows: % % o virtual_pixel_method: the virtual pixel method. % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket AcquireOneVirtualPixel(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, ExceptionInfo *exception) { PixelPacket pixel; (void) GetOneVirtualMethodPixel(image,virtual_pixel_method,x,y,&pixel, exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixels() returns the pixels associated with the last call to % QueueAuthenticPixels() or GetVirtualPixels(). % % Deprecated, replace with: % % GetVirtualPixelQueue(image); % % The format of the AcquirePixels() method is: % % const PixelPacket *AcquirePixels(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const PixelPacket *AcquirePixels(const Image *image) { return(GetVirtualPixelQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A f f i n i t y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AffinityImage() replaces the colors of an image with the closest color from % a reference image. % % Deprecated, replace with: % % RemapImage(quantize_info,image,affinity_image); % % The format of the AffinityImage method is: % % MagickBooleanType AffinityImage(const QuantizeInfo *quantize_info, % Image *image,const Image *affinity_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o affinity_image: the reference image. % */ MagickExport MagickBooleanType AffinityImage(const QuantizeInfo *quantize_info, Image *image,const Image *affinity_image) { return(RemapImage(quantize_info,image,affinity_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A f f i n i t y I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AffinityImages() replaces the colors of a sequence of images with the % closest color from a reference image. % % Deprecated, replace with: % % RemapImages(quantize_info,images,affinity_image); % % The format of the AffinityImage method is: % % MagickBooleanType AffinityImages(const QuantizeInfo *quantize_info, % Image *images,Image *affinity_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: the image sequence. % % o affinity_image: the reference image. % */ MagickExport MagickBooleanType AffinityImages(const QuantizeInfo *quantize_info, Image *images,const Image *affinity_image) { return(RemapImages(quantize_info,images,affinity_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateImage() returns a pointer to an image structure initialized to % default values. % % Deprecated, replace with: % % AcquireImage(image_info); % % The format of the AllocateImage method is: % % Image *AllocateImage(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % */ MagickExport Image *AllocateImage(const ImageInfo *image_info) { return(AcquireImage(image_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateImageColormap() allocates an image colormap and initializes % it to a linear gray colorspace. If the image already has a colormap, % it is replaced. AllocateImageColormap() returns MagickTrue if successful, % otherwise MagickFalse if there is not enough memory. % % Deprecated, replace with: % % AcquireImageColormap(image,colors); % % The format of the AllocateImageColormap method is: % % MagickBooleanType AllocateImageColormap(Image *image, % const size_t colors) % % A description of each parameter follows: % % o image: the image. % % o colors: the number of colors in the image colormap. % */ MagickExport MagickBooleanType AllocateImageColormap(Image *image, const size_t colors) { return(AcquireImageColormap(image,colors)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateNextImage() initializes the next image in a sequence to % default values. The next member of image points to the newly allocated % image. If there is a memory shortage, next is assigned NULL. % % Deprecated, replace with: % % AcquireNextImage(image_info,image); % % The format of the AllocateNextImage method is: % % void AllocateNextImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: Many of the image default values are set from this % structure. For example, filename, compression, depth, background color, % and others. % % o image: the image. % */ MagickExport void AllocateNextImage(const ImageInfo *image_info,Image *image) { AcquireNextImage(image_info,image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A l l o c a t e S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AllocateString() allocates memory for a string and copies the source string % to that memory location (and returns it). % % The format of the AllocateString method is: % % char *AllocateString(const char *source) % % A description of each parameter follows: % % o source: A character string. % */ MagickExport char *AllocateString(const char *source) { char *destination; size_t length; assert(source != (const char *) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); length=strlen(source)+MaxTextExtent+1; destination=(char *) AcquireQuantumMemory(length,sizeof(*destination)); if (destination == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *destination='\0'; if (source != (char *) NULL) (void) CopyMagickString(destination,source,length); return(destination); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A v e r a g e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AverageImages() takes a set of images and averages them together. Each % image in the set must have the same width and height. AverageImages() % returns a single image with each corresponding pixel component of each % image averaged. On failure, a NULL image is returned and exception % describes the reason for the failure. % % Deprecated, replace with: % % EvaluateImages(images,MeanEvaluateOperator,exception); % % The format of the AverageImages method is: % % Image *AverageImages(Image *images,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 *AverageImages(const Image *images,ExceptionInfo *exception) { return(EvaluateImages(images,MeanEvaluateOperator,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a n n e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Extract a channel from the image. A channel is a particular color component % of each pixel in the image. % % Deprecated, replace with: % % SeparateImageChannel(image,channel); % % The format of the ChannelImage method is: % % unsigned int ChannelImage(Image *image,const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: Identify which channel to extract: RedChannel, GreenChannel, % BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, % or BlackChannel. % */ MagickExport unsigned int ChannelImage(Image *image,const ChannelType channel) { return(SeparateImageChannel(image,channel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a n n e l T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ChannelThresholdImage() changes the value of individual pixels based on % the intensity of each pixel channel. The result is a high-contrast image. % % The format of the ChannelThresholdImage method is: % % unsigned int ChannelThresholdImage(Image *image,const char *level) % % A description of each parameter follows: % % o image: the image. % % o level: define the threshold values. % */ MagickExport unsigned int ChannelThresholdImage(Image *image,const char *level) { MagickPixelPacket threshold; GeometryInfo geometry_info; unsigned int flags, status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (level == (char *) NULL) return(MagickFalse); flags=ParseGeometry(level,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; status=BilevelImageChannel(image,RedChannel,threshold.red); status&=BilevelImageChannel(image,GreenChannel,threshold.green); status&=BilevelImageChannel(image,BlueChannel,threshold.blue); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l i p I m a g e P a t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPathImage() sets the image clip mask based any clipping path information % if it exists. % % Deprecated, replace with: % % ClipImagePath(image,pathname,inside); % % The format of the ClipImage method is: % % MagickBooleanType ClipPathImage(Image *image,const char *pathname, % const MagickBooleanType inside) % % A description of each parameter follows: % % o image: the image. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % */ MagickExport MagickBooleanType ClipPathImage(Image *image,const char *pathname, const MagickBooleanType inside) { return(ClipImagePath(image,pathname,inside)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageAttributes() clones one or more image attributes. % % Deprecated, replace with: % % CloneImageProperties(image,clone_image); % % The format of the CloneImageAttributes method is: % % MagickBooleanType CloneImageAttributes(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageAttributes(Image *image, const Image *clone_image) { return(CloneImageProperties(image,clone_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneMemory() copies size bytes from memory area source to the destination. % Copying between objects that overlap will take place correctly. It returns % destination. % % The format of the CloneMemory method is: % % void *CloneMemory(void *destination,const void *source, % const size_t size) % % A description of each parameter follows: % % o destination: the destination. % % o source: the source. % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *CloneMemory(void *destination,const void *source, const size_t size) { register const unsigned char *p; register unsigned char *q; register ssize_t i; assert(destination != (void *) NULL); assert(source != (const void *) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); p=(const unsigned char *) source; q=(unsigned char *) destination; if ((p <= q) || ((p+size) >= q)) return(CopyMagickMemory(destination,source,size)); /* Overlap, copy backwards. */ p+=size; q+=size; for (i=(ssize_t) (size-1); i >= 0; i--) *--q=(*--p); return(destination); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o s e C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloseCacheView() closes the specified view returned by a previous call to % OpenCacheView(). % % Deprecated, replace with: % % DestroyCacheView(view_info); % % The format of the CloseCacheView method is: % % CacheView *CloseCacheView(CacheView *view_info) % % A description of each parameter follows: % % o view_info: the address of a structure of type CacheView. % */ MagickExport CacheView *CloseCacheView(CacheView *view_info) { return(DestroyCacheView(view_info)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorFloodfill() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. % However, in many cases two colors may differ by a small amount. The % fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now % interpreted as the same color for the purposes of the floodfill. % % The format of the ColorFloodfillImage method is: % % MagickBooleanType ColorFloodfillImage(Image *image, % const DrawInfo *draw_info,const PixelPacket target, % const ssize_t x_offset,const ssize_t y_offset,const PaintMethod method) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o target: the RGB value of the target color. % % o x,y: the starting location of the operation. % % o method: Choose either FloodfillMethod or FillToBorderMethod. % */ #define MaxStacksize (1UL << 15) #define PushSegmentStack(up,left,right,delta) \ { \ if (s >= (segment_stack+MaxStacksize)) \ ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \ else \ { \ if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \ { \ s->x1=(double) (left); \ s->y1=(double) (up); \ s->x2=(double) (right); \ s->y2=(double) (delta); \ s++; \ } \ } \ } MagickExport MagickBooleanType ColorFloodfillImage(Image *image, const DrawInfo *draw_info,const PixelPacket target,const ssize_t x_offset, const ssize_t y_offset,const PaintMethod method) { Image *floodplane_image; MagickBooleanType skip; PixelPacket fill_color; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickSignature); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue, &image->exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); (void) SetImageAlphaChannel(floodplane_image,OpaqueAlphaChannel); /* Set floodfill color. */ segment_stack=(SegmentInfo *) AcquireQuantumMemory(MaxStacksize, sizeof(*segment_stack)); if (segment_stack == (SegmentInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Push initial segment on stack. */ x=x_offset; y=y_offset; start=0; s=segment_stack; PushSegmentStack(y,x,x,1); PushSegmentStack(y+1,x,x,-1); while (s > segment_stack) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetVirtualPixels(image,0,y,(size_t) (x1+1),1,&image->exception); q=GetAuthenticPixels(floodplane_image,0,y,(size_t) (x1+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; p+=x1; q+=x1; for (x=x1; x >= 0; x--) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; p--; q--; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetVirtualPixels(image,x,y,image->columns-x,1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,image->columns-x,1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x < (ssize_t) image->columns; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; p++; q++; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetVirtualPixels(image,x,y,(size_t) (x2-x+1),1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,(size_t) (x2-x+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x <= x2; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) != MagickFalse) break; } else if (IsColorSimilar(image,p,&target) == MagickFalse) break; p++; q++; } } start=x; } while (x <= x2); } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Tile fill color onto floodplane. */ p=GetVirtualPixels(floodplane_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) { (void) GetFillColor(draw_info,x,y,&fill_color); MagickCompositeOver(&fill_color,(MagickRealType) fill_color.opacity,q, (MagickRealType) q->opacity,q); } p++; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } segment_stack=(SegmentInfo *) RelinquishMagickMemory(segment_stack); floodplane_image=DestroyImage(floodplane_image); return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageAttribute() deletes an attribute from the image. % % Deprecated, replace with: % % DeleteImageProperty(image,key); % % The format of the DeleteImageAttribute method is: % % MagickBooleanType DeleteImageAttribute(Image *image,const char *key) % % A description of each parameter follows: % % o image: the image info. % % o key: the image key. % */ MagickExport MagickBooleanType DeleteImageAttribute(Image *image, const char *key) { return(DeleteImageProperty(image,key)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageList() deletes an image at the specified position in the list. % % The format of the DeleteImageList method is: % % unsigned int DeleteImageList(Image *images,const ssize_t offset) % % A description of each parameter follows: % % o images: the image list. % % o offset: the position within the list. % */ MagickExport unsigned int DeleteImageList(Image *images,const ssize_t offset) { register ssize_t i; if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); while (GetPreviousImageInList(images) != (Image *) NULL) images=GetPreviousImageInList(images); for (i=0; i < offset; i++) { if (GetNextImageInList(images) == (Image *) NULL) return(MagickFalse); images=GetNextImageInList(images); } DeleteImageFromList(&images); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteMagickRegistry() deletes an entry in the registry as defined by the id. % It returns MagickTrue if the entry is deleted otherwise MagickFalse if no % entry is found in the registry that matches the id. % % Deprecated, replace with: % % char key[MaxTextExtent]; % FormatLocaleString(key,MaxTextExtent,"%ld\n",id); % DeleteImageRegistry(key); % % The format of the DeleteMagickRegistry method is: % % MagickBooleanType DeleteMagickRegistry(const ssize_t id) % % A description of each parameter follows: % % o id: the registry id. % */ MagickExport MagickBooleanType DeleteMagickRegistry(const ssize_t id) { char key[MaxTextExtent]; (void) FormatLocaleString(key,MaxTextExtent,"%.20g\n",(double) id); return(DeleteImageRegistry(key)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C o n s t i t u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyConstitute() destroys the constitute component. % % The format of the DestroyConstitute method is: % % DestroyConstitute(void) % */ MagickExport void DestroyConstitute(void) { ConstituteComponentTerminus(); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyMagickRegistry() deallocates memory associated the magick registry. % % Deprecated, replace with: % % RegistryComponentTerminus(); % % The format of the DestroyMagickRegistry method is: % % void DestroyMagickRegistry(void) % */ MagickExport void DestroyMagickRegistry(void) { RegistryComponentTerminus(); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s c r i b e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DescribeImage() describes an image by printing its attributes to the file. % Attributes include the image width, height, size, and others. % % Deprecated, replace with: % % IdentifyImage(image,file,verbose); % % The format of the DescribeImage method is: % % MagickBooleanType DescribeImage(Image *image,FILE *file, % const MagickBooleanType verbose) % % A description of each parameter follows: % % o image: the image. % % o file: the file, typically stdout. % % o verbose: A value other than zero prints more detailed information % about the image. % */ MagickExport MagickBooleanType DescribeImage(Image *image,FILE *file, const MagickBooleanType verbose) { return(IdentifyImage(image,file,verbose)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageAttributes() deallocates memory associated with the image % attribute list. % % The format of the DestroyImageAttributes method is: % % DestroyImageAttributes(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageAttributes(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->attributes != (void *) NULL) image->attributes=(void *) DestroySplayTree((SplayTreeInfo *) image->attributes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImages() destroys an image list. % % Deprecated, replace with: % % DestroyImageList(image); % % The format of the DestroyImages method is: % % void DestroyImages(Image *image) % % A description of each parameter follows: % % o image: the image sequence. % */ MagickExport void DestroyImages(Image *image) { if (image == (Image *) NULL) return; if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.4.3"); image=DestroyImageList(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y M a g i c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyMagick() destroys the ImageMagick environment. % % Deprecated, replace with: % % MagickCoreTerminus(); % % The format of the DestroyMagick function is: % % DestroyMagick(void) % */ MagickExport void DestroyMagick(void) { MagickCoreTerminus(); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p a t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DispatchImage() extracts pixel data from an image and returns it to you. % The method returns MagickFalse on success otherwise MagickTrue if an error is % encountered. The data is returned as char, short int, int, ssize_t, float, % or double in the order specified by map. % % Suppose you want to extract the first scanline of a 640x480 image as % character data in red-green-blue order: % % DispatchImage(image,0,0,640,1,"RGB",CharPixel,pixels,exception); % % Deprecated, replace with: % % ExportImagePixels(image,x_offset,y_offset,columns,rows,map,type,pixels, % exception); % % The format of the DispatchImage method is: % % unsigned int DispatchImage(const Image *image,const ssize_t x_offset, % const ssize_t y_offset,const size_t columns, % const size_t rows,const char *map,const StorageType type, % void *pixels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x_offset, y_offset, columns, rows: These values define the perimeter % of a region of pixels you want to extract. % % o map: This string reflects the expected ordering of the pixel array. % It can be any combination or order of R = red, G = green, B = blue, % A = alpha, C = cyan, Y = yellow, M = magenta, K = black, or % I = intensity (for grayscale). % % o type: Define the data type of the pixels. Float and double types are % normalized to [0..1] otherwise [0..QuantumRange]. Choose from these % types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel, or % DoublePixel. % % o pixels: This array of values contain the pixel components as defined by % map and type. You must preallocate this array where the expected % length varies depending on the values of width, height, map, and type. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int DispatchImage(const Image *image,const ssize_t x_offset, const ssize_t y_offset,const size_t columns,const size_t rows, const char *map,const StorageType type,void *pixels,ExceptionInfo *exception) { unsigned int status; if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.6"); status=ExportImagePixels(image,x_offset,y_offset,columns,rows,map,type,pixels, exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x t r a c t S u b i m a g e F r o m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExtractSubimageFromImageImage() extracts a region of the image that most % closely resembles the reference. % % The format of the ExtractSubimageFromImageImage method is: % % Image *ExtractSubimageFromImage(const Image *image, % const Image *reference,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o reference: find an area of the image that closely resembles this image. % % o exception: return any errors or warnings in this structure. % */ static double GetSimilarityMetric(const Image *image,const Image *reference, const ssize_t x_offset,const ssize_t y_offset, const double similarity_threshold,ExceptionInfo *exception) { CacheView *image_view, *reference_view; double channels, normalized_similarity, similarity; ssize_t y; /* Compute the similarity in pixels between two images. */ normalized_similarity=1.0; similarity=0.0; channels=3; if ((image->matte != MagickFalse) && (reference->matte != MagickFalse)) channels++; if ((image->colorspace == CMYKColorspace) && (reference->colorspace == CMYKColorspace)) channels++; image_view=AcquireVirtualCacheView(image,exception); reference_view=AcquireVirtualCacheView(reference,exception); for (y=0; y < (ssize_t) reference->rows; y++) { register const IndexPacket *indexes, *reference_indexes; register const PixelPacket *p, *q; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset+y, reference->columns,1,exception); q=GetCacheViewVirtualPixels(reference_view,0,y,reference->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) continue; indexes=GetCacheViewVirtualIndexQueue(image_view); reference_indexes=GetCacheViewVirtualIndexQueue(reference_view); for (x=0; x < (ssize_t) reference->columns; x++) { MagickRealType pixel; pixel=QuantumScale*(GetPixelRed(p)-(double) GetPixelRed(q)); similarity+=pixel*pixel; pixel=QuantumScale*(GetPixelGreen(p)-(double) GetPixelGreen(q)); similarity+=pixel*pixel; pixel=QuantumScale*(GetPixelBlue(p)-(double) GetPixelBlue(q)); similarity+=pixel*pixel; if ((image->matte != MagickFalse) && (reference->matte != MagickFalse)) { pixel=QuantumScale*(GetPixelOpacity(p)-(double) GetPixelOpacity(q)); similarity+=pixel*pixel; } if ((image->colorspace == CMYKColorspace) && (reference->colorspace == CMYKColorspace)) { pixel=QuantumScale*(GetPixelIndex(indexes+x)-(double) GetPixelIndex(reference_indexes+x)); similarity+=pixel*pixel; } p++; q++; } normalized_similarity=sqrt(similarity)/reference->columns/reference->rows/ channels; if (normalized_similarity > similarity_threshold) break; } reference_view=DestroyCacheView(reference_view); image_view=DestroyCacheView(image_view); return(normalized_similarity); } MagickExport Image *ExtractSubimageFromImage(Image *image, const Image *reference,ExceptionInfo *exception) { double similarity_threshold; RectangleInfo offset; ssize_t y; /* Extract reference from image. */ if ((reference->columns > image->columns) || (reference->rows > image->rows)) return((Image *) NULL); similarity_threshold=(double) image->columns*image->rows; SetGeometry(reference,&offset); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) #endif for (y=0; y < (ssize_t) (image->rows-reference->rows); y++) { double similarity; register ssize_t x; for (x=0; x < (ssize_t) (image->columns-reference->columns); x++) { similarity=GetSimilarityMetric(image,reference,x,y,similarity_threshold, exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ExtractSubimageFromImage) #endif if (similarity < similarity_threshold) { similarity_threshold=similarity; offset.x=x; offset.y=y; } } } if (similarity_threshold > (QuantumScale*reference->fuzz/100.0)) return((Image *) NULL); return(CropImage(image,&offset,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l a t t e n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlattenImages() Obsolete Function: Use MergeImageLayers() instead. % % Deprecated, replace with: % % MergeImageLayers(image,FlattenLayer,exception); % % The format of the FlattenImage method is: % % Image *FlattenImage(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 *FlattenImages(Image *image,ExceptionInfo *exception) { return(MergeImageLayers(image,FlattenLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatImageAttribute() permits formatted key/value pairs to be saved as an % image attribute. % % The format of the FormatImageAttribute method is: % % MagickBooleanType FormatImageAttribute(Image *image,const char *key, % const char *format,...) % % A description of each parameter follows. % % o image: The image. % % o key: The attribute key. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport MagickBooleanType FormatImageAttributeList(Image *image, const char *key,const char *format,va_list operands) { char value[MaxTextExtent]; int n; #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(value,MaxTextExtent,format,operands); #else n=vsprintf(value,format,operands); #endif if (n < 0) value[MaxTextExtent-1]='\0'; return(SetImageProperty(image,key,value)); } MagickExport MagickBooleanType FormatImagePropertyList(Image *image, const char *property,const char *format,va_list operands) { char value[MaxTextExtent]; int n; #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(value,MaxTextExtent,format,operands); #else n=vsprintf(value,format,operands); #endif if (n < 0) value[MaxTextExtent-1]='\0'; return(SetImageProperty(image,property,value)); } MagickExport MagickBooleanType FormatImageAttribute(Image *image, const char *key,const char *format,...) { char value[MaxTextExtent]; int n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(value,MaxTextExtent,format,operands); (void) n; va_end(operands); return(SetImageProperty(image,key,value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t M a g i c k S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatMagickString() prints formatted output of a variable argument list. % % The format of the FormatMagickString method is: % % ssize_t FormatMagickString(char *string,const size_t length, % const char *format,...) % % A description of each parameter follows. % % o string: FormatMagickString() returns the formatted string in this % character buffer. % % o length: the maximum length of the string. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport ssize_t FormatMagickStringList(char *string,const size_t length, const char *format,va_list operands) { int n; #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(string,length,format,operands); #else n=vsprintf(string,format,operands); #endif if (n < 0) string[length-1]='\0'; return((ssize_t) n); } MagickExport ssize_t FormatMagickString(char *string,const size_t length, const char *format,...) { ssize_t n; va_list operands; va_start(operands,format); n=(ssize_t) FormatMagickStringList(string,length,format,operands); va_end(operands); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t S t r i n g % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatString() prints formatted output of a variable argument list. % % The format of the FormatString method is: % % void FormatString(char *string,const char *format,...) % % A description of each parameter follows. % % o string: Method FormatString returns the formatted string in this % character buffer. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport void FormatStringList(char *string,const char *format, va_list operands) { int n; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); #if defined(MAGICKCORE_HAVE_VSNPRINTF) n=vsnprintf(string,MaxTextExtent,format,operands); #else n=vsprintf(string,format,operands); #endif if (n < 0) string[MaxTextExtent-1]='\0'; } MagickExport void FormatString(char *string,const char *format,...) { va_list operands; va_start(operands,format); (void) FormatLocaleStringList(string,MaxTextExtent,format,operands); va_end(operands); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F u z z y C o l o r M a t c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FuzzyColorMatch() returns true if two pixels are identical in color. % % The format of the ColorMatch method is: % % void FuzzyColorMatch(const PixelPacket *p,const PixelPacket *q, % const double fuzz) % % A description of each parameter follows: % % o p: Pixel p. % % o q: Pixel q. % % o distance: Define how much tolerance is acceptable to consider % two colors as the same. % */ MagickExport unsigned int FuzzyColorMatch(const PixelPacket *p, const PixelPacket *q,const double fuzz) { MagickPixelPacket pixel; register MagickRealType distance; if ((fuzz == 0.0) && (GetPixelRed(p) == GetPixelRed(q)) && (GetPixelGreen(p) == GetPixelGreen(q)) && (GetPixelBlue(p) == GetPixelBlue(q))) return(MagickTrue); pixel.red=GetPixelRed(p)-(MagickRealType) GetPixelRed(q); distance=pixel.red*pixel.red; if (distance > (fuzz*fuzz)) return(MagickFalse); pixel.green=GetPixelGreen(p)-(MagickRealType) GetPixelGreen(q); distance+=pixel.green*pixel.green; if (distance > (fuzz*fuzz)) return(MagickFalse); pixel.blue=GetPixelBlue(p)-(MagickRealType) GetPixelBlue(q); distance+=pixel.blue*pixel.blue; if (distance > (fuzz*fuzz)) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F u z z y C o l o r C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FuzzyColorCompare() returns MagickTrue if the distance between two colors is % less than the specified distance in a linear three dimensional color space. % This method is used by ColorFloodFill() and other algorithms which % compare two colors. % % The format of the FuzzyColorCompare method is: % % void FuzzyColorCompare(const Image *image,const PixelPacket *p, % const PixelPacket *q) % % A description of each parameter follows: % % o image: the image. % % o p: Pixel p. % % o q: Pixel q. % */ MagickExport MagickBooleanType FuzzyColorCompare(const Image *image, const PixelPacket *p,const PixelPacket *q) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.5"); return(IsColorSimilar(image,p,q)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F u z z y O p a c i t y C o m p a r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FuzzyOpacityCompare() returns true if the distance between two opacity % values is less than the specified distance in a linear color space. This % method is used by MatteFloodFill() and other algorithms which compare % two opacity values. % % Deprecated, replace with: % % IsOpacitySimilar(image,p,q); % % The format of the FuzzyOpacityCompare method is: % % void FuzzyOpacityCompare(const Image *image,const PixelPacket *p, % const PixelPacket *q) % % A description of each parameter follows: % % o image: the image. % % o p: Pixel p. % % o q: Pixel q. % */ MagickExport MagickBooleanType FuzzyOpacityCompare(const Image *image, const PixelPacket *p,const PixelPacket *q) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.5"); return(IsOpacitySimilar(image,p,q)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C o n f i g u r e B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetConfigureBlob() returns the specified configure file as a blob. % % The format of the GetConfigureBlob method is: % % void *GetConfigureBlob(const char *filename,ExceptionInfo *exception) % % A description of each parameter follows: % % o filename: the configure file name. % % o path: return the full path information of the configure file. % % o length: This pointer to a size_t integer sets the initial length of the % blob. On return, it reflects the actual length of the blob. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetConfigureBlob(const char *filename,char *path, size_t *length,ExceptionInfo *exception) { void *blob; assert(filename != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); assert(path != (char *) NULL); assert(length != (size_t *) NULL); assert(exception != (ExceptionInfo *) NULL); blob=(void *) NULL; (void) CopyMagickString(path,filename,MaxTextExtent); #if defined(MAGICKCORE_INSTALLED_SUPPORT) #if defined(MAGICKCORE_LIBRARY_PATH) if (blob == (void *) NULL) { /* Search hard coded paths. */ (void) FormatLocaleString(path,MaxTextExtent,"%s%s", MAGICKCORE_LIBRARY_PATH,filename); if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); } #endif #if defined(MAGICKCORE_WINDOWS_SUPPORT) && !(defined(MAGICKCORE_CONFIGURE_PATH) || defined(MAGICKCORE_SHARE_PATH)) if (blob == (void *) NULL) { char *key_value; /* Locate file via registry key. */ key_value=NTRegistryKeyLookup("ConfigurePath"); if (key_value != (char *) NULL) { (void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",key_value, DirectorySeparator,filename); if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); } } #endif #else if (blob == (void *) NULL) { char *home; home=GetEnvironmentValue("MAGICK_HOME"); if (home != (char *) NULL) { /* Search MAGICK_HOME. */ #if !defined(MAGICKCORE_POSIX_SUPPORT) (void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",home, DirectorySeparator,filename); #else (void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s",home, MAGICKCORE_LIBRARY_RELATIVE_PATH,filename); #endif if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); home=DestroyString(home); } home=GetEnvironmentValue("HOME"); if (home == (char *) NULL) home=GetEnvironmentValue("USERPROFILE"); if (home != (char *) NULL) { /* Search $HOME/.magick. */ (void) FormatLocaleString(path,MaxTextExtent,"%s%s.magick%s%s",home, DirectorySeparator,DirectorySeparator,filename); if ((IsPathAccessible(path) != MagickFalse) && (blob == (void *) NULL)) blob=FileToBlob(path,~0,length,exception); home=DestroyString(home); } } if ((blob == (void *) NULL) && (*GetClientPath() != '\0')) { #if !defined(MAGICKCORE_POSIX_SUPPORT) (void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",GetClientPath(), DirectorySeparator,filename); #else char prefix[MaxTextExtent]; /* Search based on executable directory if directory is known. */ (void) CopyMagickString(prefix,GetClientPath(), MaxTextExtent); ChopPathComponents(prefix,1); (void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s",prefix, MAGICKCORE_LIBRARY_RELATIVE_PATH,filename); #endif if (IsPathAccessible(path) != MagickFalse) blob=FileToBlob(path,~0,length,exception); } /* Search current directory. */ if ((blob == (void *) NULL) && (IsPathAccessible(path) != MagickFalse)) blob=FileToBlob(path,~0,length,exception); #if defined(MAGICKCORE_WINDOWS_SUPPORT) /* Search Windows registry. */ if (blob == (void *) NULL) blob=NTResourceToBlob(filename); #endif #endif if (blob == (void *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),ConfigureWarning, "UnableToOpenConfigureFile","`%s'",path); return(blob); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCacheView() gets pixels from the in-memory or disk pixel cache as % defined by the geometry parameters. A pointer to the pixels is returned if % the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, % GetCacheViewException(cache_view)); % % The format of the GetCacheView method is: % % PixelPacket *GetCacheView(CacheView *cache_view,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows) % % A description of each parameter follows: % % o cache_view: the address of a structure of type CacheView. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *GetCacheView(CacheView *cache_view,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows) { PixelPacket *pixels; pixels=GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, GetCacheViewException(cache_view)); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C a c h e V i e w I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCacheViewIndexes() returns the indexes associated with the specified % view. % % Deprecated, replace with: % % GetCacheViewAuthenticIndexQueue(cache_view); % % The format of the GetCacheViewIndexes method is: % % IndexPacket *GetCacheViewIndexes(CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % */ MagickExport IndexPacket *GetCacheViewIndexes(CacheView *cache_view) { return(GetCacheViewAuthenticIndexQueue(cache_view)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCacheViewPixels() gets pixels from the in-memory or disk pixel cache as % defined by the geometry parameters. A pointer to the pixels is returned if % the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, % GetCacheViewException(cache_view)); % % The format of the GetCacheViewPixels method is: % % PixelPacket *GetCacheViewPixels(CacheView *cache_view,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *GetCacheViewPixels(CacheView *cache_view,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows) { PixelPacket *pixels; pixels=GetCacheViewAuthenticPixels(cache_view,x,y,columns,rows, GetCacheViewException(cache_view)); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageAttribute() searches the list of image attributes and returns % a pointer to the attribute if it exists otherwise NULL. % % The format of the GetImageAttribute method is: % % const ImageAttribute *GetImageAttribute(const Image *image, % const char *key) % % A description of each parameter follows: % % o image: the image. % % o key: These character strings are the name of an image attribute to % return. % */ static void *DestroyAttribute(void *attribute) { register ImageAttribute *p; p=(ImageAttribute *) attribute; if (p->value != (char *) NULL) p->value=DestroyString(p->value); return(RelinquishMagickMemory(p)); } MagickExport const ImageAttribute *GetImageAttribute(const Image *image, const char *key) { const char *value; ImageAttribute *attribute; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.3.1"); value=GetImageProperty(image,key); if (value == (const char *) NULL) return((const ImageAttribute *) NULL); if (image->attributes == (void *) NULL) ((Image *) image)->attributes=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,DestroyAttribute); else { const ImageAttribute *attribute; attribute=(const ImageAttribute *) GetValueFromSplayTree((SplayTreeInfo *) image->attributes,key); if (attribute != (const ImageAttribute *) NULL) return(attribute); } attribute=(ImageAttribute *) AcquireMagickMemory(sizeof(*attribute)); if (attribute == (ImageAttribute *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(attribute,0,sizeof(*attribute)); attribute->key=ConstantString(key); attribute->value=ConstantString(value); (void) AddValueToSplayTree((SplayTreeInfo *) ((Image *) image)->attributes, attribute->key,attribute); return((const ImageAttribute *) attribute); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C l i p p i n g P a t h A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageClippingPathAttribute() searches the list of image attributes and % returns a pointer to a clipping path if it exists otherwise NULL. % % Deprecated, replace with: % % GetImageAttribute(image,"8BIM:1999,2998"); % % The format of the GetImageClippingPathAttribute method is: % % const ImageAttribute *GetImageClippingPathAttribute(Image *image) % % A description of each parameter follows: % % o attribute: Method GetImageClippingPathAttribute returns the clipping % path if it exists otherwise NULL. % % o image: the image. % */ MagickExport const ImageAttribute *GetImageClippingPathAttribute(Image *image) { return(GetImageAttribute(image,"8BIM:1999,2998")); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e F r o m M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageFromMagickRegistry() gets an image from the registry as defined by % its name. If the image is not found, a NULL image is returned. % % Deprecated, replace with: % % GetImageRegistry(ImageRegistryType,name,exception); % % The format of the GetImageFromMagickRegistry method is: % % Image *GetImageFromMagickRegistry(const char *name,ssize_t *id, % ExceptionInfo *exception) % % A description of each parameter follows: % % o name: the name of the image to retrieve from the registry. % % o id: the registry id. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GetImageFromMagickRegistry(const char *name,ssize_t *id, ExceptionInfo *exception) { *id=0L; return((Image *) GetImageRegistry(ImageRegistryType,name,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickRegistry() gets a blob from the registry as defined by the id. If % the blob that matches the id is not found, NULL is returned. % % The format of the GetMagickRegistry method is: % % const void *GetMagickRegistry(const ssize_t id,RegistryType *type, % size_t *length,ExceptionInfo *exception) % % A description of each parameter follows: % % o id: the registry id. % % o type: the registry type. % % o length: the blob length in number of bytes. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetMagickRegistry(const ssize_t id,RegistryType *type, size_t *length,ExceptionInfo *exception) { char key[MaxTextExtent]; void *blob; *type=UndefinedRegistryType; *length=0; (void) FormatLocaleString(key,MaxTextExtent,"%.20g\n",(double) id); blob=(void *) GetImageRegistry(ImageRegistryType,key,exception); if (blob != (void *) NULL) return(blob); blob=(void *) GetImageRegistry(ImageInfoRegistryType,key,exception); if (blob != (void *) NULL) return(blob); return((void *) GetImageRegistry(UndefinedRegistryType,key,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageGeometry() returns a region as defined by the geometry string with % respect to the image and its gravity. % % Deprecated, replace with: % % if (size_to_fit != MagickFalse) % ParseRegionGeometry(image,geometry,region_info,&image->exception); else % ParsePageGeometry(image,geometry,region_info,&image->exception); % % The format of the GetImageGeometry method is: % % int GetImageGeometry(Image *image,const char *geometry, % const unsigned int size_to_fit,RectangeInfo *region_info) % % A description of each parameter follows: % % o flags: Method GetImageGeometry returns a bitmask that indicates % which of the four values were located in the geometry string. % % o geometry: The geometry (e.g. 100x100+10+10). % % o size_to_fit: A value other than 0 means to scale the region so it % fits within the specified width and height. % % o region_info: the region as defined by the geometry string with % respect to the image and its gravity. % */ MagickExport int GetImageGeometry(Image *image,const char *geometry, const unsigned int size_to_fit,RectangleInfo *region_info) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.4"); if (size_to_fit != MagickFalse) return((int) ParseRegionGeometry(image,geometry,region_info,&image->exception)); return((int) ParsePageGeometry(image,geometry,region_info,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageList() returns an image at the specified position in the list. % % Deprecated, replace with: % % CloneImage(GetImageFromList(images,(ssize_t) offset),0,0,MagickTrue, % exception); % % The format of the GetImageList method is: % % Image *GetImageList(const Image *images,const ssize_t offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o offset: the position within the list. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *GetImageList(const Image *images,const ssize_t offset, ExceptionInfo *exception) { Image *image; if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); image=CloneImage(GetImageFromList(images,(ssize_t) offset),0,0,MagickTrue, exception); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e L i s t I n d e x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageListIndex() returns the position in the list of the specified % image. % % Deprecated, replace with: % % GetImageIndexInList(images); % % The format of the GetImageListIndex method is: % % ssize_t GetImageListIndex(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport ssize_t GetImageListIndex(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetImageIndexInList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e L i s t S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageListSize() returns the number of images in the list. % % Deprecated, replace with: % % GetImageListLength(images); % % The format of the GetImageListSize method is: % % size_t GetImageListSize(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport size_t GetImageListSize(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetImageListLength(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a PixelPacket array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in RAM, or in a memory-mapped file. The returned pointer % should *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or if the storage class is % PseduoClass, call GetAuthenticIndexQueue() after invoking GetImagePixels() % to obtain the black color component or colormap indexes (of type IndexPacket) % corresponding to the region. Once the PixelPacket (and/or IndexPacket) % array has been updated, the changes must be saved back to the underlying % image using SyncAuthenticPixels() or they may be lost. % % Deprecated, replace with: % % GetAuthenticPixels(image,x,y,columns,rows,&image->exception); % % The format of the GetImagePixels() method is: % % PixelPacket *GetImagePixels(Image *image,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *GetImagePixels(Image *image,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows) { return(GetAuthenticPixels(image,x,y,columns,rows,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetIndexes() returns the black channel or the colormap indexes associated % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the black channel or colormap indexes are not available. % % Deprecated, replace with: % % GetAuthenticIndexQueue(image); % % The format of the GetIndexes() method is: % % IndexPacket *GetIndexes(const Image *image) % % A description of each parameter follows: % % o indexes: GetIndexes() returns the indexes associated with the last % call to QueueAuthenticPixels() or GetAuthenticPixels(). % % o image: the image. % */ MagickExport IndexPacket *GetIndexes(const Image *image) { return(GetAuthenticIndexQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t M a g i c k G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickGeometry() is similar to GetGeometry() except the returned % geometry is modified as determined by the meta characters: %, !, <, >, % and ~. % % Deprecated, replace with: % % ParseMetaGeometry(geometry,x,y,width,height); % % The format of the GetMagickGeometry method is: % % unsigned int GetMagickGeometry(const char *geometry,ssize_t *x,ssize_t *y, % size_t *width,size_t *height) % % A description of each parameter follows: % % o geometry: Specifies a character string representing the geometry % specification. % % o x,y: A pointer to an integer. The x and y offset as determined by % the geometry specification is returned here. % % o width,height: A pointer to an unsigned integer. The width and height % as determined by the geometry specification is returned here. % */ MagickExport unsigned int GetMagickGeometry(const char *geometry,ssize_t *x, ssize_t *y,size_t *width,size_t *height) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.3"); return(ParseMetaGeometry(geometry,x,y,width,height)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImage() returns the next image in a list. % % Deprecated, replace with: % % GetNextImageInList(images); % % The format of the GetNextImage method is: % % Image *GetNextImage(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *GetNextImage(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetNextImageInList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageAttribute() gets the next image attribute. % % Deprecated, replace with: % % const char *property; % property=GetNextImageProperty(image); % if (property != (const char *) NULL) % GetImageAttribute(image,property); % % The format of the GetNextImageAttribute method is: % % const ImageAttribute *GetNextImageAttribute(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const ImageAttribute *GetNextImageAttribute(const Image *image) { const char *property; property=GetNextImageProperty(image); if (property == (const char *) NULL) return((const ImageAttribute *) NULL); return(GetImageAttribute(image,property)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N u m b e r S c e n e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNumberScenes() returns the number of images in the list. % % Deprecated, replace with: % % GetImageListLength(image); % % The format of the GetNumberScenes method is: % % unsigned int GetNumberScenes(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport unsigned int GetNumberScenes(const Image *image) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return((unsigned int) GetImageListLength(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOnePixel() returns a single pixel at the specified (x,y) location. % The image background color is returned if an error occurs. % % Deprecated, replace with: % % GetOneAuthenticPixel(image,x,y,&pixel,&image->exception); % % The format of the GetOnePixel() method is: % % PixelPacket GetOnePixel(const Image image,const ssize_t x,const ssize_t y) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % */ MagickExport PixelPacket GetOnePixel(Image *image,const ssize_t x,const ssize_t y) { PixelPacket pixel; (void) GetOneAuthenticPixel(image,x,y,&pixel,&image->exception); return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixels() returns the pixels associated with the last call to % QueueAuthenticPixels() or GetAuthenticPixels(). % % Deprecated, replace with: % % GetAuthenticPixelQueue(image); % % The format of the GetPixels() method is: % % PixelPacket *GetPixels(const Image image) % % A description of each parameter follows: % % o pixels: GetPixels() returns the pixels associated with the last call % to QueueAuthenticPixels() or GetAuthenticPixels(). % % o image: the image. % */ MagickExport PixelPacket *GetPixels(const Image *image) { return(GetAuthenticPixelQueue(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P r e v i o u s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPreviousImage() returns the previous image in a list. % % Deprecated, replace with: % % GetPreviousImageInList(images)); % % The format of the GetPreviousImage method is: % % Image *GetPreviousImage(const Image *images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *GetPreviousImage(const Image *images) { if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(GetPreviousImageInList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H S L T r a n s f o r m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % HSLTransform() converts a (hue, saturation, lightness) to a (red, green, % blue) triple. % % The format of the HSLTransformImage method is: % % void HSLTransform(const double hue,const double saturation, % const double lightness,Quantum *red,Quantum *green,Quantum *blue) % % A description of each parameter follows: % % o hue, saturation, lightness: A double value representing a % component of the HSL color space. % % o red, green, blue: A pointer to a pixel component of type Quantum. % */ static inline MagickRealType HueToRGB(MagickRealType m1,MagickRealType m2, MagickRealType hue) { if (hue < 0.0) hue+=1.0; if (hue > 1.0) hue-=1.0; if ((6.0*hue) < 1.0) return(m1+6.0*(m2-m1)*hue); if ((2.0*hue) < 1.0) return(m2); if ((3.0*hue) < 2.0) return(m1+6.0*(m2-m1)*(2.0/3.0-hue)); return(m1); } MagickExport void HSLTransform(const double hue,const double saturation, const double lightness,Quantum *red,Quantum *green,Quantum *blue) { MagickRealType b, g, r, m1, m2; /* Convert HSL to RGB colorspace. */ assert(red != (Quantum *) NULL); assert(green != (Quantum *) NULL); assert(blue != (Quantum *) NULL); if (lightness <= 0.5) m2=lightness*(saturation+1.0); else m2=lightness+saturation-lightness*saturation; m1=2.0*lightness-m2; r=HueToRGB(m1,m2,hue+1.0/3.0); g=HueToRGB(m1,m2,hue); b=HueToRGB(m1,m2,hue-1.0/3.0); *red=ClampToQuantum((MagickRealType) QuantumRange*r); *green=ClampToQuantum((MagickRealType) QuantumRange*g); *blue=ClampToQuantum((MagickRealType) QuantumRange*b); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I d e n t i t y A f f i n e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IdentityAffine() initializes the affine transform to the identity matrix. % % The format of the IdentityAffine method is: % % IdentityAffine(AffineMatrix *affine) % % A description of each parameter follows: % % o affine: A pointer the affine transform of type AffineMatrix. % */ MagickExport void IdentityAffine(AffineMatrix *affine) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); assert(affine != (AffineMatrix *) NULL); (void) ResetMagickMemory(affine,0,sizeof(AffineMatrix)); affine->sx=1.0; affine->sy=1.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n i t i a l i z e M a g i c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeMagick() initializes the ImageMagick environment. % % Deprecated, replace with: % % MagickCoreGenesis(path,MagickFalse); % % The format of the InitializeMagick function is: % % InitializeMagick(const char *path) % % A description of each parameter follows: % % o path: the execution path of the current ImageMagick client. % */ MagickExport void InitializeMagick(const char *path) { MagickCoreGenesis(path,MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t e P i x e l C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolatePixelColor() applies bi-linear or tri-linear interpolation % between a pixel and it's neighbors. % % The format of the InterpolatePixelColor method is: % % MagickPixelPacket InterpolatePixelColor(const Image *image, % CacheView *view_info,InterpolatePixelMethod method,const double x, % const double y,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o image_view: the image cache view. % % o type: the type of pixel color interpolation. % % o x,y: A double representing the current (x,y) position of the pixel. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } static void BicubicInterpolate(const MagickPixelPacket *pixels,const double dx, MagickPixelPacket *pixel) { MagickRealType dx2, p, q, r, s; dx2=dx*dx; p=(pixels[3].red-pixels[2].red)-(pixels[0].red-pixels[1].red); q=(pixels[0].red-pixels[1].red)-p; r=pixels[2].red-pixels[0].red; s=pixels[1].red; pixel->red=(dx*dx2*p)+(dx2*q)+(dx*r)+s; p=(pixels[3].green-pixels[2].green)-(pixels[0].green-pixels[1].green); q=(pixels[0].green-pixels[1].green)-p; r=pixels[2].green-pixels[0].green; s=pixels[1].green; pixel->green=(dx*dx2*p)+(dx2*q)+(dx*r)+s; p=(pixels[3].blue-pixels[2].blue)-(pixels[0].blue-pixels[1].blue); q=(pixels[0].blue-pixels[1].blue)-p; r=pixels[2].blue-pixels[0].blue; s=pixels[1].blue; pixel->blue=(dx*dx2*p)+(dx2*q)+(dx*r)+s; p=(pixels[3].opacity-pixels[2].opacity)-(pixels[0].opacity-pixels[1].opacity); q=(pixels[0].opacity-pixels[1].opacity)-p; r=pixels[2].opacity-pixels[0].opacity; s=pixels[1].opacity; pixel->opacity=(dx*dx2*p)+(dx2*q)+(dx*r)+s; if (pixel->colorspace == CMYKColorspace) { p=(pixels[3].index-pixels[2].index)-(pixels[0].index-pixels[1].index); q=(pixels[0].index-pixels[1].index)-p; r=pixels[2].index-pixels[0].index; s=pixels[1].index; pixel->index=(dx*dx2*p)+(dx2*q)+(dx*r)+s; } } static inline MagickRealType CubicWeightingFunction(const MagickRealType x) { MagickRealType alpha, gamma; alpha=MagickMax(x+2.0,0.0); gamma=1.0*alpha*alpha*alpha; alpha=MagickMax(x+1.0,0.0); gamma-=4.0*alpha*alpha*alpha; alpha=MagickMax(x+0.0,0.0); gamma+=6.0*alpha*alpha*alpha; alpha=MagickMax(x-1.0,0.0); gamma-=4.0*alpha*alpha*alpha; return(gamma/6.0); } static inline double MeshInterpolate(const PointInfo *delta,const double p, const double x,const double y) { return(delta->x*x+delta->y*y+(1.0-delta->x-delta->y)*p); } static inline ssize_t NearestNeighbor(MagickRealType x) { if (x >= 0.0) return((ssize_t) (x+0.5)); return((ssize_t) (x-0.5)); } MagickExport MagickPixelPacket InterpolatePixelColor(const Image *image, CacheView *image_view,const InterpolatePixelMethod method,const double x, const double y,ExceptionInfo *exception) { MagickPixelPacket pixel; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image_view != (CacheView *) NULL); GetMagickPixelPacket(image,&pixel); switch (method) { case AverageInterpolatePixel: { double gamma; MagickPixelPacket pixels[16]; MagickRealType alpha[16]; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x)-1,(ssize_t) floor(y)-1,4,4,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 16L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } gamma=alpha[i]; gamma=PerceptibleReciprocal(gamma); pixel.red+=gamma*0.0625*pixels[i].red; pixel.green+=gamma*0.0625*pixels[i].green; pixel.blue+=gamma*0.0625*pixels[i].blue; pixel.opacity+=0.0625*pixels[i].opacity; if (image->colorspace == CMYKColorspace) pixel.index+=gamma*0.0625*pixels[i].index; p++; } break; } case BicubicInterpolatePixel: { MagickPixelPacket pixels[16], u[4]; MagickRealType alpha[16]; PointInfo delta; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x)-1,(ssize_t) floor(y)-1,4,4,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 16L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } p++; } delta.x=x-floor(x); for (i=0; i < 4L; i++) BicubicInterpolate(pixels+4*i,delta.x,u+i); delta.y=y-floor(y); BicubicInterpolate(u,delta.y,&pixel); break; } case BilinearInterpolatePixel: default: { double gamma; MagickPixelPacket pixels[16]; MagickRealType alpha[16]; PointInfo delta; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x),(ssize_t) floor(y),2,2,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 4L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } p++; } delta.x=x-floor(x); delta.y=y-floor(y); gamma=(((1.0-delta.y)*((1.0-delta.x)*alpha[0]+delta.x*alpha[1])+delta.y* ((1.0-delta.x)*alpha[2]+delta.x*alpha[3]))); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].red+delta.x* pixels[1].red)+delta.y*((1.0-delta.x)*pixels[2].red+delta.x* pixels[3].red)); pixel.green=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].green+delta.x* pixels[1].green)+delta.y*((1.0-delta.x)*pixels[2].green+ delta.x*pixels[3].green)); pixel.blue=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].blue+delta.x* pixels[1].blue)+delta.y*((1.0-delta.x)*pixels[2].blue+delta.x* pixels[3].blue)); pixel.opacity=((1.0-delta.y)*((1.0-delta.x)*pixels[0].opacity+delta.x* pixels[1].opacity)+delta.y*((1.0-delta.x)*pixels[2].opacity+delta.x* pixels[3].opacity)); if (image->colorspace == CMYKColorspace) pixel.index=gamma*((1.0-delta.y)*((1.0-delta.x)*pixels[0].index+delta.x* pixels[1].index)+delta.y*((1.0-delta.x)*pixels[2].index+delta.x* pixels[3].index)); break; } case FilterInterpolatePixel: { Image *excerpt_image, *filter_image; MagickPixelPacket pixels[1]; RectangleInfo geometry; geometry.width=4L; geometry.height=4L; geometry.x=(ssize_t) floor(x)-1L; geometry.y=(ssize_t) floor(y)-1L; excerpt_image=ExcerptImage(image,&geometry,exception); if (excerpt_image == (Image *) NULL) break; filter_image=ResizeImage(excerpt_image,1,1,image->filter,image->blur, exception); excerpt_image=DestroyImage(excerpt_image); if (filter_image == (Image *) NULL) break; p=GetVirtualPixels(filter_image,0,0,1,1,exception); if (p == (const PixelPacket *) NULL) { filter_image=DestroyImage(filter_image); break; } indexes=GetVirtualIndexQueue(filter_image); GetMagickPixelPacket(image,pixels); SetMagickPixelPacket(image,p,indexes,&pixel); filter_image=DestroyImage(filter_image); break; } case IntegerInterpolatePixel: { MagickPixelPacket pixels[1]; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x),(ssize_t) floor(y),1,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); GetMagickPixelPacket(image,pixels); SetMagickPixelPacket(image,p,indexes,&pixel); break; } case MeshInterpolatePixel: { double gamma; MagickPixelPacket pixels[4]; MagickRealType alpha[4]; PointInfo delta, luminance; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x),(ssize_t) floor(y),2,2,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); for (i=0; i < 4L; i++) { GetMagickPixelPacket(image,pixels+i); SetMagickPixelPacket(image,p,indexes+i,pixels+i); alpha[i]=1.0; if (image->matte != MagickFalse) { alpha[i]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[i].red*=alpha[i]; pixels[i].green*=alpha[i]; pixels[i].blue*=alpha[i]; if (image->colorspace == CMYKColorspace) pixels[i].index*=alpha[i]; } p++; } delta.x=x-floor(x); delta.y=y-floor(y); luminance.x=MagickPixelLuma(pixels+0)-MagickPixelLuma(pixels+3); luminance.y=MagickPixelLuma(pixels+1)-MagickPixelLuma(pixels+2); if (fabs(luminance.x) < fabs(luminance.y)) { /* Diagonal 0-3 NW-SE. */ if (delta.x <= delta.y) { /* Bottom-left triangle (pixel:2, diagonal: 0-3). */ delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[2].red, pixels[3].red,pixels[0].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[2].green, pixels[3].green,pixels[0].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[2].blue, pixels[3].blue,pixels[0].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[2].opacity, pixels[3].opacity,pixels[0].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[2].index, pixels[3].index,pixels[0].index); } else { /* Top-right triangle (pixel:1, diagonal: 0-3). */ delta.x=1.0-delta.x; gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[1].red, pixels[0].red,pixels[3].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[1].green, pixels[0].green,pixels[3].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[1].blue, pixels[0].blue,pixels[3].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[1].opacity, pixels[0].opacity,pixels[3].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[1].index, pixels[0].index,pixels[3].index); } } else { /* Diagonal 1-2 NE-SW. */ if (delta.x <= (1.0-delta.y)) { /* Top-left triangle (pixel 0, diagonal: 1-2). */ gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[0].red, pixels[1].red,pixels[2].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[0].green, pixels[1].green,pixels[2].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[0].blue, pixels[1].blue,pixels[2].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[0].opacity, pixels[1].opacity,pixels[2].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[0].index, pixels[1].index,pixels[2].index); } else { /* Bottom-right triangle (pixel: 3, diagonal: 1-2). */ delta.x=1.0-delta.x; delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]); gamma=PerceptibleReciprocal(gamma); pixel.red=gamma*MeshInterpolate(&delta,pixels[3].red, pixels[2].red,pixels[1].red); pixel.green=gamma*MeshInterpolate(&delta,pixels[3].green, pixels[2].green,pixels[1].green); pixel.blue=gamma*MeshInterpolate(&delta,pixels[3].blue, pixels[2].blue,pixels[1].blue); pixel.opacity=gamma*MeshInterpolate(&delta,pixels[3].opacity, pixels[2].opacity,pixels[1].opacity); if (image->colorspace == CMYKColorspace) pixel.index=gamma*MeshInterpolate(&delta,pixels[3].index, pixels[2].index,pixels[1].index); } } break; } case NearestNeighborInterpolatePixel: { MagickPixelPacket pixels[1]; p=GetCacheViewVirtualPixels(image_view,NearestNeighbor(x), NearestNeighbor(y),1,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); GetMagickPixelPacket(image,pixels); SetMagickPixelPacket(image,p,indexes,&pixel); break; } case SplineInterpolatePixel: { double gamma; MagickPixelPacket pixels[16]; MagickRealType alpha[16], dx, dy; PointInfo delta; ssize_t j, n; p=GetCacheViewVirtualPixels(image_view,(ssize_t) floor(x)-1,(ssize_t) floor(y)-1,4,4,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewVirtualIndexQueue(image_view); n=0; delta.x=x-floor(x); delta.y=y-floor(y); for (i=(-1); i < 3L; i++) { dy=CubicWeightingFunction((MagickRealType) i-delta.y); for (j=(-1); j < 3L; j++) { GetMagickPixelPacket(image,pixels+n); SetMagickPixelPacket(image,p,indexes+n,pixels+n); alpha[n]=1.0; if (image->matte != MagickFalse) { alpha[n]=QuantumScale*((MagickRealType) GetPixelAlpha(p)); pixels[n].red*=alpha[n]; pixels[n].green*=alpha[n]; pixels[n].blue*=alpha[n]; if (image->colorspace == CMYKColorspace) pixels[n].index*=alpha[n]; } dx=CubicWeightingFunction(delta.x-(MagickRealType) j); gamma=alpha[n]; gamma=PerceptibleReciprocal(gamma); pixel.red+=gamma*dx*dy*pixels[n].red; pixel.green+=gamma*dx*dy*pixels[n].green; pixel.blue+=gamma*dx*dy*pixels[n].blue; if (image->matte != MagickFalse) pixel.opacity+=dx*dy*pixels[n].opacity; if (image->colorspace == CMYKColorspace) pixel.index+=gamma*dx*dy*pixels[n].index; n++; p++; } } break; } } return(pixel); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e A t t r i b u t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageAttributes() replaces any embedded formatting characters with % the appropriate image attribute and returns the translated text. % % Deprecated, replace with: % % InterpretImageProperties(image_info,image,embed_text); % % The format of the InterpretImageAttributes method is: % % char *InterpretImageAttributes(const ImageInfo *image_info,Image *image, % const char *embed_text) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o embed_text: the address of a character string containing the embedded % formatting characters. % */ MagickExport char *InterpretImageAttributes(const ImageInfo *image_info, Image *image,const char *embed_text) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.3.1"); return(InterpretImageProperties(image_info,image,embed_text)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e s R G B C o m p a n d o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InversesRGBCompandor() removes the gamma function from a sRGB pixel. % % The format of the InversesRGBCompandor method is: % % MagickRealType InversesRGBCompandor(const MagickRealType pixel) % % A description of each parameter follows: % % o pixel: the pixel. % */ MagickExport MagickRealType InversesRGBCompandor(const MagickRealType pixel) { if (pixel <= (0.0404482362771076*QuantumRange)) return(pixel/12.92); return(QuantumRange*pow((QuantumScale*pixel+0.055)/1.055,2.4)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s S u b i m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSubimage() returns MagickTrue if the geometry is a valid subimage % specification (e.g. [1], [1-9], [1,7,4]). % % The format of the IsSubimage method is: % % unsigned int IsSubimage(const char *geometry,const unsigned int pedantic) % % A description of each parameter follows: % % o geometry: This string is the geometry specification. % % o pedantic: A value other than 0 invokes a more restrictive set of % conditions for a valid specification (e.g. [1], [1-4], [4-1]). % */ MagickExport unsigned int IsSubimage(const char *geometry, const unsigned int pedantic) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (geometry == (const char *) NULL) return(MagickFalse); if ((strchr(geometry,'x') != (char *) NULL) || (strchr(geometry,'X') != (char *) NULL)) return(MagickFalse); if ((pedantic != MagickFalse) && (strchr(geometry,',') != (char *) NULL)) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L e v e l I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LevelImageColor() will map the given color to "black" and "white" % values, limearly spreading out the colors, and level values on a channel by % channel bases, as per LevelImage(). The given colors allows you to specify % different level ranges for each of the color channels separately. % % If the boolean 'invert' is set true the image values will modifyed in the % reverse direction. That is any existing "black" and "white" colors in the % image will become the color values given, with all other values compressed % appropriatally. This effectivally maps a greyscale gradient into the given % color gradient. % % Deprecated, replace with: % % LevelColorsImageChannel(image,channel,black_color,white_color,invert); % % The format of the LevelImageColors method is: % % MagickBooleanType LevelImageColors(Image *image,const ChannelType channel, % const MagickPixelPacket *black_color,const MagickPixelPacket *white_color, % const MagickBooleanType invert) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o black_color: The color to map black to/from % % o white_point: The color to map white to/from % % o invert: if true map the colors (levelize), rather than from (level) % */ MagickBooleanType LevelImageColors(Image *image,const ChannelType channel, const MagickPixelPacket *black_color,const MagickPixelPacket *white_color, const MagickBooleanType invert) { return(LevelColorsImageChannel(image,channel,black_color,white_color,invert)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i b e r a t e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiberateMemory() frees memory that has already been allocated, and NULL's % the pointer to it. % % The format of the LiberateMemory method is: % % void LiberateMemory(void **memory) % % A description of each parameter follows: % % o memory: A pointer to a block of memory to free for reuse. % */ MagickExport void LiberateMemory(void **memory) { assert(memory != (void **) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (*memory == (void *) NULL) return; free(*memory); *memory=(void *) NULL; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i b e r a t e S e m a p h o r e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiberateSemaphoreInfo() relinquishes a semaphore. % % Deprecated, replace with: % % UnlockSemaphoreInfo(*semaphore_info); % % The format of the LiberateSemaphoreInfo method is: % % LiberateSemaphoreInfo(void **semaphore_info) % % A description of each parameter follows: % % o semaphore_info: Specifies a pointer to an SemaphoreInfo structure. % */ MagickExport void LiberateSemaphoreInfo(SemaphoreInfo **semaphore_info) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); UnlockSemaphoreInfo(*semaphore_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k I n c a r n a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickIncarnate() initializes the ImageMagick environment. % % Deprecated, replace with: % % MagickCoreGenesis(path,MagickFalse); % % The format of the MagickIncarnate function is: % % MagickIncarnate(const char *path) % % A description of each parameter follows: % % o path: the execution path of the current ImageMagick client. % */ MagickExport void MagickIncarnate(const char *path) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); MagickCoreGenesis(path,MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M o n i t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMonitor() calls the monitor handler method with a text string that % describes the task and a measure of completion. The method returns % MagickTrue on success otherwise MagickFalse if an error is encountered, e.g. % if there was a user interrupt. % % The format of the MagickMonitor method is: % % MagickBooleanType MagickMonitor(const char *text, % const MagickOffsetType offset,const MagickSizeType span, % void *client_data) % % A description of each parameter follows: % % o offset: the position relative to the span parameter which represents % how much progress has been made toward completing a task. % % o span: the span relative to completing a task. % % o client_data: the client data. % */ MagickExport MagickBooleanType MagickMonitor(const char *text, const MagickOffsetType offset,const MagickSizeType span, void *magick_unused(client_data)) { ExceptionInfo *exception; MagickBooleanType status; assert(text != (const char *) NULL); (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",text); ProcessPendingEvents(text); status=MagickTrue; exception=AcquireExceptionInfo(); if (monitor_handler != (MonitorHandler) NULL) status=(*monitor_handler)(text,offset,span,exception); exception=DestroyExceptionInfo(exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MapImage() replaces the colors of an image with the closest color from a % reference image. % % Deprecated, replace with: % % QuantizeInfo quantize_info; % GetQuantizeInfo(&quantize_info); % quantize_info.dither=dither; % RemapImage(&quantize_info,image,map_image); % % The format of the MapImage method is: % % MagickBooleanType MapImage(Image *image,const Image *map_image, % const MagickBooleanType dither) % % A description of each parameter follows: % % o image: Specifies a pointer to an Image structure. % % o map_image: the image. Reduce image to a set of colors represented by % this image. % % o dither: Set this integer value to something other than zero to % dither the mapped image. % */ MagickExport MagickBooleanType MapImage(Image *image,const Image *map_image, const MagickBooleanType dither) { QuantizeInfo quantize_info; /* Initialize color cube. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(map_image != (Image *) NULL); assert(map_image->signature == MagickSignature); GetQuantizeInfo(&quantize_info); quantize_info.dither=dither; return(RemapImage(&quantize_info,image,map_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a p I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MapImages() replaces the colors of a sequence of images with the closest % color from a reference image. % % Deprecated, replace with: % % QuantizeInfo quantize_info; % GetQuantizeInfo(&quantize_info); % quantize_info.dither=dither; % RemapImages(&quantize_info,images,map_image); % % The format of the MapImage method is: % % MagickBooleanType MapImages(Image *images,Image *map_image, % const MagickBooleanType dither) % % A description of each parameter follows: % % o image: Specifies a pointer to a set of Image structures. % % o map_image: the image. Reduce image to a set of colors represented by % this image. % % o dither: Set this integer value to something other than zero to % dither the quantized image. % */ MagickExport MagickBooleanType MapImages(Image *images,const Image *map_image, const MagickBooleanType dither) { QuantizeInfo quantize_info; assert(images != (Image *) NULL); assert(images->signature == MagickSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); GetQuantizeInfo(&quantize_info); quantize_info.dither=dither; return(RemapImages(&quantize_info,images,map_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a t t e F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MatteFloodfill() changes the transparency value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod % is specified, the transparency value is changed for any neighbor pixel % that does not match the bordercolor member of image. % % By default target must match a particular pixel transparency exactly. % However, in many cases two transparency values may differ by a % small amount. The fuzz member of image defines how much tolerance is % acceptable to consider two transparency values as the same. For example, % set fuzz to 10 and the opacity values of 100 and 102 respectively are % now interpreted as the same value for the purposes of the floodfill. % % The format of the MatteFloodfillImage method is: % % MagickBooleanType MatteFloodfillImage(Image *image, % const PixelPacket target,const Quantum opacity,const ssize_t x_offset, % const ssize_t y_offset,const PaintMethod method) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o opacity: the level of transparency: 0 is fully opaque and QuantumRange is % fully transparent. % % o x,y: the starting location of the operation. % % o method: Choose either FloodfillMethod or FillToBorderMethod. % */ MagickExport MagickBooleanType MatteFloodfillImage(Image *image, const PixelPacket target,const Quantum opacity,const ssize_t x_offset, const ssize_t y_offset,const PaintMethod method) { Image *floodplane_image; MagickBooleanType skip; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue, &image->exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); (void) SetImageAlphaChannel(floodplane_image,OpaqueAlphaChannel); /* Set floodfill color. */ segment_stack=(SegmentInfo *) AcquireQuantumMemory(MaxStacksize, sizeof(*segment_stack)); if (segment_stack == (SegmentInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } /* Push initial segment on stack. */ x=x_offset; y=y_offset; start=0; s=segment_stack; PushSegmentStack(y,x,x,1); PushSegmentStack(y+1,x,x,-1); while (s > segment_stack) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetVirtualPixels(image,0,y,(size_t) (x1+1),1,&image->exception); q=GetAuthenticPixels(floodplane_image,0,y,(size_t) (x1+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; p+=x1; q+=x1; for (x=x1; x >= 0; x--) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; q--; p--; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetVirtualPixels(image,x,y,image->columns-x,1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,image->columns-x,1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x < (ssize_t) image->columns; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) == MagickFalse) break; } else if (IsColorSimilar(image,p,&target) != MagickFalse) break; q->opacity=(Quantum) TransparentOpacity; q++; p++; } if (SyncAuthenticPixels(floodplane_image,&image->exception) == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetVirtualPixels(image,x,y,(size_t) (x2-x+1),1, &image->exception); q=GetAuthenticPixels(floodplane_image,x,y,(size_t) (x2-x+1),1, &image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for ( ; x <= x2; x++) { if (q->opacity == (Quantum) TransparentOpacity) break; if (method == FloodfillMethod) { if (IsColorSimilar(image,p,&target) != MagickFalse) break; } else if (IsColorSimilar(image,p,&target) == MagickFalse) break; p++; q++; } } start=x; } while (x <= x2); } for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *restrict p; register ssize_t x; register PixelPacket *restrict q; /* Tile fill color onto floodplane. */ p=GetVirtualPixels(floodplane_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) q->opacity=opacity; p++; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } segment_stack=(SegmentInfo *) RelinquishMagickMemory(segment_stack); floodplane_image=DestroyImage(floodplane_image); return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a x i m u m I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaximumImages() returns the maximum intensity of an image sequence. % % Deprecated, replace with: % % EvaluateImages(images,MinEvaluateOperator,exception); % % The format of the MaxImages method is: % % Image *MaximumImages(Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MaximumImages(const Image *images,ExceptionInfo *exception) { return(EvaluateImages(images,MinEvaluateOperator,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M i n i m u m I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MinimumImages() returns the minimum intensity of an image sequence. % % Deprecated, replace with: % % EvaluateImages(images,MinEvaluateOperator,exception); % % The format of the MinimumImages method is: % % Image *MinimumImages(Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MinimumImages(const Image *images,ExceptionInfo *exception) { return(EvaluateImages(images,MinEvaluateOperator,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e d i a n F i l t e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MedianFilterImage() applies a digital filter that improves the quality % of a noisy image. Each pixel is replaced by the median in a set of % neighboring pixels as defined by radius. % % The algorithm was contributed by Mike Edmonds and implements an insertion % sort for selecting median color-channel values. For more on this algorithm % see "Skip Lists: A probabilistic Alternative to Balanced Trees" by William % Pugh in the June 1990 of Communications of the ACM. % % The format of the MedianFilterImage method is: % % Image *MedianFilterImage(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 *MedianFilterImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *median_image; median_image=StatisticImage(image,MedianStatistic,(size_t) radius,(size_t) radius,exception); return(median_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ModeImage() makes each pixel the 'predominant color' of the neighborhood % of the specified radius. % % The format of the ModeImage method is: % % Image *ModeImage(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 *ModeImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *mode_image; mode_image=StatisticImage(image,ModeStatistic,(size_t) radius,(size_t) radius, exception); return(mode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o s a i c I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MosaicImages() Obsolete Function: Use MergeImageLayers() instead. % % Deprecated, replace with: % % MergeImageLayers(image,MosaicLayer,exception); % % The format of the MosaicImage method is: % % Image *MosaicImages(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MosaicImages(Image *image,ExceptionInfo *exception) { return(MergeImageLayers(image,MosaicLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p a q u e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpaqueImage() changes any pixel that matches color with the color % defined by fill. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the OpaqueImage method is: % % MagickBooleanType OpaqueImage(Image *image, % const PixelPacket *target,const PixelPacket fill) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o fill: the replacement color. % */ MagickExport MagickBooleanType OpaqueImage(Image *image, const PixelPacket target,const PixelPacket fill) { #define OpaqueImageTag "Opaque/Image" MagickBooleanType proceed; register ssize_t i; ssize_t y; /* Make image color opaque. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.1.0"); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (image->storage_class) { case DirectClass: default: { /* Make DirectClass image opaque. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) != MagickFalse) *q=fill; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; proceed=SetImageProgress(image,OpaqueImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } break; } case PseudoClass: { /* Make PseudoClass image opaque. */ for (i=0; i < (ssize_t) image->colors; i++) { if (IsColorSimilar(image,&image->colormap[i],&target) != MagickFalse) image->colormap[i]=fill; } if (fill.opacity != OpaqueOpacity) { for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) != MagickFalse) q->opacity=fill.opacity; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } } (void) SyncImage(image); break; } } if (fill.opacity != OpaqueOpacity) image->matte=MagickTrue; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p e n C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenCacheView() opens a view into the pixel cache, using the % VirtualPixelMethod that is defined within the given image itself. % % Deprecated, replace with: % % AcquireVirtualCacheView(image,&image->exception); % % The format of the OpenCacheView method is: % % CacheView *OpenCacheView(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheView *OpenCacheView(const Image *image) { return(AcquireVirtualCacheView(image,&((Image *) image)->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p e n M a g i c k S t r e a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenMagickStream() opens the file at the specified path and return the % associated stream. % % The path of the OpenMagickStream method is: % % FILE *OpenMagickStream(const char *path,const char *mode) % % A description of each parameter follows. % % o path: the file path. % % o mode: the file mode. % */ #if defined(MAGICKCORE_HAVE__WFOPEN) static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16) { register const unsigned char *p; if (utf16 != (wchar_t *) NULL) { register wchar_t *q; wchar_t c; /* Convert UTF-8 to UTF-16. */ q=utf16; for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) *q=(*p); else if ((*p & 0xE0) == 0xC0) { c=(*p); *q=(c & 0x1F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else if ((*p & 0xF0) == 0xE0) { c=(*p); *q=c << 12; p++; if ((*p & 0xC0) != 0x80) return(0); c=(*p); *q|=(c & 0x3F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else return(0); q++; } *q++='\0'; return(q-utf16); } /* Compute UTF-16 string length. */ for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) ; else if ((*p & 0xE0) == 0xC0) { p++; if ((*p & 0xC0) != 0x80) return(0); } else if ((*p & 0xF0) == 0xE0) { p++; if ((*p & 0xC0) != 0x80) return(0); p++; if ((*p & 0xC0) != 0x80) return(0); } else return(0); } return(p-utf8); } static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source) { size_t length; wchar_t *utf16; length=UTF8ToUTF16(source,(wchar_t *) NULL); if (length == 0) { register ssize_t i; /* Not UTF-8, just copy. */ length=strlen((const char *) source); utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); for (i=0; i <= (ssize_t) length; i++) utf16[i]=source[i]; return(utf16); } utf16=(wchar_t *) AcquireQuantumMemory(length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); length=UTF8ToUTF16(source,utf16); return(utf16); } #endif MagickExport FILE *OpenMagickStream(const char *path,const char *mode) { FILE *file; if ((path == (const char *) NULL) || (mode == (const char *) NULL)) { errno=EINVAL; return((FILE *) NULL); } file=(FILE *) NULL; #if defined(MAGICKCORE_HAVE__WFOPEN) { wchar_t *unicode_mode, *unicode_path; unicode_path=ConvertUTF8ToUTF16((const unsigned char *) path); if (unicode_path == (wchar_t *) NULL) return((FILE *) NULL); unicode_mode=ConvertUTF8ToUTF16((const unsigned char *) mode); if (unicode_mode == (wchar_t *) NULL) { unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path); return((FILE *) NULL); } file=_wfopen(unicode_path,unicode_mode); unicode_mode=(wchar_t *) RelinquishMagickMemory(unicode_mode); unicode_path=(wchar_t *) RelinquishMagickMemory(unicode_path); } #endif if (file == (FILE *) NULL) file=fopen(path,mode); return(file); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P a i n t F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PaintFloodfill() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. % However, in many cases two colors may differ by a small amount. The % fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now % interpreted as the same color for the purposes of the floodfill. % % Deprecated, replace with: % % FloodfillPaintImage(image,channel,draw_info,target,x,y, % method == FloodfillMethod ? MagickFalse : MagickTrue); % % The format of the PaintFloodfillImage method is: % % MagickBooleanType PaintFloodfillImage(Image *image, % const ChannelType channel,const MagickPixelPacket target, % const ssize_t x,const ssize_t y,const DrawInfo *draw_info, % const PaintMethod method) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o target: the RGB value of the target color. % % o x,y: the starting location of the operation. % % o draw_info: the draw info. % % o method: Choose either FloodfillMethod or FillToBorderMethod. % */ MagickExport MagickBooleanType PaintFloodfillImage(Image *image, const ChannelType channel,const MagickPixelPacket *target,const ssize_t x, const ssize_t y,const DrawInfo *draw_info,const PaintMethod method) { MagickBooleanType status; status=FloodfillPaintImage(image,channel,draw_info,target,x,y, method == FloodfillMethod ? MagickFalse : MagickTrue); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % P a i n t O p a q u e I m a g e % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PaintOpaqueImage() changes any pixel that matches color with the color % defined by fill. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % Deprecated, replace with: % % OpaquePaintImageChannel(image,DefaultChannels,target,fill,MagickFalse); % OpaquePaintImageChannel(image,channel,target,fill,MagickFalse); % % The format of the PaintOpaqueImage method is: % % MagickBooleanType PaintOpaqueImage(Image *image, % const PixelPacket *target,const PixelPacket *fill) % MagickBooleanType PaintOpaqueImageChannel(Image *image, % const ChannelType channel,const PixelPacket *target, % const PixelPacket *fill) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel(s). % % o target: the RGB value of the target color. % % o fill: the replacement color. % */ MagickExport MagickBooleanType PaintOpaqueImage(Image *image, const MagickPixelPacket *target,const MagickPixelPacket *fill) { MagickBooleanType status; status=OpaquePaintImageChannel(image,DefaultChannels,target,fill,MagickFalse); return(status); } MagickExport MagickBooleanType PaintOpaqueImageChannel(Image *image, const ChannelType channel,const MagickPixelPacket *target, const MagickPixelPacket *fill) { return(OpaquePaintImageChannel(image,channel,target,fill,MagickFalse)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P a i n t T r a n s p a r e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PaintTransparentImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % Deprecated, replace with: % % TransparentPaintImage(image,target,opacity,MagickFalse); % % The format of the PaintTransparentImage method is: % % MagickBooleanType PaintTransparentImage(Image *image, % const MagickPixelPacket *target,const Quantum opacity) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o opacity: the replacement opacity value. % */ MagickExport MagickBooleanType PaintTransparentImage(Image *image, const MagickPixelPacket *target,const Quantum opacity) { return(TransparentPaintImage(image,target,opacity,MagickFalse)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P a r s e I m a g e G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ParseImageGeometry() is similar to GetGeometry() except the returned % geometry is modified as determined by the meta characters: %, !, <, % and >. % % Deprecated, replace with: % % ParseMetaGeometry(geometry,x,y,width,height); % % The format of the ParseImageGeometry method is: % % int ParseImageGeometry(char *geometry,ssize_t *x,ssize_t *y, % size_t *width,size_t *height) % % A description of each parameter follows: % % o flags: Method ParseImageGeometry returns a bitmask that indicates % which of the four values were located in the geometry string. % % o image_geometry: Specifies a character string representing the geometry % specification. % % o x,y: A pointer to an integer. The x and y offset as determined by % the geometry specification is returned here. % % o width,height: A pointer to an unsigned integer. The width and height % as determined by the geometry specification is returned here. % */ MagickExport int ParseImageGeometry(const char *geometry,ssize_t *x,ssize_t *y, size_t *width,size_t *height) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); return((int) ParseMetaGeometry(geometry,x,y,width,height)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P a r s e S i z e G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ParseSizeGeometry() returns a region as defined by the geometry string with % respect to the image dimensions and aspect ratio. % % Deprecated, replace with: % % ParseMetaGeometry(geometry,&region_info->x,&region_info->y, % &region_info->width,&region_info->height); % % The format of the ParseSizeGeometry method is: % % MagickStatusType ParseSizeGeometry(const Image *image, % const char *geometry,RectangeInfo *region_info) % % A description of each parameter follows: % % o geometry: The geometry (e.g. 100x100+10+10). % % o region_info: the region as defined by the geometry string. % */ MagickExport MagickStatusType ParseSizeGeometry(const Image *image, const char *geometry,RectangleInfo *region_info) { MagickStatusType flags; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.4.7"); SetGeometry(image,region_info); flags=ParseMetaGeometry(geometry,&region_info->x,&region_info->y, &region_info->width,&region_info->height); return(flags); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o p I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PopImageList() removes the last image in the list. % % Deprecated, replace with: % % RemoveLastImageFromList(images); % % The format of the PopImageList method is: % % Image *PopImageList(Image **images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *PopImageList(Image **images) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(RemoveLastImageFromList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o p I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PopImagePixels() transfers one or more pixel components from the image pixel % cache to a user supplied buffer. The pixels are returned in network byte % order. MagickTrue is returned if the pixels are successfully transferred, % otherwise MagickFalse. % % The format of the PopImagePixels method is: % % size_t PopImagePixels(Image *,const QuantumType quantum, % unsigned char *destination) % % A description of each parameter follows: % % o image: the image. % % o quantum: Declare which pixel components to transfer (RGB, RGBA, etc). % % o destination: The components are transferred to this buffer. % */ MagickExport size_t PopImagePixels(Image *image,const QuantumType quantum, unsigned char *destination) { QuantumInfo *quantum_info; size_t length; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) return(0); length=ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info, quantum,destination,&image->exception); quantum_info=DestroyQuantumInfo(quantum_info); return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o s t s c r i p t G e o m e t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PostscriptGeometry() replaces any page mneumonic with the equivalent size in % picas. % % Deprecated, replace with: % % GetPageGeometry(page); % % The format of the PostscriptGeometry method is: % % char *PostscriptGeometry(const char *page) % % A description of each parameter follows. % % o page: Specifies a pointer to an array of characters. % The string is either a Postscript page name (e.g. A4) or a postscript % page geometry (e.g. 612x792+36+36). % */ MagickExport char *PostscriptGeometry(const char *page) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); return(GetPageGeometry(page)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P u s h I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PushImageList() adds an image to the end of the list. % % Deprecated, replace with: % % AppendImageToList(images,CloneImageList(image,exception)); % % The format of the PushImageList method is: % % unsigned int PushImageList(Image *images,const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int PushImageList(Image **images,const Image *image, ExceptionInfo *exception) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); AppendImageToList(images,CloneImageList(image,exception)); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P u s h I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PushImagePixels() transfers one or more pixel components from a user % supplied buffer into the image pixel cache of an image. The pixels are % expected in network byte order. It returns MagickTrue if the pixels are % successfully transferred, otherwise MagickFalse. % % The format of the PushImagePixels method is: % % size_t PushImagePixels(Image *image,const QuantumType quantum, % const unsigned char *source) % % A description of each parameter follows: % % o image: the image. % % o quantum: Declare which pixel components to transfer (red, green, blue, % opacity, RGB, or RGBA). % % o source: The pixel components are transferred from this buffer. % */ MagickExport size_t PushImagePixels(Image *image,const QuantumType quantum, const unsigned char *source) { QuantumInfo *quantum_info; size_t length; quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image); if (quantum_info == (QuantumInfo *) NULL) return(0); length=ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,quantum, source,&image->exception); quantum_info=DestroyQuantumInfo(quantum_info); return(length); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z a t i o n E r r o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizationError() measures the difference between the original and % quantized images. This difference is the total quantization error. The % error is computed by summing over all pixels in an image the distance % squared in RGB space between each reference pixel value and its quantized % value. These values are computed: % % o mean_error_per_pixel: This value is the mean error for any single % pixel in the image. % % o normalized_mean_square_error: This value is the normalized mean % quantization error for any single pixel in the image. This distance % measure is normalized to a range between 0 and 1. It is independent % of the range of red, green, and blue values in the image. % % o normalized_maximum_square_error: Thsi value is the normalized % maximum quantization error for any single pixel in the image. This % distance measure is normalized to a range between 0 and 1. It is % independent of the range of red, green, and blue values in your image. % % Deprecated, replace with: % % GetImageQuantizeError(image); % % The format of the QuantizationError method is: % % unsigned int QuantizationError(Image *image) % % A description of each parameter follows. % % o image: Specifies a pointer to an Image structure; returned from % ReadImage. % */ MagickExport unsigned int QuantizationError(Image *image) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.3"); return(GetImageQuantizeError(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % R a n d o m C h a n n e l T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomChannelThresholdImage() changes the value of individual pixels based % on the intensity of each pixel compared to a random threshold. The result % is a low-contrast, two color image. % % The format of the RandomChannelThresholdImage method is: % % unsigned int RandomChannelThresholdImage(Image *image, % const char *channel, const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing LOWxHIGH thresholds. % If the string contains 2x2, 3x3, or 4x4, then an ordered % dither of order 2, 3, or 4 will be performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int RandomChannelThresholdImage(Image *image,const char *channel,const char *thresholds,ExceptionInfo *exception) { #define RandomChannelThresholdImageText " RandomChannelThreshold image... " double lower_threshold, upper_threshold; RandomInfo *random_info; ssize_t count, y; static MagickRealType o2[4]={0.2f, 0.6f, 0.8f, 0.4f}, o3[9]={0.1f, 0.6f, 0.3f, 0.7f, 0.5f, 0.8f, 0.4f, 0.9f, 0.2f}, o4[16]={0.1f, 0.7f, 1.1f, 0.3f, 1.0f, 0.5f, 1.5f, 0.8f, 1.4f, 1.6f, 0.6f, 1.2f, 0.4f, 0.9f, 1.3f, 0.2f}, threshold=128; size_t order; /* Threshold image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (thresholds == (const char *) NULL) return(MagickTrue); if (LocaleCompare(thresholds,"2x2") == 0) order=2; else if (LocaleCompare(thresholds,"3x3") == 0) order=3; else if (LocaleCompare(thresholds,"4x4") == 0) order=4; else { order=1; lower_threshold=0; upper_threshold=0; count=(ssize_t) sscanf(thresholds,"%lf[/x%%]%lf",&lower_threshold, &upper_threshold); if (strchr(thresholds,'%') != (char *) NULL) { upper_threshold*=(.01*QuantumRange); lower_threshold*=(.01*QuantumRange); } if (count == 1) upper_threshold=(MagickRealType) QuantumRange-lower_threshold; } if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " RandomChannelThresholdImage: channel type=%s",channel); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Thresholds: %s (%fx%f)",thresholds,lower_threshold,upper_threshold); if (LocaleCompare(channel,"all") == 0 || LocaleCompare(channel,"intensity") == 0) if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfo(); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register IndexPacket index, *restrict indexes; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (LocaleCompare(channel,"all") == 0 || LocaleCompare(channel,"intensity") == 0) { indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType intensity; intensity=GetPixelIntensity(image,q); if (order == 1) { if (intensity < lower_threshold) threshold=lower_threshold; else if (intensity > upper_threshold) threshold=upper_threshold; else threshold=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info)); } else if (order == 2) threshold=(MagickRealType) QuantumRange*o2[(x%2)+2*(y%2)]; else if (order == 3) threshold=(MagickRealType) QuantumRange*o3[(x%3)+3*(y%3)]; else if (order == 4) threshold=(MagickRealType) QuantumRange*o4[(x%4)+4*(y%4)]; index=(IndexPacket) (intensity <= threshold ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } if (LocaleCompare(channel,"opacity") == 0 || LocaleCompare(channel,"all") == 0 || LocaleCompare(channel,"matte") == 0) { if (image->matte != MagickFalse) for (x=0; x < (ssize_t) image->columns; x++) { if (order == 1) { if ((MagickRealType) q->opacity < lower_threshold) threshold=lower_threshold; else if ((MagickRealType) q->opacity > upper_threshold) threshold=upper_threshold; else threshold=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info)); } else if (order == 2) threshold=(MagickRealType) QuantumRange*o2[(x%2)+2*(y%2)]; else if (order == 3) threshold=(MagickRealType) QuantumRange*o3[(x%3)+3*(y%3)]; else if (order == 4) threshold=(MagickRealType) QuantumRange*o4[(x%4)+4*(y%4)]/1.7; SetPixelOpacity(q,(MagickRealType) q->opacity <= threshold ? 0 : QuantumRange); q++; } } else { /* To Do: red, green, blue, cyan, magenta, yellow, black */ if (LocaleCompare(channel,"intensity") != 0) ThrowBinaryException(OptionError,"UnrecognizedChannelType", image->filename); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } random_info=DestroyRandomInfo(random_info); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a c q u i r e M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReacquireMemory() changes the size of the memory and returns a pointer to % the (possibly moved) block. The contents will be unchanged up to the % lesser of the new and old sizes. % % The format of the ReacquireMemory method is: % % void ReacquireMemory(void **memory,const size_t size) % % A description of each parameter follows: % % o memory: A pointer to a memory allocation. On return the pointer % may change but the contents of the original allocation will not. % % o size: the new size of the allocated memory. % */ MagickExport void ReacquireMemory(void **memory,const size_t size) { void *allocation; assert(memory != (void **) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (*memory == (void *) NULL) { *memory=AcquireMagickMemory(size); return; } allocation=realloc(*memory,size); if (allocation == (void *) NULL) *memory=RelinquishMagickMemory(*memory); *memory=allocation; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e c o l o r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RecolorImage() apply color transformation to an image. The method permits % saturation changes, hue rotation, luminance to alpha, and various other % effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the RecolorImage method is: % % Image *RecolorImage(const Image *image,const size_t order, % const double *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o order: the number of columns and rows in the recolor matrix. % % o color_matrix: An array of double representing the recolor matrix. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *RecolorImage(const Image *image,const size_t order, const double *color_matrix,ExceptionInfo *exception) { KernelInfo *kernel_info; Image *recolor_image; kernel_info=AcquireKernelInfo("1"); if (kernel_info == (KernelInfo *) NULL) return((Image *) NULL); kernel_info->width=order; kernel_info->height=order; kernel_info->values=(double *) color_matrix; recolor_image=ColorMatrixImage(image,kernel_info,exception); kernel_info->values=(double *) NULL; kernel_info=DestroyKernelInfo(kernel_info); return(recolor_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e d u c e N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReduceNoiseImage() smooths the contours of an image while still preserving % edge information. The algorithm works by replacing each pixel with its % neighbor closest in value. A neighbor is defined by radius. Use a radius % of 0 and ReduceNoise() selects a suitable radius for you. % % The format of the ReduceNoiseImage method is: % % Image *ReduceNoiseImage(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 *ReduceNoiseImage(const Image *image,const double radius, ExceptionInfo *exception) { Image *reduce_image; reduce_image=StatisticImage(image,NonpeakStatistic,(size_t) radius,(size_t) radius,exception); return(reduce_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e A t t r i b u t e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageAttributeIterator() resets the image attributes iterator. Use it % in conjunction with GetNextImageAttribute() to iterate over all the values % associated with an image. % % Deprecated, replace with: % % ResetImagePropertyIterator(image); % % The format of the ResetImageAttributeIterator method is: % % ResetImageAttributeIterator(const ImageInfo *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageAttributeIterator(const Image *image) { ResetImagePropertyIterator(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetCacheViewPixels() gets pixels from the in-memory or disk pixel cache as % defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % Deprecated, replace with: % % QueueCacheViewAuthenticPixels(cache_view,x,y,columns,rows, % GetCacheViewException(cache_view)); % % The format of the SetCacheViewPixels method is: % % PixelPacket *SetCacheViewPixels(CacheView *cache_view,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows) % % A description of each parameter follows: % % o cache_view: the cache view. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *SetCacheViewPixels(CacheView *cache_view,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows) { PixelPacket *pixels; pixels=QueueCacheViewAuthenticPixels(cache_view,x,y,columns,rows, GetCacheViewException(cache_view)); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t C a c h e T h e s h o l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetCacheThreshold() sets the amount of free memory allocated for the pixel % cache. Once this threshold is exceeded, all subsequent pixels cache % operations are to/from disk. % % The format of the SetCacheThreshold() method is: % % void SetCacheThreshold(const size_t threshold) % % A description of each parameter follows: % % o threshold: the number of megabytes of memory available to the pixel % cache. % */ MagickExport void SetCacheThreshold(const size_t size) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.1"); (void) SetMagickResourceLimit(MemoryResource,size*1024*1024); (void) SetMagickResourceLimit(MapResource,2*size*1024*1024); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t E x c e p t i o n I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetExceptionInfo() sets the exception severity. % % The format of the SetExceptionInfo method is: % % MagickBooleanType SetExceptionInfo(ExceptionInfo *exception, % ExceptionType severity) % % A description of each parameter follows: % % o exception: the exception info. % % o severity: the exception severity. % */ MagickExport MagickBooleanType SetExceptionInfo(ExceptionInfo *exception, ExceptionType severity) { assert(exception != (ExceptionInfo *) NULL); ClearMagickException(exception); exception->severity=severity; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImage() sets the red, green, and blue components of each pixel to % the image background color and the opacity component to the specified % level of transparency. The background color is defined by the % background_color member of the image. % % The format of the SetImage method is: % % void SetImage(Image *image,const Quantum opacity) % % A description of each parameter follows: % % o image: the image. % % o opacity: Set each pixel to this level of transparency. % */ MagickExport void SetImage(Image *image,const Quantum opacity) { PixelPacket background_color; ssize_t y; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.0"); assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); background_color=image->background_color; if (opacity != OpaqueOpacity) background_color.opacity=opacity; if (background_color.opacity != OpaqueOpacity) { (void) SetImageStorageClass(image,DirectClass); image->matte=MagickTrue; } if ((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) { /* Set colormapped or CMYK image. */ for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRGBO(q,&background_color); q++; } indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,0); if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } return; } /* Set DirectClass image. */ for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRGBO(q,&background_color); q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageAttribute() searches the list of image attributes and replaces the % attribute value. If it is not found in the list, the attribute name % and value is added to the list. % % Deprecated, replace with: % % SetImageProperty(image,key,value); % % The format of the SetImageAttribute method is: % % MagickBooleanType SetImageAttribute(Image *image,const char *key, % const char *value) % % A description of each parameter follows: % % o image: the image. % % o key: the key. % % o value: the value. % */ MagickExport MagickBooleanType SetImageAttribute(Image *image,const char *key, const char *value) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.3.1"); return(SetImageProperty(image,key,value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageList() inserts an image into the list at the specified position. % % The format of the SetImageList method is: % % unsigned int SetImageList(Image *images,const Image *image, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o image: the image. % % o offset: the position within the list. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int SetImageList(Image **images,const Image *image, const ssize_t offset,ExceptionInfo *exception) { Image *clone; register ssize_t i; (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); clone=CloneImageList(image,exception); while (GetPreviousImageInList(*images) != (Image *) NULL) (*images)=GetPreviousImageInList(*images); for (i=0; i < offset; i++) { if (GetNextImageInList(*images) == (Image *) NULL) return(MagickFalse); (*images)=GetNextImageInList(*images); } InsertImageInList(images,clone); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImagePixels() queues a mutable pixel region. % If the region is successfully initialized a pointer to a PixelPacket % array representing the region is returned, otherwise NULL is returned. % The returned pointer may point to a temporary working buffer for the % pixels or it may point to the final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This useful while the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % SetImagePixels() any way it pleases. SetImagePixels() does not initialize % the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in RAM, or in a % memory-mapped file. The returned pointer should *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to obtain % the black color component or the colormap indexes (of type IndexPacket) % corresponding to the region. Once the PixelPacket (and/or IndexPacket) % array has been updated, the changes must be saved back to the underlying % image using SyncAuthenticPixels() or they may be lost. % % Deprecated, replace with: % % QueueAuthenticPixels(image,x,y,columns,rows,&image->exception); % % The format of the SetImagePixels() method is: % % PixelPacket *SetImagePixels(Image *image,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows) % % A description of each parameter follows: % % o pixels: SetImagePixels returns a pointer to the pixels if they are % transferred, otherwise a NULL is returned. % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % */ MagickExport PixelPacket *SetImagePixels(Image *image,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows) { return(QueueAuthenticPixels(image,x,y,columns,rows,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M a g i c k R e g i s t r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMagickRegistry() sets a blob into the registry and returns a unique ID. % If an error occurs, -1 is returned. % % The format of the SetMagickRegistry method is: % % ssize_t SetMagickRegistry(const RegistryType type,const void *blob, % const size_t length,ExceptionInfo *exception) % % A description of each parameter follows: % % o type: the registry type. % % o blob: the address of a Binary Large OBject. % % o length: For a registry type of ImageRegistryType use sizeof(Image) % otherise the blob length in number of bytes. % % o exception: return any errors or warnings in this structure. % */ MagickExport ssize_t SetMagickRegistry(const RegistryType type,const void *blob, const size_t magick_unused(length),ExceptionInfo *exception) { char key[MaxTextExtent]; MagickBooleanType status; static ssize_t id = 0; (void) FormatLocaleString(key,MaxTextExtent,"%.20g\n",(double) id); status=SetImageRegistry(type,key,blob,exception); if (status == MagickFalse) return(-1); return(id++); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M o n i t o r H a n d l e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMonitorHandler() sets the monitor handler to the specified method % and returns the previous monitor handler. % % The format of the SetMonitorHandler method is: % % MonitorHandler SetMonitorHandler(MonitorHandler handler) % % A description of each parameter follows: % % o handler: Specifies a pointer to a method to handle monitors. % */ MagickExport MonitorHandler GetMonitorHandler(void) { return(monitor_handler); } MagickExport MonitorHandler SetMonitorHandler(MonitorHandler handler) { MonitorHandler previous_handler; previous_handler=monitor_handler; monitor_handler=handler; return(previous_handler); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h i f t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShiftImageList() removes an image from the beginning of the list. % % Deprecated, replace with: % % RemoveFirstImageFromList(images); % % The format of the ShiftImageList method is: % % Image *ShiftImageList(Image **images) % % A description of each parameter follows: % % o images: the image list. % */ MagickExport Image *ShiftImageList(Image **images) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); return(RemoveFirstImageFromList(images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S i z e B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SizeBlob() returns the current length of the image file or blob. % % Deprecated, replace with: % % GetBlobSize(image); % % The format of the SizeBlob method is: % % off_t SizeBlob(Image *image) % % A description of each parameter follows: % % o size: Method SizeBlob returns the current length of the image file % or blob. % % o image: the image. % */ MagickExport MagickOffsetType SizeBlob(Image *image) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.4.3"); return((MagickOffsetType) GetBlobSize(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p l i c e I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpliceImageList() removes the images designated by offset and length from % the list and replaces them with the specified list. % % The format of the SpliceImageList method is: % % Image *SpliceImageList(Image *images,const ssize_t offset, % const size_t length,const Image *splices, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o offset: the position within the list. % % o length: the length of the image list to remove. % % o splice: Replace the removed image list with this list. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpliceImageList(Image *images,const ssize_t offset, const size_t length,const Image *splices,ExceptionInfo *exception) { Image *clone; register ssize_t i; if (images->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); clone=CloneImageList(splices,exception); while (GetPreviousImageInList(images) != (Image *) NULL) images=GetPreviousImageInList(images); for (i=0; i < offset; i++) { if (GetNextImageInList(images) == (Image *) NULL) return((Image *) NULL); images=GetNextImageInList(images); } (void) SpliceImageIntoList(&images,length,clone); return(images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % s R G B C o m p a n d o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % sRGBCompandor() adds the gamma function to a sRGB pixel. % % The format of the sRGBCompandor method is: % % MagickRealType sRGBCompandor(const MagickRealType pixel) % % A description of each parameter follows: % % o pixel: the pixel. % */ MagickExport MagickRealType sRGBCompandor(const MagickRealType pixel) { if (pixel <= (0.0031306684425005883*QuantumRange)) return(12.92*pixel); return(QuantumRange*(1.055*pow(QuantumScale*pixel,1.0/2.4)-0.055)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t r i p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Strip() strips any whitespace or quotes from the beginning and end of a % string of characters. % % The format of the Strip method is: % % void Strip(char *message) % % A description of each parameter follows: % % o message: Specifies an array of characters. % */ MagickExport void Strip(char *message) { register char *p, *q; assert(message != (char *) NULL); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (*message == '\0') return; if (strlen(message) == 1) return; p=message; while (isspace((int) ((unsigned char) *p)) != 0) p++; if ((*p == '\'') || (*p == '"')) p++; q=message+strlen(message)-1; while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p)) q--; if (q > p) if ((*q == '\'') || (*q == '"')) q--; (void) CopyMagickMemory(message,p,(size_t) (q-p+1)); message[q-p+1]='\0'; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c C a c h e V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncCacheView() saves the cache view pixels to the in-memory or disk % cache. It returns MagickTrue if the pixel region is synced, otherwise % MagickFalse. % % Deprecated, replace with: % % SyncCacheViewAuthenticPixels(cache_view,GetCacheViewException(cache_view)); % % The format of the SyncCacheView method is: % % MagickBooleanType SyncCacheView(CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % */ MagickExport MagickBooleanType SyncCacheView(CacheView *cache_view) { MagickBooleanType status; status=SyncCacheViewAuthenticPixels(cache_view, GetCacheViewException(cache_view)); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c C a c h e V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncCacheViewPixels() saves the cache view pixels to the in-memory % or disk cache. It returns MagickTrue if the pixel region is flushed, % otherwise MagickFalse. % % Deprecated, replace with: % % SyncCacheViewAuthenticPixels(cache_view,GetCacheViewException(cache_view)); % % The format of the SyncCacheViewPixels method is: % % MagickBooleanType SyncCacheViewPixels(CacheView *cache_view) % % A description of each parameter follows: % % o cache_view: the cache view. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncCacheViewPixels(CacheView *cache_view) { MagickBooleanType status; status=SyncCacheViewAuthenticPixels(cache_view, GetCacheViewException(cache_view)); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is synced, otherwise % MagickFalse. % % Deprecated, replace with: % % SyncAuthenticPixels(image,&image->exception); % % The format of the SyncImagePixels() method is: % % MagickBooleanType SyncImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType SyncImagePixels(Image *image) { return(SyncAuthenticPixels(image,&image->exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e m p o r a r y F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TemporaryFilename() replaces the contents of path by a unique path name. % % The format of the TemporaryFilename method is: % % void TemporaryFilename(char *path) % % A description of each parameter follows. % % o path: Specifies a pointer to an array of characters. The unique path % name is returned in this array. % */ MagickExport void TemporaryFilename(char *path) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.6"); (void) AcquireUniqueFilename(path); (void) RelinquishUniqueFileResource(path); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThresholdImage() changes the value of individual pixels based on % the intensity of each pixel compared to threshold. The result is a % high-contrast, two color image. % % The format of the ThresholdImage method is: % % unsigned int ThresholdImage(Image *image,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the threshold value % */ MagickExport unsigned int ThresholdImage(Image *image,const double threshold) { #define ThresholdImageTag "Threshold/Image" IndexPacket index; ssize_t y; /* Threshold image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.7"); if (!AcquireImageColormap(image,2)) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", "UnableToThresholdImage"); for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=(IndexPacket) (GetPixelIntensity(image,q) <= threshold ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (!SyncAuthenticPixels(image,&image->exception)) break; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h r e s h o l d I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThresholdImageChannel() changes the value of individual pixels based on % the intensity of each pixel channel. The result is a high-contrast image. % % The format of the ThresholdImageChannel method is: % % unsigned int ThresholdImageChannel(Image *image,const char *threshold) % % A description of each parameter follows: % % o image: the image. % % o threshold: define the threshold values. % */ MagickExport unsigned int ThresholdImageChannel(Image *image, const char *threshold) { #define ThresholdImageTag "Threshold/Image" MagickPixelPacket pixel; GeometryInfo geometry_info; IndexPacket index; ssize_t y; unsigned int flags; /* Threshold image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (threshold == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(threshold,&geometry_info); pixel.red=geometry_info.rho; if (flags & SigmaValue) pixel.green=geometry_info.sigma; else pixel.green=pixel.red; if (flags & XiValue) pixel.blue=geometry_info.xi; else pixel.blue=pixel.red; if (flags & PsiValue) pixel.opacity=geometry_info.psi; else pixel.opacity=(MagickRealType) OpaqueOpacity; if (flags & PercentValue) { pixel.red*=QuantumRange/100.0f; pixel.green*=QuantumRange/100.0f; pixel.blue*=QuantumRange/100.0f; pixel.opacity*=QuantumRange/100.0f; } if (!(flags & SigmaValue)) { if (!AcquireImageColormap(image,2)) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", "UnableToThresholdImage"); if (pixel.red == 0) (void) GetImageDynamicThreshold(image,2.0,2.0,&pixel,&image->exception); } for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (IsMagickGray(&pixel) != MagickFalse) for (x=0; x < (ssize_t) image->columns; x++) { index=(IndexPacket) (GetPixelIntensity(image,q) <= pixel.red ? 0 : 1); SetPixelIndex(indexes+x,index); SetPixelRed(q,image->colormap[(ssize_t) index].red); SetPixelGreen(q,image->colormap[(ssize_t) index].green); SetPixelBlue(q,image->colormap[(ssize_t) index].blue); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,(MagickRealType) q->red <= pixel.red ? 0 : QuantumRange); SetPixelGreen(q,(MagickRealType) q->green <= pixel.green ? 0 : QuantumRange); SetPixelBlue(q,(MagickRealType) q->blue <= pixel.blue ? 0 : QuantumRange); SetPixelOpacity(q,(MagickRealType) q->opacity <= pixel.opacity ? 0 : QuantumRange); q++; } if (!SyncAuthenticPixels(image,&image->exception)) break; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a n s f o r m C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformColorspace() converts the image to a specified colorspace. % If the image is already in the requested colorspace, no work is performed. % Note that the current colorspace is stored in the image colorspace member. % The transformation matrices are not necessarily the standard ones: the % weights are rescaled to normalize the range of the transformed values to % be [0..QuantumRange]. % % Deprecated, replace with: % % TransformImageColorspace(image,colorspace); % % The format of the TransformColorspace method is: % % unsigned int (void) TransformColorspace(Image *image, % const ColorspaceType colorspace) % % A description of each parameter follows: % % o image: the image to transform % % o colorspace: the desired colorspace. % */ MagickExport unsigned int TransformColorspace(Image *image, const ColorspaceType colorspace) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.6"); return(TransformImageColorspace(image,colorspace)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m H S L % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformHSL() converts a (red, green, blue) to a (hue, saturation, % lightness) triple. % % The format of the TransformHSL method is: % % void TransformHSL(const Quantum red,const Quantum green, % const Quantum blue,double *hue,double *saturation,double *lightness) % % A description of each parameter follows: % % o red, green, blue: A Quantum value representing the red, green, and % blue component of a pixel.. % % o hue, saturation, lightness: A pointer to a double value representing a % component of the HSL color space. % */ static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } MagickExport void TransformHSL(const Quantum red,const Quantum green, const Quantum blue,double *hue,double *saturation,double *lightness) { MagickRealType b, delta, g, max, min, r; /* Convert RGB to HSL colorspace. */ assert(hue != (double *) NULL); assert(saturation != (double *) NULL); assert(lightness != (double *) NULL); r=QuantumScale*red; g=QuantumScale*green; b=QuantumScale*blue; max=MagickMax(r,MagickMax(g,b)); min=MagickMin(r,MagickMin(g,b)); *hue=0.0; *saturation=0.0; *lightness=(double) ((min+max)/2.0); delta=max-min; if (delta == 0.0) return; *saturation=(double) (delta/((*lightness < 0.5) ? (min+max) : (2.0-max-min))); if (r == max) *hue=(double) (g == min ? 5.0+(max-b)/delta : 1.0-(max-g)/delta); else if (g == max) *hue=(double) (b == min ? 1.0+(max-r)/delta : 3.0-(max-b)/delta); else *hue=(double) (r == min ? 3.0+(max-g)/delta : 5.0-(max-r)/delta); *hue/=6.0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s l a t e T e x t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TranslateText() replaces any embedded formatting characters with the % appropriate image attribute and returns the translated text. % % Deprecated, replace with: % % InterpretImageProperties(image_info,image,embed_text); % % The format of the TranslateText method is: % % char *TranslateText(const ImageInfo *image_info,Image *image, % const char *embed_text) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % % o embed_text: the address of a character string containing the embedded % formatting characters. % */ MagickExport char *TranslateText(const ImageInfo *image_info,Image *image, const char *embed_text) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.2.6"); return(InterpretImageProperties(image_info,image,embed_text)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. Fuzz defines % how much tolerance is acceptable to consider two colors as the same. % For example, set fuzz to 10 and the color red at intensities of 100 and % 102 respectively are now interpreted as the same color. % % The format of the TransparentImage method is: % % MagickBooleanType TransparentImage(Image *image, % const PixelPacket target,const Quantum opacity) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o opacity: the replacement opacity value. % */ MagickExport MagickBooleanType TransparentImage(Image *image, const PixelPacket target,const Quantum opacity) { #define TransparentImageTag "Transparent/Image" MagickBooleanType proceed; ssize_t y; /* Make image color transparent. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v6.1.0"); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *restrict q; q=GetAuthenticPixels(image,0,y,image->columns,1,&image->exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsColorSimilar(image,q,&target) != MagickFalse) q->opacity=opacity; q++; } if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) break; proceed=SetImageProgress(image,TransparentImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n s h i f t I m a g e L i s t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnshiftImageList() adds the image to the beginning of the list. % % Deprecated, replace with: % % PrependImageToList(images,CloneImageList(image,exception)); % % The format of the UnshiftImageList method is: % % unsigned int UnshiftImageList(Image *images,const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport unsigned int UnshiftImageList(Image **images,const Image *image, ExceptionInfo *exception) { (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.5.2"); PrependImageToList(images,CloneImageList(image,exception)); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + V a l i d a t e C o l o r m a p I n d e x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ValidateColormapIndex() validates the colormap index. If the index does % not range from 0 to the number of colors in the colormap an exception % issued and 0 is returned. % % Deprecated, replace with: % % ConstrainColormapIndex(image,index); % % The format of the ValidateColormapIndex method is: % % IndexPacket ValidateColormapIndex(Image *image,const unsigned int index) % % A description of each parameter follows: % % o index: Method ValidateColormapIndex returns colormap index if it is % valid other an exception issued and 0 is returned. % % o image: the image. % % o index: This integer is the colormap index. % */ MagickExport IndexPacket ValidateColormapIndex(Image *image, const size_t index) { if (image->debug != MagickFalse) (void) LogMagickEvent(DeprecateEvent,GetMagickModule(),"last use: v5.4.4"); return(ConstrainColormapIndex(image,index)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Z o o m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZoomImage() creates a new image that is a scaled size of an existing one. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. The Point filter gives fast pixel replication, % Triangle is equivalent to bi-linear interpolation, and Mitchel giver slower, % very high-quality results. See Graphic Gems III for details on this % algorithm. % % The filter member of the Image structure specifies which image filter to % use. Blur specifies the blur factor where > 1 is blurry, < 1 is sharp. % % The format of the ZoomImage method is: % % Image *ZoomImage(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: An integer that specifies the number of columns in the zoom % image. % % o rows: An integer that specifies the number of rows in the scaled % image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ZoomImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { Image *zoom_image; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); zoom_image=ResizeImage(image,columns,rows,image->filter,image->blur, exception); return(zoom_image); } #endif
parallel_if_parallel.c
#include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif int main() { int a, b, c; a = 0; #pragma omp parallel if (parallel : a == 0) if (a != 0) { printf("This is for testing parser and AST construction, which could be only syntax correct.\n"); } return 0; }
RungeKutta76.h
/* 7th and 6th order Runge-Kutta-Nystrom method as described in: J.R. Dormand & P.J. Prince (1978): New Runge-Kutta algorithms for numerical simulation in dynamical astronomy. Celestial Mechanics, Vol. 18, p. 223-232. Steps exceeding the maximum allowed error (e_target) will be repeated. */ int RungeKutta76(configuration_values *config_data, SpiceDouble *nstate, FILE *statefile) { // Create some variables int stepcount = 0, substepcount = 0, j = 0, k = 0, m = 0, interp_ret = 0; SpiceDouble h = 10000.0 // [s] (initial) step size , floating_stepcount = 0. // not strictly the step counter , hp2 // [s^2] h squared , tEps = config_data->e_target // [km] error allowed per step , tEps_p = 0.0; // [km] temporary storage of partial error per space dimension config_data->saving = 0; // Create body arrays and set initial body positions SpiceDouble **(body[9]); // body[0] is t = time[1] - h, body[1] is t = time[1], ..., body[8] is t = time[1] + h for (k = 0; k < 9; k++) { body[k] = (SpiceDouble **)malloc(config_data->N_bodys * sizeof(SpiceDouble *)); if (body[k] == NULL) { printf("\n\nerror: could not allocate body state array (OOM)"); return 1; } } for (j = 0; j < config_data->N_bodys; j++) { for (k = 0; k < 9; k++) { body[k][j] = (SpiceDouble *)malloc(6 * sizeof(SpiceDouble)); if (body[k][j] == NULL) { printf("\n\nerror: could not allocate body state array (OOM)"); return 1; } } #pragma omp critical(SPICE) { // Critical section is only executed on one thread at a time (spice is not threadsafe) get_body_state(config_data, j, &nstate[6], &body[8]); } } // Create some more variables SpiceDouble initPos[3], initVel[3], dir_SSB[3], time[9], dtime[9]; SpiceDouble f[9][3], sun_dist; // Body coefficient variable SpiceDouble **body_c[6]; // positions 4-6 may not be used for order = 2, or none for order = 0 // Allocate memory for coefficients if (interp_body_states_malloc(config_data, &body_c)) { return 1; // OOM } dtimepowers dtp; dtime[0] = 0; #ifdef __WSTEPINFO SpiceDouble hmin = config_data->final_time - nstate[6], hmax = 0.0, maxEps = 0; #endif // Integrate while (nstate[6] < config_data->final_time) { // Set initial state for this step initPos[0] = nstate[0]; initPos[1] = nstate[1]; initPos[2] = nstate[2]; initVel[0] = nstate[3]; initVel[1] = nstate[4]; initVel[2] = nstate[5]; time[1] = nstate[6]; for (j = 0; j < config_data->N_bodys; j++) { for (k = 0; k < 6; k++) { // Save previous body state (body[1] is only a useful value from the second step onwards) body[0][j][k] = body[1][j][k]; // Set new initial body state (body[8] is always a useful value) body[1][j][k] = body[8][j][k]; } } // F1 dir_SSB[0] = -(initPos[0]); dir_SSB[1] = -(initPos[1]); dir_SSB[2] = -(initPos[2]); calc_accel(config_data, dir_SSB, &body[1], f[0], initVel, 0.); if ((nstate[6] + h) > config_data->start_time_save) { if (config_data->saving != 1) { config_data->saving = 1; } #ifdef __SaveRateOpt // save rate optimization for close encounters with un-sunny bodies. if (calc_save_factor(config_data, dir_SSB, &body[1], f[0], initVel, 0.)) { printf("\n\nerror: Sun missing."); return 1; } #endif } // dtime: time difference compared to time[0] dtime[1] = time[1] - time[0]; do { // Set dynamic step size if (tEps > (config_data->e_target / 22.)) // do not increase the step size by more than a factor of 1.4 at a time { h = 0.9 * h * pow(config_data->e_target / tEps, 1. / 7); } else { h = h * 1.4; } // End integration on time if (config_data->endontime) { if (time[1] + h > config_data->final_time) { h = config_data->final_time - time[1]; } } // Calculate times dtime[2] = dtime[1] + h / 10.; dtime[3] = dtime[1] + h / 5.; dtime[4] = dtime[1] + 3. / 8. * h; dtime[5] = dtime[1] + h / 2.; dtime[6] = dtime[1] + h * ((7. - sqrt(21)) / 14.); dtime[7] = dtime[1] + h * ((7. + sqrt(21)) / 14.); dtime[8] = dtime[1] + h; precompute_dtime_powers(config_data, &dtp, dtime); for (j = 2; j < 9; j++) { time[j] = time[0] + dtime[j]; } // Get body positions // Instead of body[9], body[8] is just used below. They would always be identical. The same applies for dtime[8/9] and time[8/9] for (j = 0; j < config_data->N_bodys; j++) { if (stepcount > 1) // not during the first two steps { // Get new end state of body #pragma omp critical(SPICE) { get_body_state(config_data, j, &time[8], &body[8]); } // Interpolate body states interp_ret = interp_body_states(config_data, &body, &body_c, dtime, &dtp, h, j); if (interp_ret == 0) // all is well { ; } else if (interp_ret == 2) // cspice everything { #pragma omp critical(SPICE) // Critical section is only executed on one thread at a time (spice is not threadsafe) { for (m = 2; m < 8; m++) // body[8][j] already done above { get_body_state(config_data, j, &time[m], &body[m]); } } } } else // first step, no previous position available for interpolation -> get all body positions with SPICE { #pragma omp critical(SPICE) // Critical section is only executed on one thread at a time (spice is not threadsafe) { //printf("\nbefore: h = %.8le, time[1] = %.8le, tEpsMax = %.8le, tEps = %.8le ",h,time[1],tEpsMax,tEps); for (m = 2; m < 9; m++) { get_body_state(config_data, j, &time[m], &body[m]); } } } } hp2 = h * h; // F2 dir_SSB[0] = -(initPos[0] + h / 10 * initVel[0] + 1. / 200 * hp2 * f[0][0]); dir_SSB[1] = -(initPos[1] + h / 10 * initVel[1] + 1. / 200 * hp2 * f[0][1]); dir_SSB[2] = -(initPos[2] + h / 10 * initVel[2] + 1. / 200 * hp2 * f[0][2]); calc_accel(config_data, dir_SSB, &body[2], f[1], initVel, dtime[2] - dtime[1]); // F3 dir_SSB[0] = -(initPos[0] + h / 5 * initVel[0] + hp2 / 150 * (f[0][0] + 2 * f[1][0])); dir_SSB[1] = -(initPos[1] + h / 5 * initVel[1] + hp2 / 150 * (f[0][1] + 2 * f[1][1])); dir_SSB[2] = -(initPos[2] + h / 5 * initVel[2] + hp2 / 150 * (f[0][2] + 2 * f[1][2])); calc_accel(config_data, dir_SSB, &body[3], f[2], initVel, dtime[3] - dtime[1]); // F4 dir_SSB[0] = -(initPos[0] + 3. / 8. * h * initVel[0] + hp2 * (171. / 8192 * f[0][0] + 45. / 4096 * f[1][0] + 315. / 8192 * f[2][0])); dir_SSB[1] = -(initPos[1] + 3. / 8. * h * initVel[1] + hp2 * (171. / 8192 * f[0][1] + 45. / 4096 * f[1][1] + 315. / 8192 * f[2][1])); dir_SSB[2] = -(initPos[2] + 3. / 8. * h * initVel[2] + hp2 * (171. / 8192 * f[0][2] + 45. / 4096 * f[1][2] + 315. / 8192 * f[2][2])); calc_accel(config_data, dir_SSB, &body[4], f[3], initVel, dtime[4] - dtime[1]); // F5 dir_SSB[0] = -(initPos[0] + h / 2 * initVel[0] + hp2 * (5. / 288 * f[0][0] + 25. / 528 * f[1][0] + 25. / 672 * f[2][0] + 16. / 693 * f[3][0])); dir_SSB[1] = -(initPos[1] + h / 2 * initVel[1] + hp2 * (5. / 288 * f[0][1] + 25. / 528 * f[1][1] + 25. / 672 * f[2][1] + 16. / 693 * f[3][1])); dir_SSB[2] = -(initPos[2] + h / 2 * initVel[2] + hp2 * (5. / 288 * f[0][2] + 25. / 528 * f[1][2] + 25. / 672 * f[2][2] + 16. / 693 * f[3][2])); calc_accel(config_data, dir_SSB, &body[5], f[4], initVel, dtime[5] - dtime[1]); // F6 dir_SSB[0] = -(initPos[0] + (7. - sqrt(21)) * h / 14 * initVel[0] + hp2 * ((1003. - 205. * sqrt(21)) / 12348 * f[0][0] - 25. * (751. - 173. * sqrt(21)) / 90552 * f[1][0] + 25. * (624. - 137. * sqrt(21)) / 43218 * f[2][0] - 128. * (361. - 79. * sqrt(21)) / 237699 * f[3][0] + (3411. - 745. * sqrt(21)) / 24696 * f[4][0])); dir_SSB[1] = -(initPos[1] + (7. - sqrt(21)) * h / 14 * initVel[1] + hp2 * ((1003. - 205. * sqrt(21)) / 12348 * f[0][1] - 25. * (751. - 173. * sqrt(21)) / 90552 * f[1][1] + 25. * (624. - 137. * sqrt(21)) / 43218 * f[2][1] - 128. * (361. - 79. * sqrt(21)) / 237699 * f[3][1] + (3411. - 745. * sqrt(21)) / 24696 * f[4][1])); dir_SSB[2] = -(initPos[2] + (7. - sqrt(21)) * h / 14 * initVel[2] + hp2 * ((1003. - 205. * sqrt(21)) / 12348 * f[0][2] - 25. * (751. - 173. * sqrt(21)) / 90552 * f[1][2] + 25. * (624. - 137. * sqrt(21)) / 43218 * f[2][2] - 128. * (361. - 79. * sqrt(21)) / 237699 * f[3][2] + (3411. - 745. * sqrt(21)) / 24696 * f[4][2])); calc_accel(config_data, dir_SSB, &body[6], f[5], initVel, dtime[6] - dtime[1]); // F7 dir_SSB[0] = -(initPos[0] + (7. + sqrt(21)) * h / 14 * initVel[0] + hp2 * ((793. + 187. * sqrt(21)) / 12348 * f[0][0] - 25. * (331. + 113. * sqrt(21)) / 90552 * f[1][0] + 25. * (1044. + 247. * sqrt(21)) / 43218 * f[2][0] - 128. * (14885. + 3779. * sqrt(21)) / 9745659 * f[3][0] + (3327. + 797. * sqrt(21)) / 24696 * f[4][0] - (581. + 127. * sqrt(21)) / 1722 * f[5][0])); dir_SSB[1] = -(initPos[1] + (7. + sqrt(21)) * h / 14 * initVel[1] + hp2 * ((793. + 187. * sqrt(21)) / 12348 * f[0][1] - 25. * (331. + 113. * sqrt(21)) / 90552 * f[1][1] + 25. * (1044. + 247. * sqrt(21)) / 43218 * f[2][1] - 128. * (14885. + 3779. * sqrt(21)) / 9745659 * f[3][1] + (3327. + 797. * sqrt(21)) / 24696 * f[4][1] - (581. + 127. * sqrt(21)) / 1722 * f[5][1])); dir_SSB[2] = -(initPos[2] + (7. + sqrt(21)) * h / 14 * initVel[2] + hp2 * ((793. + 187. * sqrt(21)) / 12348 * f[0][2] - 25. * (331. + 113. * sqrt(21)) / 90552 * f[1][2] + 25. * (1044. + 247. * sqrt(21)) / 43218 * f[2][2] - 128. * (14885. + 3779. * sqrt(21)) / 9745659 * f[3][2] + (3327. + 797. * sqrt(21)) / 24696 * f[4][2] - (581. + 127. * sqrt(21)) / 1722 * f[5][2])); calc_accel(config_data, dir_SSB, &body[7], f[6], initVel, dtime[7] - dtime[1]); // F8 dir_SSB[0] = -(initPos[0] + h * initVel[0] + hp2 * ((-1.) * (157. - 3. * sqrt(21)) / 378 * f[0][0] + 25. * (143. - 10. * sqrt(21)) / 2772 * f[1][0] - 25. * (876. + 55. * sqrt(21)) / 3969 * f[2][0] + 1280. * (913. + 18. * sqrt(21)) / 596673 * f[3][0] - (1353. + 26. * sqrt(21)) / 2268 * f[4][0] + 7. * (1777. + 377. * sqrt(21)) / 4428 * f[5][0] + 7. * (5. - sqrt(21)) / 36 * f[6][0])); dir_SSB[1] = -(initPos[1] + h * initVel[1] + hp2 * ((-1.) * (157. - 3. * sqrt(21)) / 378 * f[0][1] + 25. * (143. - 10. * sqrt(21)) / 2772 * f[1][1] - 25. * (876. + 55. * sqrt(21)) / 3969 * f[2][1] + 1280. * (913. + 18. * sqrt(21)) / 596673 * f[3][1] - (1353. + 26. * sqrt(21)) / 2268 * f[4][1] + 7. * (1777. + 377. * sqrt(21)) / 4428 * f[5][1] + 7. * (5. - sqrt(21)) / 36 * f[6][1])); dir_SSB[2] = -(initPos[2] + h * initVel[2] + hp2 * ((-1.) * (157. - 3. * sqrt(21)) / 378 * f[0][2] + 25. * (143. - 10. * sqrt(21)) / 2772 * f[1][2] - 25. * (876. + 55. * sqrt(21)) / 3969 * f[2][2] + 1280. * (913. + 18. * sqrt(21)) / 596673 * f[3][2] - (1353. + 26. * sqrt(21)) / 2268 * f[4][2] + 7. * (1777. + 377. * sqrt(21)) / 4428 * f[5][2] + 7. * (5. - sqrt(21)) / 36 * f[6][2])); calc_accel(config_data, dir_SSB, &body[8], f[7], initVel, dtime[8] - dtime[1]); // F9 - only used for error calculation dir_SSB[0] = -(initPos[0] + h * initVel[0] + hp2 * (1. / 20 * f[0][0] + 8. / 45 * f[4][0] + 7. * (7. + sqrt(21)) / 360 * f[5][0] + 7. * (7. - sqrt(21)) / 360 * f[6][0])); dir_SSB[1] = -(initPos[1] + h * initVel[1] + hp2 * (1. / 20 * f[0][1] + 8. / 45 * f[4][1] + 7. * (7. + sqrt(21)) / 360 * f[5][1] + 7. * (7. - sqrt(21)) / 360 * f[6][1])); dir_SSB[2] = -(initPos[2] + h * initVel[2] + hp2 * (1. / 20 * f[0][2] + 8. / 45 * f[4][2] + 7. * (7. + sqrt(21)) / 360 * f[5][2] + 7. * (7. - sqrt(21)) / 360 * f[6][2])); calc_accel(config_data, dir_SSB, &body[8], f[8], initVel, dtime[8] - dtime[1]); // Absolute error (2-norm) tEps_p = (f[7][0] - f[8][0]); tEps = tEps_p * tEps_p; tEps_p = (f[7][1] - f[8][1]); tEps += tEps_p * tEps_p; tEps_p = (f[7][2] - f[8][2]); tEps += tEps_p * tEps_p; tEps = hp2 / 20 * sqrt(tEps); substepcount++; } while (tEps > config_data->e_target); // while the error is too big. #ifdef __WSTEPINFO if (tEps > maxEps) { maxEps = tEps; } #endif // Update solution // x7th_i+1 nstate[0] = initPos[0] + h * initVel[0] + hp2 * (18. * f[0][0] + 64. * f[4][0] + (7. * (7. + sqrt(21))) * f[5][0] + (7. * (7. - sqrt(21))) * f[6][0]) / 360; nstate[1] = initPos[1] + h * initVel[1] + hp2 * (18. * f[0][1] + 64. * f[4][1] + (7. * (7. + sqrt(21))) * f[5][1] + (7. * (7. - sqrt(21))) * f[6][1]) / 360; nstate[2] = initPos[2] + h * initVel[2] + hp2 * (18. * f[0][2] + 64. * f[4][2] + (7. * (7. + sqrt(21))) * f[5][2] + (7. * (7. - sqrt(21))) * f[6][2]) / 360; // v7th_i+1 nstate[3] = initVel[0] + h * (18. * (f[0][0] + f[7][0]) + 128. * f[4][0] + 98. * f[5][0] + 98. * f[6][0]) / 360; nstate[4] = initVel[1] + h * (18. * (f[0][1] + f[7][1]) + 128. * f[4][1] + 98. * f[5][1] + 98. * f[6][1]) / 360; nstate[5] = initVel[2] + h * (18. * (f[0][2] + f[7][2]) + 128. * f[4][2] + 98. * f[5][2] + 98. * f[6][2]) / 360; /* x6th_i+1, not necessary to compute nstate[3] = initVel[0] + h * (18 * f[0][0] + 64 * f[4][0] + (7 * (7 + sqrt(21))) * f[5][0] + (7 * (7 - sqrt(21))) * f[6][0] - 18 * f[7][0] + 18 * f[8][0]) / 360; nstate[4] = initVel[1] + h * (18 * f[0][1] + 64 * f[4][1] + (7 * (7 + sqrt(21))) * f[5][1] + (7 * (7 - sqrt(21))) * f[6][1] - 18 * f[7][1] + 18 * f[8][1]) / 360; nstate[5] = initVel[2] + h * (18 * f[0][2] + 64 * f[4][2] + (7 * (7 + sqrt(21))) * f[5][2] + (7 * (7 - sqrt(21))) * f[6][2] - 18 * f[7][2] + 18 * f[8][2]) / 360; */ // Update time nstate[6] = time[1] + h; // Save previous time for body location interpolation time[0] = time[1]; #ifdef __WSTEPINFO if (h < hmin) // calculate smallest time step { hmin = h; } else if (h > hmax) // calculate largest time step { hmax = h; } #endif stepcount++; // Increase StepCount #ifdef __SaveRateOpt floating_stepcount += config_data->step_multiplier; #else floating_stepcount += 1.; #endif // __SaveRateOpt // If distance to the Sun is less than 10 sun radii terminate particle by setting coordinates to 99 and breaking integration loop sun_dist = sqrt(nstate[0] * nstate[0] + nstate[1] * nstate[1] + nstate[2] * nstate[2]); if (sun_dist < 7000000) { nstate[0] = 99; nstate[1] = 99; nstate[2] = 99; nstate[3] = 99; nstate[4] = 99; nstate[5] = 99; break; } // Save nth state if (config_data->saving == 1) { if (floating_stepcount >= config_data->n) { printpdata(statefile, nstate); floating_stepcount = 0.; } } } // Print last state to file and close file if (floating_stepcount != 0.) { printpdata(statefile, nstate); } // Deallocate body array for (k = 0; k < 9; k++) { for (j = 0; j < config_data->N_bodys; j++) { free(body[k][j]); } free(body[k]); } // Free body state coefficient memory interp_body_states_free(config_data, &body_c); #ifdef __WSTEPINFO printf("\n Smallest time step: %.4le s", hmin); printf(" - Largest time step: %.4le s", hmax); printf(" - Total number of steps: %d", stepcount); printf(" - Total number of substeps: %d", substepcount); printf(" - Largest error per step: %.4le km", maxEps); #endif return 0; }
random.c
/* Copyright (c) 2013, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /************************************************************* Copyright (c) 2013 The University of Tennessee. 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 listed in this license in the documentation and/or other materials provided with the distribution. - Neither the name of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. in no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. *************************************************************/ /******************************************************************* NAME: RandomAccess PURPOSE: This program tests the efficiency of the memory subsystem to update elements of an array with irregular stride. USAGE: The program takes as input the number of threads involved, the 2log of the size of the table that gets updated, the ratio of table size over number of updates, and the vector length of simultaneously updatable table elements. When multiple threads participate, they all share the same table. This can lead to conflicts in memory accesses. Setting the ATOMICFLAG variable in the Makefile will avoid conflicts, but at a large price, because the atomic directive is currently not implemented on IA for the type of update operation used here. Instead, a critical section is used, serializing the main loop. If the CHUNKFLAG variable is set, contiguous, non-overlapping chunks of the array are assigned to individual threads. Each thread computes all pseudo-random indices into the table, but only updates table elements that fall inside its chunk. Hence, this version is safe, and there is no false sharing. It is also non-scalable. <progname> <# threads> <log2 tablesize> <#update ratio> <vector length> FUNCTIONS CALLED: Other than OpenMP or standard C functions, the following functions are used in this program: wtime() bail_out() PRK_starts() poweroftwo() NOTES: This program is derived from HPC Challenge Random Access. The random number generator computes successive powers of 0x2, modulo the primitive polynomial x^63+x^2+x+1. The principal differences between this code and the HPCC version are: - we start the stream of random numbers not with seed 0x1, but the SEQSEED-th element in the stream of powers of 0x2. - the timed code applies the RandomAccess operator twice to the table of computed resuls (starting with the same seed(s) for "ran" in both iterations. The second pass makes sure that any update to any table element that sets high-order bits in the first pass resets those bits to zero. - the verification test now simply constitutes checking whether table element j equals j. - the number of independent streams (vector length) can be changed by the user. We note that the vectorized version of this code (i.e. nstarts unequal to 1), does not feature exactly the same sequence of accesses and intermediate update values in the table as the scalar version. The reason for this is twofold. 1. the elements in the stream of powers of 0x2 that get computed outside the main timed loop as seeds for independent streams in the vectorized version, using the jump-ahead function PRK_starts, are computed inside the timed loop for the scalar version. However, since both versions do the same number of timed random accesses, the vectorized version must progress further in the sequence of powers of 0x2. 2. The independent streams of powers of 0x2 computed in the vectorized version can (and will) cause updates of the same elements of the table in an order that is not consistent with the scalar version. That is, distinct values of "ran" can refer to the same table element "ran&(tablesize-1)," but the operation Table[ran&(tablesize-1)] ^= ran will deposit different values in that table element for different values of ran. At the end of each pass over the data set, the table will contain the same values in the vector and scalar version (ignoring the small differences caused by 1.) because of commutativity of the XOR operator. If the update operator had been non-commutative, the vector and scalar version would have yielded different results. HISTORY: Written by Rob Van der Wijngaart, June 2006. Histogram code (verbose mode) courtesy Roger Golliver Shared table version derived from random.c by Michael Frumkin, October 2006 ************************************************************************************/ #include <par-res-kern_general.h> #include <par-res-kern_omp.h> /* Define constants */ /* PERIOD = (2^63-1)/7 = 7*73*127*337*92737*649657 */ #ifdef LONG_IS_64BITS #define POLY 0x0000000000000007UL #define PERIOD 1317624576693539401L /* sequence number in stream of random numbers to be used as initial value */ #define SEQSEED 834568137686317453L #else #define POLY 0x0000000000000007ULL #define PERIOD 1317624576693539401LL /* sequence number in stream of random numbers to be used as initial value */ #define SEQSEED 834568137686317453LL #endif #ifdef HPCC #undef ATOMIC #undef CHUNKED #undef ERRORPERCENT #define ERRORPERCENT 1 #else #ifndef ERRORPERCENT #define ERRORPERCENT 0 #endif #ifdef CHUNKED #undef ATOMIC #endif #endif static u64Int PRK_starts(s64Int); static int poweroftwo(int); int main(int argc, char **argv) { int my_ID; /* thread ID */ int update_ratio; /* multiplier of tablesize for # updates */ int nstarts; /* vector length */ s64Int i, j, round, oldsize; /* dummies */ s64Int error; /* number of incorrect table elements */ s64Int tablesize; /* aggregate table size (all threads */ s64Int nupdate; /* number of updates per thread */ size_t tablespace; /* bytes per thread required for table */ u64Int *ran; /* vector of random numbers */ s64Int index; /* index into Table */ #ifdef VERBOSE u64Int * RESTRICT Hist; /* histogram of # updates to table elements */ unsigned int *HistHist; /* histogram of update frequencies */ #endif u64Int * RESTRICT Table; /* (pseudo-)randomly accessed array */ double random_time; int nthread_input; /* thread parameters */ int nthread; int log2tablesize; /* log2 of aggregate table size */ int num_error=0; /* flag that signals that requested and obtained numbers of threads are the same */ #ifdef LONG_IS_64BITS if (sizeof(long) != 8) { printf("ERROR: Makefile says \"long\" is 8 bytes, but it is %d bytes\n", sizeof(long)); exit(EXIT_FAILURE); } #endif /********************************************************************* ** process and test input parameters *********************************************************************/ if (argc != 5){ printf("Usage: %s <# threads> <log2 tablesize> <#update ratio> ", *argv); printf("<vector length>\n"); exit(EXIT_FAILURE); } nthread_input = atoi(*++argv); /* test whether number of threads is positive */ if (nthread_input <1) { printf("ERROR: Invalid number of threads: %d, must be positive\n", nthread_input); exit(EXIT_FAILURE); } omp_set_num_threads(nthread_input); log2tablesize = atoi(*++argv); if (log2tablesize < 1){ printf("ERROR: Log2 tablesize is %d; must be >= 1\n",log2tablesize); exit(EXIT_FAILURE); } update_ratio = atoi(*++argv); /* test whether update ratio is positive */ if (update_ratio <1) { printf("ERROR: Invalid update ratio: %d, must be positive\n", update_ratio); exit(EXIT_FAILURE); } nstarts = atoi(*++argv); /* if whether vector length is positive */ if (nstarts <1) { printf("ERROR: Invalid vector length: %d, must be positive\n", nstarts); exit(EXIT_FAILURE); } /* do some additional divisibility tests */ if (nstarts%nthread_input) { printf("ERROR: vector length %d must be divisible by # threads %d\n", nstarts, nthread_input); exit(EXIT_FAILURE); } if (update_ratio%nstarts) { printf("ERROR: update ratio %d must be divisible by vector length %d\n", update_ratio, nstarts); exit(EXIT_FAILURE); } /* compute table size carefully to make sure it can be represented */ tablesize = 1; for (i=0; i<log2tablesize; i++) { oldsize = tablesize; tablesize <<=1; if (tablesize/2 != oldsize) { printf("Requested table size too large; reduce log2 tablesize = %d\n", log2tablesize); exit(EXIT_FAILURE); } } /* even though the table size can be represented, computing the space required for the table may lead to overflow */ tablespace = (size_t) tablesize*sizeof(u64Int); if ((tablespace/sizeof(u64Int)) != tablesize || tablespace <=0) { printf("Cannot represent space for table on this system; "); printf("reduce log2 tablesize\n"); exit(EXIT_FAILURE); } #ifdef VERBOSE Hist = (u64Int *) malloc(tablespace); HistHist = (unsigned int *) malloc(tablespace); if (!Hist || ! HistHist) { printf("ERROR: Could not allocate space for histograms\n"); exit(EXIT_FAILURE); } #endif /* compute number of updates carefully to make sure it can be represented */ nupdate = update_ratio * tablesize; if (nupdate/tablesize != update_ratio) { printf("Requested number of updates too large; "); printf("reduce log2 tablesize or update ratio\n"); exit(EXIT_FAILURE); } Table = (u64Int *) malloc(tablespace); if (!Table) { printf("ERROR: Could not allocate space of "FSTR64U" bytes for table\n", (u64Int) tablespace); exit(EXIT_FAILURE); } error = 0; #pragma omp parallel private(i, j, ran, round, index, my_ID) reduction(+:error) { int my_starts; my_ID = omp_get_thread_num(); #pragma omp master { nthread = omp_get_num_threads(); printf("OpenMP Random Access test\n"); if (nthread != nthread_input) { num_error = 1; printf("ERROR: number of requested threads %d does not equal ", nthread_input); printf("number of spawned threads %d\n", nthread); } else { printf("Number of threads = "FSTR64U"\n", (u64Int) nthread_input); printf("Table size (shared) = "FSTR64U"\n", tablesize); printf("Update ratio = "FSTR64U"\n", (u64Int) update_ratio); printf("Number of updates = "FSTR64U"\n", nupdate); printf("Vector length = "FSTR64U"\n", (u64Int) nstarts); printf("Percent errors allowed = "FSTR64U"\n", (u64Int) ERRORPERCENT); #if defined(ATOMIC) && !defined(CHUNKED) printf("Shared table, atomic updates\n"); #elif defined(CHUNKED) printf("Shared, chunked table\n"); #else printf("Shared table, non-atomic updates\n"); #endif } } bail_out(num_error); #ifdef CHUNKED /* compute upper and lower table bounds for this thread */ u64Int low = my_ID *(tablesize/nthread); u64Int up = (my_ID+1)*(tablesize/nthread); my_starts = nstarts; #else my_starts = nstarts/nthread; #endif ran = (u64Int *) malloc(my_starts*sizeof(u64Int)); if (!ran) { printf("ERROR: Thread %d Could not allocate %d bytes for random numbers\n", my_ID, my_starts*(int)sizeof(u64Int)); num_error = 1; } bail_out(num_error); /* initialize the table */ #pragma omp for for(i=0;i<tablesize;i++) Table[i] = (u64Int) i; #pragma omp barrier #pragma omp master { random_time = wtime(); } /* ran is privatized. Must make sure for non-chunked version that we pick the right section of the originally shared ran array */ #ifdef CHUNKED int offset = 0; #else int offset = my_ID*my_starts; #endif /* do two identical rounds of Random Access to make sure we recover the initial condition */ for (round=0; round <2; round++) { for (j=0; j<my_starts; j++) { ran[j] = PRK_starts(SEQSEED+(nupdate/nstarts)*(j+offset)); } for (j=0; j<my_starts; j++) { /* because we do two rounds, we divide nupdates in two */ for (i=0; i<nupdate/(nstarts*2); i++) { ran[j] = (ran[j] << 1) ^ ((s64Int)ran[j] < 0? POLY: 0); index = ran[j] & (tablesize-1); #if defined(ATOMIC) #pragma omp atomic #elif defined(CHUNKED) if (index >= low && index < up) { #endif Table[index] ^= ran[j]; #ifdef VERBOSE #pragma omp atomic Hist[index] += 1; #endif #ifdef CHUNKED } #endif } } } #pragma omp master { random_time = wtime() - random_time; } } /* end of OpenMP parallel region */ /* verification test */ for(i=0;i<tablesize;i++) { if(Table[i] != (u64Int) i) { #ifdef VERBOSE printf("Error Table["FSTR64U"]="FSTR64U"\n",i,Table[i]); #endif error++; } } if ((error && (ERRORPERCENT==0)) || ((double)error/(double)tablesize > ((double) ERRORPERCENT)*0.01)) { printf("ERROR: number of incorrect table elements = "FSTR64U"\n", error); exit(EXIT_FAILURE); } else { printf("Solution validates, number of errors: %ld\n",(long) error); printf("Rate (GUPs/s): %lf, time (s) = %lf\n", 1.e-9*nupdate/random_time,random_time); } #ifdef VERBOSE for(i=0;i<tablesize;i++) HistHist[Hist[i]]+=1; for(i=0;i<=tablesize;i++) if (HistHist[i] != 0) printf("HistHist[%4.1d]=%9.1d\n",(int)i,HistHist[i]); #endif exit(EXIT_SUCCESS); } /* Utility routine to start random number generator at nth step */ u64Int PRK_starts(s64Int n) { int i, j; u64Int m2[64]; u64Int temp, ran; while (n < 0) n += PERIOD; while (n > PERIOD) n -= PERIOD; if (n == 0) return 0x1; temp = 0x1; for (i=0; i<64; i++) { m2[i] = temp; temp = (temp << 1) ^ ((s64Int) temp < 0 ? POLY : 0); temp = (temp << 1) ^ ((s64Int) temp < 0 ? POLY : 0); } for (i=62; i>=0; i--) if ((n >> i) & 1) break; ran = 0x2; while (i > 0) { temp = 0; for (j=0; j<64; j++) if ((unsigned int)((ran >> j) & 1)) temp ^= m2[j]; ran = temp; i -= 1; if ((n >> i) & 1) ran = (ran << 1) ^ ((s64Int) ran < 0 ? POLY : 0); } return ran; } /* utility routine that tests whether an integer is a power of two */ int poweroftwo(int n) { int log2n = 0; while ((1<<log2n)<n) log2n++; if (1<<log2n != n) return (-1); else return (log2n); }
triplet_iw.c
/* Copyright (C) 2016 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* * Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* * Neither the name of the phonopy project nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ #include "triplet_iw.h" #include <math.h> #include "grgrid.h" #include "phonoc_utils.h" #include "tetrahedron_method.h" #include "triplet.h" static void set_freq_vertices(double freq_vertices[3][24][4], const double *frequencies1, const double *frequencies2, const long vertices[2][24][4], const long num_band1, const long num_band2, const long b1, const long b2, const long tp_type); static long set_g(double g[3], const double f0, const double freq_vertices[3][24][4], const long max_i); static void get_triplet_tetrahedra_vertices( long vertices[2][24][4], const long tp_relative_grid_address[2][24][4][3], const long triplet[3], const ConstBZGrid *bzgrid); static void get_neighboring_grid_points_type1( long *neighboring_grid_points, const long grid_point, const long (*relative_grid_address)[3], const long num_relative_grid_address, const ConstBZGrid *bzgrid); static void get_neighboring_grid_points_type2( long *neighboring_grid_points, const long grid_point, const long (*relative_grid_address)[3], const long num_relative_grid_address, const ConstBZGrid *bzgrid); void tpi_get_integration_weight( double *iw, char *iw_zero, const double *frequency_points, const long num_band0, const long tp_relative_grid_address[2][24][4][3], const long triplets[3], const long num_triplets, const ConstBZGrid *bzgrid, const double *frequencies1, const long num_band1, const double *frequencies2, const long num_band2, const long tp_type, const long openmp_per_bands) { long max_i, j, b1, b2, b12, num_band_prod, adrs_shift; long vertices[2][24][4]; double g[3]; double freq_vertices[3][24][4]; get_triplet_tetrahedra_vertices(vertices, tp_relative_grid_address, triplets, bzgrid); num_band_prod = num_triplets * num_band0 * num_band1 * num_band2; /* tp_type: Type of integration weights stored */ /* */ /* g0 -> \delta(f0 - (-f1 + f2)) */ /* g1 -> \delta(f0 - (f1 - f2)) */ /* g2 -> \delta(f0 - (f1 + f2)) */ /* */ /* tp_type = 2: (g[2], g[0] - g[1]) mainly for ph-ph */ /* tp_type = 3: (g[2], g[0] - g[1], g[0] + g[1] + g[2]) mainly for ph-ph */ /* tp_type = 4: (g[0]) mainly for el-ph phonon decay, */ /* f0: ph, f1: el_i, f2: el_f */ if ((tp_type == 2) || (tp_type == 3)) { max_i = 3; } if (tp_type == 4) { max_i = 1; } #ifdef _OPENMP #pragma omp parallel for private(j, b1, b2, adrs_shift, g, \ freq_vertices) if (openmp_per_bands) #endif for (b12 = 0; b12 < num_band1 * num_band2; b12++) { b1 = b12 / num_band2; b2 = b12 % num_band2; set_freq_vertices(freq_vertices, frequencies1, frequencies2, vertices, num_band1, num_band2, b1, b2, tp_type); for (j = 0; j < num_band0; j++) { adrs_shift = j * num_band1 * num_band2 + b1 * num_band2 + b2; iw_zero[adrs_shift] = set_g(g, frequency_points[j], freq_vertices, max_i); if (tp_type == 2) { iw[adrs_shift] = g[2]; adrs_shift += num_band_prod; iw[adrs_shift] = g[0] - g[1]; } if (tp_type == 3) { iw[adrs_shift] = g[2]; adrs_shift += num_band_prod; iw[adrs_shift] = g[0] - g[1]; adrs_shift += num_band_prod; iw[adrs_shift] = g[0] + g[1] + g[2]; } if (tp_type == 4) { iw[adrs_shift] = g[0]; } } } } void tpi_get_integration_weight_with_sigma( double *iw, char *iw_zero, const double sigma, const double cutoff, const double *frequency_points, const long num_band0, const long triplet[3], const long const_adrs_shift, const double *frequencies, const long num_band, const long tp_type, const long openmp_per_bands) { long j, b12, b1, b2, adrs_shift; double f0, f1, f2, g0, g1, g2; #ifdef _OPENMP #pragma omp parallel for private(j, b1, b2, f0, f1, f2, g0, g1, g2, \ adrs_shift) if (openmp_per_bands) #endif for (b12 = 0; b12 < num_band * num_band; b12++) { b1 = b12 / num_band; b2 = b12 % num_band; f1 = frequencies[triplet[1] * num_band + b1]; f2 = frequencies[triplet[2] * num_band + b2]; for (j = 0; j < num_band0; j++) { f0 = frequency_points[j]; adrs_shift = j * num_band * num_band + b1 * num_band + b2; if ((tp_type == 2) || (tp_type == 3)) { if (cutoff > 0 && fabs(f0 + f1 - f2) > cutoff && fabs(f0 - f1 + f2) > cutoff && fabs(f0 - f1 - f2) > cutoff) { iw_zero[adrs_shift] = 1; g0 = 0; g1 = 0; g2 = 0; } else { iw_zero[adrs_shift] = 0; g0 = phonoc_gaussian(f0 + f1 - f2, sigma); g1 = phonoc_gaussian(f0 - f1 + f2, sigma); g2 = phonoc_gaussian(f0 - f1 - f2, sigma); } if (tp_type == 2) { iw[adrs_shift] = g2; adrs_shift += const_adrs_shift; iw[adrs_shift] = g0 - g1; } if (tp_type == 3) { iw[adrs_shift] = g2; adrs_shift += const_adrs_shift; iw[adrs_shift] = g0 - g1; adrs_shift += const_adrs_shift; iw[adrs_shift] = g0 + g1 + g2; } } if (tp_type == 4) { if (cutoff > 0 && fabs(f0 + f1 - f2) > cutoff) { iw_zero[adrs_shift] = 1; iw[adrs_shift] = 0; } else { iw_zero[adrs_shift] = 0; iw[adrs_shift] = phonoc_gaussian(f0 + f1 - f2, sigma); } } } } } void tpi_get_neighboring_grid_points(long *neighboring_grid_points, const long grid_point, const long (*relative_grid_address)[3], const long num_relative_grid_address, const ConstBZGrid *bzgrid) { if (bzgrid->type == 1) { get_neighboring_grid_points_type1(neighboring_grid_points, grid_point, relative_grid_address, num_relative_grid_address, bzgrid); } else { get_neighboring_grid_points_type2(neighboring_grid_points, grid_point, relative_grid_address, num_relative_grid_address, bzgrid); } } static void set_freq_vertices(double freq_vertices[3][24][4], const double *frequencies1, const double *frequencies2, const long vertices[2][24][4], const long num_band1, const long num_band2, const long b1, const long b2, const long tp_type) { long i, j; double f1, f2; for (i = 0; i < 24; i++) { for (j = 0; j < 4; j++) { f1 = frequencies1[vertices[0][i][j] * num_band1 + b1]; f2 = frequencies2[vertices[1][i][j] * num_band2 + b2]; if ((tp_type == 2) || (tp_type == 3)) { if (f1 < 0) { f1 = 0; } if (f2 < 0) { f2 = 0; } freq_vertices[0][i][j] = -f1 + f2; freq_vertices[1][i][j] = f1 - f2; freq_vertices[2][i][j] = f1 + f2; } else { freq_vertices[0][i][j] = -f1 + f2; } } } } /* Integration weight g is calculated. */ /* iw_zero = 1 means g[0] to g[max_i - 1] are all zero. */ /* max_i depends on what we compute, e.g., ph-ph lifetime, */ /* ph-ph collision matrix, and el-ph relaxation time. */ /* iw_zero is definitely determined by in_tetrahedra in case that */ /* f0 is out of the tetrahedra. */ /* iw_zero=1 information can be used to omit to compute particles */ /* interaction strength that is often heaviest part in throughout */ /* calculation. */ static long set_g(double g[3], const double f0, const double freq_vertices[3][24][4], const long max_i) { long i, iw_zero; iw_zero = 1; for (i = 0; i < max_i; i++) { if (thm_in_tetrahedra(f0, freq_vertices[i])) { g[i] = thm_get_integration_weight(f0, freq_vertices[i], 'I'); iw_zero = 0; } else { g[i] = 0; } } return iw_zero; } static void get_triplet_tetrahedra_vertices( long vertices[2][24][4], const long tp_relative_grid_address[2][24][4][3], const long triplet[3], const ConstBZGrid *bzgrid) { long i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 24; j++) { tpi_get_neighboring_grid_points(vertices[i][j], triplet[i + 1], tp_relative_grid_address[i][j], 4, bzgrid); } } } static void get_neighboring_grid_points_type1( long *neighboring_grid_points, const long grid_point, const long (*relative_grid_address)[3], const long num_relative_grid_address, const ConstBZGrid *bzgrid) { long bzmesh[3], bz_address[3]; long i, j, bz_gp, prod_bz_mesh; for (i = 0; i < 3; i++) { bzmesh[i] = bzgrid->D_diag[i] * 2; } prod_bz_mesh = bzmesh[0] * bzmesh[1] * bzmesh[2]; for (i = 0; i < num_relative_grid_address; i++) { for (j = 0; j < 3; j++) { bz_address[j] = bzgrid->addresses[grid_point][j] + relative_grid_address[i][j]; } bz_gp = bzgrid->gp_map[grg_get_grid_index(bz_address, bzmesh)]; if (bz_gp == prod_bz_mesh) { neighboring_grid_points[i] = grg_get_grid_index(bz_address, bzgrid->D_diag); } else { neighboring_grid_points[i] = bz_gp; } } } static void get_neighboring_grid_points_type2( long *neighboring_grid_points, const long grid_point, const long (*relative_grid_address)[3], const long num_relative_grid_address, const ConstBZGrid *bzgrid) { long bz_address[3]; long i, j, gp; for (i = 0; i < num_relative_grid_address; i++) { for (j = 0; j < 3; j++) { bz_address[j] = bzgrid->addresses[grid_point][j] + relative_grid_address[i][j]; } gp = grg_get_grid_index(bz_address, bzgrid->D_diag); neighboring_grid_points[i] = bzgrid->gp_map[gp]; if (bzgrid->gp_map[gp + 1] - bzgrid->gp_map[gp] > 1) { for (j = bzgrid->gp_map[gp]; j < bzgrid->gp_map[gp + 1]; j++) { if (bz_address[0] == bzgrid->addresses[j][0] && bz_address[1] == bzgrid->addresses[j][1] && bz_address[2] == bzgrid->addresses[j][2]) { neighboring_grid_points[i] = j; break; } } } } }
ndarray.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <assert.h> #include <time.h> #include <math.h> #include <omp.h> #include "ndarray.h" #include "ndshape.h" size_t get_item_size(DataType datatype) { switch(datatype) { case DT_INT: return sizeof(int); break; case DT_DOUBLE: return sizeof(double); break; case DT_BOOL: return sizeof(char); default: return -1; } } NdArray* NdArray_new(void *data, NdShape *ndshape, DataType datatype) { NdArray *ndarray = (NdArray*)malloc(sizeof(NdArray)); ndarray->shape = NdShape_copy(ndshape); ndarray->datatype = datatype; ndarray->item_size = get_item_size(ndarray->datatype); ndarray->size = ndarray->item_size * ndarray->shape->len; ndarray->data = malloc(ndarray->size); if(data == NULL) { memset(ndarray->data, 0, ndarray->size); } else { memcpy(ndarray->data, data, ndarray->size); } return ndarray; } NdArray* NdArray_copy(NdArray *src) { NdArray *dest = NdArray_new(NULL, src->shape, src->datatype); memcpy(dest->data, src->data, src->size); return dest; } void NdArray_free(NdArray **dptr_ndarray) { NdShape_free(&((*dptr_ndarray)->shape)); free((*dptr_ndarray)->data); free(*dptr_ndarray); *dptr_ndarray= NULL; } void NdArray_sub_free(NdArray **dptr_ndarray) { NdShape_free(&((*dptr_ndarray)->shape)); free(*dptr_ndarray); *dptr_ndarray= NULL; } NdArray* NdArray_zeros(unsigned int len, DataType datatype) { NdShape *ndshape = NdShape_new(1, len); NdArray *ndarray = NdArray_new(NULL, ndshape, datatype); NdShape_free(&ndshape); return ndarray; } NdArray* NdArray_ones(unsigned int len, DataType datatype) { NdArray *ndarray = NdArray_zeros(len, datatype); void *cur = ndarray->data; for(int i = 0; i < len; i++) { switch(datatype) { case DT_INT: *((int*)cur + i) = 1; break; case DT_DOUBLE: *((double*)cur + i) = 1.0; break; default: abort(); } } return ndarray; } NdArray* NdArray_arange(unsigned int start, unsigned int end, DataType datatype) { int len = end - start; NdArray *ndarray = NdArray_zeros(len, datatype); void *cur = ndarray->data; for(int i = 0; i < len; i++) { switch(datatype) { case DT_INT: *((int*)cur + i) = start + i; break; case DT_DOUBLE: *((double*)cur + i) = (double)(start + i); break; default: abort(); } } return ndarray; } NdArray* NdArray_random(unsigned int len, DataType datatype) { NdArray *ndarray = NdArray_zeros(len, datatype); void* cur = ndarray->data; srand(time(NULL)); for(int i = 0; i < ndarray->shape->len; i++) { switch(datatype) { case DT_INT: *((int*)cur + i) = rand(); break; case DT_DOUBLE: *((double*)cur + i) = (double)rand() / (RAND_MAX - 10); break; default: abort(); } } return ndarray; } NdArray* NdArray_random_range(unsigned int len, unsigned int low, unsigned int high, DataType datatype) { assert(len > 0); assert(low < high); NdArray *ndarray = NdArray_zeros(len, datatype); void* cur = ndarray->data; int bound = high - low; srand(time(NULL)); for(int i = 0; i < ndarray->shape->len; i++) { switch(datatype) { case DT_INT: *((int*)cur + i) = rand() % bound + low; break; case DT_DOUBLE: *((double*)cur + i) = (double)rand() / (RAND_MAX) + rand() % bound + low; break; default: abort(); } } return ndarray; } double get_gaussian_random_value() { double v1, v2, s; do { v1 = 2 * ((double) rand() / RAND_MAX) - 1; v2 = 2 * ((double) rand() / RAND_MAX) - 1; s = v1 * v1 + v2 * v2; } while(s >= 1 || s == 0); s = sqrt((-2 * log(s)) / s); return v1 * s; } NdArray* NdArray_random_gaussian(unsigned int len) { NdArray *ndarray = NdArray_zeros(len, DT_DOUBLE); double *cur = ndarray->data; srand(time(NULL)); for(int i = 0; i < len; i++) { cur[i] = get_gaussian_random_value(); } return ndarray; } NdArray* NdArray_shuffle(NdArray *array) { srand(time(NULL)); for(int i = array->shape->len-1; i > 0; i--) { int random_idx = rand() % i; switch(array->datatype) { case DT_INT: { int *cur = array->data; int temp = cur[i]; cur[i] = cur[random_idx]; cur[random_idx] = temp; } break; case DT_DOUBLE: { double *cur = array->data; double temp = cur[i]; cur[i] = cur[random_idx]; cur[random_idx] = temp; } break; default: abort(); } } return array; } NdArray* NdArray_choice(unsigned int pick_len, unsigned int len, DataType datatype) { assert(len >= pick_len ); NdArray* choices = NdArray_zeros(pick_len, datatype); NdArray* temp = NdArray_arange(0, len, datatype); NdArray_shuffle(temp); memcpy(choices->data, temp->data, choices->size); NdArray_free(&temp); return choices; } int NdArray_reshape(NdArray *ndarray, NdShape *ndshape) { return NdShape_reshape(ndarray->shape, ndshape); } int NdArray_reshape_fixed_array(NdArray *self, unsigned int dim, unsigned int *arr) { return NdShape_reshape_fixed_array(self->shape, dim, arr); } int NdArray_reshape_variadic(NdArray *self, unsigned int dim, ...) { unsigned int arr[dim]; va_list args; va_start(args, dim); for(int i = 0; i < dim; i++) { arr[i] = va_arg(args, unsigned int); } va_end(args); return NdShape_reshape_fixed_array(self->shape, dim, arr); } unsigned int get_offset(NdArray *ndarray, unsigned int *position, int pdim) { unsigned int offset = 0; unsigned int len = ndarray->shape->len; for(int i = 0; i < pdim; i++) { len /= ndarray->shape->arr[i]; offset += position[i] * len; } offset *= ndarray->item_size; return offset; } void* NdArray_getAt(NdArray *ndarray, unsigned int *position) { unsigned int offset = get_offset(ndarray, position, ndarray->shape->dim); return ndarray->data + offset; } void NdArray_setAt(NdArray *ndarray, unsigned int *position, void* data) { void *target_address = NdArray_getAt(ndarray, position); switch(ndarray->datatype) { case DT_INT: *((int*)target_address) = *(int*)data; break; case DT_DOUBLE: *((double*)target_address) = *(double*)data; break; default: fprintf(stderr, "invalid datatype"); abort(); } } NdArray* NdArray_subarray(NdArray *ndarray, unsigned int *position, int pdim) { unsigned int offset = get_offset(ndarray, position, pdim); unsigned int subarray_dim = ndarray->shape->dim - pdim; NdShape *subshape = NdShape_empty(subarray_dim); for(int i = 0; i < subarray_dim; i++) { subshape->arr[i] = ndarray->shape->arr[pdim + i]; subshape->len *= subshape->arr[i]; } NdArray *subarray = NdArray_new(ndarray->data + offset, subshape, ndarray->datatype); return subarray; } void print_element(NdArray *ndarray, unsigned int *position) { void* ptr_element = NdArray_getAt(ndarray, position); switch(ndarray->datatype) { case DT_INT: printf("%d ", *(int*)ptr_element); break; case DT_DOUBLE: printf("%f ", *(double*)ptr_element); break; case DT_BOOL: printf("%d ", *(char*)ptr_element); break; default: abort(); } } void printArray(NdArray *ndarray, unsigned int *position, int dim) { if(dim == ndarray->shape->dim) { print_element(ndarray, position); return; } printf("[ "); for(int i = 0; i < ndarray->shape->arr[dim]; i++) { position[dim] = i; printArray(ndarray, position, dim+1); } printf("] "); } void NdArray_printArray(NdArray *ndarray) { unsigned int position[ndarray->shape->dim]; memset(position, 0, sizeof(unsigned int) * ndarray->shape->dim); printArray(ndarray, position, 0); printf("\n"); } void NdArray_printShape(NdArray *ndarray) { return NdShape_print(ndarray->shape); } int NdArray_is_arithmetically_vaild(NdArray *a, NdArray *b){ if(a->datatype != b->datatype) { return 0; } if(a->shape->dim < b->shape->dim) { return 0; } for(int i = 0; i < b->shape->dim; i++) { if(a->shape->arr[a->shape->dim-i-1] != b->shape->arr[b->shape->dim-i-1]) { return 0; } } return 1; } int NdArray_add(NdArray *dest, NdArray *src) { void *cur_dest; void *cur_src; if(!NdArray_is_arithmetically_vaild(dest, src)) { return 0; } cur_dest = dest->data; for(int i = 0; i < dest->shape->len / src->shape->len; i++) { cur_src = src->data; for(int j = 0; j < src->shape->len; j++) { switch(dest->datatype) { case DT_INT: *((int*)cur_dest) += *((int*)cur_src); break; case DT_DOUBLE: *((double*)cur_dest) += *((double*)cur_src); break; default: abort(); } cur_dest += dest->item_size; cur_src += src->item_size; } } return 1; } int NdArray_sub(NdArray *dest, NdArray *src) { void *cur_dest; void *cur_src; if(!NdArray_is_arithmetically_vaild(dest, src)) { return 0; } cur_dest = dest->data; for(int i = 0; i < dest->shape->len / src->shape->len; i++) { cur_src = src->data; for(int j = 0; j < src->shape->len; j++) { switch(dest->datatype) { case DT_INT: *((int*)cur_dest) -= *((int*)cur_src); break; case DT_DOUBLE: *((double*)cur_dest) -= *((double*)cur_src); break; default: abort(); } cur_dest += dest->item_size; cur_src += src->item_size; } } return 1; } int NdArray_mul(NdArray *dest, NdArray *src) { void *cur_dest; void *cur_src; if(!NdArray_is_arithmetically_vaild(dest, src)) { return 0; } cur_dest = dest->data; for(int i = 0; i < dest->shape->len / src->shape->len; i++) { cur_src = src->data; for(int j = 0; j < src->shape->len; j++) { switch(dest->datatype) { case DT_INT: *((int*)cur_dest) *= *((int*)cur_src); break; case DT_DOUBLE: *((double*)cur_dest) *= *((double*)cur_src); break; default: abort(); } cur_dest += dest->item_size; cur_src += src->item_size; } } return 1; } int NdArray_div(NdArray *dest, NdArray *src) { void *cur_dest; void *cur_src; if(!NdArray_is_arithmetically_vaild(dest, src)) { return 0; } cur_dest = dest->data; for(int i = 0; i < dest->shape->len / src->shape->len; i++) { cur_src = src->data; for(int j = 0; j < src->shape->len; j++) { switch(dest->datatype) { case DT_INT: *((int*)cur_dest) /= *((int*)cur_src); break; case DT_DOUBLE: *((double*)cur_dest) /= *((double*)cur_src); break; default: abort(); } cur_dest += dest->item_size; cur_src += src->item_size; } } return 1; } int NdArray_mod(NdArray *dest, NdArray *src) { assert(dest->datatype != DT_DOUBLE || src->datatype != DT_DOUBLE); if(!NdShape_compare(dest->shape, src->shape)) { return 0; } void *ptr_data_dest = dest->data; void *ptr_data_src = src->data; for(int i = 0; i < dest->shape->len; i++) { switch(dest->datatype) { case DT_INT: *((int*)ptr_data_dest) %= *((int*)ptr_data_src); break; case DT_DOUBLE: default: abort(); } ptr_data_dest += dest->item_size; ptr_data_src += src->item_size; } return 1; } void matmul_int(int *a, int *b, int *c, int p, int q, int r) { #pragma omp parallel for for(int i = 0; i < p; i++) { for(int k = 0; k < q; k++) { register int v = a[i * q + k]; for(int j = 0; j < r; j++) { c[i * r + j] += v * b[k * r + j]; } } } } void matmul_double(double *a, double *b, double *c, int p, int q, int r) { #pragma omp parallel for for(int i = 0; i < p; i++) { for(int k = 0; k < q; k++) { register double v = a[i * q + k]; for(int j = 0; j < r; j++) { c[i * r + j] += v * b[k * r + j]; } } } } NdArray* matmul_2d(NdArray *a, NdArray *b) { NdShape *shape_result = NdShape_new(2, a->shape->arr[0], b->shape->arr[1]); NdArray *result = NdArray_new(NULL, shape_result, a->datatype); switch(result->datatype) { case DT_INT: matmul_int(a->data, b->data, result->data, result->shape->arr[0], a->shape->arr[1], result->shape->arr[1]); break; case DT_DOUBLE: matmul_double(a->data, b->data, result->data, result->shape->arr[0], a->shape->arr[1], result->shape->arr[1]); break; default: abort(); } return result; } void matmul_recursive(NdArray *result, NdArray *a, NdArray *b, unsigned int *position, unsigned int dim) { NdShape *shape_result = result->shape; if(dim >= shape_result->dim-2) { NdShape *shape_a = a->shape; NdShape *shape_b = b->shape; unsigned int position_a[shape_a->dim-2]; unsigned int position_b[shape_b->dim-2]; int offset_a = (shape_a->dim >= shape_b->dim) ? 0 : shape_b->dim - shape_a->dim; int offset_b = (shape_a->dim >= shape_b->dim) ? shape_a->dim - shape_b->dim : 0; memcpy(position_a, position + offset_a, sizeof(unsigned int) * (shape_a->dim-2)); memcpy(position_b, position + offset_b, sizeof(unsigned int) * (shape_b->dim-2)); void *mat_a = a->data + get_offset(a, position_a, shape_a->dim-2); void *mat_b = b->data + get_offset(b, position_b, shape_b->dim-2); void *mat_result = result->data + get_offset(result, position, dim); int p = a->shape->arr[shape_a->dim-2]; int q = a->shape->arr[shape_a->dim-1]; int r = b->shape->arr[shape_b->dim-1]; switch(result->datatype) { case DT_INT: matmul_int(mat_a, mat_b, mat_result, p, q, r); break; case DT_DOUBLE: matmul_double(mat_a, mat_b, mat_result, p, q, r); break; default: abort(); } return; } for(int i = 0; i < shape_result->arr[dim]; i++) { position[dim] = i; matmul_recursive(result, a, b, position, dim+1); } } NdArray* matmul_nd(NdArray *a, NdArray *b) { NdArray *result; NdShape *shape_result; DataType datatype_result; datatype_result = a->datatype; NdShape *shape_a = a->shape; NdShape *shape_b = b->shape; int bound = (shape_a->dim >= shape_b->dim) ? shape_b->dim-2 : shape_a->dim-2; for(int i = 0; i < bound; i++) { if(shape_a->arr[shape_a->dim-i-3] != shape_b->arr[shape_b->dim-i-3]) { return NULL; } } if(shape_a->dim >= shape_b->dim) { shape_result = NdShape_copy(shape_a); shape_result->arr[shape_result->dim-1] = shape_b->arr[shape_b->dim-1]; } else { shape_result = NdShape_copy(shape_b); shape_result->arr[shape_result->dim-2] = shape_a->arr[shape_a->dim-2]; } result = NdArray_new(NULL, shape_result, datatype_result); unsigned int position[shape_result->dim-2]; memset(position, 0, sizeof(unsigned int) * (shape_result->dim-2)); matmul_recursive(result, a, b, position, 0); return result; } NdArray* dot_2d(NdArray *a, NdArray *b) { return matmul_2d(a, b); } void dot_recursive(NdArray *result, NdArray *a, NdArray *b, unsigned int *position, unsigned int dim) { NdShape *shape_result = result->shape; if(dim >= shape_result->dim) { NdShape *shape_a = a->shape; NdShape *shape_b = b->shape; unsigned int position_a[shape_a->dim]; unsigned int position_b[shape_b->dim]; memcpy(position_a, position, sizeof(unsigned int) * (shape_a->dim-1)); memcpy(position_b, position + (shape_a->dim-1), sizeof(unsigned int) * (shape_b->dim-1)); position_b[shape_b->dim-1] = position_b[shape_b->dim-2]; void *ptr_value_a; void *ptr_value_b; void *ptr_value_result = NdArray_getAt(result, position); memset(ptr_value_result, 0, result->item_size); for(int i = 0; i < shape_a->arr[shape_a->dim-1]; i++) { position_a[shape_a->dim-1] = i; position_b[shape_b->dim-2] = i; ptr_value_a = NdArray_getAt(a, position_a); ptr_value_b = NdArray_getAt(b, position_b); if(result->datatype == DT_INT) { *(int*)ptr_value_result += (*(int*)ptr_value_a) * (*(int*)ptr_value_b); } else if(result->datatype == DT_DOUBLE) { *(double*)ptr_value_result += (*(double*)ptr_value_a) * (*(double*)ptr_value_b); } } return; } for(int i = 0; i < shape_result->arr[dim]; i++) { position[dim] = i; dot_recursive(result, a, b, position, dim+1); } } NdArray* dot_nd(NdArray *a, NdArray *b) { NdArray *result; NdShape *shape_result; DataType datatype_result; datatype_result = a->datatype; NdShape *shape_a = a->shape; NdShape *shape_b = b->shape; shape_result = NdShape_empty(shape_a->dim + shape_b->dim - 2); memcpy(shape_result->arr, shape_a->arr, sizeof(unsigned int) * (shape_a->dim-1)); memcpy(shape_result->arr + (shape_a->dim-1), shape_b->arr, sizeof(unsigned int) * (shape_b->dim-1)); shape_result->arr[shape_result->dim-1] = shape_b->arr[shape_b->dim-1]; for(int i = 0; i < shape_result->dim; i++) { shape_result->len *= shape_result->arr[i]; } result = NdArray_new(NULL, shape_result, datatype_result); unsigned int position[shape_result->dim]; memset(position, 0, sizeof(unsigned int) * shape_result->dim); dot_recursive(result, a, b, position, 0); return result; } NdArray* NdArray_dot(NdArray *a, NdArray *b) { if(a->shape->arr[a->shape->dim-1] != b->shape->arr[b->shape->dim-2]) { abort(); } if(a->shape->dim == 2 && b->shape->dim == 2) { return dot_2d(a, b); } else { return dot_nd(a, b); } } NdArray* NdArray_matmul(NdArray *a, NdArray *b) { if(a->shape->arr[a->shape->dim-1] != b->shape->arr[b->shape->dim-2]) { abort(); } if(a->shape->dim == 2 && b->shape->dim == 2) { return matmul_2d(a, b); } else { return matmul_nd(a, b); } } void transpose_recursive(NdArray* array, NdArray *transposed, unsigned int *position, int dim) { if(dim >= array->shape->dim) { unsigned int tdim = transposed->shape->dim; unsigned int position_transpose[tdim]; for(int i = 0; i < tdim; i++) { position_transpose[i] = position[tdim-i-1]; } unsigned int offset_array = get_offset(array, position, array->shape->dim); unsigned int offset_transposed = get_offset(transposed, position_transpose, transposed->shape->dim); void *cur_array = array->data + offset_array; void *cur_transposed = transposed->data + offset_transposed; memcpy(cur_transposed, cur_array, array->item_size); return; } for(int i = 0; i < array->shape->arr[dim]; i++) { position[dim] = i; transpose_recursive(array, transposed, position, dim+1); } } NdArray* NdArray_transpose(NdArray *self) { NdShape *shape_transposed = NdShape_reverse(self->shape); NdArray *transposed = NdArray_zeros(self->shape->len, self->datatype); NdArray_reshape(transposed, shape_transposed); unsigned int position[self->shape->dim]; transpose_recursive(self, transposed, position, 0); NdShape_free(&shape_transposed); return transposed; } void NdArray_add_scalar(NdArray *ndarray, double value) { void *ptr_data = ndarray->data; for(int i = 0; i < ndarray->shape->len; i++) { switch(ndarray->datatype) { case DT_INT: *(int*)ptr_data += (int)value; break; case DT_DOUBLE: *(double*)ptr_data += value; break; default: abort(); } ptr_data += ndarray->item_size; } } void NdArray_sub_scalar(NdArray *ndarray, double value) { void *ptr_data = ndarray->data; for(int i = 0; i < ndarray->shape->len; i++) { switch(ndarray->datatype) { case DT_INT: *(int*)ptr_data -= (int)value; break; case DT_DOUBLE: *(double*)ptr_data -= value; break; default: abort(); } ptr_data += ndarray->item_size; } } void NdArray_mul_scalar(NdArray *ndarray, double value) { void *ptr_data = ndarray->data; for(int i = 0; i < ndarray->shape->len; i++) { switch(ndarray->datatype) { case DT_INT: *(int*)ptr_data *= (int)value; break; case DT_DOUBLE: *(double*)ptr_data *= value; break; default: abort(); } ptr_data += ndarray->item_size; } } void NdArray_div_scalar(NdArray *ndarray, double value) { assert(value != 0); void *ptr_data = ndarray->data; for(int i = 0; i < ndarray->shape->len; i++) { switch(ndarray->datatype) { case DT_INT: *(int*)ptr_data /= (int)value; break; case DT_DOUBLE: *(double*)ptr_data /= value; break; default: abort(); } ptr_data += ndarray->item_size; } } void NdArray_mod_scalar(NdArray *ndarray, int value) { assert(ndarray->datatype != DT_DOUBLE); assert(value != 0); void *ptr_data = ndarray->data; for(int i = 0; i < ndarray->shape->len; i++) { switch(ndarray->datatype) { case DT_INT: *(int*)ptr_data %= (int)value; break; case DT_DOUBLE: default: abort(); } ptr_data += ndarray->item_size; } } void NdArray_broadcast(NdArray *ndarray, broadcast_func bfunc) { void *ptr_data = ndarray->data; for(int i = 0; i < ndarray->shape->len; i++) { switch(ndarray->datatype) { case DT_INT: case DT_DOUBLE: bfunc(ptr_data); break; default: abort(); } ptr_data += ndarray->item_size; } } long NdArray_sum_char(NdArray *ndarray) { char *data = (char*)ndarray->data; long sum = 0; for(int i = 0; i < ndarray->shape->len; i++) { sum += data[i]; } return sum; } long NdArray_sum_int(NdArray *ndarray) { int *data = (int*)ndarray->data; long sum = 0; for(int i = 0; i < ndarray->shape->len; i++) { sum += data[i]; } return sum; } long double NdArray_sum_double(NdArray *ndarray) { double *data = (double*)ndarray->data; long double sum = 0; for(int i = 0; i < ndarray->shape->len; i++) { sum += data[i]; } return sum; } void* NdArray_sum(NdArray *ndarray) { void *ptr_sum = malloc(ndarray->item_size); if(ndarray->datatype == DT_INT) { *(int*)ptr_sum = NdArray_sum_int(ndarray); } else if(ndarray->datatype == DT_DOUBLE) { *(double*)ptr_sum = NdArray_sum_double(ndarray); } else if(ndarray->datatype == DT_BOOL) { *(char*)ptr_sum = NdArray_sum_char(ndarray); } else { abort(); } return ptr_sum; } NdShape* get_ndshape_axis(NdShape *self, unsigned int axis) { NdShape *shape_sum = NdShape_empty(self->dim-1); for(int i = 0; i < shape_sum->dim; i++) { shape_sum->arr[i] = (i >= axis) ? self->arr[i+1] : self->arr[i]; shape_sum->len *= shape_sum->arr[i]; } return shape_sum; } NdArray* get_ndarray_axis(NdArray *self, unsigned int axis, DataType datatype) { NdShape *shape_self = self->shape; NdShape *shape_sum = get_ndshape_axis(self->shape, axis); NdArray *array_sum = NdArray_new(NULL, shape_sum, datatype); return array_sum; } unsigned int get_step_axis(NdShape *self, unsigned int axis) { unsigned int step = self->len; for(int i = 0; i <= axis; i++) { step /= self->arr[i]; } return step; } NdArray* cal_array_sum_axis(NdArray *self, NdArray *result, unsigned int axis) { unsigned int step = get_step_axis(self->shape, axis); unsigned int memo[self->shape->len]; for(int i = 0; i < self->shape->len; i++) { memo[i] = 0; } void *cur = self->data; void *cur_result = result->data; void *sum = malloc(result->item_size); for(int i = 0; i < self->shape->len; i++) { if(memo[i] == 1) { continue; } memset(sum, 0, result->item_size); for(int j = 0; j < self->shape->arr[axis]; j++) { int idx = i + j * step; switch(result->datatype) { case DT_INT: *(int*)sum += *((int*)cur + idx); break; case DT_DOUBLE: *(double*)sum += *((double*)cur + idx); break; default: abort(); } memo[idx] = 1; } memcpy(cur_result, sum, result->item_size); cur_result += result->item_size; } free(sum); return result; } NdArray* cal_array_argmax_axis(NdArray *self, NdArray *result, unsigned int axis) { unsigned int step = get_step_axis(self->shape, axis); unsigned int memo[self->shape->len]; for(int i = 0; i < self->shape->len; i++) { memo[i] = 0; } void *cur = self->data; int *cur_result = result->data; void *max = malloc(self->item_size); int max_idx; for(int i = 0; i < self->shape->len; i++) { if(memo[i] == 1) { continue; } memcpy(max, cur + i * self->item_size, self->item_size); max_idx = 0; for(int j = 1; j < self->shape->arr[axis]; j++) { int idx = i + j * step; switch(self->datatype) { case DT_INT: if(*(int*)max < *((int*)cur + idx)) { *(int*)max = *((int*)cur + idx); max_idx = j; } break; case DT_DOUBLE: if(*(double*)max < *((double*)cur + idx)) { *(double*)max = *((double*)cur + idx); max_idx = j; } break; default: abort(); } memo[idx] = 1; } *cur_result = max_idx; cur_result++; } return result; } NdArray* cal_array_max_axis(NdArray *self, NdArray *result, unsigned int axis) { unsigned int step = get_step_axis(self->shape, axis); unsigned int memo[self->shape->len]; for(int i = 0; i < self->shape->len; i++) { memo[i] = 0; } void *cur = self->data; void *cur_result = result->data; void *max = malloc(self->item_size); for(int i = 0; i < self->shape->len; i++) { if(memo[i] == 1) { continue; } memcpy(max, cur + i * self->item_size, self->item_size); for(int j = 1; j < self->shape->arr[axis]; j++) { int idx = i + j * step; switch(self->datatype) { case DT_INT: if(*(int*)max < *((int*)cur + idx)) { *(int*)max = *((int*)cur + idx); } break; case DT_DOUBLE: if(*(double*)max < *((double*)cur + idx)) { *(double*)max = *((double*)cur + idx); } break; default: abort(); } memo[idx] = 1; } memcpy(cur_result, max, result->item_size); cur_result += result->item_size; } return result; } NdArray* NdArray_sum_axis(NdArray *self, unsigned int axis) { if(axis > self->shape->dim) { return NULL; } NdArray *array_sum = get_ndarray_axis(self, axis, self->datatype); cal_array_sum_axis(self, array_sum, axis); return array_sum; } NdArray* NdArray_max_axis(NdArray *self, unsigned int axis) { if(axis > self->shape->dim) { return NULL; } NdArray *array_max = get_ndarray_axis(self, axis, self->datatype); cal_array_max_axis(self, array_max, axis); return array_max; } NdArray* NdArray_argmax_axis(NdArray *self, unsigned int axis) { if(axis > self->shape->dim) { return NULL; } NdArray *array_argmax = get_ndarray_axis(self, axis, DT_INT); cal_array_argmax_axis(self, array_argmax, axis); return array_argmax; } int NdArray_max_int(NdArray *ndarray) { int *data = (int*)ndarray->data; int max = data[0]; for(int i = 1; i < ndarray->shape->len; i++) { max = (max < data[i]) ? data[i] : max; } return max; } double NdArray_max_double(NdArray *ndarray) { double *data = (double*)ndarray->data; double max = data[0]; for(int i = 1; i < ndarray->shape->len; i++) { max = (max < data[i]) ? data[i] : max; } return max; } void* NdArray_max(NdArray *ndarray) { void *ptr_max = malloc(ndarray->item_size); if(ndarray->datatype == DT_INT) { *(int*)ptr_max = NdArray_max_int(ndarray); } else if(ndarray->datatype == DT_DOUBLE) { *(double*)ptr_max = NdArray_max_double(ndarray); } return ptr_max; } int NdArray_min_int(NdArray *ndarray) { int *data = (int*)ndarray->data; int min = data[0]; for(int i = 1; i < ndarray->shape->len; i++) { min = (min > data[i]) ? data[i] : min; } return min; } double NdArray_min_double(NdArray *ndarray) { double *data = (double*)ndarray->data; double min = data[0]; for(int i = 1; i < ndarray->shape->len; i++) { min = (min > data[i]) ? data[i] : min; } return min; } void* NdArray_min(NdArray *ndarray) { void *ptr_min = malloc(ndarray->item_size); if(ndarray->datatype == DT_INT) { *(int*)ptr_min = NdArray_min_int(ndarray); } else if(ndarray->datatype == DT_DOUBLE) { *(double*)ptr_min = NdArray_min_double(ndarray); } return ptr_min; } double NdArray_mean_int(NdArray *ndarray) { int *data = (int*)ndarray->data; double mean = (double)NdArray_sum_int(ndarray) / ndarray->shape->len; return mean; } double NdArray_mean_double(NdArray *ndarray) { double *data = (double*)ndarray->data; double mean = NdArray_sum_double(ndarray) / ndarray->shape->len; return mean; } void* NdArray_mean(NdArray *ndarray) { void *ptr_mean = malloc(ndarray->item_size); if(ndarray->datatype == DT_INT) { *(int*)ptr_mean = NdArray_mean_int(ndarray); } else if(ndarray->datatype == DT_DOUBLE) { *(double*)ptr_mean = NdArray_mean_double(ndarray); } return ptr_mean; } int NdArray_argmax_int(NdArray *ndarray) { int *cur = ndarray->data; int max = *cur; unsigned int idx_max = 0; for(int i = 0; i < ndarray->shape->len; i++) { if(max < *cur) { max = *cur; idx_max = i; } cur++; } return idx_max; } int NdArray_argmax_double(NdArray *ndarray) { double *cur = ndarray->data; double max = *cur; unsigned int idx_max = 0; for(int i = 0; i < ndarray->shape->len; i++) { if(max < *cur) { max = *cur; idx_max = i; } cur++; } return idx_max; } int NdArray_argmax(NdArray *ndarray) { void *cur = ndarray->data; if(ndarray->datatype == DT_INT) { return NdArray_argmax_int(ndarray); } else if(ndarray->datatype == DT_DOUBLE) { return NdArray_argmax_double(ndarray); } return -1; } int NdArray_argmin_int(NdArray *ndarray) { int *cur = ndarray->data; int min = *cur; unsigned int idx_min = 0; for(int i = 0; i < ndarray->shape->len; i++) { if(min > *cur) { min = *cur; idx_min = i; } cur++; } return idx_min; } int NdArray_argmin_double(NdArray *ndarray) { double *cur = ndarray->data; double min = *cur; unsigned int idx_min = 0; for(int i = 0; i < ndarray->shape->len; i++) { if(min > *cur) { min = *cur; idx_min = i; } cur++; } return idx_min; } int NdArray_argmin(NdArray *ndarray) { void *cur = ndarray->data; if(ndarray->datatype == DT_INT) { return NdArray_argmin_int(ndarray); } else if(ndarray->datatype == DT_DOUBLE) { return NdArray_argmin_double(ndarray); } return -1; } void _convert_datatype_from_int_to_double(NdArray **ptr_self) { NdArray *self = *ptr_self; NdArray *converted = NdArray_new(NULL, self->shape, DT_DOUBLE); int* cur_self = self->data; double* cur_conv = converted->data; for(int i = 0; i < converted->shape->len; i++) { cur_conv[i] = (double)cur_self[i]; } NdArray_free(&self); *ptr_self = converted; } void _convert_datatype_from_double_to_int(NdArray **ptr_self) { NdArray *self = *ptr_self; NdArray *converted = NdArray_new(NULL, self->shape, DT_INT); double* cur_self = self->data; int* cur_conv = converted->data; for(int i = 0; i < converted->shape->len; i++) { cur_conv[i] = (int)cur_self[i]; } NdArray_free(&self); *ptr_self = converted; } void NdArray_convert_type(NdArray **ptr_self, DataType datatype) { NdArray *self = *ptr_self; if(self->datatype == datatype) { return; } if(self->datatype == DT_INT && datatype == DT_DOUBLE) { _convert_datatype_from_int_to_double(ptr_self); } else if(self->datatype == DT_DOUBLE && datatype == DT_INT) { _convert_datatype_from_double_to_int(ptr_self); } } int _compare_int(int a, int b) { return a - b; } int _compare_double(double a, double b) { double temp = a - b; if(temp > 0) { return 1; } else if(temp < 0) { return -1; } else { return 0; } } int _compare_element(const void *a, const void *b, DataType datatype) { if(datatype == DT_INT) { return _compare_int(*(int*)a, *(int*)b); } else if(datatype == DT_DOUBLE) { return _compare_double(*(double*)a, *(double*)b); } else { abort(); } } int _compare_element_scalar(const void *self, double value, DataType datatype) { if(datatype == DT_INT) { double temp = (double)(*(int*)self); return _compare_double(temp, value); } else if(datatype == DT_DOUBLE) { return _compare_double(*(double*)self, value); } else { abort(); } } void _set_bool(void *cur, DataType datatype, int bool_value, CompareTag ct) { if(ct == CT_GT && bool_value <= 0) { memset(cur, 0, get_item_size(datatype)); } else if(ct == CT_GE && bool_value < 0) { memset(cur, 0, get_item_size(datatype)); } else if(ct == CT_LT && bool_value >= 0) { memset(cur, 0, get_item_size(datatype)); } else if(ct == CT_LE && bool_value > 0) { memset(cur, 0, get_item_size(datatype)); } else if(ct == CT_EQ && bool_value != 0) { memset(cur, 0, get_item_size(datatype)); } else { *(char*)cur= 1; } } NdArray* NdArray_compare(NdArray *a, NdArray *b, CompareTag ct) { assert(a->shape->dim == b->shape->dim); assert(a->shape->len == b->shape->len); assert(a->datatype == b->datatype); NdArray *result = NdArray_new(NULL, a->shape, DT_BOOL); void *cur_a = a->data; void *cur_b = b->data; void *cur_result = result->data; int bool_value = 0; for(int i = 0; i < a->shape->len; i++) { int bool_value = _compare_element(cur_a, cur_b, a->datatype); _set_bool(cur_result, result->datatype, bool_value, ct); cur_a += a->item_size; cur_b += b->item_size; cur_result += result->item_size; } return result; } NdArray* NdArray_compare_scalar(NdArray *self, double value, CompareTag ct) { NdArray *result = NdArray_new(NULL, self->shape, DT_BOOL); void *cur_self = self->data; void *cur_result = result->data; int bool_value = 0; for(int i = 0; i < self->shape->len; i++) { int bool_value = _compare_element_scalar(cur_self, value, self->datatype); _set_bool(cur_result, result->datatype, bool_value, ct); cur_self += self->item_size; cur_result += result->item_size; } return result; } NdArray* NdArray_mask(NdArray *self, NdArray *mask) { NdArray* result = NdArray_new(NULL, self->shape, self->datatype); void* cur_self = self->data; void* cur_mask = mask->data; void* cur_result = result->data; for(int i = 0; i < self->shape->len; i++) { if(*(char*)cur_mask) { memcpy(cur_result, cur_self, self->item_size); } cur_self += self->item_size; cur_mask += mask->item_size; cur_result += result->item_size; } return result; }
GB_unop__tanh_fc32_fc32.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__tanh_fc32_fc32) // op(A') function: GB (_unop_tran__tanh_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = ctanhf (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 = ctanhf (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] = ctanhf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TANH || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__tanh_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] = ctanhf (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] = ctanhf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__tanh_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
openmp.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <OpenCL/opencl.h> // #include <omp.h> //Student ID: 21804416 //Name: SUN QIANG //Where use openmp speed up: //Here we have four tasks using openmp to speed up //1. use openmp to sort all columns //2. use openmp to generate blocks //3. The key point here, use openmp to sort all the signtures(29333879), the openmp speed up is very useful here // At first, I can not sort 29333879 signtures with my computer using only one thread, always core down // Then, when I use openmp here, then problem solved. //4. Divide sorted signatures with different parts, and find collisions with openmp //Where still need speed up //There are still some problems we can do to speed up: //The last column(500), generated 29321366 signtures, and the left 499 colunms generated 12510 signtures // So when we find blocks, most time spent on find blocks in 500 columns with one thread, the other threads are idle. // However, the time spent to find the blocks in 500 colunm is not very long; // And we need to keep this program working for any M*N matrix, so I have not done any improvement here. // we can change the N & M to make this program suitable for some other N*M matrix // we can change the dia to other value // Change the Max value if the number of blocks is larger than that #define N 500 #define M 4400 #define dia 0.000001 #define Max 30000000 // --------- // The data array to store the data information // The key array to store key information // When we want to sort values in each column in data, we only need to sort the seq array to store the sequences // Location of data value, not directly modify the data array. // Signs array to store the signtures for blocks // Location array to store the row ids and column for corresponding signture, for example 434044402220999499 means // The block combined by 434,444,222,999 rows from 499 column. // Indexs to store how many blocks generated // Id is the same function as the seq array, to store the location information of the signture //---------- //readData() and readkey() to read values from txt, generate two arrays // Generate() is to generate the seq array // sort() is to sort each column in data // SelectSort() Bubblesort() are used to sort the values (we can use some other methods) // Findblock() and findblockcol() are used to generate columns //Sortsign() and BubbleSortsign() are single thread ways to sort the signtures. // quicksort() is the method which use multiple threads with openmp to sort the signtures based on quicksort. // resulttxt() is used to print the outcome with two colunm (signture,id) static double data[N][M]; static long key[M]; static int seq[N][M]; static long signs[Max]; static long location[Max]; static int indexs; static int id[Max]={-1}; int k=0; void readData(); void readkey(); void generate(); void sort(); void SelectSort(int a[],int n,double b[]); void BubbleSort(int a[],int n,double b[]); void findblock(); void findblockcol(int i,double x[]); void Sortsign(int a[],int n, long b[]); void BubbleSortsign(int a[],int n,long b[]); void resulttxt(); void quicksort(long arr[], int low_index, int high_index); int partition(long * a, int p, int r); int main(){ //start to count time //pre-process for the data readData(); readkey(); generate(); // sort each column sort(); indexs=0; // Find all blocks and store them into signs and location findblock(); //print number of blocks found printf("Number of blcoks found %d\n",indexs); int i; for(i=0;i<indexs;i++){ id[i]=i; } //Sort signture with different ways (Sortsign and bubblesort are using single thread, and quicksort is using openmp) // Sortsign(id,indexs,signs); // quicksort for openmp here quicksort(signs,0,indexs-1); //Find collsions and print it to result.txt resulttxt(); } //Print out the results into results.txt with (signtures,id)(id generate by four row ids and the column id) void resulttxt(){ int left =0; int indexsnon=0; long where; FILE *fp; fp = fopen("results.txt","a"); int i; int col=0; for(i=0;i<indexs;i++){ if(signs[id[i]]!=signs[id[i+1]] && signs[id[i]]!=signs[id[i-1]]){ indexsnon=indexsnon+1; } else{ fprintf(fp,"%ld %ld\n",signs[id[i]],location[id[i]]); col=col+1; } } fclose(fp); printf("The number of collsions found: %d\n",col); } //Read keys void readkey() { FILE *fp; char *line = NULL; size_t len = 0; ssize_t read; int line_index = 0; int column_index = 0; fp = fopen("keys.txt","r"); if (fp ==NULL) exit(EXIT_FAILURE); while((read = getline(&line,&len,fp))!=-1) { char *pch; pch=strtok(line," "); while (pch!=NULL) { sscanf(pch,"%ld",&key[column_index]); column_index +=1; pch = strtok(NULL," "); } line_index+=1; } fclose(fp); if(line) free(line); } //Read data void readData() { FILE *fp; char *line = NULL; size_t len = 0; ssize_t read; int line_index = 0; int column_index; fp = fopen("data.txt","r"); if (fp ==NULL) exit(EXIT_FAILURE); while((read = getline(&line,&len,fp))!=-1) { char *pch; column_index=0; pch=strtok(line," ,"); while (pch!=NULL) { sscanf(pch,"%lf",&data[column_index][line_index]); column_index +=1; pch = strtok(NULL," ,"); } line_index+=1; } fclose(fp); if(line) free(line); } void generate(){ //Generate an array with N*M, and each a[i] with 0-4399 int i,j; for(i = 0;i<N;i++) { for (j =0;j<M;j++) { seq[i][j]=j; } } } //Sort each column void sort() { int i,j; ////////Here to change #pragma omp parallel for for(i = 0;i < N-1;i++){ // We can use different methods to sort here SelectSort(seq[i],M,data[i]); // BubbleSort(seq[i],M,data[i]); } } //Select sort method to sort column void SelectSort(int a[],int n, double b[]) { int i,j; for(i=0;i<n-1;i++) { int k=i; for(j=i+1;j<n;j++) if(b[a[k]]>b[a[j]]) k=j; if(k!=i) { int temp=a[i]; a[i]=a[k]; a[k]=temp; } } } //Select sort method for signtures void Sortsign(int a[],int n, long b[]) { int i,j; for(i=0;i<n-1;i++) { //printf("%d %ld\n", i,b[i]); int k=i; for(j=i+1;j<n;j++) if(b[a[k]]>b[a[j]]) k=j; if(k!=i) { int temp=a[i]; a[i]=a[k]; a[k]=temp; } } } //Bubble sort for signtures void BubbleSortsign(int a[],int n,long b[]) { int i,j; for(i=n-1;i>0;--i){ // printf("%d %ld\n", i,b[i]); for(j=0;j<i;j++){ if(b[a[j]]>b[a[j+1]]) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("ok\n"); } //Find all blocks void findblock(){ ///////Here to change int i,j; //Use the openmp here to find blocks #pragma omp parallel for //Change i<N-1 to calculate the outcome without last column. i<N to calculate the outcome with last column. for(i=0;i<N-1;i++){ findblockcol(i,data[i]); } } void findblockcol(int i,double x[]){ int nums=0; int a,c,d; long b; long sign; long uni; // FILE *fp; // fp=fopen("blocks.txt","a"); #pragma omp parallel for for(a=0;a<M;a++){ b=a+1; while(x[seq[i][b]]-x[seq[i][a]]<dia && b <M && x[seq[i][a]]!=0 && x[seq[i][b]]!=0) { c=b+1; while(x[seq[i][c]]-x[seq[i][a]]<dia && c<M && x[seq[i][c]]!=0){ d = c+1; while(x[seq[i][d]]-x[seq[i][a]]<dia && d<M && x[seq[i][d]]!=0) { indexs=indexs+1; sign=key[a]+key[b]+key[c]+key[d]; signs[indexs-1]=sign; uni=(a*1000000000000+b*100000000+c*10000+d)*1000+i; location[indexs-1]=uni; // fprintf(fp,"%ld %ld \n",sign,uni); d = d+1; nums=nums+1; } c=c+1; } b=b+1; } } // fclose(fp); printf("Number found for %d column: %d\n",i+1,nums); } int partition(long * a, int p, int r) { int lt[r-p]; int gt[r-p]; int i; int j; int key = a[r]; int lt_n = 0; int gt_n = 0; #pragma omp parallel for for(i = p; i < r; i++){ if(a[i] < a[r]){ lt[lt_n++] = a[i]; }else{ gt[gt_n++] = a[i]; } } for(i = 0; i < lt_n; i++){ a[p + i] = lt[i]; } a[p + lt_n] = key; for(j = 0; j < gt_n; j++){ a[p + lt_n + j + 1] = gt[j]; } return p + lt_n; } void quicksort(long * a, int p, int r) { int div; if(p < r){ div = partition(a, p, r); #pragma omp parallel sections { #pragma omp section quicksort(a, p, div - 1); #pragma omp section quicksort(a, div + 1, r); } } }
GB_binop__isle_int16.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__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_08__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_02__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_04__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isle_int16) // A*D function (colscale): GB (_AxD__isle_int16) // D*A function (rowscale): GB (_DxB__isle_int16) // C+=B function (dense accum): GB (_Cdense_accumB__isle_int16) // C+=b function (dense accum): GB (_Cdense_accumb__isle_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isle_int16) // C=scalar+B GB (_bind1st__isle_int16) // C=scalar+B' GB (_bind1st_tran__isle_int16) // C=A+scalar GB (_bind2nd__isle_int16) // C=A'+scalar GB (_bind2nd_tran__isle_int16) // C type: int16_t // A type: int16_t // A pattern? 0 // B type: int16_t // B pattern? 0 // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_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) \ int16_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) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x <= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISLE || GxB_NO_INT16 || GxB_NO_ISLE_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isle_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isle_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isle_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isle_int16) ( 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 int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isle_int16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isle_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; int16_t alpha_scalar ; int16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int16_t *) alpha_scalar_in)) ; beta_scalar = (*((int16_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isle_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isle_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isle_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isle_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isle_int16) ( 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 int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x <= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isle_int16) ( 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 ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = 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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB (_bind1st_tran__isle_int16) ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB (_bind2nd_tran__isle_int16) ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_fp32_int32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fp32_int32) // op(A') function: GB (_unop_tran__identity_fp32_int32) // C type: float // A type: int32_t // cast: float cij = (float) aij // unaryop: cij = aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ float // 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) \ float z = (float) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (float) aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fp32_int32) ( float *Cx, // Cx and Ax may be aliased const int32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (int32_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t aij = Ax [p] ; float z = (float) aij ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int32_t aij = Ax [p] ; float z = (float) 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_fp32_int32) ( 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
nvector_openmp.c
/* ----------------------------------------------------------------- * Programmer(s): David J. Gardner and Carol S. Woodward @ LLNL * ----------------------------------------------------------------- * Acknowledgements: This NVECTOR module is based on the NVECTOR * Serial module by Scott D. Cohen, Alan C. * Hindmarsh, Radu Serban, and Aaron Collier * @ 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 implementation file for an OpenMP implementation * of the NVECTOR module. * -----------------------------------------------------------------*/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <nvector/nvector_openmp.h> #include <sundials/sundials_math.h> #define ZERO RCONST(0.0) #define HALF RCONST(0.5) #define ONE RCONST(1.0) #define ONEPT5 RCONST(1.5) /* Private functions for special cases of vector operations */ static void VCopy_OpenMP(N_Vector x, N_Vector z); /* z=x */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x+y */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x-y */ static void VNeg_OpenMP(N_Vector x, N_Vector z); /* z=-x */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x+y) */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x-y) */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax+y */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax-y */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y); /* y <- ax+y */ static void VScaleBy_OpenMP(realtype a, N_Vector x); /* x <- ax */ /* Private functions for special cases of vector array operations */ static int VSumVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X+Y */ static int VDiffVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X-Y */ static int VScaleSumVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X+Y) */ static int VScaleDiffVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X-Y) */ static int VLin1VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX+Y */ static int VLin2VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX-Y */ static int VaxpyVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y); /* Y <- aX+Y */ /* * ----------------------------------------------------------------- * exported functions * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------- * Returns vector type ID. Used to identify vector implementation * from abstract N_Vector interface. */ N_Vector_ID N_VGetVectorID_OpenMP(N_Vector v) { return SUNDIALS_NVEC_OPENMP; } /* ---------------------------------------------------------------------------- * Function to create a new empty vector */ N_Vector N_VNewEmpty_OpenMP(sunindextype length, int num_threads) { N_Vector v; N_Vector_Ops ops; N_VectorContent_OpenMP content; /* Create vector */ v = NULL; v = (N_Vector) malloc(sizeof *v); if (v == NULL) return(NULL); /* Create vector operation structure */ ops = NULL; ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops)); if (ops == NULL) { free(v); return(NULL); } ops->nvgetvectorid = N_VGetVectorID_OpenMP; ops->nvclone = N_VClone_OpenMP; ops->nvcloneempty = N_VCloneEmpty_OpenMP; ops->nvdestroy = N_VDestroy_OpenMP; ops->nvspace = N_VSpace_OpenMP; ops->nvgetarraypointer = N_VGetArrayPointer_OpenMP; ops->nvsetarraypointer = N_VSetArrayPointer_OpenMP; /* standard vector operations */ ops->nvlinearsum = N_VLinearSum_OpenMP; ops->nvconst = N_VConst_OpenMP; ops->nvprod = N_VProd_OpenMP; ops->nvdiv = N_VDiv_OpenMP; ops->nvscale = N_VScale_OpenMP; ops->nvabs = N_VAbs_OpenMP; ops->nvinv = N_VInv_OpenMP; ops->nvaddconst = N_VAddConst_OpenMP; ops->nvdotprod = N_VDotProd_OpenMP; ops->nvmaxnorm = N_VMaxNorm_OpenMP; ops->nvwrmsnormmask = N_VWrmsNormMask_OpenMP; ops->nvwrmsnorm = N_VWrmsNorm_OpenMP; ops->nvmin = N_VMin_OpenMP; ops->nvwl2norm = N_VWL2Norm_OpenMP; ops->nvl1norm = N_VL1Norm_OpenMP; ops->nvcompare = N_VCompare_OpenMP; ops->nvinvtest = N_VInvTest_OpenMP; ops->nvconstrmask = N_VConstrMask_OpenMP; ops->nvminquotient = N_VMinQuotient_OpenMP; /* fused vector operations (optional, NULL means disabled by default) */ ops->nvlinearcombination = NULL; ops->nvscaleaddmulti = NULL; ops->nvdotprodmulti = NULL; /* vector array operations (optional, NULL means disabled by default) */ ops->nvlinearsumvectorarray = NULL; ops->nvscalevectorarray = NULL; ops->nvconstvectorarray = NULL; ops->nvwrmsnormvectorarray = NULL; ops->nvwrmsnormmaskvectorarray = NULL; ops->nvscaleaddmultivectorarray = NULL; ops->nvlinearcombinationvectorarray = NULL; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof(struct _N_VectorContent_OpenMP)); if (content == NULL) { free(ops); free(v); return(NULL); } content->length = length; content->num_threads = num_threads; content->own_data = SUNFALSE; content->data = NULL; /* Attach content and ops */ v->content = content; v->ops = ops; return(v); } /* ---------------------------------------------------------------------------- * Function to create a new vector */ N_Vector N_VNew_OpenMP(sunindextype length, int num_threads) { N_Vector v; realtype *data; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create a vector with user data component */ N_Vector N_VMake_OpenMP(sunindextype length, realtype *v_data, int num_threads) { N_Vector v; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); if (length > 0) { /* Attach data */ NV_OWN_DATA_OMP(v) = SUNFALSE; NV_DATA_OMP(v) = v_data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors. */ N_Vector *N_VCloneVectorArray_OpenMP(int count, N_Vector w) { N_Vector *vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector *) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VClone_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors with NULL data array. */ N_Vector *N_VCloneVectorArrayEmpty_OpenMP(int count, N_Vector w) { N_Vector *vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector *) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VCloneEmpty_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to free an array created with N_VCloneVectorArray_OpenMP */ void N_VDestroyVectorArray_OpenMP(N_Vector *vs, int count) { int j; for (j = 0; j < count; j++) N_VDestroy_OpenMP(vs[j]); free(vs); vs = NULL; return; } /* ---------------------------------------------------------------------------- * Function to return number of vector elements */ sunindextype N_VGetLength_OpenMP(N_Vector v) { return NV_LENGTH_OMP(v); } /* ---------------------------------------------------------------------------- * Function to print a vector to stdout */ void N_VPrint_OpenMP(N_Vector x) { N_VPrintFile_OpenMP(x, stdout); } /* ---------------------------------------------------------------------------- * Function to print a vector to outfile */ void N_VPrintFile_OpenMP(N_Vector x, FILE *outfile) { sunindextype i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); for (i = 0; i < N; i++) { #if defined(SUNDIALS_EXTENDED_PRECISION) fprintf(outfile, "%11.8Lg\n", xd[i]); #elif defined(SUNDIALS_DOUBLE_PRECISION) fprintf(outfile, "%11.8g\n", xd[i]); #else fprintf(outfile, "%11.8g\n", xd[i]); #endif } fprintf(outfile, "\n"); return; } /* * ----------------------------------------------------------------- * implementation of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Create new vector from existing vector without attaching data */ N_Vector N_VCloneEmpty_OpenMP(N_Vector w) { N_Vector v; N_Vector_Ops ops; N_VectorContent_OpenMP content; if (w == NULL) return(NULL); /* Create vector */ v = NULL; v = (N_Vector) malloc(sizeof *v); if (v == NULL) return(NULL); /* Create vector operation structure */ ops = NULL; ops = (N_Vector_Ops) malloc(sizeof(struct _generic_N_Vector_Ops)); if (ops == NULL) { free(v); return(NULL); } ops->nvgetvectorid = w->ops->nvgetvectorid; ops->nvclone = w->ops->nvclone; ops->nvcloneempty = w->ops->nvcloneempty; ops->nvdestroy = w->ops->nvdestroy; ops->nvspace = w->ops->nvspace; ops->nvgetarraypointer = w->ops->nvgetarraypointer; ops->nvsetarraypointer = w->ops->nvsetarraypointer; /* standard vector operations */ ops->nvlinearsum = w->ops->nvlinearsum; ops->nvconst = w->ops->nvconst; ops->nvprod = w->ops->nvprod; ops->nvdiv = w->ops->nvdiv; ops->nvscale = w->ops->nvscale; ops->nvabs = w->ops->nvabs; ops->nvinv = w->ops->nvinv; ops->nvaddconst = w->ops->nvaddconst; ops->nvdotprod = w->ops->nvdotprod; ops->nvmaxnorm = w->ops->nvmaxnorm; ops->nvwrmsnormmask = w->ops->nvwrmsnormmask; ops->nvwrmsnorm = w->ops->nvwrmsnorm; ops->nvmin = w->ops->nvmin; ops->nvwl2norm = w->ops->nvwl2norm; ops->nvl1norm = w->ops->nvl1norm; ops->nvcompare = w->ops->nvcompare; ops->nvinvtest = w->ops->nvinvtest; ops->nvconstrmask = w->ops->nvconstrmask; ops->nvminquotient = w->ops->nvminquotient; /* fused vector operations */ ops->nvlinearcombination = w->ops->nvlinearcombination; ops->nvscaleaddmulti = w->ops->nvscaleaddmulti; ops->nvdotprodmulti = w->ops->nvdotprodmulti; /* vector array operations */ ops->nvlinearsumvectorarray = w->ops->nvlinearsumvectorarray; ops->nvscalevectorarray = w->ops->nvscalevectorarray; ops->nvconstvectorarray = w->ops->nvconstvectorarray; ops->nvwrmsnormvectorarray = w->ops->nvwrmsnormvectorarray; ops->nvwrmsnormmaskvectorarray = w->ops->nvwrmsnormmaskvectorarray; ops->nvscaleaddmultivectorarray = w->ops->nvscaleaddmultivectorarray; ops->nvlinearcombinationvectorarray = w->ops->nvlinearcombinationvectorarray; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof(struct _N_VectorContent_OpenMP)); if (content == NULL) { free(ops); free(v); return(NULL); } content->length = NV_LENGTH_OMP(w); content->num_threads = NV_NUM_THREADS_OMP(w); content->own_data = SUNFALSE; content->data = NULL; /* Attach content and ops */ v->content = content; v->ops = ops; return(v); } /* ---------------------------------------------------------------------------- * Create new vector from existing vector and attach data */ N_Vector N_VClone_OpenMP(N_Vector w) { N_Vector v; realtype *data; sunindextype length; v = NULL; v = N_VCloneEmpty_OpenMP(w); if (v == NULL) return(NULL); length = NV_LENGTH_OMP(w); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Destroy vector and free vector memory */ void N_VDestroy_OpenMP(N_Vector v) { if (NV_OWN_DATA_OMP(v) == SUNTRUE) { free(NV_DATA_OMP(v)); NV_DATA_OMP(v) = NULL; } free(v->content); v->content = NULL; free(v->ops); v->ops = NULL; free(v); v = NULL; return; } /* ---------------------------------------------------------------------------- * Get storage requirement for N_Vector */ void N_VSpace_OpenMP(N_Vector v, sunindextype *lrw, sunindextype *liw) { *lrw = NV_LENGTH_OMP(v); *liw = 1; return; } /* ---------------------------------------------------------------------------- * Get vector data pointer */ realtype *N_VGetArrayPointer_OpenMP(N_Vector v) { return((realtype *) NV_DATA_OMP(v)); } /* ---------------------------------------------------------------------------- * Set vector data pointer */ void N_VSetArrayPointer_OpenMP(realtype *v_data, N_Vector v) { if (NV_LENGTH_OMP(v) > 0) NV_DATA_OMP(v) = v_data; return; } /* ---------------------------------------------------------------------------- * Compute linear combination z[i] = a*x[i]+b*y[i] */ void N_VLinearSum_OpenMP(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z) { sunindextype i, N; realtype c, *xd, *yd, *zd; N_Vector v1, v2; booleantype test; xd = yd = zd = NULL; if ((b == ONE) && (z == y)) { /* BLAS usage: axpy y <- ax+y */ Vaxpy_OpenMP(a,x,y); return; } if ((a == ONE) && (z == x)) { /* BLAS usage: axpy x <- by+x */ Vaxpy_OpenMP(b,y,x); return; } /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) { VSum_OpenMP(x, y, z); return; } /* Cases: (1) a == 1.0, b = -1.0, (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { v1 = test ? y : x; v2 = test ? x : y; VDiff_OpenMP(v2, v1, z); return; } /* Cases: (1) a == 1.0, b == other or 0.0, (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin1_OpenMP(c, v1, v2, z); return; } /* Cases: (1) a == -1.0, b != 1.0, (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin2_OpenMP(c, v1, v2, z); return; } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) { VScaleSum_OpenMP(a, x, y, z); return; } /* Case: a == -b */ if (a == -b) { VScaleDiff_OpenMP(a, x, y, z); return; } /* Do all cases not handled above: (1) a == other, b == 0.0 - user should have called N_VScale (2) a == 0.0, b == other - user should have called N_VScale (3) a,b == other, a !=b, a != -b */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,b,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+(b*yd[i]); return; } /* ---------------------------------------------------------------------------- * Assigns constant value to all vector elements, z[i] = c */ void N_VConst_OpenMP(realtype c, N_Vector z) { sunindextype i, N; realtype *zd; zd = NULL; N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(z)) for (i = 0; i < N; i++) zd[i] = c; return; } /* ---------------------------------------------------------------------------- * Compute componentwise product z[i] = x[i]*y[i] */ void N_VProd_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]*yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise division z[i] = x[i]/y[i] */ void N_VDiv_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]/yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaler multiplication z[i] = c*x[i] */ void N_VScale_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; if (z == x) { /* BLAS usage: scale x <- cx */ VScaleBy_OpenMP(c, x); return; } if (c == ONE) { VCopy_OpenMP(x, z); } else if (c == -ONE) { VNeg_OpenMP(x, z); } else { N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*xd[i]; } return; } /* ---------------------------------------------------------------------------- * Compute absolute value of vector components z[i] = SUNRabs(x[i]) */ void N_VAbs_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = SUNRabs(xd[i]); return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = 1 / x[i] */ void N_VInv_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = ONE/xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise addition of a scaler to a vector z[i] = x[i] + b */ void N_VAddConst_OpenMP(N_Vector x, realtype b, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,b,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+b; return; } /* ---------------------------------------------------------------------------- * Computes the dot product of two vectors, a = sum(x[i]*y[i]) */ realtype N_VDotProd_OpenMP(N_Vector x, N_Vector y) { sunindextype i, N; realtype sum, *xd, *yd; sum = ZERO; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); #pragma omp parallel for default(none) private(i) shared(N,xd,yd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += xd[i]*yd[i]; } return(sum); } /* ---------------------------------------------------------------------------- * Computes max norm of a vector */ realtype N_VMaxNorm_OpenMP(N_Vector x) { sunindextype i, N; realtype tmax, max, *xd; max = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel default(none) private(i,tmax) shared(N,max,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmax = ZERO; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (SUNRabs(xd[i]) > tmax) tmax = SUNRabs(xd[i]); } #pragma omp critical { if (tmax > max) max = tmax; } } return(max); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a vector */ realtype N_VWrmsNorm_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum/N)); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a masked vector */ realtype N_VWrmsNormMask_OpenMP(N_Vector x, N_Vector w, N_Vector id) { sunindextype i, N; realtype sum, *xd, *wd, *idd; sum = ZERO; xd = wd = idd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); idd = NV_DATA_OMP(id); #pragma omp parallel for default(none) private(i) shared(N,xd,wd,idd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (idd[i] > ZERO) { sum += SUNSQR(xd[i]*wd[i]); } } return(SUNRsqrt(sum / N)); } /* ---------------------------------------------------------------------------- * Finds the minimun component of a vector */ realtype N_VMin_OpenMP(N_Vector x) { sunindextype i, N; realtype min, *xd; realtype tmin; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); min = xd[0]; #pragma omp parallel default(none) private(i,tmin) shared(N,min,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmin = xd[0]; #pragma omp for schedule(static) for (i = 1; i < N; i++) { if (xd[i] < tmin) tmin = xd[i]; } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* ---------------------------------------------------------------------------- * Computes weighted L2 norm of a vector */ realtype N_VWL2Norm_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum)); } /* ---------------------------------------------------------------------------- * Computes L1 norm of a vector */ realtype N_VL1Norm_OpenMP(N_Vector x) { sunindextype i, N; realtype sum, *xd; sum = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,xd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i<N; i++) sum += SUNRabs(xd[i]); return(sum); } /* ---------------------------------------------------------------------------- * Compare vector component values to a scaler */ void N_VCompare_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { zd[i] = (SUNRabs(xd[i]) >= c) ? ONE : ZERO; } return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = ONE/x[i] and checks if x[i] == ZERO */ booleantype N_VInvTest_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd, val; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); val = ZERO; #pragma omp parallel for default(none) private(i) shared(N,val,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (xd[i] == ZERO) val = ONE; else zd[i] = ONE/xd[i]; } if (val > ZERO) return (SUNFALSE); else return (SUNTRUE); } /* ---------------------------------------------------------------------------- * Compute constraint mask of a vector */ booleantype N_VConstrMask_OpenMP(N_Vector c, N_Vector x, N_Vector m) { sunindextype i, N; realtype temp; realtype *cd, *xd, *md; booleantype test; cd = xd = md = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); cd = NV_DATA_OMP(c); md = NV_DATA_OMP(m); temp = ZERO; #pragma omp parallel for default(none) private(i,test) shared(N,xd,cd,md,temp) \ schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { md[i] = ZERO; /* Continue if no constraints were set for the variable */ if (cd[i] == ZERO) continue; /* Check if a set constraint has been violated */ test = (SUNRabs(cd[i]) > ONEPT5 && xd[i]*cd[i] <= ZERO) || (SUNRabs(cd[i]) > HALF && xd[i]*cd[i] < ZERO); if (test) { temp = md[i] = ONE; /* Here is a race to write to temp */ } } /* Return false if any constraint was violated */ return (temp == ONE) ? SUNFALSE : SUNTRUE; } /* ---------------------------------------------------------------------------- * Compute minimum componentwise quotient */ realtype N_VMinQuotient_OpenMP(N_Vector num, N_Vector denom) { sunindextype i, N; realtype *nd, *dd, min, tmin, val; nd = dd = NULL; N = NV_LENGTH_OMP(num); nd = NV_DATA_OMP(num); dd = NV_DATA_OMP(denom); min = BIG_REAL; #pragma omp parallel default(none) private(i,tmin,val) shared(N,min,nd,dd) \ num_threads(NV_NUM_THREADS_OMP(num)) { tmin = BIG_REAL; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (dd[i] != ZERO) { val = nd[i]/dd[i]; if (val < tmin) tmin = val; } } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* * ----------------------------------------------------------------- * fused vector operations * ----------------------------------------------------------------- */ int N_VLinearCombination_OpenMP(int nvec, realtype* c, N_Vector* X, N_Vector z) { int i; sunindextype j, N; realtype* zd=NULL; realtype* xd=NULL; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VScale */ if (nvec == 1) { N_VScale_OpenMP(c[0], X[0], z); return(0); } /* should have called N_VLinearSum */ if (nvec == 2) { N_VLinearSum_OpenMP(c[0], X[0], c[1], X[1], z); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); /* * X[0] += c[i]*X[i], i = 1,...,nvec-1 */ if ((X[0] == z) && (c[0] == ONE)) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } /* * X[0] = c[0] * X[0] + sum{ c[i] * X[i] }, i = 1,...,nvec-1 */ if (X[0] == z) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] *= c[0]; } for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } /* * z = sum{ c[i] * X[i] }, i = 0,...,nvec-1 */ #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { xd = NV_DATA_OMP(X[0]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c[0] * xd[j]; } for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } int N_VScaleAddMulti_OpenMP(int nvec, realtype* a, N_Vector x, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VLinearSum */ if (nvec == 1) { N_VLinearSum_OpenMP(a[0], x, ONE, Y[0], Z[0]); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); /* * Y[i][j] += a[i] * x[j] */ if (Y == Z) { #pragma omp parallel default(none) private(i,j,yd) shared(nvec,Y,N,a,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { yd[j] += a[i] * xd[j]; } } } return(0); } /* * Z[i][j] = Y[i][j] + a[i] * x[j] */ #pragma omp parallel default(none) private(i,j,yd,zd) shared(nvec,Y,Z,N,a,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = a[i] * xd[j] + yd[j]; } } } return(0); } int N_VDotProdMulti_OpenMP(int nvec, N_Vector x, N_Vector* Y, realtype* dotprods) { int i; sunindextype j, N; realtype sum; realtype* xd=NULL; realtype* yd=NULL; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VDotProd */ if (nvec == 1) { dotprods[0] = N_VDotProd_OpenMP(x, Y[0]); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); /* initialize dot products */ for (i=0; i<nvec; i++) { dotprods[i] = ZERO; } /* compute multiple dot products */ #pragma omp parallel default(none) private(i,j,yd,sum) shared(nvec,Y,N,xd,dotprods) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { sum += xd[j] * yd[j]; } #pragma omp critical { dotprods[i] += sum; } } } return(0); } /* * ----------------------------------------------------------------- * vector array operations * ----------------------------------------------------------------- */ int N_VLinearSumVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, realtype b, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; realtype c; N_Vector* V1; N_Vector* V2; booleantype test; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VLinearSum */ if (nvec == 1) { N_VLinearSum_OpenMP(a, X[0], b, Y[0], Z[0]); return(0); } /* BLAS usage: axpy y <- ax+y */ if ((b == ONE) && (Z == Y)) return(VaxpyVectorArray_OpenMP(nvec, a, X, Y)); /* BLAS usage: axpy x <- by+x */ if ((a == ONE) && (Z == X)) return(VaxpyVectorArray_OpenMP(nvec, b, Y, X)); /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) return(VSumVectorArray_OpenMP(nvec, X, Y, Z)); /* Cases: */ /* (1) a == 1.0, b = -1.0, */ /* (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { V1 = test ? Y : X; V2 = test ? X : Y; return(VDiffVectorArray_OpenMP(nvec, V2, V1, Z)); } /* Cases: */ /* (1) a == 1.0, b == other or 0.0, */ /* (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; V1 = test ? Y : X; V2 = test ? X : Y; return(VLin1VectorArray_OpenMP(nvec, c, V1, V2, Z)); } /* Cases: */ /* (1) a == -1.0, b != 1.0, */ /* (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; V1 = test ? Y : X; V2 = test ? X : Y; return(VLin2VectorArray_OpenMP(nvec, c, V1, V2, Z)); } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) return(VScaleSumVectorArray_OpenMP(nvec, a, X, Y, Z)); /* Case: a == -b */ if (a == -b) return(VScaleDiffVectorArray_OpenMP(nvec, a, X, Y, Z)); /* Do all cases not handled above: */ /* (1) a == other, b == 0.0 - user should have called N_VScale */ /* (2) a == 0.0, b == other - user should have called N_VScale */ /* (3) a,b == other, a !=b, a != -b */ /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* compute linear sum for each vector pair in vector arrays */ #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a,b) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = a * xd[j] + b * yd[j]; } } } return(0); } int N_VScaleVectorArray_OpenMP(int nvec, realtype* c, N_Vector* X, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* zd=NULL; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VScale */ if (nvec == 1) { N_VScale_OpenMP(c[0], X[0], Z[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* * X[i] *= c[i] */ if (X == Z) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { xd[j] *= c[i]; } } } return(0); } /* * Z[i] = c[i] * X[i] */ #pragma omp parallel default(none) private(i,j,xd,zd) shared(nvec,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c[i] * xd[j]; } } } return(0); } int N_VConstVectorArray_OpenMP(int nvec, realtype c, N_Vector* Z) { int i; sunindextype j, N; realtype* zd=NULL; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VConst */ if (nvec == 1) { N_VConst_OpenMP(c, Z[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* set each vector in the vector array to a constant */ #pragma omp parallel default(none) private(i,j,zd) shared(nvec,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c; } } } return(0); } int N_VWrmsNormVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* W, realtype* nrm) { int i; sunindextype j, N; realtype sum; realtype* wd=NULL; realtype* xd=NULL; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VWrmsNorm */ if (nvec == 1) { nrm[0] = N_VWrmsNorm_OpenMP(X[0], W[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(X[0]); /* initialize norms */ for (i=0; i<nvec; i++) { nrm[i] = ZERO; } /* compute the WRMS norm for each vector in the vector array */ #pragma omp parallel default(none) private(i,j,xd,wd,sum) shared(nvec,X,W,N,nrm) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); wd = NV_DATA_OMP(W[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { sum += SUNSQR(xd[j] * wd[j]); } #pragma omp critical { nrm[i] += sum; } } } for (i=0; i<nvec; i++) { nrm[i] = SUNRsqrt(nrm[i]/N); } return(0); } int N_VWrmsNormMaskVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* W, N_Vector id, realtype* nrm) { int i; sunindextype j, N; realtype sum; realtype* wd=NULL; realtype* xd=NULL; realtype* idd=NULL; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VWrmsNorm */ if (nvec == 1) { nrm[0] = N_VWrmsNormMask_OpenMP(X[0], W[0], id); return(0); } /* get vector length and mask data array */ N = NV_LENGTH_OMP(X[0]); idd = NV_DATA_OMP(id); /* initialize norms */ for (i=0; i<nvec; i++) { nrm[i] = ZERO; } /* compute the WRMS norm for each vector in the vector array */ #pragma omp parallel default(none) private(i,j,xd,wd,sum) shared(nvec,X,W,N,idd,nrm) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); wd = NV_DATA_OMP(W[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { if (idd[j] > ZERO) sum += SUNSQR(xd[j] * wd[j]); } #pragma omp critical { nrm[i] += sum; } } } for (i=0; i<nvec; i++) { nrm[i] = SUNRsqrt(nrm[i]/N); } return(0); } int N_VScaleAddMultiVectorArray_OpenMP(int nvec, int nsum, realtype* a, N_Vector* X, N_Vector** Y, N_Vector** Z) { int i, j; sunindextype k, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; int retval; N_Vector* YY; N_Vector* ZZ; /* invalid number of vectors */ if (nvec < 1) return(-1); if (nsum < 1) return(-1); /* --------------------------- * Special cases for nvec == 1 * --------------------------- */ if (nvec == 1) { /* should have called N_VLinearSum */ if (nsum == 1) { N_VLinearSum_OpenMP(a[0], X[0], ONE, Y[0][0], Z[0][0]); return(0); } /* should have called N_VScaleAddMulti */ YY = (N_Vector *) malloc(nsum * sizeof(N_Vector)); ZZ = (N_Vector *) malloc(nsum * sizeof(N_Vector)); for (j=0; j<nsum; j++) { YY[j] = Y[j][0]; ZZ[j] = Z[j][0]; } retval = N_VScaleAddMulti_OpenMP(nsum, a, X[0], YY, ZZ); free(YY); free(ZZ); return(retval); } /* -------------------------- * Special cases for nvec > 1 * -------------------------- */ /* should have called N_VLinearSumVectorArray */ if (nsum == 1) { retval = N_VLinearSumVectorArray_OpenMP(nvec, a[0], X, ONE, Y[0], Z[0]); return(retval); } /* ---------------------------- * Compute multiple linear sums * ---------------------------- */ /* get vector length */ N = NV_LENGTH_OMP(X[0]); /* * Y[i][j] += a[i] * x[j] */ if (Y == Z) { #pragma omp parallel default(none) private(i,j,k,xd,yd) shared(nvec,nsum,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); for (j=0; j<nsum; j++) { yd = NV_DATA_OMP(Y[j][i]); #pragma omp for schedule(static) for (k=0; k<N; k++) { yd[k] += a[j] * xd[k]; } } } } return(0); } /* * Z[i][j] = Y[i][j] + a[i] * x[j] */ #pragma omp parallel default(none) private(i,j,k,xd,yd,zd) shared(nvec,nsum,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); for (j=0; j<nsum; j++) { yd = NV_DATA_OMP(Y[j][i]); zd = NV_DATA_OMP(Z[j][i]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] = a[j] * xd[k] + yd[k]; } } } } return(0); } int N_VLinearCombinationVectorArray_OpenMP(int nvec, int nsum, realtype* c, N_Vector** X, N_Vector* Z) { int i; /* vector arrays index in summation [0,nsum) */ int j; /* vector index in vector array [0,nvec) */ sunindextype k; /* element index in vector [0,N) */ sunindextype N; realtype* zd=NULL; realtype* xd=NULL; realtype* ctmp; N_Vector* Y; /* invalid number of vectors */ if (nvec < 1) return(-1); if (nsum < 1) return(-1); /* --------------------------- * Special cases for nvec == 1 * --------------------------- */ if (nvec == 1) { /* should have called N_VScale */ if (nsum == 1) { N_VScale_OpenMP(c[0], X[0][0], Z[0]); return(0); } /* should have called N_VLinearSum */ if (nsum == 2) { N_VLinearSum_OpenMP(c[0], X[0][0], c[1], X[1][0], Z[0]); return(0); } /* should have called N_VLinearCombination */ Y = (N_Vector *) malloc(nsum * sizeof(N_Vector)); for (i=0; i<nsum; i++) { Y[i] = X[i][0]; } N_VLinearCombination_OpenMP(nsum, c, Y, Z[0]); free(Y); return(0); } /* -------------------------- * Special cases for nvec > 1 * -------------------------- */ /* should have called N_VScaleVectorArray */ if (nsum == 1) { ctmp = (realtype*) malloc(nvec * sizeof(realtype)); for (j=0; j<nvec; j++) { ctmp[j] = c[0]; } N_VScaleVectorArray_OpenMP(nvec, ctmp, X[0], Z); free(ctmp); return(0); } /* should have called N_VLinearSumVectorArray */ if (nsum == 2) { N_VLinearSumVectorArray_OpenMP(nvec, c[0], X[0], c[1], X[1], Z); return(0); } /* -------------------------- * Compute linear combination * -------------------------- */ /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* * X[0][j] += c[i]*X[i][j], i = 1,...,nvec-1 */ if ((X[0] == Z) && (c[0] == ONE)) { #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { zd = NV_DATA_OMP(Z[j]); for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * X[0][j] = c[0] * X[0][j] + sum{ c[i] * X[i][j] }, i = 1,...,nvec-1 */ if (X[0] == Z) { #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { zd = NV_DATA_OMP(Z[j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] *= c[0]; } for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * Z[j] = sum{ c[i] * X[i][j] }, i = 0,...,nvec-1 */ #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { /* scale first vector in the sum into the output vector */ xd = NV_DATA_OMP(X[0][j]); zd = NV_DATA_OMP(Z[j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] = c[0] * xd[k]; } /* scale and sum remaining vectors into the output vector */ for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * ----------------------------------------------------------------- * private functions for special cases of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Copy vector components into a second vector */ static void VCopy_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector sum */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute the negative of a vector */ static void VNeg_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = -xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector sum */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]+yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute scaled vector difference */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]-yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute vector sum z[i] = a*x[i]+y[i] */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference z[i] = a*x[i]-y[i] */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute special cases of linear sum */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y) { sunindextype i, N; realtype *xd, *yd; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); if (a == ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += xd[i]; return; } if (a == -ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] -= xd[i]; return; } #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += a*xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector x[i] = a*x[i] */ static void VScaleBy_OpenMP(realtype a, N_Vector x) { sunindextype i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,a,xd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) xd[i] *= a; return; } /* * ----------------------------------------------------------------- * private functions for special cases of vector array operations * ----------------------------------------------------------------- */ static int VSumVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = xd[j] + yd[j]; } } return(0); } static int VDiffVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = xd[j] - yd[j]; } } return(0); } static int VScaleSumVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = c * (xd[j] + yd[j]); } } return(0); } static int VScaleDiffVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = c * (xd[j] - yd[j]); } } return(0); } static int VLin1VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = (a * xd[j]) + yd[j]; } } return(0); } static int VLin2VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = (a * xd[j]) - yd[j]; } } return(0); } static int VaxpyVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; N = NV_LENGTH_OMP(X[0]); if (a == ONE) { #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] += xd[j]; } } return(0); } if (a == -ONE) { #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] -= xd[j]; } } return(0); } #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] += a * xd[j]; } } return(0); } /* * ----------------------------------------------------------------- * Enable / Disable fused and vector array operations * ----------------------------------------------------------------- */ int N_VEnableFusedOps_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); if (tf) { /* enable all fused vector operations */ v->ops->nvlinearcombination = N_VLinearCombination_OpenMP; v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMP; v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMP; /* enable all vector array operations */ v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMP; v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMP; v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMP; v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMP; v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMP; v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMP; v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMP; } else { /* disable all fused vector operations */ v->ops->nvlinearcombination = NULL; v->ops->nvscaleaddmulti = NULL; v->ops->nvdotprodmulti = NULL; /* disable all vector array operations */ v->ops->nvlinearsumvectorarray = NULL; v->ops->nvscalevectorarray = NULL; v->ops->nvconstvectorarray = NULL; v->ops->nvwrmsnormvectorarray = NULL; v->ops->nvwrmsnormmaskvectorarray = NULL; v->ops->nvscaleaddmultivectorarray = NULL; v->ops->nvlinearcombinationvectorarray = NULL; } /* return success */ return(0); } int N_VEnableLinearCombination_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearcombination = N_VLinearCombination_OpenMP; else v->ops->nvlinearcombination = NULL; /* return success */ return(0); } int N_VEnableScaleAddMulti_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMP; else v->ops->nvscaleaddmulti = NULL; /* return success */ return(0); } int N_VEnableDotProdMulti_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMP; else v->ops->nvdotprodmulti = NULL; /* return success */ return(0); } int N_VEnableLinearSumVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMP; else v->ops->nvlinearsumvectorarray = NULL; /* return success */ return(0); } int N_VEnableScaleVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMP; else v->ops->nvscalevectorarray = NULL; /* return success */ return(0); } int N_VEnableConstVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMP; else v->ops->nvconstvectorarray = NULL; /* return success */ return(0); } int N_VEnableWrmsNormVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMP; else v->ops->nvwrmsnormvectorarray = NULL; /* return success */ return(0); } int N_VEnableWrmsNormMaskVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMP; else v->ops->nvwrmsnormmaskvectorarray = NULL; /* return success */ return(0); } int N_VEnableScaleAddMultiVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMP; else v->ops->nvscaleaddmultivectorarray = NULL; /* return success */ return(0); } int N_VEnableLinearCombinationVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMP; else v->ops->nvlinearcombinationvectorarray = NULL; /* return success */ return(0); }
core_zlacpy_band.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" /******************************************************************************* * * @ingroup core_plasma_complex64_t * * plasma_core_zlacpy copies a sub-block A of a band matrix stored in LAPACK's band format * to a corresponding sub-block B of a band matrix in PLASMA's band format * ******************************************************************************* * * @param[in] it * The row block index of the tile. * * @param[in] jt * The column block index of the tile. * * @param[in] m * The number of rows of the matrices A and B. M >= 0. * * @param[in] n * The number of columns of the matrices A and B. N >= 0. * * @param[in] A * The M-by-N matrix to copy. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,M). * * @param[out] B * The M-by-N copy of the matrix A. * On exit, B = A ONLY in the locations specified by uplo. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,M). * ******************************************************************************/ __attribute__((weak)) void plasma_core_zlacpy_lapack2tile_band(plasma_enum_t uplo, int it, int jt, int m, int n, int nb, int kl, int ku, const plasma_complex64_t *A, int lda, plasma_complex64_t *B, int ldb) { int i, j; int j_start, j_end; if (uplo == PlasmaGeneral) { j_start = 0; // pivot back and could fill in j_end = (jt <= it ? n : imin(n, (it-jt)*nb+m+ku+kl+1)); } else if (uplo == PlasmaUpper) { j_start = 0; j_end = imin(n, (it-jt)*nb+m+ku+1); } else { j_start = imax(0, (it-jt)*nb-kl); j_end = n; } for (j = 0; j < j_start; j++) { for (i = 0; i < m; i++) { B[i + j*ldb] = 0.0; } } for (j = j_start; j < j_end; j++) { int i_start, i_end; if (uplo == PlasmaGeneral) { i_start = (jt <= it ? 0 : imax(0, (jt-it)*nb+j-ku-kl)); i_end = (jt >= it ? m : imin(m, (jt-it)*nb+j+kl+nb+1)); // +nb because we use zgetrf on panel and pivot back within the panel. // so the last tile in panel could fill. } else if (uplo == PlasmaUpper) { i_start = imax(0, (jt-it)*nb+j-ku); i_end = imin(m, (jt-it)*nb+j+1); } else { i_start = imax(0, (jt-it)*nb+j); i_end = imin(m, (jt-it)*nb+j+kl+1); } for (i = 0; i < i_start; i++) { B[i + j*ldb] = 0.0; } for (i = i_start; i < i_end; i++) { B[i + j*ldb] = A[i + j*lda]; } for (i = i_end; i < m; i++) { B[i + j*ldb] = 0.0; } } for (j = j_end; j < n; j++) { for (i = 0; i < m; i++) { B[i + j*ldb] = 0.0; } } } /******************************************************************************/ void plasma_core_omp_zlacpy_lapack2tile_band(plasma_enum_t uplo, int it, int jt, int m, int n, int nb, int kl, int ku, const plasma_complex64_t *A, int lda, plasma_complex64_t *B, int ldb) { #pragma omp task depend(in:A[0:lda*n]) \ depend(out:B[0:ldb*n]) plasma_core_zlacpy_lapack2tile_band(uplo, it, jt, m, n, nb, kl, ku, A, lda, B, ldb); } /******************************************************************************* * * @ingroup core_plasma_complex64_t * * plasma_core_zlacpy copies all or part of a two-dimensional matrix A to another * matrix B * ******************************************************************************* * * @param[in] it * The row block index of the tile. * * @param[in] jt * The column block index of the tile. * * @param[in] m * The number of rows of the matrices A and B. m >= 0. * * @param[in] n * The number of columns of the matrices A and B. n >= 0. * * @param[in] A * The m-by-n matrix to copy. * * @param[in] lda * The leading dimension of the array A. lda >= max(1, m). * * @param[out] B * The m-by-n copy of the matrix A. * On exit, B = A ONLY in the locations specified by uplo. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1, m). * ******************************************************************************/ __attribute__((weak)) void plasma_core_zlacpy_tile2lapack_band(plasma_enum_t uplo, int it, int jt, int m, int n, int nb, int kl, int ku, const plasma_complex64_t *B, int ldb, plasma_complex64_t *A, int lda) { int i, j; int j_start, j_end; if (uplo == PlasmaGeneral) { j_start = 0; // pivot back and could fill in j_end = (jt <= it ? n : imin(n, (it-jt)*nb+m+ku+kl+1)); } else if (uplo == PlasmaUpper) { j_start = 0; j_end = imin(n, (it-jt)*nb+m+ku+1); } else { j_start = imax(0, (it-jt)*nb-kl); j_end = n; } for (j = j_start; j < j_end; j++) { int i_start, i_end; if (uplo == PlasmaGeneral) { i_start = (jt <= it ? 0 : imax(0, (jt-it)*nb+j-ku-kl)); i_end = (jt >= it ? m : imin(m, (jt-it)*nb+j+kl+nb+1)); // +nb because we use zgetrf on panel and pivot back within the panel. // so the last tile in panel could fill. } else if (uplo == PlasmaUpper) { i_start = imax(0, (jt-it)*nb+j-ku); i_end = imin(m, (jt-it)*nb+j+1); } else { i_start = imax(0, (jt-it)*nb+j); i_end = imin(m, (jt-it)*nb+j+kl+1); } for (i = i_start; i < i_end; i++) { A[i + j*lda] = B[i + j*ldb]; } } } /******************************************************************************/ void plasma_core_omp_zlacpy_tile2lapack_band(plasma_enum_t uplo, int it, int jt, int m, int n, int nb, int kl, int ku, const plasma_complex64_t *B, int ldb, plasma_complex64_t *A, int lda) { #pragma omp task depend(in:B[0:ldb*n]) \ depend(out:A[0:lda*n]) plasma_core_zlacpy_tile2lapack_band(uplo, it, jt, m, n, nb, kl, ku, B, ldb, A, lda); }
IJVector_parcsr.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * IJVector_Par interface * *****************************************************************************/ #include "_hypre_IJ_mv.h" #include "../HYPRE.h" /****************************************************************************** * * hypre_IJVectorCreatePar * * creates ParVector if necessary, and leaves a pointer to it as the * hypre_IJVector object * *****************************************************************************/ HYPRE_Int hypre_IJVectorCreatePar(hypre_IJVector *vector, HYPRE_BigInt *IJpartitioning) { MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt global_n, partitioning[2], jmin; HYPRE_Int j; jmin = hypre_IJVectorGlobalFirstRow(vector); global_n = hypre_IJVectorGlobalNumRows(vector); /* Shift to zero-based partitioning for ParVector object */ for (j = 0; j < 2; j++) { partitioning[j] = IJpartitioning[j] - jmin; } hypre_IJVectorObject(vector) = hypre_ParVectorCreate(comm, global_n, partitioning); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorDestroyPar * * frees ParVector local storage of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorDestroyPar(hypre_IJVector *vector) { return hypre_ParVectorDestroy((hypre_ParVector*)hypre_IJVectorObject(vector)); } /****************************************************************************** * * hypre_IJVectorInitializePar * * initializes ParVector of IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorInitializePar(hypre_IJVector *vector) { return hypre_IJVectorInitializePar_v2(vector, hypre_IJVectorMemoryLocation(vector)); } HYPRE_Int hypre_IJVectorInitializePar_v2(hypre_IJVector *vector, HYPRE_MemoryLocation memory_location) { hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); HYPRE_BigInt *partitioning = hypre_ParVectorPartitioning(par_vector); hypre_Vector *local_vector = hypre_ParVectorLocalVector(par_vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_Int my_id; MPI_Comm comm = hypre_IJVectorComm(vector); hypre_MPI_Comm_rank(comm, &my_id); HYPRE_MemoryLocation memory_location_aux = hypre_GetExecPolicy1(memory_location) == HYPRE_EXEC_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE; if (!partitioning) { if (print_level) { hypre_printf("No ParVector partitioning for initialization -- "); hypre_printf("hypre_IJVectorInitializePar\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_VectorSize(local_vector) = (HYPRE_Int)(partitioning[1] - partitioning[0]); hypre_ParVectorInitialize_v2(par_vector, memory_location); if (!aux_vector) { hypre_AuxParVectorCreate(&aux_vector); hypre_IJVectorTranslator(vector) = aux_vector; } hypre_AuxParVectorInitialize_v2(aux_vector, memory_location_aux); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorSetMaxOffProcElmtsPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorSetMaxOffProcElmtsPar(hypre_IJVector *vector, HYPRE_Int max_off_proc_elmts) { hypre_AuxParVector *aux_vector; aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); if (!aux_vector) { hypre_AuxParVectorCreate(&aux_vector); hypre_IJVectorTranslator(vector) = aux_vector; } hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_AuxParVectorUsrOffProcElmts(aux_vector) = max_off_proc_elmts; #endif return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorDistributePar * * takes an IJVector generated for one processor and distributes it * across many processors according to vec_starts, * if vec_starts is NULL, it distributes them evenly? * *****************************************************************************/ HYPRE_Int hypre_IJVectorDistributePar(hypre_IJVector *vector, const HYPRE_Int *vec_starts) { hypre_ParVector *old_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_ParVector *par_vector; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); if (!old_vector) { if (print_level) { hypre_printf("old_vector == NULL -- "); hypre_printf("hypre_IJVectorDistributePar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } par_vector = hypre_VectorToParVector(hypre_ParVectorComm(old_vector), hypre_ParVectorLocalVector(old_vector), (HYPRE_BigInt *)vec_starts); if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorDistributePar\n"); hypre_printf("**** Vector storage is unallocated ****\n"); } hypre_error_in_arg(1); } hypre_ParVectorDestroy(old_vector); hypre_IJVectorObject(vector) = par_vector; return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorZeroValuesPar * * zeroes all local components of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorZeroValuesPar(hypre_IJVector *vector) { HYPRE_Int my_id; HYPRE_BigInt vec_start, vec_stop; hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt *partitioning; hypre_Vector *local_vector; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } partitioning = hypre_ParVectorPartitioning(par_vector); local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = partitioning[0]; vec_stop = partitioning[1]; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorZeroValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_assert(hypre_VectorSize(local_vector) == (HYPRE_Int)(vec_stop - vec_start)); hypre_SeqVectorSetConstantValues(local_vector, 0.0); return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorSetValuesPar * * sets a potentially noncontiguous set of components of an IJVectorPar * *****************************************************************************/ HYPRE_Int hypre_IJVectorSetValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, const HYPRE_Complex *values) { HYPRE_Int my_id; HYPRE_Int j, k; HYPRE_BigInt i, vec_start, vec_stop; HYPRE_Complex *data; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); MPI_Comm comm = hypre_IJVectorComm(vector); hypre_Vector *local_vector; /* If no components are to be set, perform no checking and return */ if (num_values < 1) { return 0; } hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1] - 1; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorSetValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } /* Determine whether indices points to local indices only, and if not, store indices and values in auxiliary vector structure. If indices == NULL, assume that num_values components are to be set in a block starting at vec_start. NOTE: If indices == NULL off proc values are ignored!!! */ data = hypre_VectorData(local_vector); if (indices) { for (j = 0; j < num_values; j++) { i = indices[j]; if (i >= vec_start && i <= vec_stop) { k = (HYPRE_Int)( i - vec_start); data[k] = values[j]; } } } else { if (num_values > (HYPRE_Int)(vec_stop - vec_start) + 1) { if (print_level) { hypre_printf("Warning! Indices beyond local range not identified!\n "); hypre_printf("Off processor values have been ignored!\n"); } num_values = (HYPRE_Int)(vec_stop - vec_start) + 1; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_values; j++) { data[j] = values[j]; } } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorAddToValuesPar * * adds to a potentially noncontiguous set of IJVectorPar components * *****************************************************************************/ HYPRE_Int hypre_IJVectorAddToValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, const HYPRE_Complex *values) { HYPRE_Int my_id; HYPRE_Int i, j, vec_start, vec_stop; HYPRE_Complex *data; HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); MPI_Comm comm = hypre_IJVectorComm(vector); hypre_Vector *local_vector; /* If no components are to be retrieved, perform no checking and return */ if (num_values < 1) { return 0; } hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1] - 1; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorAddToValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } data = hypre_VectorData(local_vector); if (indices) { HYPRE_Int current_num_elmts = hypre_AuxParVectorCurrentOffProcElmts(aux_vector); HYPRE_Int max_off_proc_elmts = hypre_AuxParVectorMaxOffProcElmts(aux_vector); HYPRE_BigInt *off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); HYPRE_Complex *off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); HYPRE_Int k; for (j = 0; j < num_values; j++) { i = indices[j]; if (i < vec_start || i > vec_stop) { /* if elements outside processor boundaries, store in off processor stash */ if (!max_off_proc_elmts) { max_off_proc_elmts = 100; hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; hypre_AuxParVectorOffProcI(aux_vector) = hypre_CTAlloc(HYPRE_BigInt, max_off_proc_elmts, HYPRE_MEMORY_HOST); hypre_AuxParVectorOffProcData(aux_vector) = hypre_CTAlloc(HYPRE_Complex, max_off_proc_elmts, HYPRE_MEMORY_HOST); off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); } else if (current_num_elmts + 1 > max_off_proc_elmts) { max_off_proc_elmts += 10; off_proc_i = hypre_TReAlloc(off_proc_i, HYPRE_BigInt, max_off_proc_elmts, HYPRE_MEMORY_HOST); off_proc_data = hypre_TReAlloc(off_proc_data, HYPRE_Complex, max_off_proc_elmts, HYPRE_MEMORY_HOST); hypre_AuxParVectorMaxOffProcElmts(aux_vector) = max_off_proc_elmts; hypre_AuxParVectorOffProcI(aux_vector) = off_proc_i; hypre_AuxParVectorOffProcData(aux_vector) = off_proc_data; } off_proc_i[current_num_elmts] = i; off_proc_data[current_num_elmts++] = values[j]; hypre_AuxParVectorCurrentOffProcElmts(aux_vector) = current_num_elmts; } else /* local values are added to the vector */ { k = (HYPRE_Int)(i - vec_start); data[k] += values[j]; } } } else { if (num_values > (HYPRE_Int)(vec_stop - vec_start) + 1) { if (print_level) { hypre_printf("Warning! Indices beyond local range not identified!\n "); hypre_printf("Off processor values have been ignored!\n"); } num_values = (HYPRE_Int)(vec_stop - vec_start) + 1; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_values; j++) { data[j] += values[j]; } } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorAssemblePar * * currently tests existence of of ParVector object and its partitioning * *****************************************************************************/ HYPRE_Int hypre_IJVectorAssemblePar(hypre_IJVector *vector) { hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_AuxParVector *aux_vector = (hypre_AuxParVector*) hypre_IJVectorTranslator(vector); MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorAssemblePar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); } if (aux_vector) { HYPRE_Int off_proc_elmts, current_num_elmts; HYPRE_Int max_off_proc_elmts; HYPRE_BigInt *off_proc_i; HYPRE_Complex *off_proc_data; current_num_elmts = hypre_AuxParVectorCurrentOffProcElmts(aux_vector); hypre_MPI_Allreduce(&current_num_elmts, &off_proc_elmts, 1, HYPRE_MPI_INT, hypre_MPI_SUM, comm); if (off_proc_elmts) { max_off_proc_elmts = hypre_AuxParVectorMaxOffProcElmts(aux_vector); off_proc_i = hypre_AuxParVectorOffProcI(aux_vector); off_proc_data = hypre_AuxParVectorOffProcData(aux_vector); hypre_IJVectorAssembleOffProcValsPar(vector, max_off_proc_elmts, current_num_elmts, HYPRE_MEMORY_HOST, off_proc_i, off_proc_data); hypre_TFree(hypre_AuxParVectorOffProcI(aux_vector), HYPRE_MEMORY_HOST); hypre_TFree(hypre_AuxParVectorOffProcData(aux_vector), HYPRE_MEMORY_HOST); hypre_AuxParVectorMaxOffProcElmts(aux_vector) = 0; hypre_AuxParVectorCurrentOffProcElmts(aux_vector) = 0; } } return hypre_error_flag; } /****************************************************************************** * * hypre_IJVectorGetValuesPar * * get a potentially noncontiguous set of IJVectorPar components * *****************************************************************************/ HYPRE_Int hypre_IJVectorGetValuesPar(hypre_IJVector *vector, HYPRE_Int num_values, const HYPRE_BigInt *indices, HYPRE_Complex *values) { HYPRE_Int my_id; MPI_Comm comm = hypre_IJVectorComm(vector); HYPRE_BigInt *IJpartitioning = hypre_IJVectorPartitioning(vector); HYPRE_BigInt vec_start; HYPRE_BigInt vec_stop; HYPRE_BigInt jmin = hypre_IJVectorGlobalFirstRow(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); HYPRE_Int print_level = hypre_IJVectorPrintLevel(vector); /* If no components are to be retrieved, perform no checking and return */ if (num_values < 1) { return 0; } hypre_MPI_Comm_rank(comm, &my_id); /* If par_vector == NULL or partitioning == NULL or local_vector == NULL let user know of catastrophe and exit */ if (!par_vector) { if (print_level) { hypre_printf("par_vector == NULL -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** Vector storage is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_Vector *local_vector = hypre_ParVectorLocalVector(par_vector); if (!local_vector) { if (print_level) { hypre_printf("local_vector == NULL -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** Vector local data is either unallocated or orphaned ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } vec_start = IJpartitioning[0]; vec_stop = IJpartitioning[1]; if (vec_start > vec_stop) { if (print_level) { hypre_printf("vec_start > vec_stop -- "); hypre_printf("hypre_IJVectorGetValuesPar\n"); hypre_printf("**** This vector partitioning should not occur ****\n"); } hypre_error_in_arg(1); return hypre_error_flag; } hypre_ParVectorGetValues2(par_vector, num_values, (HYPRE_BigInt *) indices, jmin, values); return hypre_error_flag; } /****************************************************************************** * hypre_IJVectorAssembleOffProcValsPar * * This is for handling set and get values calls to off-proc. entries - it is * called from assemble. There is an alternate version for when the assumed * partition is being used. *****************************************************************************/ HYPRE_Int hypre_IJVectorAssembleOffProcValsPar( hypre_IJVector *vector, HYPRE_Int max_off_proc_elmts, HYPRE_Int current_num_elmts, HYPRE_MemoryLocation memory_location, HYPRE_BigInt *off_proc_i, HYPRE_Complex *off_proc_data) { HYPRE_Int myid; HYPRE_BigInt global_first_row, global_num_rows; HYPRE_Int i, j, in, k; HYPRE_Int proc_id, last_proc, prev_id, tmp_id; HYPRE_Int max_response_size; HYPRE_Int ex_num_contacts = 0; HYPRE_BigInt range_start, range_end; HYPRE_Int storage; HYPRE_Int indx; HYPRE_BigInt row; HYPRE_Int num_ranges, row_count; HYPRE_Int num_recvs; HYPRE_Int counter; HYPRE_BigInt upper_bound; HYPRE_Int num_real_procs; HYPRE_BigInt *row_list = NULL; HYPRE_Int *a_proc_id = NULL, *orig_order = NULL; HYPRE_Int *real_proc_id = NULL, *us_real_proc_id = NULL; HYPRE_Int *ex_contact_procs = NULL, *ex_contact_vec_starts = NULL; HYPRE_Int *recv_starts = NULL; HYPRE_BigInt *response_buf = NULL; HYPRE_Int *response_buf_starts = NULL; HYPRE_Int *num_rows_per_proc = NULL; HYPRE_Int tmp_int; HYPRE_Int obj_size_bytes, big_int_size, complex_size; HYPRE_Int first_index; void *void_contact_buf = NULL; void *index_ptr; void *recv_data_ptr; HYPRE_Complex tmp_complex; HYPRE_BigInt *ex_contact_buf = NULL; HYPRE_Complex *vector_data; HYPRE_Complex value; hypre_DataExchangeResponse response_obj1, response_obj2; hypre_ProcListElements send_proc_obj; MPI_Comm comm = hypre_IJVectorComm(vector); hypre_ParVector *par_vector = (hypre_ParVector*) hypre_IJVectorObject(vector); hypre_IJAssumedPart *apart; hypre_MPI_Comm_rank(comm, &myid); global_num_rows = hypre_IJVectorGlobalNumRows(vector); global_first_row = hypre_IJVectorGlobalFirstRow(vector); if (memory_location == HYPRE_MEMORY_DEVICE) { HYPRE_BigInt *off_proc_i_h = hypre_TAlloc(HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST); HYPRE_Complex *off_proc_data_h = hypre_TAlloc(HYPRE_Complex, current_num_elmts, HYPRE_MEMORY_HOST); hypre_TMemcpy(off_proc_i_h, off_proc_i, HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(off_proc_data_h, off_proc_data, HYPRE_Complex, current_num_elmts, HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE); off_proc_i = off_proc_i_h; off_proc_data = off_proc_data_h; } /* call hypre_IJVectorAddToValuesParCSR directly inside this function * with one chunk of data */ HYPRE_Int off_proc_nelm_recv_cur = 0; HYPRE_Int off_proc_nelm_recv_max = 0; HYPRE_BigInt *off_proc_i_recv = NULL; HYPRE_Complex *off_proc_data_recv = NULL; HYPRE_BigInt *off_proc_i_recv_d = NULL; HYPRE_Complex *off_proc_data_recv_d = NULL; /* verify that we have created the assumed partition */ if (hypre_IJVectorAssumedPart(vector) == NULL) { hypre_IJVectorCreateAssumedPartition(vector); } apart = (hypre_IJAssumedPart*) hypre_IJVectorAssumedPart(vector); /* get the assumed processor id for each row */ a_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); orig_order = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); real_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); row_list = hypre_CTAlloc(HYPRE_BigInt, current_num_elmts, HYPRE_MEMORY_HOST); if (current_num_elmts > 0) { for (i = 0; i < current_num_elmts; i++) { row = off_proc_i[i]; row_list[i] = row; hypre_GetAssumedPartitionProcFromRow(comm, row, global_first_row, global_num_rows, &proc_id); a_proc_id[i] = proc_id; orig_order[i] = i; } /* now we need to find the actual order of each row - sort on row - this will result in proc ids sorted also...*/ hypre_BigQsortb2i(row_list, a_proc_id, orig_order, 0, current_num_elmts - 1); /* calculate the number of contacts */ ex_num_contacts = 1; last_proc = a_proc_id[0]; for (i = 1; i < current_num_elmts; i++) { if (a_proc_id[i] > last_proc) { ex_num_contacts++; last_proc = a_proc_id[i]; } } } /* now we will go through a create a contact list - need to contact assumed processors and find out who the actual row owner is - we will contact with a range (2 numbers) */ ex_contact_procs = hypre_CTAlloc(HYPRE_Int, ex_num_contacts, HYPRE_MEMORY_HOST); ex_contact_vec_starts = hypre_CTAlloc(HYPRE_Int, ex_num_contacts + 1, HYPRE_MEMORY_HOST); ex_contact_buf = hypre_CTAlloc(HYPRE_BigInt, ex_num_contacts * 2, HYPRE_MEMORY_HOST); counter = 0; range_end = -1; for (i = 0; i < current_num_elmts; i++) { if (row_list[i] > range_end) { /* assumed proc */ proc_id = a_proc_id[i]; /* end of prev. range */ if (counter > 0) { ex_contact_buf[counter * 2 - 1] = row_list[i - 1]; } /*start new range*/ ex_contact_procs[counter] = proc_id; ex_contact_vec_starts[counter] = counter * 2; ex_contact_buf[counter * 2] = row_list[i]; counter++; hypre_GetAssumedPartitionRowRange(comm, proc_id, global_first_row, global_num_rows, &range_start, &range_end); } } /*finish the starts*/ ex_contact_vec_starts[counter] = counter * 2; /*finish the last range*/ if (counter > 0) { ex_contact_buf[counter * 2 - 1] = row_list[current_num_elmts - 1]; } /* create response object - can use same fill response as used in the commpkg routine */ response_obj1.fill_response = hypre_RangeFillResponseIJDetermineRecvProcs; response_obj1.data1 = apart; /* this is necessary so we can fill responses*/ response_obj1.data2 = NULL; max_response_size = 6; /* 6 means we can fit 3 ranges*/ hypre_DataExchangeList(ex_num_contacts, ex_contact_procs, ex_contact_buf, ex_contact_vec_starts, sizeof(HYPRE_BigInt), sizeof(HYPRE_BigInt), &response_obj1, max_response_size, 4, comm, (void**) &response_buf, &response_buf_starts); /* now response_buf contains a proc_id followed by an upper bound for the range. */ hypre_TFree(ex_contact_procs, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_buf, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_vec_starts, HYPRE_MEMORY_HOST); hypre_TFree(a_proc_id, HYPRE_MEMORY_HOST); a_proc_id = NULL; /*how many ranges were returned?*/ num_ranges = response_buf_starts[ex_num_contacts]; num_ranges = num_ranges / 2; prev_id = -1; j = 0; counter = 0; num_real_procs = 0; /* loop through ranges - create a list of actual processor ids*/ for (i = 0; i < num_ranges; i++) { upper_bound = response_buf[i * 2 + 1]; counter = 0; tmp_id = (HYPRE_Int)response_buf[i * 2]; /* loop through row_list entries - counting how many are in the range */ while (j < current_num_elmts && row_list[j] <= upper_bound) { real_proc_id[j] = tmp_id; j++; counter++; } if (counter > 0 && tmp_id != prev_id) { num_real_procs++; } prev_id = tmp_id; } /* now we have the list of real procesors ids (real_proc_id) - and the number of distinct ones - so now we can set up data to be sent - we have HYPRE_Int and HYPRE_Complex data. (row number and value) - we will send everything as a void since we may not know the rel sizes of ints and doubles */ /* first find out how many elements to send per proc - so we can do storage */ complex_size = sizeof(HYPRE_Complex); big_int_size = sizeof(HYPRE_BigInt); obj_size_bytes = hypre_max(big_int_size, complex_size); ex_contact_procs = hypre_CTAlloc(HYPRE_Int, num_real_procs, HYPRE_MEMORY_HOST); num_rows_per_proc = hypre_CTAlloc(HYPRE_Int, num_real_procs, HYPRE_MEMORY_HOST); counter = 0; if (num_real_procs > 0 ) { ex_contact_procs[0] = real_proc_id[0]; num_rows_per_proc[0] = 1; /* loop through real procs - these are sorted (row_list is sorted also)*/ for (i = 1; i < current_num_elmts; i++) { if (real_proc_id[i] == ex_contact_procs[counter]) /* same processor */ { num_rows_per_proc[counter] += 1; /*another row */ } else /* new processor */ { counter++; ex_contact_procs[counter] = real_proc_id[i]; num_rows_per_proc[counter] = 1; } } } /* calculate total storage and make vec_starts arrays */ storage = 0; ex_contact_vec_starts = hypre_CTAlloc(HYPRE_Int, num_real_procs + 1, HYPRE_MEMORY_HOST); ex_contact_vec_starts[0] = -1; for (i = 0; i < num_real_procs; i++) { storage += 1 + 2 * num_rows_per_proc[i]; ex_contact_vec_starts[i + 1] = -storage - 1; /* need negative for next loop */ } /*void_contact_buf = hypre_MAlloc(storage*obj_size_bytes);*/ void_contact_buf = hypre_CTAlloc(char, storage * obj_size_bytes, HYPRE_MEMORY_HOST); index_ptr = void_contact_buf; /* step through with this index */ /* set up data to be sent to send procs */ /* for each proc, ex_contact_buf_d contains #rows, row #, data, etc. */ /* un-sort real_proc_id - we want to access data arrays in order */ us_real_proc_id = hypre_CTAlloc(HYPRE_Int, current_num_elmts, HYPRE_MEMORY_HOST); for (i = 0; i < current_num_elmts; i++) { us_real_proc_id[orig_order[i]] = real_proc_id[i]; } hypre_TFree(real_proc_id, HYPRE_MEMORY_HOST); prev_id = -1; for (i = 0; i < current_num_elmts; i++) { proc_id = us_real_proc_id[i]; /* can't use row list[i] - you loose the negative signs that differentiate add/set values */ row = off_proc_i[i]; /* find position of this processor */ indx = hypre_BinarySearch(ex_contact_procs, proc_id, num_real_procs); in = ex_contact_vec_starts[indx]; index_ptr = (void *) ((char *) void_contact_buf + in * obj_size_bytes); /* first time for this processor - add the number of rows to the buffer */ if (in < 0) { in = -in - 1; /* re-calc. index_ptr since in_i was negative */ index_ptr = (void *) ((char *) void_contact_buf + in * obj_size_bytes); tmp_int = num_rows_per_proc[indx]; hypre_TMemcpy( index_ptr, &tmp_int, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; } /* add row # */ hypre_TMemcpy( index_ptr, &row, HYPRE_BigInt, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; /* add value */ tmp_complex = off_proc_data[i]; hypre_TMemcpy( index_ptr, &tmp_complex, HYPRE_Complex, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); index_ptr = (void *) ((char *) index_ptr + obj_size_bytes); in++; /* increment the indexes to keep track of where we are - fix later */ ex_contact_vec_starts[indx] = in; } /* some clean up */ hypre_TFree(response_buf, HYPRE_MEMORY_HOST); hypre_TFree(response_buf_starts, HYPRE_MEMORY_HOST); hypre_TFree(us_real_proc_id, HYPRE_MEMORY_HOST); hypre_TFree(orig_order, HYPRE_MEMORY_HOST); hypre_TFree(row_list, HYPRE_MEMORY_HOST); hypre_TFree(num_rows_per_proc, HYPRE_MEMORY_HOST); for (i = num_real_procs; i > 0; i--) { ex_contact_vec_starts[i] = ex_contact_vec_starts[i - 1]; } ex_contact_vec_starts[0] = 0; /* now send the data */ /***********************************/ /* now get the info in send_proc_obj_d */ /* the response we expect is just a confirmation*/ response_buf = NULL; response_buf_starts = NULL; /*build the response object*/ /* use the send_proc_obj for the info kept from contacts */ /*estimate inital storage allocation */ send_proc_obj.length = 0; send_proc_obj.storage_length = num_real_procs + 5; send_proc_obj.id = NULL; /* don't care who sent it to us */ send_proc_obj.vec_starts = hypre_CTAlloc(HYPRE_Int, send_proc_obj.storage_length + 1, HYPRE_MEMORY_HOST); send_proc_obj.vec_starts[0] = 0; send_proc_obj.element_storage_length = storage + 20; send_proc_obj.v_elements = hypre_TAlloc(char, obj_size_bytes * send_proc_obj.element_storage_length, HYPRE_MEMORY_HOST); response_obj2.fill_response = hypre_FillResponseIJOffProcVals; response_obj2.data1 = NULL; response_obj2.data2 = &send_proc_obj; max_response_size = 0; hypre_DataExchangeList(num_real_procs, ex_contact_procs, void_contact_buf, ex_contact_vec_starts, obj_size_bytes, 0, &response_obj2, max_response_size, 5, comm, (void **) &response_buf, &response_buf_starts); /***********************************/ hypre_TFree(response_buf, HYPRE_MEMORY_HOST); hypre_TFree(response_buf_starts, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_procs, HYPRE_MEMORY_HOST); hypre_TFree(void_contact_buf, HYPRE_MEMORY_HOST); hypre_TFree(ex_contact_vec_starts, HYPRE_MEMORY_HOST); /* Now we can unpack the send_proc_objects and either set or add to the vector data */ num_recvs = send_proc_obj.length; /* alias */ recv_data_ptr = send_proc_obj.v_elements; recv_starts = send_proc_obj.vec_starts; vector_data = hypre_VectorData(hypre_ParVectorLocalVector(par_vector)); first_index = hypre_ParVectorFirstIndex(par_vector); for (i = 0; i < num_recvs; i++) { indx = recv_starts[i]; /* get the number of rows for this recv */ hypre_TMemcpy( &row_count, recv_data_ptr, HYPRE_Int, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; for (j = 0; j < row_count; j++) /* for each row: unpack info */ { /* row # */ hypre_TMemcpy( &row, recv_data_ptr, HYPRE_BigInt, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; /* value */ hypre_TMemcpy( &value, recv_data_ptr, HYPRE_Complex, 1, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); recv_data_ptr = (void *) ((char *)recv_data_ptr + obj_size_bytes); indx++; if (memory_location == HYPRE_MEMORY_HOST) { k = (HYPRE_Int)(row - first_index - global_first_row); vector_data[k] += value; } else { if (off_proc_nelm_recv_cur >= off_proc_nelm_recv_max) { off_proc_nelm_recv_max = 2 * (off_proc_nelm_recv_cur + 1); off_proc_i_recv = hypre_TReAlloc(off_proc_i_recv, HYPRE_BigInt, off_proc_nelm_recv_max, HYPRE_MEMORY_HOST); off_proc_data_recv = hypre_TReAlloc(off_proc_data_recv, HYPRE_Complex, off_proc_nelm_recv_max, HYPRE_MEMORY_HOST); } off_proc_i_recv[off_proc_nelm_recv_cur] = row; off_proc_data_recv[off_proc_nelm_recv_cur] = value; off_proc_nelm_recv_cur ++; } } } if (memory_location == HYPRE_MEMORY_DEVICE) { off_proc_i_recv_d = hypre_TAlloc(HYPRE_BigInt, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE); off_proc_data_recv_d = hypre_TAlloc(HYPRE_Complex, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE); hypre_TMemcpy(off_proc_i_recv_d, off_proc_i_recv, HYPRE_BigInt, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); hypre_TMemcpy(off_proc_data_recv_d, off_proc_data_recv, HYPRE_Complex, off_proc_nelm_recv_cur, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST); #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_IJVectorSetAddValuesParDevice(vector, off_proc_nelm_recv_cur, off_proc_i_recv_d, off_proc_data_recv_d, "add"); #endif } hypre_TFree(send_proc_obj.v_elements, HYPRE_MEMORY_HOST); hypre_TFree(send_proc_obj.vec_starts, HYPRE_MEMORY_HOST); if (memory_location == HYPRE_MEMORY_DEVICE) { hypre_TFree(off_proc_i, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_data, HYPRE_MEMORY_HOST); } hypre_TFree(off_proc_i_recv, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_data_recv, HYPRE_MEMORY_HOST); hypre_TFree(off_proc_i_recv_d, HYPRE_MEMORY_DEVICE); hypre_TFree(off_proc_data_recv_d, HYPRE_MEMORY_DEVICE); return hypre_error_flag; }
cofold.c
/* * minimum free energy * RNA secondary structure prediction * * c Ivo Hofacker, Chrisoph Flamm * original implementation by * Walter Fontana * * Vienna RNA package */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> #include <limits.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/utils/strings.h" #include "ViennaRNA/utils/structures.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/subopt.h" #include "ViennaRNA/fold.h" #include "ViennaRNA/loops/all.h" #include "ViennaRNA/gquad.h" #include "ViennaRNA/alphabet.h" #include "ViennaRNA/cofold.h" #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY #ifdef _OPENMP #include <omp.h> #endif #endif #define MAXSECTORS 500 /* dimension for a backtrack array */ /* ################################# # GLOBAL VARIABLES # ################################# */ /* ################################# # PRIVATE VARIABLES # ################################# */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY /* some backward compatibility stuff */ PRIVATE int backward_compat = 0; PRIVATE vrna_fold_compound_t *backward_compat_compound = NULL; PRIVATE float mfe1, mfe2; /* minimum free energies of the monomers */ #ifdef _OPENMP #pragma omp threadprivate(mfe1, mfe2, backward_compat_compound, backward_compat) #endif #endif /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ PRIVATE int backtrack(sect bt_stack[], vrna_bp_stack_t *bp_list, vrna_fold_compound_t *vc); PRIVATE int fill_arrays(vrna_fold_compound_t *vc, int zuker); PRIVATE void free_end(int *array, int i, int start, vrna_fold_compound_t *vc); PRIVATE void doubleseq(vrna_fold_compound_t *vc); /* do magic */ PRIVATE void halfseq(vrna_fold_compound_t *vc); /* undo magic */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY /* wrappers for old API compatibility */ PRIVATE void wrap_array_export(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **fc_p, int **indx_p, char **ptype_p); PRIVATE float wrap_cofold(const char *string, char *structure, vrna_param_t *parameters, int is_constrained); PRIVATE SOLUTION * wrap_zukersubopt(const char *string, vrna_param_t *parameters); #endif /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ PUBLIC float vrna_mfe_dimer(vrna_fold_compound_t *vc, char *structure) { int length, energy; char *s; sect bt_stack[MAXSECTORS]; /* stack of partial structures for backtracking */ vrna_bp_stack_t *bp; length = (int)vc->length; vc->sequence_encoding[0] = vc->sequence_encoding2[0]; /* store length at pos. 0 in S1 too */ if (!vrna_fold_compound_prepare(vc, VRNA_OPTION_MFE | VRNA_OPTION_HYBRID)) { vrna_message_warning("vrna_mfe_dimer@cofold.c: Failed to prepare vrna_fold_compound"); return (float)(INF / 100.); } /* call user-defined recursion status callback function */ if (vc->stat_cb) vc->stat_cb(VRNA_STATUS_MFE_PRE, vc->auxdata); energy = fill_arrays(vc, 0); /* call user-defined recursion status callback function */ if (vc->stat_cb) vc->stat_cb(VRNA_STATUS_MFE_POST, vc->auxdata); if (structure && vc->params->model_details.backtrack) { bp = (vrna_bp_stack_t *)vrna_alloc(sizeof(vrna_bp_stack_t) * (4 * (1 + length / 2))); /* add a guess of how many G's may be involved in a G quadruplex */ backtrack(bt_stack, bp, vc); s = vrna_db_from_bp_stack(bp, length); strncpy(structure, s, length + 1); free(s); free(bp); } if (vc->params->model_details.backtrack_type == 'C') return (float)vc->matrices->c[vc->jindx[length] + 1] / 100.; else if (vc->params->model_details.backtrack_type == 'M') return (float)vc->matrices->fML[vc->jindx[length] + 1] / 100.; else return (float)energy / 100.; } PRIVATE int fill_arrays(vrna_fold_compound_t *vc, int zuker) { /* fill "c", "fML" and "f5" arrays and return optimal energy */ unsigned int strands, *sn, *ss, *se, *so; int i, j, length, energy; int uniq_ML; int no_close, type, maxj, *indx; int *my_f5, *my_c, *my_fML, *my_fM1, *my_fc; int *cc, *cc1; /* auxilary arrays for canonical structures */ int *Fmi; /* holds row i of fML (avoids jumps in memory) */ int *DMLi; /* DMLi[j] holds MIN(fML[i,k]+fML[k+1,j]) */ int *DMLi1; /* MIN(fML[i+1,k]+fML[k+1,j]) */ int *DMLi2; /* MIN(fML[i+2,k]+fML[k+1,j]) */ int dangle_model, noGUclosure, noLP, hc_decompose, turn; char *ptype; unsigned char *hard_constraints; vrna_param_t *P; vrna_mx_mfe_t *matrices; vrna_hc_t *hc; length = (int)vc->length; ptype = vc->ptype; indx = vc->jindx; P = vc->params; dangle_model = P->model_details.dangles; noGUclosure = P->model_details.noGUclosure; noLP = P->model_details.noLP; uniq_ML = P->model_details.uniq_ML; strands = vc->strands; sn = vc->strand_number; ss = vc->strand_start; se = vc->strand_end; so = vc->strand_order; hc = vc->hc; hard_constraints = hc->mx; matrices = vc->matrices; my_f5 = matrices->f5; my_c = matrices->c; my_fML = matrices->fML; my_fM1 = matrices->fM1; my_fc = matrices->fc; turn = P->model_details.min_loop_size; /* allocate memory for all helper arrays */ cc = (int *)vrna_alloc(sizeof(int) * (length + 2)); cc1 = (int *)vrna_alloc(sizeof(int) * (length + 2)); Fmi = (int *)vrna_alloc(sizeof(int) * (length + 1)); DMLi = (int *)vrna_alloc(sizeof(int) * (length + 1)); DMLi1 = (int *)vrna_alloc(sizeof(int) * (length + 1)); DMLi2 = (int *)vrna_alloc(sizeof(int) * (length + 1)); /* hard code min_loop_size to 0, since we can not be sure yet that this is already the case */ turn = 0; for (j = 1; j <= length; j++) { Fmi[j] = DMLi[j] = DMLi1[j] = DMLi2[j] = INF; my_fc[j] = 0; } for (j = 1; j <= length; j++) for (i = 1; i <= j; i++) { my_c[indx[j] + i] = my_fML[indx[j] + i] = INF; if (uniq_ML) my_fM1[indx[j] + i] = INF; } for (i = length - turn - 1; i >= 1; i--) { /* i,j in [1..length] */ maxj = (zuker) ? (MIN2(i + se[so[0]], length)) : length; for (j = i + turn + 1; j <= maxj; j++) { int ij; ij = indx[j] + i; type = vrna_get_ptype(ij, ptype); hc_decompose = hard_constraints[length * i + j]; energy = INF; no_close = (((type == 3) || (type == 4)) && noGUclosure); if (hc_decompose) { /* we have a pair */ int new_c = INF; if (!no_close) { /* check for hairpin loop */ energy = vrna_E_hp_loop(vc, i, j); new_c = MIN2(new_c, energy); /* check for multibranch loops */ energy = vrna_E_mb_loop_fast(vc, i, j, DMLi1, DMLi2); new_c = MIN2(new_c, energy); } if (dangle_model == 3) { /* coaxial stacking */ energy = vrna_E_mb_loop_stack(vc, i, j); new_c = MIN2(new_c, energy); } /* check for interior loops */ energy = vrna_E_int_loop(vc, i, j); new_c = MIN2(new_c, energy); /* remember stack energy for --noLP option */ if (noLP) { if ((sn[i] == sn[i + 1]) && (sn[j - 1] == sn[j])) { int stackEnergy = vrna_E_stack(vc, i, j); new_c = MIN2(new_c, cc1[j - 1] + stackEnergy); my_c[ij] = cc1[j - 1] + stackEnergy; } else { /* currently we don't allow stacking over the cut point */ my_c[ij] = FORBIDDEN; } cc[j] = new_c; } else { my_c[ij] = new_c; } } /* end >> if (pair) << */ else { my_c[ij] = INF; } /* * done with c[i,j], now compute fML[i,j] * free ends ? ----------------------------------------- */ my_fML[ij] = vrna_E_ml_stems_fast(vc, i, j, Fmi, DMLi); if (uniq_ML) /* compute fM1 for unique decomposition */ my_fM1[ij] = E_ml_rightmost_stem(i, j, vc); } if (i == se[so[0]] + 1) for (j = i; j <= maxj; j++) free_end(my_fc, j, ss[so[1]], vc); if (i <= se[so[0]]) free_end(my_fc, i, se[so[0]], vc); { int *FF; /* rotate the auxilliary arrays */ FF = DMLi2; DMLi2 = DMLi1; DMLi1 = DMLi; DMLi = FF; FF = cc1; cc1 = cc; cc = FF; for (j = 1; j <= maxj; j++) cc[j] = Fmi[j] = DMLi[j] = INF; } } /* calculate energies of 5' and 3' fragments */ for (i = 1; i <= length; i++) free_end(my_f5, i, 1, vc); if (strands > 1) { mfe1 = my_f5[se[so[0]]]; mfe2 = my_fc[length]; /* add DuplexInit, check whether duplex*/ for (i = ss[so[1]]; i <= length; i++) { if (my_f5[i] != INF) my_f5[i] += P->DuplexInit; if ((my_fc[i] != INF) && (my_fc[1] != INF)) { energy = my_fc[i] + my_fc[1]; if (energy < my_f5[i]) my_f5[i] = energy; } } } energy = my_f5[length]; if (strands == 1) mfe1 = mfe2 = energy; /* clean up memory */ free(cc); free(cc1); free(Fmi); free(DMLi); free(DMLi1); free(DMLi2); return energy; } PRIVATE int backtrack_co(sect bt_stack[], vrna_bp_stack_t *bp_list, int s, int b, /* b=0: start new structure, b \ne 0: add to existing structure */ vrna_fold_compound_t *vc) { /*------------------------------------------------------------------ * trace back through the "c", "fc", "f5" and "fML" arrays to get the * base pairing list. No search for equivalent structures is done. * This is fast, since only few structure elements are recalculated. * ------------------------------------------------------------------*/ unsigned int *se, *so; int i, j, ij, k, length, no_close, type, ret; char *string = vc->sequence; vrna_param_t *P = vc->params; int *indx = vc->jindx; char *ptype = vc->ptype; int noLP = P->model_details.noLP; int noGUclosure = P->model_details.noGUclosure; char backtrack_type = P->model_details.backtrack_type; /* the folding matrices */ int *my_c; ret = 1; length = vc->length; my_c = vc->matrices->c; se = vc->strand_end; so = vc->strand_order; /* int b=0;*/ length = strlen(string); if (s == 0) { bt_stack[++s].i = 1; bt_stack[s].j = length; bt_stack[s].ml = (backtrack_type == 'M') ? 1 : ((backtrack_type == 'C') ? 2 : 0); } while (s > 0) { int ml, cij; int canonical = 1; /* (i,j) closes a canonical structure */ /* pop one element from stack */ i = bt_stack[s].i; j = bt_stack[s].j; ml = bt_stack[s--].ml; switch (ml) { /* backtrack in f5 */ case 0: { int p, q; if (vrna_BT_ext_loop_f5(vc, &j, &p, &q, bp_list, &b)) { if (j > 0) { bt_stack[++s].i = 1; bt_stack[s].j = j; bt_stack[s].ml = 0; } if (p > 0) { i = p; j = q; goto repeat1; } continue; } else { vrna_message_warning("backtracking failed in f5, segment [%d,%d]\n", i, j); ret = 0; goto backtrack_exit; } } break; /* true multi-loop backtrack in fML */ case 1: { int p, q, comp1, comp2; if (vrna_BT_mb_loop_split(vc, &i, &j, &p, &q, &comp1, &comp2, bp_list, &b)) { if (i > 0) { bt_stack[++s].i = i; bt_stack[s].j = j; bt_stack[s].ml = comp1; } if (p > 0) { bt_stack[++s].i = p; bt_stack[s].j = q; bt_stack[s].ml = comp2; } continue; } else { vrna_message_warning("backtrack failed in fML\n%s", string); ret = 0; goto backtrack_exit; } } break; case 2: bp_list[++b].i = i; bp_list[b].j = j; goto repeat1; /* backtrack fake-multi loop parts */ case 3: case 4: { int lower, k, p, q; p = i; q = j; lower = (i <= se[so[0]]) ? 1 : 0; if (vrna_BT_mb_loop_fake(vc, &k, &i, &j, bp_list, &b)) { if (k > 0) { bt_stack[++s].i = (lower) ? k : p; bt_stack[s].j = (lower) ? q : k; bt_stack[s].ml = ml; } if (i > 0) goto repeat1; continue; } else { vrna_message_warning("backtrack failed in fc\n%s", string); ret = 0; goto backtrack_exit; } } break; } /* end of switch(ml) */ repeat1: /*----- begin of "repeat:" -----*/ ij = indx[j] + i; if (canonical) cij = my_c[ij]; type = vrna_get_ptype(ij, ptype); if (noLP) { if (vrna_BT_stack(vc, &i, &j, &cij, bp_list, &b)) { canonical = 0; goto repeat1; } } canonical = 1; no_close = (((type == 3) || (type == 4)) && noGUclosure); if (no_close) { if (cij == FORBIDDEN) continue; } else { if (vrna_BT_hp_loop(vc, i, j, cij, bp_list, &b)) continue; } if (vrna_BT_int_loop(vc, &i, &j, cij, bp_list, &b)) { if (i < 0) continue; else goto repeat1; } /* (i.j) must close a fake or true multi-loop */ int comp1, comp2; if (vrna_BT_mb_loop(vc, &i, &j, &k, cij, &comp1, &comp2)) { bt_stack[++s].i = i; bt_stack[s].j = k; bt_stack[s].ml = comp1; bt_stack[++s].i = k + 1; bt_stack[s].j = j; bt_stack[s].ml = comp2; } else { vrna_message_warning("backtracking failed in repeat, segment [%d,%d]\n", i, j); ret = 0; goto backtrack_exit; } /* end of repeat: --------------------------------------------------*/ } /* end >> while (s>0) << */ backtrack_exit: bp_list[0].i = b; /* save the total number of base pairs */ return ret; } PRIVATE void free_end(int *array, int i, int start, vrna_fold_compound_t *vc) { unsigned int *sn; int inc, type, energy, en, length, j, left, right, dangle_model, with_gquad, *indx, *c, *ggg, turn; vrna_param_t *P; short *S1; char *ptype; unsigned char *hard_constraints; vrna_mx_mfe_t *matrices; vrna_hc_t *hc; vrna_sc_t *sc; P = vc->params; dangle_model = P->model_details.dangles; with_gquad = P->model_details.gquad; turn = P->model_details.min_loop_size; inc = (i > start) ? 1 : -1; length = (int)vc->length; S1 = vc->sequence_encoding; ptype = vc->ptype; indx = vc->jindx; sn = vc->strand_number; matrices = vc->matrices; c = matrices->c; ggg = matrices->ggg; hc = vc->hc; sc = vc->sc; hard_constraints = hc->mx; if (hc->up_ext[i]) { if (i == start) array[i] = 0; else array[i] = array[i - inc]; if (sc) { if (sc->energy_up) array[i] += sc->energy_up[i][1]; if (sc->f) array[i] += sc->f(start, i, start, i - 1, VRNA_DECOMP_EXT_EXT, sc->data); } } else { array[i] = INF; } if (inc > 0) { left = start; right = i; } else { left = i; right = start; } /* hard code min_loop_size to 0, since we can not be sure yet that this is already the case */ turn = 0; for (j = start; inc * (i - j) > turn; j += inc) { int ii, jj; short si, sj; if (i > j) { ii = j; jj = i; } /* inc>0 */ else { ii = i; jj = j; } /* inc<0 */ if (hard_constraints[length * ii + jj] & VRNA_CONSTRAINT_CONTEXT_EXT_LOOP) { type = vrna_get_ptype(indx[jj] + ii, ptype); si = ((ii > 1) && (sn[ii - 1] == sn[ii])) ? S1[ii - 1] : -1; sj = ((jj < length) && (sn[jj] == sn[jj + 1])) ? S1[jj + 1] : -1; energy = c[indx[jj] + ii]; if ((sc) && (sc->f)) energy += sc->f(start, jj, ii - 1, ii, VRNA_DECOMP_EXT_EXT_STEM, sc->data); if (energy != INF) { switch (dangle_model) { case 0: if (array[j - inc] != INF) { en = array[j - inc] + energy + vrna_E_ext_stem(type, -1, -1, P); array[i] = MIN2(array[i], en); } break; case 2: if (array[j - inc] != INF) { en = array[j - inc] + energy + vrna_E_ext_stem(type, si, sj, P); array[i] = MIN2(array[i], en); } break; default: if (array[j - inc] != INF) { en = array[j - inc] + energy + vrna_E_ext_stem(type, -1, -1, P); array[i] = MIN2(array[i], en); } if (inc > 0) { if (j > left) { if (hc->up_ext[ii - 1]) { if (array[j - 2] != INF) { en = array[j - 2] + energy + vrna_E_ext_stem(type, si, -1, P); if (sc) if (sc->energy_up) en += sc->energy_up[ii - 1][1]; array[i] = MIN2(array[i], en); } } } } else if (j < right) { if (hc->up_ext[jj + 1]) { if (array[j + 2] != INF) { en = array[j + 2] + energy + vrna_E_ext_stem(type, -1, sj, P); if (sc) if (sc->energy_up) en += sc->energy_up[jj + 1][1]; array[i] = MIN2(array[i], en); } } } break; } } } if (with_gquad) { if (sn[ii] == sn[jj]) if (array[j - inc] != INF) array[i] = MIN2(array[i], array[j - inc] + ggg[indx[jj] + ii]); } if (dangle_model % 2 == 1) { /* interval ends in a dangle (i.e. i-inc is paired) */ if (i > j) { ii = j; jj = i - 1; } /* inc>0 */ else { ii = i + 1; jj = j; } /* inc<0 */ if (!(hard_constraints[length * ii + jj] & VRNA_CONSTRAINT_CONTEXT_EXT_LOOP)) continue; type = vrna_get_ptype(indx[jj] + ii, ptype); si = (ii > left) && (sn[ii - 1] == sn[ii]) ? S1[ii - 1] : -1; sj = (jj < right) && (sn[jj] == sn[jj + 1]) ? S1[jj + 1] : -1; energy = c[indx[jj] + ii]; if (energy != INF) { if (inc > 0) { if (hc->up_ext[jj - 1]) { if (array[j - inc] != INF) { en = array[j - inc] + energy + vrna_E_ext_stem(type, -1, sj, P); if (sc) if (sc->energy_up) en += sc->energy_up[jj + 1][1]; array[i] = MIN2(array[i], en); } } } else { if (hc->up_ext[ii - 1]) { if (array[j - inc] != INF) { en = array[j - inc] + energy + vrna_E_ext_stem(type, si, -1, P); if (sc) if (sc->energy_up) en += sc->energy_up[ii - 1][1]; array[i] = MIN2(array[i], en); } } } if (j != start) { /* dangle_model on both sides */ if (hc->up_ext[jj - 1] && hc->up_ext[ii - 1]) { if (array[j - 2 * inc] != INF) { en = array[j - 2 * inc] + energy + vrna_E_ext_stem(type, si, sj, P); if (sc) if (sc->energy_up) en += sc->energy_up[ii - 1][1] + sc->energy_up[jj + 1][1]; array[i] = MIN2(array[i], en); } } } } } } } PRIVATE int backtrack(sect bt_stack[], vrna_bp_stack_t *bp_list, vrna_fold_compound_t *vc) { /*routine to call backtrack_co from 1 to n, backtrack type??*/ return backtrack_co(bt_stack, bp_list, 0, 0, vc); } PRIVATE void doubleseq(vrna_fold_compound_t *vc) { unsigned int length, i, s; length = vc->length; /* do some magic to re-use cofold code */ vc->sequence = vrna_realloc(vc->sequence, sizeof(char) * (2 * length + 2)); memcpy(vc->sequence + length, vc->sequence, sizeof(char) * length); vc->sequence[2 * length] = '\0'; vc->length = (unsigned int)strlen(vc->sequence); vc->cutpoint = length + 1; vc->strands = 2; free(vc->strand_number); vc->strand_number = (unsigned int *)vrna_alloc(sizeof(unsigned int) * (vc->length + 1)); for (s = i = 0; i <= vc->length; i++) { if (i == length + 1) s++; vc->strand_number[i] = s; } free(vc->strand_order); free(vc->strand_start); free(vc->strand_end); vc->strand_order = (unsigned int *)vrna_alloc(sizeof(unsigned int) * (vc->strands + 1)); vc->strand_start = (unsigned int *)vrna_alloc(sizeof(unsigned int) * (vc->strands + 1)); vc->strand_end = (unsigned int *)vrna_alloc(sizeof(unsigned int) * (vc->strands + 1)); vc->strand_order[0] = 0; vc->strand_order[1] = 1; vc->strand_start[0] = 1; vc->strand_end[0] = vc->strand_start[0] + length - 1; vc->strand_start[1] = vc->strand_end[0] + 1; vc->strand_end[1] = vc->strand_start[1] + length - 1; vc->sequence_encoding = vrna_realloc(vc->sequence_encoding, sizeof(short) * (vc->length + 2)); memcpy(vc->sequence_encoding + length + 1, vc->sequence_encoding + 1, sizeof(short) * length); vc->sequence_encoding[0] = vc->sequence_encoding[vc->length]; vc->sequence_encoding[vc->length + 1] = vc->sequence_encoding[1]; vc->sequence_encoding2 = vrna_realloc(vc->sequence_encoding2, sizeof(short) * (vc->length + 2)); memcpy(vc->sequence_encoding2 + length + 1, vc->sequence_encoding2 + 1, sizeof(short) * length); vc->sequence_encoding2[0] = vc->length; vc->sequence_encoding2[vc->length + 1] = 0; free(vc->ptype); vc->ptype = vrna_ptypes(vc->sequence_encoding2, &(vc->params->model_details)); free(vc->iindx); vc->iindx = vrna_idx_row_wise(vc->length); free(vc->jindx); vc->jindx = vrna_idx_col_wise(vc->length); vrna_hc_init(vc); /* add DP matrices */ vrna_mx_mfe_add(vc, VRNA_MX_DEFAULT, 0); } PRIVATE void halfseq(vrna_fold_compound_t *vc) { unsigned int halflength; halflength = vc->length / 2; vc->sequence = vrna_realloc(vc->sequence, sizeof(char) * (halflength + 1)); vc->sequence[halflength] = '\0'; vc->length = (unsigned int)strlen(vc->sequence); vc->cutpoint = -1; vc->strands = 1; vc->strand_number = (unsigned int *)vrna_realloc(vc->strand_number, sizeof(unsigned int) * (vc->length + 1)); vc->strand_order = (unsigned int *)vrna_realloc(vc->strand_order, sizeof(unsigned int) * (vc->strands + 1)); vc->strand_start = (unsigned int *)vrna_realloc(vc->strand_start, sizeof(unsigned int) * (vc->strands + 1)); vc->strand_end = (unsigned int *)vrna_realloc(vc->strand_end, sizeof(unsigned int) * (vc->strands + 1)); vc->sequence_encoding = vrna_realloc(vc->sequence_encoding, sizeof(short) * (vc->length + 2)); vc->sequence_encoding[0] = vc->sequence_encoding[vc->length]; vc->sequence_encoding[vc->length + 1] = vc->sequence_encoding[1]; vc->sequence_encoding2 = vrna_realloc(vc->sequence_encoding2, sizeof(short) * (vc->length + 2)); vc->sequence_encoding2[0] = vc->length; vc->sequence_encoding2[vc->length + 1] = 0; free(vc->ptype); vc->ptype = vrna_ptypes(vc->sequence_encoding2, &(vc->params->model_details)); free(vc->iindx); vc->iindx = vrna_idx_row_wise(vc->length); free(vc->jindx); vc->jindx = vrna_idx_col_wise(vc->length); vrna_hc_init(vc); /* add DP matrices */ vrna_mx_mfe_add(vc, VRNA_MX_DEFAULT, 0); } typedef struct { int i; int j; int e; int idxj; } zuker_pair; PRIVATE int comp_pair(const void *A, const void *B) { zuker_pair *x, *y; int ex, ey; x = (zuker_pair *)A; y = (zuker_pair *)B; ex = x->e; ey = y->e; if (ex > ey) return 1; if (ex < ey) return -1; return x->idxj + x->i - y->idxj + y->i; } PUBLIC SOLUTION * vrna_subopt_zuker(vrna_fold_compound_t *vc) { /* Compute zuker suboptimal. Here, we're abusing the cofold() code * "double" sequence, compute dimerarray entries, track back every base pair. * This is slightly wasteful compared to the normal solution */ char *structure, *mfestructure, **todo, *ptype; int i, j, counter, num_pairs, psize, p, *indx, *c, turn; unsigned int length, doublelength; float energy; SOLUTION *zukresults; vrna_bp_stack_t *bp_list; zuker_pair *pairlist; sect bt_stack[MAXSECTORS]; /* stack of partial structures for backtracking */ vrna_mx_mfe_t *matrices; vrna_md_t *md; md = &(vc->params->model_details); turn = md->min_loop_size; /* do some magic to re-use cofold code although vc is single sequence */ md->min_loop_size = 0; doubleseq(vc); if (!vrna_fold_compound_prepare(vc, VRNA_OPTION_MFE | VRNA_OPTION_HYBRID)) { vrna_message_warning("vrna_subopt_zuker@cofold.c: Failed to prepare vrna_fold_compound"); return NULL; } doublelength = vc->length; length = doublelength / 2; indx = vc->jindx; ptype = vc->ptype; matrices = vc->matrices; c = matrices->c; num_pairs = counter = 0; mfestructure = (char *)vrna_alloc((unsigned)doublelength + 1); structure = (char *)vrna_alloc((unsigned)doublelength + 1); zukresults = (SOLUTION *)vrna_alloc(((length * (length - 1)) / 2) * sizeof(SOLUTION)); mfestructure[0] = '\0'; /* store length at pos. 0 */ vc->sequence_encoding[0] = vc->sequence_encoding2[0]; /* get mfe and do forward recursion */ (void)fill_arrays(vc, 1); psize = length; pairlist = (zuker_pair *)vrna_alloc(sizeof(zuker_pair) * (psize + 1)); bp_list = (vrna_bp_stack_t *)vrna_alloc(sizeof(vrna_bp_stack_t) * (1 + length / 2)); todo = (char **)vrna_alloc(sizeof(char *) * (length + 1)); for (i = 1; i < length; i++) todo[i] = (char *)vrna_alloc(sizeof(char) * (length + 1)); /* Make a list of all base pairs */ for (i = 1; i < length; i++) { for (j = i + turn + 1 /*??*/; j <= length; j++) { if (ptype[indx[j] + i] == 0) continue; if (num_pairs >= psize) { psize = 1.2 * psize + 32; pairlist = vrna_realloc(pairlist, sizeof(zuker_pair) * (psize + 1)); } pairlist[num_pairs].i = i; pairlist[num_pairs].j = j; pairlist[num_pairs].e = c[indx[j] + i] + c[indx[i + length] + j]; pairlist[num_pairs++].idxj = indx[j]; todo[i][j] = 1; } } qsort(pairlist, num_pairs, sizeof(zuker_pair), comp_pair); for (p = 0; p < num_pairs; p++) { i = pairlist[p].i; j = pairlist[p].j; if (todo[i][j]) { int k; char *sz; bt_stack[1].i = i; bt_stack[1].j = j; bt_stack[1].ml = 2; backtrack_co(bt_stack, bp_list, 1, 0, vc); bt_stack[1].i = j; bt_stack[1].j = i + length; bt_stack[1].ml = 2; backtrack_co(bt_stack, bp_list, 1, bp_list[0].i, vc); energy = pairlist[p].e; sz = vrna_db_from_bp_stack(bp_list, length); zukresults[counter].energy = energy / 100.; zukresults[counter++].structure = sz; for (k = 1; k <= bp_list[0].i; k++) { /* mark all pairs in structure as done */ int x, y; x = bp_list[k].i; y = bp_list[k].j; if (x > length) x -= length; if (y > length) y -= length; if (x > y) { int temp; temp = x; x = y; y = temp; } todo[x][y] = 0; } } } /* clean up */ free(pairlist); for (i = 1; i < length; i++) free(todo[i]); free(todo); free(structure); free(mfestructure); free(bp_list); /* undo magic */ halfseq(vc); md->min_loop_size = turn; return zukresults; } /* *########################################### *# deprecated functions below # *########################################### */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY PRIVATE void wrap_array_export(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **fc_p, int **indx_p, char **ptype_p) { /* make the DP arrays available to routines such as subopt() */ if (backward_compat_compound) { *f5_p = backward_compat_compound->matrices->f5; *c_p = backward_compat_compound->matrices->c; *fML_p = backward_compat_compound->matrices->fML; *fM1_p = backward_compat_compound->matrices->fM1; *fc_p = backward_compat_compound->matrices->fc; *indx_p = backward_compat_compound->jindx; *ptype_p = backward_compat_compound->ptype; } } /*--------------------------------------------------------------------------*/ PRIVATE float wrap_cofold(const char *string, char *structure, vrna_param_t *parameters, int is_constrained) { unsigned int length; char *seq; vrna_fold_compound_t *vc; vrna_param_t *P; float mfe; vc = NULL; length = strlen(string); #ifdef _OPENMP /* Explicitly turn off dynamic threads */ omp_set_dynamic(0); #endif /* we need the parameter structure for hard constraints */ if (parameters) { P = vrna_params_copy(parameters); } else { vrna_md_t md; set_model_details(&md); md.temperature = temperature; P = vrna_params(&md); } P->model_details.min_loop_size = 0; /* set min loop length to 0 */ /* dirty hack to reinsert the '&' according to the global variable 'cut_point' */ seq = vrna_cut_point_insert(string, cut_point); /* get compound structure */ vc = vrna_fold_compound(seq, &(P->model_details), 0); if (parameters) { /* replace params if necessary */ free(vc->params); vc->params = P; } else { free(P); } /* handle hard constraints in pseudo dot-bracket format if passed via simple interface */ if (is_constrained && structure) { unsigned int constraint_options = 0; constraint_options |= VRNA_CONSTRAINT_DB | VRNA_CONSTRAINT_DB_PIPE | VRNA_CONSTRAINT_DB_DOT | VRNA_CONSTRAINT_DB_X | VRNA_CONSTRAINT_DB_ANG_BRACK | VRNA_CONSTRAINT_DB_RND_BRACK | VRNA_CONSTRAINT_DB_INTRAMOL | VRNA_CONSTRAINT_DB_INTERMOL; vrna_constraints_add(vc, (const char *)structure, constraint_options); } if (backward_compat_compound) vrna_fold_compound_free(backward_compat_compound); backward_compat_compound = vc; backward_compat = 1; /* cleanup */ free(seq); /* call mfe_dimer without backtracing */ mfe = vrna_mfe_dimer(vc, NULL); /* now we backtrace in a backward compatible way */ if (structure && vc->params->model_details.backtrack) { char *s; sect bt_stack[MAXSECTORS]; vrna_bp_stack_t *bp; bp = (vrna_bp_stack_t *)vrna_alloc(sizeof(vrna_bp_stack_t) * (4 * (1 + length / 2))); /* add a guess of how many G's may be involved in a G quadruplex */ backtrack(bt_stack, bp, vc); s = vrna_db_from_bp_stack(bp, length); strncpy(structure, s, length + 1); free(s); if (base_pair) free(base_pair); base_pair = bp; } return mfe; } PRIVATE SOLUTION * wrap_zukersubopt(const char *string, vrna_param_t *parameters) { vrna_fold_compound_t *vc; vrna_param_t *P; vc = NULL; #ifdef _OPENMP /* Explicitly turn off dynamic threads */ omp_set_dynamic(0); #endif /* we need the parameter structure for hard constraints */ if (parameters) { P = vrna_params_copy(parameters); } else { vrna_md_t md; set_model_details(&md); md.temperature = temperature; P = vrna_params(&md); } /* get compound structure */ vc = vrna_fold_compound(string, &(P->model_details), VRNA_OPTION_DEFAULT); if (parameters) { /* replace params if necessary */ free(vc->params); vc->params = P; } else { free(P); } if (backward_compat_compound) vrna_fold_compound_free(backward_compat_compound); backward_compat_compound = vc; backward_compat = 1; return vrna_subopt_zuker(vc); } PUBLIC void initialize_cofold(int length) { /* DO NOTHING */ } PUBLIC void free_co_arrays(void) { if (backward_compat_compound && backward_compat) { vrna_fold_compound_free(backward_compat_compound); backward_compat_compound = NULL; backward_compat = 0; } } /*--------------------------------------------------------------------------*/ PUBLIC void export_cofold_arrays_gq(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **fc_p, int **ggg_p, int **indx_p, char **ptype_p) { /* make the DP arrays available to routines such as subopt() */ wrap_array_export(f5_p, c_p, fML_p, fM1_p, fc_p, indx_p, ptype_p); if (backward_compat_compound) *ggg_p = backward_compat_compound->matrices->ggg; } PUBLIC void export_cofold_arrays(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **fc_p, int **indx_p, char **ptype_p) { wrap_array_export(f5_p, c_p, fML_p, fM1_p, fc_p, indx_p, ptype_p); } PUBLIC float cofold(const char *string, char *structure) { return wrap_cofold(string, structure, NULL, fold_constrained); } PUBLIC float cofold_par(const char *string, char *structure, vrna_param_t *parameters, int is_constrained) { return wrap_cofold(string, structure, parameters, is_constrained); } PUBLIC SOLUTION * zukersubopt(const char *string) { return wrap_zukersubopt(string, NULL); } PUBLIC SOLUTION * zukersubopt_par(const char *string, vrna_param_t *parameters) { return wrap_zukersubopt(string, parameters); } PUBLIC void update_cofold_params(void) { vrna_fold_compound_t *v; if (backward_compat_compound && backward_compat) { vrna_md_t md; v = backward_compat_compound; if (v->params) free(v->params); set_model_details(&md); v->params = vrna_params(&md); } } PUBLIC void update_cofold_params_par(vrna_param_t *parameters) { vrna_fold_compound_t *v; if (backward_compat_compound && backward_compat) { v = backward_compat_compound; if (v->params) free(v->params); if (parameters) { v->params = vrna_params_copy(parameters); } else { vrna_md_t md; set_model_details(&md); md.temperature = temperature; v->params = vrna_params(&md); } } } PUBLIC void get_monomere_mfes(float *e1, float *e2) { /*exports monomere free energies*/ *e1 = mfe1; *e2 = mfe2; } #endif
softmax-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file softmax-inl.h * \brief */ #ifndef MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #define MXNET_OPERATOR_NN_SOFTMAX_INL_H_ #include <vector> #include "../mxnet_op.h" #include "../operator_common.h" #include "../tensor/broadcast_reduce_op.h" namespace mxnet { namespace op { namespace mxnet_op { struct softmax_fwd { template<typename DType> MSHADOW_XINLINE static DType Map(DType a, DType b) { return DType(expf(a)/b); } }; struct log_softmax_fwd { template<typename DType> MSHADOW_XINLINE static DType Map(DType a, DType b) { return DType(a - logf(b)); } }; template<typename OP, typename DType, int ndim> inline void Softmax(Stream<cpu> *s, DType *in, DType *out, Shape<ndim> shape, int axis) { index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; #pragma omp parallel for for (int i = 0; i < static_cast<int>(N); ++i) { index_t base = unravel_dot(i, sshape, stride); DType mmax = in[base]; for (index_t j = 1; j < M; ++j) { if (mmax < in[base + j*sa]) mmax = in[base + j*sa]; } DType sum = DType(0); for (index_t j = 0; j < M; ++j) { sum += std::exp(in[base + j*sa] - mmax); } for (index_t j = 0; j < M; ++j) { out[base + j*sa] = OP::Map(in[base + j*sa] - mmax, sum); } } } struct softmax_bwd { template<typename DType> MSHADOW_XINLINE static DType Map(DType ograd, DType out, DType sum) { return DType(out * (ograd - sum)); } }; struct log_softmax_bwd { template<typename DType> MSHADOW_XINLINE static DType Map(DType ograd, DType out, DType sum) { return DType(ograd - expf(out)*sum); } }; template<typename OP1, typename OP2, typename DType, int ndim> inline void SoftmaxGrad(Stream<cpu> *s, DType *out, DType *ograd, DType *igrad, Shape<ndim> shape, int axis) { index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; index_t sa = stride[axis]; #pragma omp parallel for for (int i = 0; i < static_cast<int>(N); ++i) { index_t base = unravel_dot(i, sshape, stride); DType sum = DType(0); for (index_t j = 0; j < M; ++j) { sum += OP1::Map(ograd[base + j*sa], out[base + j*sa]); } for (index_t j = 0; j < M; ++j) { igrad[base + j*sa] = OP2::Map(ograd[base + j*sa], out[base + j*sa], sum); } } } #ifdef __CUDACC__ template<int x_bits, typename OP, typename DType, int ndim> __global__ void softmax_compute_kernel(DType *in, DType *out, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride) { const unsigned x_size = 1 << x_bits; __shared__ DType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t x = threadIdx.x; red::maximum::SetInitValue(smem[x]); for (index_t i = x; i < M; i += x_size) { red::maximum::Reduce(smem[x], in[base + i*sa]); } __syncthreads(); cuda::Reduce1D<red::maximum, x_bits>(smem); __syncthreads(); DType smax = smem[0]; __syncthreads(); red::sum::SetInitValue(smem[x]); for (index_t i = x; i < M; i += x_size) { red::sum::Reduce(smem[x], static_cast<DType>(expf(in[base + i*sa] - smax))); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); DType ssum = smem[0]; __syncthreads(); for (index_t i = x; i < M; i += x_size) { out[base + i*sa] = OP::Map(in[base + i*sa] - smax, ssum); } } template<typename OP, typename DType, int ndim> inline void Softmax(Stream<gpu> *s, DType *in, DType *out, Shape<ndim> shape, int axis) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; softmax_compute_kernel<x_bits, OP, DType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( in, out, M, axis, sshape, stride); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_compute_kernel); } template<int x_bits, typename OP1, typename OP2, typename DType, int ndim> __global__ void softmax_gradient_kernel(DType *out, DType *ograd, DType *igrad, index_t M, int axis, Shape<ndim> sshape, Shape<ndim> stride) { const unsigned x_size = 1 << x_bits; __shared__ DType smem[x_size]; index_t sa = stride[axis]; index_t base = unravel_dot(blockIdx.x, sshape, stride); index_t x = threadIdx.x; red::sum::SetInitValue(smem[x]); for (index_t i = x; i < M; i += x_size) { red::sum::Reduce(smem[x], OP1::Map(ograd[base + i*sa], out[base + i*sa])); } __syncthreads(); cuda::Reduce1D<red::sum, x_bits>(smem); __syncthreads(); DType ssum = smem[0]; __syncthreads(); for (index_t i = x; i < M; i += x_size) { igrad[base + i*sa] = OP2::Map(ograd[base + i*sa], out[base + i*sa], ssum); } } template<typename OP1, typename OP2, typename DType, int ndim> inline void SoftmaxGrad(Stream<gpu> *s, DType *out, DType *ograd, DType *igrad, Shape<ndim> shape, int axis) { const int x_bits = 7; const int x_size = 1 << x_bits; index_t M = shape[axis]; index_t N = shape.Size()/M; Shape<ndim> stride = calc_stride(shape); Shape<ndim> sshape = shape; sshape[axis] = 1; softmax_gradient_kernel<x_bits, OP1, OP2, DType, ndim> <<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>( out, ograd, igrad, M, axis, sshape, stride); MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_gradient_kernel); } #endif } // namespace mxnet_op struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> { int axis; DMLC_DECLARE_PARAMETER(SoftmaxParam) { DMLC_DECLARE_FIELD(axis).set_default(-1) .describe("The axis along which to compute softmax."); } }; template<typename xpu, typename OP> void SoftmaxCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; CHECK_NE(req[0], kAddTo); const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, { if (shape.ndim() == 2) { Softmax<OP>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), shape.get<2>(), axis); } else { Softmax<OP>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), shape.get<3>(), axis); } }); } //template<typename xpu, typename OP1, typename OP2> //void SoftmaxGradCompute(const nnvm::NodeAttrs& attrs, // const OpContext& ctx, // const std::vector<TBlob>& inputs, // const std::vector<OpReqType>& req, // const std::vector<TBlob>& outputs) { // using namespace mxnet_op; // if (req[0] == kNullOp) return; // CHECK_NE(req[0], kAddTo); // const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed); // int axis = CheckAxis(param.axis, inputs[0].ndim()); // TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true); // MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, { // if (shape.ndim() == 2) { // SoftmaxGrad<OP1, OP2>(ctx.get_stream<xpu>(), inputs[1].dptr<DType>(), // inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), // shape.get<2>(), axis); // } else { // SoftmaxGrad<OP1, OP2>(ctx.get_stream<xpu>(), inputs[1].dptr<DType>(), // inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), // shape.get<3>(), axis); // } // }); //} } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NN_SOFTMAX_INL_H_
yescrypt-opt.c
/*- * Copyright 2009 Colin Percival * Copyright 2013,2014 Alexander Peslyak * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file was originally written by Colin Percival as part of the Tarsnap * online backup system. */ #include <errno.h> #include <stdint.h> #include <stdlib.h> #include "sha256_Y.h" #include "sysendian.h" #include "yescrypt-platform.c" static inline uint32_t le32dec(const void *pp) { const uint8_t *p = (uint8_t const *)pp; return ((uint32_t)(p[0]) + ((uint32_t)(p[1]) << 8) + ((uint32_t)(p[2]) << 16) + ((uint32_t)(p[3]) << 24)); } static inline void le32enc(void *pp, uint32_t x) { uint8_t * p = (uint8_t *)pp; p[0] = x & 0xff; p[1] = (x >> 8) & 0xff; p[2] = (x >> 16) & 0xff; p[3] = (x >> 24) & 0xff; } static inline void blkcpy(uint64_t * dest, const uint64_t * src, size_t count) { do { *dest++ = *src++; *dest++ = *src++; *dest++ = *src++; *dest++ = *src++; } while (count -= 4); } static inline void blkxor(uint64_t * dest, const uint64_t * src, size_t count) { do { *dest++ ^= *src++; *dest++ ^= *src++; *dest++ ^= *src++; *dest++ ^= *src++; } while (count -= 4); } typedef union { uint32_t w[16]; uint64_t d[8]; } salsa20_blk_t; static inline void salsa20_simd_shuffle(const salsa20_blk_t * Bin, salsa20_blk_t * Bout) { #define COMBINE(out, in1, in2) \ Bout->d[out] = Bin->w[in1 * 2] | ((uint64_t)Bin->w[in2 * 2 + 1] << 32); COMBINE(0, 0, 2) COMBINE(1, 5, 7) COMBINE(2, 2, 4) COMBINE(3, 7, 1) COMBINE(4, 4, 6) COMBINE(5, 1, 3) COMBINE(6, 6, 0) COMBINE(7, 3, 5) #undef COMBINE } static inline void salsa20_simd_unshuffle(const salsa20_blk_t * Bin, salsa20_blk_t * Bout) { #define COMBINE(out, in1, in2) \ Bout->w[out * 2] = Bin->d[in1]; \ Bout->w[out * 2 + 1] = Bin->d[in2] >> 32; COMBINE(0, 0, 6) COMBINE(1, 5, 3) COMBINE(2, 2, 0) COMBINE(3, 7, 5) COMBINE(4, 4, 2) COMBINE(5, 1, 7) COMBINE(6, 6, 4) COMBINE(7, 3, 1) #undef COMBINE } /** * salsa20_8(B): * Apply the salsa20/8 core to the provided block. */ static void salsa20_8(uint64_t B[8]) { size_t i; salsa20_blk_t X; #define x X.w salsa20_simd_unshuffle((const salsa20_blk_t *)B, &X); for (i = 0; i < 8; i += 2) { #define R(a,b) (((a) << (b)) | ((a) >> (32 - (b)))) /* Operate on columns */ x[ 4] ^= R(x[ 0]+x[12], 7); x[ 8] ^= R(x[ 4]+x[ 0], 9); x[12] ^= R(x[ 8]+x[ 4],13); x[ 0] ^= R(x[12]+x[ 8],18); x[ 9] ^= R(x[ 5]+x[ 1], 7); x[13] ^= R(x[ 9]+x[ 5], 9); x[ 1] ^= R(x[13]+x[ 9],13); x[ 5] ^= R(x[ 1]+x[13],18); x[14] ^= R(x[10]+x[ 6], 7); x[ 2] ^= R(x[14]+x[10], 9); x[ 6] ^= R(x[ 2]+x[14],13); x[10] ^= R(x[ 6]+x[ 2],18); x[ 3] ^= R(x[15]+x[11], 7); x[ 7] ^= R(x[ 3]+x[15], 9); x[11] ^= R(x[ 7]+x[ 3],13); x[15] ^= R(x[11]+x[ 7],18); /* Operate on rows */ x[ 1] ^= R(x[ 0]+x[ 3], 7); x[ 2] ^= R(x[ 1]+x[ 0], 9); x[ 3] ^= R(x[ 2]+x[ 1],13); x[ 0] ^= R(x[ 3]+x[ 2],18); x[ 6] ^= R(x[ 5]+x[ 4], 7); x[ 7] ^= R(x[ 6]+x[ 5], 9); x[ 4] ^= R(x[ 7]+x[ 6],13); x[ 5] ^= R(x[ 4]+x[ 7],18); x[11] ^= R(x[10]+x[ 9], 7); x[ 8] ^= R(x[11]+x[10], 9); x[ 9] ^= R(x[ 8]+x[11],13); x[10] ^= R(x[ 9]+x[ 8],18); x[12] ^= R(x[15]+x[14], 7); x[13] ^= R(x[12]+x[15], 9); x[14] ^= R(x[13]+x[12],13); x[15] ^= R(x[14]+x[13],18); #undef R } #undef x { salsa20_blk_t Y; salsa20_simd_shuffle(&X, &Y); for (i = 0; i < 16; i += 4) { ((salsa20_blk_t *)B)->w[i] += Y.w[i]; ((salsa20_blk_t *)B)->w[i + 1] += Y.w[i + 1]; ((salsa20_blk_t *)B)->w[i + 2] += Y.w[i + 2]; ((salsa20_blk_t *)B)->w[i + 3] += Y.w[i + 3]; } } } /** * blockmix_salsa8(Bin, Bout, X, r): * Compute Bout = BlockMix_{salsa20/8, r}(Bin). The input Bin must be 128r * bytes in length; the output Bout must also be the same size. The * temporary space X must be 64 bytes. */ static void blockmix_salsa8(const uint64_t * Bin, uint64_t * Bout, uint64_t * X, size_t r) { size_t i; /* 1: X <-- B_{2r - 1} */ blkcpy(X, &Bin[(2 * r - 1) * 8], 8); /* 2: for i = 0 to 2r - 1 do */ for (i = 0; i < 2 * r; i += 2) { /* 3: X <-- H(X \xor B_i) */ blkxor(X, &Bin[i * 8], 8); salsa20_8(X); /* 4: Y_i <-- X */ /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ blkcpy(&Bout[i * 4], X, 8); /* 3: X <-- H(X \xor B_i) */ blkxor(X, &Bin[i * 8 + 8], 8); salsa20_8(X); /* 4: Y_i <-- X */ /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ blkcpy(&Bout[i * 4 + r * 8], X, 8); } } /* These are tunable */ #define S_BITS 8 #define S_SIMD 2 #define S_P 4 #define S_ROUNDS 6 /* Number of S-boxes. Not tunable, hard-coded in a few places. */ #define S_N 2 /* Derived values. Not tunable on their own. */ #define S_SIZE1 (1 << S_BITS) #define S_MASK ((S_SIZE1 - 1) * S_SIMD * 8) #define S_MASK2 (((uint64_t)S_MASK << 32) | S_MASK) #define S_SIZE_ALL (S_N * S_SIZE1 * S_SIMD) #define S_P_SIZE (S_P * S_SIMD) #define S_MIN_R ((S_P * S_SIMD + 15) / 16) /** * pwxform(B): * Transform the provided block using the provided S-boxes. */ static void block_pwxform(uint64_t * B, const uint64_t * S) { uint64_t (*X)[S_SIMD] = (uint64_t (*)[S_SIMD])B; const uint8_t *S0 = (const uint8_t *)S; const uint8_t *S1 = (const uint8_t *)(S + S_SIZE1 * S_SIMD); size_t i, j; #if S_SIMD > 2 size_t k; #endif for (j = 0; j < S_P; j++) { uint64_t *Xj = X[j]; uint64_t x0 = Xj[0]; #if S_SIMD > 1 uint64_t x1 = Xj[1]; #endif for (i = 0; i < S_ROUNDS; i++) { uint64_t x = x0 & S_MASK2; const uint64_t *p0, *p1; p0 = (const uint64_t *)(S0 + (uint32_t)x); p1 = (const uint64_t *)(S1 + (x >> 32)); x0 = (uint64_t)(x0 >> 32) * (uint32_t)x0; x0 += p0[0]; x0 ^= p1[0]; #if S_SIMD > 1 x1 = (uint64_t)(x1 >> 32) * (uint32_t)x1; x1 += p0[1]; x1 ^= p1[1]; #endif #if S_SIMD > 2 for (k = 2; k < S_SIMD; k++) { x = Xj[k]; x = (uint64_t)(x >> 32) * (uint32_t)x; x += p0[k]; x ^= p1[k]; Xj[k] = x; } #endif } Xj[0] = x0; #if S_SIMD > 1 Xj[1] = x1; #endif } } /** * blockmix_pwxform(Bin, Bout, S, r): * Compute Bout = BlockMix_pwxform{salsa20/8, S, r}(Bin). The input Bin must * be 128r bytes in length; the output Bout must also be the same size. * * S lacks const qualifier to match blockmix_salsa8()'s prototype, which we * need to refer to both functions via the same function pointers. */ static void blockmix_pwxform(const uint64_t * Bin, uint64_t * Bout, uint64_t * S, size_t r) { size_t r1, r2, i; /* Convert 128-byte blocks to (S_P_SIZE * 64-bit) blocks */ r1 = r * 128 / (S_P_SIZE * 8); /* X <-- B_{r1 - 1} */ blkcpy(Bout, &Bin[(r1 - 1) * S_P_SIZE], S_P_SIZE); /* X <-- X \xor B_i */ blkxor(Bout, Bin, S_P_SIZE); /* X <-- H'(X) */ /* B'_i <-- X */ block_pwxform(Bout, S); /* for i = 0 to r1 - 1 do */ for (i = 1; i < r1; i++) { /* X <-- X \xor B_i */ blkcpy(&Bout[i * S_P_SIZE], &Bout[(i - 1) * S_P_SIZE], S_P_SIZE); blkxor(&Bout[i * S_P_SIZE], &Bin[i * S_P_SIZE], S_P_SIZE); /* X <-- H'(X) */ /* B'_i <-- X */ block_pwxform(&Bout[i * S_P_SIZE], S); } /* Handle partial blocks */ if (i * S_P_SIZE < r * 16) blkcpy(&Bout[i * S_P_SIZE], &Bin[i * S_P_SIZE], r * 16 - i * S_P_SIZE); i = (r1 - 1) * S_P_SIZE / 8; /* Convert 128-byte blocks to 64-byte blocks */ r2 = r * 2; /* B'_i <-- H(B'_i) */ salsa20_8(&Bout[i * 8]); i++; for (; i < r2; i++) { /* B'_i <-- H(B'_i \xor B'_{i-1}) */ blkxor(&Bout[i * 8], &Bout[(i - 1) * 8], 8); salsa20_8(&Bout[i * 8]); } } /** * integerify(B, r): * Return the result of parsing B_{2r-1} as a little-endian integer. */ static inline uint64_t integerify(const uint64_t * B, size_t r) { /* * Our 64-bit words are in host byte order, and word 6 holds the second 32-bit * word of B_{2r-1} due to SIMD shuffling. The 64-bit value we return is also * in host byte order, as it should be. */ const uint64_t * X = &B[(2 * r - 1) * 8]; uint32_t lo = X[0]; uint32_t hi = X[6] >> 32; return ((uint64_t)hi << 32) + lo; } /** * smix1(B, r, N, flags, V, NROM, shared, XY, S): * Compute first loop of B = SMix_r(B, N). The input B must be 128r bytes in * length; the temporary storage V must be 128rN bytes in length; the temporary * storage XY must be 256r + 64 bytes in length. The value N must be even and * no smaller than 2. */ static void smix1(uint64_t * B, size_t r, uint64_t N, yescrypt_flags_t flags, uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared, uint64_t * XY, uint64_t * S) { void (*blockmix)(const uint64_t *, uint64_t *, uint64_t *, size_t) = (S ? blockmix_pwxform : blockmix_salsa8); const uint64_t * VROM = shared->shared1.aligned; uint32_t VROM_mask = shared->mask1; size_t s = 16 * r; uint64_t * X = V; uint64_t * Y = &XY[s]; uint64_t * Z = S ? S : &XY[2 * s]; uint64_t n, i, j; size_t k; /* 1: X <-- B */ /* 3: V_i <-- X */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&B[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&X[i * 8]; for (k = 0; k < 16; k++) tmp->w[k] = le32dec(&src->w[k]); salsa20_simd_shuffle(tmp, dst); } /* 4: X <-- H(X) */ /* 3: V_i <-- X */ blockmix(X, Y, Z, r); blkcpy(&V[s], Y, s); X = XY; if (NROM && (VROM_mask & 1)) { if ((1 & VROM_mask) == 1) { /* j <-- Integerify(X) mod NROM */ j = integerify(Y, r) & (NROM - 1); /* X <-- H(X \xor VROM_j) */ blkxor(Y, &VROM[j * s], s); } blockmix(Y, X, Z, r); /* 2: for i = 0 to N - 1 do */ for (n = 1, i = 2; i < N; i += 2) { /* 3: V_i <-- X */ blkcpy(&V[i * s], X, s); if ((i & (i - 1)) == 0) n <<= 1; /* j <-- Wrap(Integerify(X), i) */ j = integerify(X, r) & (n - 1); j += i - n; /* X <-- X \xor V_j */ blkxor(X, &V[j * s], s); /* 4: X <-- H(X) */ blockmix(X, Y, Z, r); /* 3: V_i <-- X */ blkcpy(&V[(i + 1) * s], Y, s); j = integerify(Y, r); if (((i + 1) & VROM_mask) == 1) { /* j <-- Integerify(X) mod NROM */ j &= NROM - 1; /* X <-- H(X \xor VROM_j) */ blkxor(Y, &VROM[j * s], s); } else { /* j <-- Wrap(Integerify(X), i) */ j &= n - 1; j += i + 1 - n; /* X <-- H(X \xor V_j) */ blkxor(Y, &V[j * s], s); } blockmix(Y, X, Z, r); } } else { yescrypt_flags_t rw = flags & YESCRYPT_RW; /* 4: X <-- H(X) */ blockmix(Y, X, Z, r); /* 2: for i = 0 to N - 1 do */ for (n = 1, i = 2; i < N; i += 2) { /* 3: V_i <-- X */ blkcpy(&V[i * s], X, s); if (rw) { if ((i & (i - 1)) == 0) n <<= 1; /* j <-- Wrap(Integerify(X), i) */ j = integerify(X, r) & (n - 1); j += i - n; /* X <-- X \xor V_j */ blkxor(X, &V[j * s], s); } /* 4: X <-- H(X) */ blockmix(X, Y, Z, r); /* 3: V_i <-- X */ blkcpy(&V[(i + 1) * s], Y, s); if (rw) { /* j <-- Wrap(Integerify(X), i) */ j = integerify(Y, r) & (n - 1); j += (i + 1) - n; /* X <-- X \xor V_j */ blkxor(Y, &V[j * s], s); } /* 4: X <-- H(X) */ blockmix(Y, X, Z, r); } } /* B' <-- X */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&X[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&B[i * 8]; for (k = 0; k < 16; k++) le32enc(&tmp->w[k], src->w[k]); salsa20_simd_unshuffle(tmp, dst); } } /** * smix2(B, r, N, Nloop, flags, V, NROM, shared, XY, S): * Compute second loop of B = SMix_r(B, N). The input B must be 128r bytes in * length; the temporary storage V must be 128rN bytes in length; the temporary * storage XY must be 256r + 64 bytes in length. The value N must be a * power of 2 greater than 1. The value Nloop must be even. */ static void smix2(uint64_t * B, size_t r, uint64_t N, uint64_t Nloop, yescrypt_flags_t flags, uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared, uint64_t * XY, uint64_t * S) { void (*blockmix)(const uint64_t *, uint64_t *, uint64_t *, size_t) = (S ? blockmix_pwxform : blockmix_salsa8); const uint64_t * VROM = shared->shared1.aligned; uint32_t VROM_mask = shared->mask1 | 1; size_t s = 16 * r; yescrypt_flags_t rw = flags & YESCRYPT_RW; uint64_t * X = XY; uint64_t * Y = &XY[s]; uint64_t * Z = S ? S : &XY[2 * s]; uint64_t i, j; size_t k; if (Nloop == 0) return; /* X <-- B' */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&B[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&X[i * 8]; for (k = 0; k < 16; k++) tmp->w[k] = le32dec(&src->w[k]); salsa20_simd_shuffle(tmp, dst); } if (NROM) { /* 6: for i = 0 to N - 1 do */ for (i = 0; i < Nloop; i += 2) { /* 7: j <-- Integerify(X) mod N */ j = integerify(X, r) & (N - 1); /* 8: X <-- H(X \xor V_j) */ blkxor(X, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], X, s); blockmix(X, Y, Z, r); j = integerify(Y, r); if (((i + 1) & VROM_mask) == 1) { /* j <-- Integerify(X) mod NROM */ j &= NROM - 1; /* X <-- H(X \xor VROM_j) */ blkxor(Y, &VROM[j * s], s); } else { /* 7: j <-- Integerify(X) mod N */ j &= N - 1; /* 8: X <-- H(X \xor V_j) */ blkxor(Y, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], Y, s); } blockmix(Y, X, Z, r); } } else { /* 6: for i = 0 to N - 1 do */ i = Nloop / 2; do { /* 7: j <-- Integerify(X) mod N */ j = integerify(X, r) & (N - 1); /* 8: X <-- H(X \xor V_j) */ blkxor(X, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], X, s); blockmix(X, Y, Z, r); /* 7: j <-- Integerify(X) mod N */ j = integerify(Y, r) & (N - 1); /* 8: X <-- H(X \xor V_j) */ blkxor(Y, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], Y, s); blockmix(Y, X, Z, r); } while (--i); } /* 10: B' <-- X */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&X[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&B[i * 8]; for (k = 0; k < 16; k++) le32enc(&tmp->w[k], src->w[k]); salsa20_simd_unshuffle(tmp, dst); } } /** * p2floor(x): * Largest power of 2 not greater than argument. */ static uint64_t p2floor(uint64_t x) { uint64_t y; while ((y = x & (x - 1))) x = y; return x; } /** * smix(B, r, N, p, t, flags, V, NROM, shared, XY, S): * Compute B = SMix_r(B, N). The input B must be 128rp bytes in length; the * temporary storage V must be 128rN bytes in length; the temporary storage * XY must be 256r+64 or (256r+64)*p bytes in length (the larger size is * required with OpenMP-enabled builds). The value N must be a power of 2 * greater than 1. */ static void smix(uint64_t * B, size_t r, uint64_t N, uint32_t p, uint32_t t, yescrypt_flags_t flags, uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared, uint64_t * XY, uint64_t * S) { size_t s = 16 * r; uint64_t Nchunk = N / p, Nloop_all, Nloop_rw; uint32_t i; Nloop_all = Nchunk; if (flags & YESCRYPT_RW) { if (t <= 1) { if (t) Nloop_all *= 2; /* 2/3 */ Nloop_all = (Nloop_all + 2) / 3; /* 1/3, round up */ } else { Nloop_all *= t - 1; } } else if (t) { if (t == 1) Nloop_all += (Nloop_all + 1) / 2; /* 1.5, round up */ Nloop_all *= t; } Nloop_rw = 0; if (flags & __YESCRYPT_INIT_SHARED) Nloop_rw = Nloop_all; else if (flags & YESCRYPT_RW) Nloop_rw = Nloop_all / p; Nchunk &= ~(uint64_t)1; /* round down to even */ Nloop_all++; Nloop_all &= ~(uint64_t)1; /* round up to even */ Nloop_rw &= ~(uint64_t)1; /* round down to even */ #ifdef _OPENMP #pragma omp parallel if (p > 1) default(none) private(i) shared(B, r, N, p, flags, V, NROM, shared, XY, S, s, Nchunk, Nloop_all, Nloop_rw) { #pragma omp for #endif for (i = 0; i < p; i++) { uint64_t Vchunk = i * Nchunk; uint64_t * Bp = &B[i * s]; uint64_t * Vp = &V[Vchunk * s]; #ifdef _OPENMP uint64_t * XYp = &XY[i * (2 * s + 8)]; #else uint64_t * XYp = XY; #endif uint64_t Np = (i < p - 1) ? Nchunk : (N - Vchunk); uint64_t * Sp = S ? &S[i * S_SIZE_ALL] : S; if (Sp) smix1(Bp, 1, S_SIZE_ALL / 16, flags & ~YESCRYPT_PWXFORM, Sp, NROM, shared, XYp, NULL); if (!(flags & __YESCRYPT_INIT_SHARED_2)) smix1(Bp, r, Np, flags, Vp, NROM, shared, XYp, Sp); smix2(Bp, r, p2floor(Np), Nloop_rw, flags, Vp, NROM, shared, XYp, Sp); } if (Nloop_all > Nloop_rw) { #ifdef _OPENMP #pragma omp for #endif for (i = 0; i < p; i++) { uint64_t * Bp = &B[i * s]; #ifdef _OPENMP uint64_t * XYp = &XY[i * (2 * s + 8)]; #else uint64_t * XYp = XY; #endif uint64_t * Sp = S ? &S[i * S_SIZE_ALL] : S; smix2(Bp, r, N, Nloop_all - Nloop_rw, flags & ~YESCRYPT_RW, V, NROM, shared, XYp, Sp); } } #ifdef _OPENMP } #endif } /** * yescrypt_kdf(shared, local, passwd, passwdlen, salt, saltlen, * N, r, p, t, flags, buf, buflen): * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r, * p, buflen), or a revision of scrypt as requested by flags and shared, and * write the result into buf. The parameters r, p, and buflen must satisfy * r * p < 2^30 and buflen <= (2^32 - 1) * 32. The parameter N must be a power * of 2 greater than 1. * * t controls computation time while not affecting peak memory usage. shared * and flags may request special modes as described in yescrypt.h. local is * the thread-local data structure, allowing to preserve and reuse a memory * allocation across calls, thereby reducing its overhead. * * Return 0 on success; or -1 on error. */ int yescrypt_kdf(const yescrypt_shared_t * shared, yescrypt_local_t * local, const uint8_t * passwd, size_t passwdlen, const uint8_t * salt, size_t saltlen, uint64_t N, uint32_t r, uint32_t p, uint32_t t, yescrypt_flags_t flags, uint8_t * buf, size_t buflen) { yescrypt_region_t tmp; uint64_t NROM; size_t B_size, V_size, XY_size, need; uint64_t * B, * V, * XY, * S; uint64_t sha256[4]; /* * YESCRYPT_PARALLEL_SMIX is a no-op at p = 1 for its intended purpose, * so don't let it have side-effects. Without this adjustment, it'd * enable the SHA-256 password pre-hashing and output post-hashing, * because any deviation from classic scrypt implies those. */ if (p == 1) flags &= ~YESCRYPT_PARALLEL_SMIX; /* Sanity-check parameters */ if (flags & ~YESCRYPT_KNOWN_FLAGS) { errno = EINVAL; return -1; } #if SIZE_MAX > UINT32_MAX if (buflen > (((uint64_t)(1) << 32) - 1) * 32) { errno = EFBIG; return -1; } #endif if ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) { errno = EFBIG; return -1; } if (((N & (N - 1)) != 0) || (N <= 1) || (r < 1) || (p < 1)) { errno = EINVAL; return -1; } if ((flags & YESCRYPT_PARALLEL_SMIX) && (N / p <= 1)) { errno = EINVAL; return -1; } #if S_MIN_R > 1 if ((flags & YESCRYPT_PWXFORM) && (r < S_MIN_R)) { errno = EINVAL; return -1; } #endif if ((p > SIZE_MAX / ((size_t)256 * r + 64)) || #if SIZE_MAX / 256 <= UINT32_MAX (r > SIZE_MAX / 256) || #endif (N > SIZE_MAX / 128 / r)) { errno = ENOMEM; return -1; } if (N > UINT64_MAX / ((uint64_t)t + 1)) { errno = EFBIG; return -1; } #ifdef _OPENMP if (!(flags & YESCRYPT_PARALLEL_SMIX) && (N > SIZE_MAX / 128 / (r * p))) { errno = ENOMEM; return -1; } #endif if ((flags & YESCRYPT_PWXFORM) && #ifndef _OPENMP (flags & YESCRYPT_PARALLEL_SMIX) && #endif p > SIZE_MAX / (S_SIZE_ALL * sizeof(*S))) { errno = ENOMEM; return -1; } NROM = 0; if (shared->shared1.aligned) { NROM = shared->shared1.aligned_size / ((size_t)128 * r); if (((NROM & (NROM - 1)) != 0) || (NROM <= 1) || !(flags & YESCRYPT_RW)) { errno = EINVAL; return -1; } } /* Allocate memory */ V = NULL; V_size = (size_t)128 * r * N; #ifdef _OPENMP if (!(flags & YESCRYPT_PARALLEL_SMIX)) V_size *= p; #endif need = V_size; if (flags & __YESCRYPT_INIT_SHARED) { if (local->aligned_size < need) { if (local->base || local->aligned || local->base_size || local->aligned_size) { errno = EINVAL; return -1; } if (!alloc_region(local, need)) return -1; } V = (uint64_t *)local->aligned; need = 0; } B_size = (size_t)128 * r * p; need += B_size; if (need < B_size) { errno = ENOMEM; return -1; } XY_size = (size_t)256 * r + 64; #ifdef _OPENMP XY_size *= p; #endif need += XY_size; if (need < XY_size) { errno = ENOMEM; return -1; } if (flags & YESCRYPT_PWXFORM) { size_t S_size = S_SIZE_ALL * sizeof(*S); #ifdef _OPENMP S_size *= p; #else if (flags & YESCRYPT_PARALLEL_SMIX) S_size *= p; #endif need += S_size; if (need < S_size) { errno = ENOMEM; return -1; } } if (flags & __YESCRYPT_INIT_SHARED) { if (!alloc_region(&tmp, need)) return -1; B = (uint64_t *)tmp.aligned; XY = (uint64_t *)((uint8_t *)B + B_size); } else { init_region(&tmp); if (local->aligned_size < need) { if (free_region(local)) return -1; if (!alloc_region(local, need)) return -1; } B = (uint64_t *)local->aligned; V = (uint64_t *)((uint8_t *)B + B_size); XY = (uint64_t *)((uint8_t *)V + V_size); } S = NULL; if (flags & YESCRYPT_PWXFORM) S = (uint64_t *)((uint8_t *)XY + XY_size); if (t || flags) { SHA256_CTX_Y ctx; SHA256_Init_Y(&ctx); SHA256_Update_Y(&ctx, passwd, passwdlen); SHA256_Final_Y((uint8_t *)sha256, &ctx); passwd = (uint8_t *)sha256; passwdlen = sizeof(sha256); } /* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */ PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1, (uint8_t *)B, B_size); if (t || flags) blkcpy(sha256, B, sizeof(sha256) / sizeof(sha256[0])); if (p == 1 || (flags & YESCRYPT_PARALLEL_SMIX)) { smix(B, r, N, p, t, flags, V, NROM, shared, XY, S); } else { uint32_t i; /* 2: for i = 0 to p - 1 do */ #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(B, r, N, p, t, flags, V, NROM, shared, XY, S) #endif for (i = 0; i < p; i++) { /* 3: B_i <-- MF(B_i, N) */ #ifdef _OPENMP smix(&B[(size_t)16 * r * i], r, N, 1, t, flags, &V[(size_t)16 * r * i * N], NROM, shared, &XY[((size_t)32 * r + 8) * i], S ? &S[S_SIZE_ALL * i] : S); #else smix(&B[(size_t)16 * r * i], r, N, 1, t, flags, V, NROM, shared, XY, S); #endif } } /* 5: DK <-- PBKDF2(P, B, 1, dkLen) */ PBKDF2_SHA256(passwd, passwdlen, (uint8_t *)B, B_size, 1, buf, buflen); /* * Except when computing classic scrypt, allow all computation so far * to be performed on the client. The final steps below match those of * SCRAM (RFC 5802), so that an extension of SCRAM (with the steps so * far in place of SCRAM's use of PBKDF2 and with SHA-256 in place of * SCRAM's use of SHA-1) would be usable with yescrypt hashes. */ if ((t || flags) && buflen == sizeof(sha256)) { /* Compute ClientKey */ { HMAC_SHA256_CTX_Y ctx; HMAC_SHA256_Init_Y(&ctx, buf, buflen); if (r == 32) { // yescryptR32 HMAC_SHA256_Update_Y(&ctx, "WaviBanana", 10); } else if (r == 16) { // yescryptR16 HMAC_SHA256_Update_Y(&ctx, "Client Key", 10); } else { // yescrypt HMAC_SHA256_Update_Y(&ctx, salt, saltlen); } HMAC_SHA256_Final_Y((uint8_t *)sha256, &ctx); } /* Compute StoredKey */ { SHA256_CTX_Y ctx; SHA256_Init_Y(&ctx); SHA256_Update_Y(&ctx, (uint8_t *)sha256, sizeof(sha256)); SHA256_Final_Y(buf, &ctx); } } if (free_region(&tmp)) return -1; /* Success! */ return 0; }
LAGraph_ConnectedComponents.c
//------------------------------------------------------------------------------ // LAGraph_ConnectedComponents: connected components //------------------------------------------------------------------------------ // LAGraph, (c) 2021 by The LAGraph Contributors, All Rights Reserved. // SPDX-License-Identifier: BSD-2-Clause //------------------------------------------------------------------------------ // Code is based on the algorithm described in the following paper // Zhang, Azad, Hu. FastSV: FastSV: A Distributed-Memory Connected Component // Algorithm with Fast Convergence (SIAM PP20) // A subsequent update to the algorithm is here (which might not be reflected // in this code): // // Yongzhe Zhang, Ariful Azad, Aydin Buluc: Parallel algorithms for finding // connected components using linear algebra. J. Parallel Distributed Comput. // 144: 14-27 (2020). // Modified by Tim Davis, Texas A&M University // The input matrix A must be symmetric. Self-edges (diagonal entries) are // OK, and are ignored. The values and type of A are ignored; just its // pattern is accessed. // The matrix A must have dimension 2^32 or less. // todo: Need a 64-bit version of this method. // todo: this function is not thread-safe, since it exports G->A and then // reimports it back. G->A is unchanged when the function returns, but during // execution G->A is invalid. #define LAGraph_FREE_ALL ; #include "LG_internal.h" //------------------------------------------------------------------------------ // hash functions: todo describe me //------------------------------------------------------------------------------ // hash table size must be a power of 2 #define HASH_SIZE 1024 // number of samples to insert into the hash table // todo: this seems to be a lot of entries for a HASH_SIZE of 1024. // There could be lots of collisions. #define HASH_SAMPLES 864 #define HASH(x) (((x << 4) + x) & (HASH_SIZE-1)) #define NEXT(x) ((x + 23) & (HASH_SIZE-1)) //------------------------------------------------------------------------------ // ht_init: todo describe me //------------------------------------------------------------------------------ // Clear the hash table counts (ht_val [0:HASH_SIZE-1] = 0), and set all hash // table entries as empty (ht_key [0:HASH_SIZE-1] =-1). // todo: the memset of ht_key is confusing // todo: the name "ht_val" is confusing. It is not a value, but a count of // the number of times the value x = ht_key [h] has been inserted into the // hth position in the hash table. It should be renamed ht_cnt. static inline void ht_init ( int32_t *ht_key, int32_t *ht_val ) { memset (ht_key, -1, sizeof (int32_t) * HASH_SIZE) ; memset (ht_val, 0, sizeof (int32_t) * HASH_SIZE) ; } //------------------------------------------------------------------------------ // ht_sample: todo describe me //------------------------------------------------------------------------------ // static inline void ht_sample ( uint32_t *V32, // array of size n (todo: this is a bad variable name) int32_t n, int32_t samples, // number of samples to take from V32 int32_t *ht_key, int32_t *ht_val, uint64_t *seed ) { for (int32_t k = 0 ; k < samples ; k++) { // select an entry from V32 at random int32_t x = V32 [LAGraph_Random60 (seed) % n] ; // find x in the hash table // todo: make this loop a static inline function (see also below) int32_t h = HASH (x) ; while (ht_key [h] != -1 && ht_key [h] != x) { h = NEXT (h) ; } ht_key [h] = x ; ht_val [h]++ ; } } //------------------------------------------------------------------------------ // ht_most_frequent: todo describe me //------------------------------------------------------------------------------ // todo what if key is returned as -1? Code breaks. todo: handle this case static inline int32_t ht_most_frequent ( int32_t *ht_key, int32_t *ht_val ) { int32_t key = -1 ; int32_t val = 0 ; // max (ht_val [0:HASH_SIZE-1]) for (int32_t h = 0 ; h < HASH_SIZE ; h++) { if (ht_val [h] > val) { key = ht_key [h] ; val = ht_val [h] ; } } return (key) ; // return most frequent key } //------------------------------------------------------------------------------ // Reduce_assign32: w (index) += s, using MIN as the "+=" accum operator //------------------------------------------------------------------------------ // mask = NULL, accumulator = GrB_MIN_UINT32, descriptor = NULL. // Duplicates are summed with the accumulator, which differs from how // GrB_assign works. GrB_assign states that the presence of duplicates results // in undefined behavior. GrB_assign in SuiteSparse:GraphBLAS follows the // MATLAB rule, which discards all but the first of the duplicates. // todo: add this to GraphBLAS as a variant of GrB_assign, either as // GxB_assign_accum (or another name), or as a GxB_* descriptor setting. static inline int Reduce_assign32 ( GrB_Vector *w_handle, // vector of size n, all entries present GrB_Vector *s_handle, // vector of size n, all entries present uint32_t *index, // array of size n, can have duplicates GrB_Index n, int nthreads, int32_t *ht_key, // hash table int32_t *ht_val, // hash table (count of # of entries) uint64_t *seed, // random char *msg ) { GrB_Type w_type, s_type ; GrB_Index w_n, s_n, w_nvals, s_nvals, *w_i, *s_i, w_size, s_size ; uint32_t *w_x, *s_x ; bool s_iso = false ; //-------------------------------------------------------------------------- // export w and s //-------------------------------------------------------------------------- // export the GrB_Vectors w and s as full arrays, to get direct access to // their contents. Note that this would fail if w or s are not full, with // all entries present. GrB_TRY (GxB_Vector_export_Full (w_handle, &w_type, &w_n, (void **) &w_x, &w_size, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) NULL, #endif NULL)) ; GrB_TRY (GxB_Vector_export_Full (s_handle, &s_type, &s_n, (void **) &s_x, &s_size, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) &s_iso, #endif NULL)) ; if (nthreads >= 4) { // allocate a buf array for each thread, of size HASH_SIZE uint32_t *mem = LAGraph_Malloc (nthreads*HASH_SIZE, sizeof (uint32_t)) ; // todo: check out-of-memory condition here // todo why is hashing needed here? hashing is slow for what needs // to be computed here. GraphBLAS has fast MIN atomic monoids that // do not require hashing. ht_init (ht_key, ht_val) ; ht_sample (index, n, HASH_SAMPLES, ht_key, ht_val, seed) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (int tid = 0 ; tid < nthreads ; tid++) { // get the thread-specific buf array of size HASH_SIZE // todo: buf is a bad variable name; it's not a "buffer", // but a local workspace to compute the local version of w_x. uint32_t *buf = mem + tid * HASH_SIZE ; // copy the values from the global hash table into buf for (int32_t h = 0 ; h < HASH_SIZE ; h++) { if (ht_key [h] != -1) { buf [h] = w_x [ht_key [h]] ; } } // this thread works on index [kstart:kend] int32_t kstart = (n * tid + nthreads - 1) / nthreads ; int32_t kend = (n * tid + n + nthreads - 1) / nthreads ; for (int32_t k = kstart ; k < kend ; k++) { uint32_t i = index [k] ; // todo: make this loop a static inline function int32_t h = HASH (i) ; while (ht_key [h] != -1 && ht_key [h] != i) { h = NEXT (h) ; } if (ht_key [h] == -1) { // todo is this a race condition? w_x [i] = LAGraph_MIN (w_x [i], s_x [s_iso?0:k]) ; } else { buf [h] = LAGraph_MIN (buf [h], s_x [s_iso?0:k]) ; } } } // combine intermediate results from each thread for (int32_t h = 0 ; h < HASH_SIZE ; h++) { int32_t i = ht_key [h] ; if (i != -1) { for (int32_t tid = 0 ; tid < nthreads ; tid++) { w_x [i] = LAGraph_MIN (w_x [i], mem [tid * HASH_SIZE + h]) ; } } } LAGraph_Free ((void **) &mem) ; } else { // sequential version for (GrB_Index k = 0 ; k < n ; k++) { uint32_t i = index [k] ; w_x [i] = LAGraph_MIN (w_x [i], s_x [s_iso?0:k]) ; } } //-------------------------------------------------------------------------- // reimport w and s back into GrB_Vectors, and return result //-------------------------------------------------------------------------- // s is unchanged. It was exported only to compute w (index) += s GrB_TRY (GxB_Vector_import_Full (w_handle, w_type, w_n, (void **) &w_x, w_size, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) false, #endif NULL)) ; GrB_TRY (GxB_Vector_import_Full (s_handle, s_type, s_n, (void **) &s_x, s_size, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) s_iso, #endif NULL)) ; return (0) ; } //------------------------------------------------------------------------------ // LAGraph_ConnectedComponents //------------------------------------------------------------------------------ // The output of LAGraph_ConnectedComponents is a vector component, where // component(i)=s if node i is in the connected compononent whose // representative node is node s. If s is a representative, then // component(s)=s. The number of connected components in the graph G is the // number of representatives. #undef LAGraph_FREE_ALL #define LAGraph_FREE_ALL \ { \ LAGraph_Free ((void **) &I) ; \ LAGraph_Free ((void **) &V32) ; \ LAGraph_Free ((void **) &ht_key) ; \ LAGraph_Free ((void **) &ht_val) ; \ /* todo why is T not freed?? */ \ GrB_free (&f) ; \ GrB_free (&gp) ; \ GrB_free (&mngp) ; \ GrB_free (&gp_new) ; \ GrB_free (&mod) ; \ } int LAGraph_ConnectedComponents ( // output GrB_Vector *component, // component(i)=s if node is in the component s // inputs LAGraph_Graph G, // input graph, G->A can change char *msg ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- LG_CLEAR_MSG ; uint32_t *V32 = NULL ; int32_t *ht_key = NULL, *ht_val = NULL ; GrB_Index n, nnz, *I = NULL ; GrB_Vector f = NULL, gp_new = NULL, mngp = NULL, mod = NULL, gp = NULL ; GrB_Matrix T = NULL ; LG_CHECK (LAGraph_CheckGraph (G, msg), -1, "graph is invalid") ; LG_CHECK (component == NULL, -1, "component parameter is NULL") ; if (G->kind == LAGRAPH_ADJACENCY_UNDIRECTED || (G->kind == LAGRAPH_ADJACENCY_DIRECTED && G->A_pattern_is_symmetric == LAGRAPH_TRUE)) { // A must be symmetric ; } else { // A must not be unsymmetric LG_CHECK (false, -1, "input must be symmetric") ; } GrB_Matrix S = G->A ; GrB_TRY (GrB_Matrix_nrows (&n, S)) ; GrB_TRY (GrB_Matrix_nvals (&nnz, S)) ; LG_CHECK (n > UINT32_MAX, -1, "problem too large (fixme)") ; #define FASTSV_SAMPLES 4 bool sampling = (n * FASTSV_SAMPLES * 2 < nnz) ; // random number seed uint64_t seed = n ; //-------------------------------------------------------------------------- // initializations //-------------------------------------------------------------------------- // determine # of threads to use for Reduce_assign int nthreads ; LAGraph_TRY (LAGraph_GetNumThreads (&nthreads, NULL)) ; nthreads = LAGraph_MIN (nthreads, n / 16) ; nthreads = LAGraph_MAX (nthreads, 1) ; // # of threads to use for typecast int nthreads2 = n / (64*1024) ; nthreads2 = LAGraph_MIN (nthreads2, nthreads) ; nthreads2 = LAGraph_MAX (nthreads2, 1) ; // vectors GrB_TRY (GrB_Vector_new (&f, GrB_UINT32, n)) ; GrB_TRY (GrB_Vector_new (&gp_new, GrB_UINT32, n)) ; GrB_TRY (GrB_Vector_new (&mod, GrB_BOOL, n)) ; // temporary arrays I = LAGraph_Malloc (n, sizeof (GrB_Index)) ; V32 = LAGraph_Malloc (n, sizeof (uint32_t)) ; // todo: check out-of-memory condition // prepare vectors #pragma omp parallel for num_threads(nthreads2) schedule(static) for (GrB_Index i = 0 ; i < n ; i++) { I [i] = i ; V32 [i] = (uint32_t) i ; } GrB_TRY (GrB_Vector_build (f, I, V32, n, GrB_PLUS_UINT32)) ; GrB_TRY (GrB_Vector_dup (&gp, f)) ; GrB_TRY (GrB_Vector_dup (&mngp, f)) ; // allocate the hash table ht_key = LAGraph_Malloc (HASH_SIZE, sizeof (int32_t)) ; ht_val = LAGraph_Malloc (HASH_SIZE, sizeof (int32_t)) ; LG_CHECK (ht_key == NULL || ht_val == NULL, -1, "out of memory") ; //-------------------------------------------------------------------------- // sample phase //-------------------------------------------------------------------------- if (sampling) { //---------------------------------------------------------------------- // export S = G->A in CSR format //---------------------------------------------------------------------- // S is not modified. It is only exported so that its contents can be // read by the parallel loops below. GrB_Type type ; GrB_Index nrows, ncols, nvals ; size_t typesize ; int64_t nonempty ; GrB_Index *Sp, *Sj ; void *Sx ; bool S_jumbled = false ; GrB_Index Sp_size, Sj_size, Sx_size ; bool S_iso = false ; GrB_TRY (GrB_Matrix_nvals (&nvals, S)) ; GrB_TRY (GxB_Matrix_export_CSR (&S, &type, &nrows, &ncols, &Sp, &Sj, &Sx, &Sp_size, &Sj_size, &Sx_size, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,1,0) &S_iso, #elif GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) NULL, #endif &S_jumbled, NULL)) ; GrB_TRY (GxB_Type_size (&typesize, type)) ; G->A = NULL ; //---------------------------------------------------------------------- // allocate space to construct T //---------------------------------------------------------------------- GrB_Index Tp_len = nrows+1, Tp_size = Tp_len*sizeof(GrB_Index); GrB_Index Tj_len = nvals, Tj_size = Tj_len*sizeof(GrB_Index); GrB_Index Tx_len = nvals ; GrB_Index *Tp = LAGraph_Malloc (Tp_len, sizeof (GrB_Index)) ; GrB_Index *Tj = LAGraph_Malloc (Tj_len, sizeof (GrB_Index)) ; #if GxB_IMPLEMENTATION >= GxB_VERSION (5,1,0) GrB_Index Tx_size = typesize ; void *Tx = LAGraph_Calloc (1, typesize) ; // T is iso #else GrB_Index Tx_size = Tx_len*typesize ; void *Tx = LAGraph_Malloc (Tx_len, typesize) ; #endif // todo check out-of-memory conditions //---------------------------------------------------------------------- // allocate workspace //---------------------------------------------------------------------- int32_t *range = LAGraph_Malloc (nthreads + 1, sizeof (int32_t)) ; GrB_Index *count = LAGraph_Malloc (nthreads + 1, sizeof (GrB_Index)) ; // todo check out-of-memory conditions memset (count, 0, sizeof (GrB_Index) * (nthreads + 1)) ; //---------------------------------------------------------------------- // define parallel tasks to construct T //---------------------------------------------------------------------- // thread tid works on rows range[tid]:range[tid+1]-1 of S and T for (int tid = 0 ; tid <= nthreads ; tid++) { range [tid] = (n * tid + nthreads - 1) / nthreads ; } //---------------------------------------------------------------------- // determine the number entries to be constructed in T for each thread //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(static) for (int tid = 0 ; tid < nthreads ; tid++) { for (int32_t i = range [tid] ; i < range [tid+1] ; i++) { int32_t deg = Sp [i + 1] - Sp [i] ; count [tid + 1] += LAGraph_MIN (FASTSV_SAMPLES, deg) ; } } //---------------------------------------------------------------------- // count = cumsum (count) //---------------------------------------------------------------------- for (int tid = 0 ; tid < nthreads ; tid++) { count [tid + 1] += count [tid] ; } //---------------------------------------------------------------------- // construct T //---------------------------------------------------------------------- // T (i,:) consists of the first FASTSV_SAMPLES of S (i,:). // todo: this could be done by GxB_Select, using a new operator. Need // to define a set of GxB_SelectOp operators that would allow for this. // Note that Tx is not modified. Only Tp and Tj are constructed. #pragma omp parallel for num_threads(nthreads) schedule(static) for (int tid = 0 ; tid < nthreads ; tid++) { GrB_Index p = count [tid] ; Tp [range [tid]] = p ; for (int32_t i = range [tid] ; i < range [tid+1] ; i++) { // construct T (i,:) from the first entries in S (i,:) for (int32_t j = 0 ; j < FASTSV_SAMPLES && Sp [i] + j < Sp [i + 1] ; j++) { Tj [p++] = Sj [Sp [i] + j] ; } Tp [i + 1] = p ; } } //---------------------------------------------------------------------- // import the result into the GrB_Matrix T //---------------------------------------------------------------------- // Note that Tx is unmodified. #if GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) // in SuiteSparse:GraphBLAS v5, sizes are in bytes, not entries GrB_Index Tp_siz = Tp_size ; GrB_Index Tj_siz = Tj_size ; GrB_Index Tx_siz = Tx_size ; #else // in SuiteSparse:GraphBLAS v4, sizes are in # of entries, not bytes GrB_Index Tp_siz = Tp_len ; GrB_Index Tj_siz = Tj_len ; GrB_Index Tx_siz = Tx_len ; #endif GrB_Index t_nvals = Tp [nrows] ; GrB_TRY (GxB_Matrix_import_CSR (&T, type, nrows, ncols, &Tp, &Tj, &Tx, Tp_siz, Tj_siz, Tx_siz, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,1,0) true, // T is iso #elif GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) false, #endif S_jumbled, NULL)) ; //---------------------------------------------------------------------- // find the connected components of T //---------------------------------------------------------------------- // todo: this is nearly identical to the final phase below. // Make this a function bool change = true, is_first = true ; while (change) { // hooking & shortcutting GrB_TRY (GrB_mxv (mngp, NULL, GrB_MIN_UINT32, GxB_MIN_SECOND_UINT32, T, gp, NULL)) ; if (!is_first) { LAGraph_TRY (Reduce_assign32 (&f, &mngp, V32, n, nthreads, ht_key, ht_val, &seed, msg)) ; } GrB_TRY (GrB_eWiseAdd (f, NULL, GrB_MIN_UINT32, GrB_MIN_UINT32, mngp, gp, NULL)) ; // calculate grandparent // fixme: NULL parameter is SS:GrB extension GrB_TRY (GrB_Vector_extractTuples (NULL, V32, &n, f)) ; // fixme #pragma omp parallel for num_threads(nthreads2) schedule(static) for (uint32_t i = 0 ; i < n ; i++) { I [i] = (GrB_Index) V32 [i] ; } GrB_TRY (GrB_extract (gp_new, NULL, NULL, f, I, n, NULL)) ; // todo: GrB_Vector_extract should have a variant where the index // list is not given by an array I, but as a GrB_Vector of type // GrB_UINT64 (or which can be typecast to GrB_UINT64). This is a // common issue that arises in other algorithms as well. // Likewise GrB_Matrix_extract, and all forms of GrB_assign. // check termination GrB_TRY (GrB_eWiseMult (mod, NULL, NULL, GrB_NE_UINT32, gp_new, gp, NULL)) ; GrB_TRY (GrB_reduce (&change, NULL, GxB_LOR_BOOL_MONOID, mod, NULL)) ; // swap gp and gp_new GrB_Vector t = gp ; gp = gp_new ; gp_new = t ; is_first = false ; } //---------------------------------------------------------------------- // todo: describe me //---------------------------------------------------------------------- ht_init (ht_key, ht_val) ; ht_sample (V32, n, HASH_SAMPLES, ht_key, ht_val, &seed) ; int32_t key = ht_most_frequent (ht_key, ht_val) ; // todo: what if key is returned as -1? Then T below is invalid. int64_t t_nonempty = -1 ; bool T_jumbled = false, T_iso = true ; // export T GrB_TRY (GxB_Matrix_export_CSR (&T, &type, &nrows, &ncols, &Tp, &Tj, &Tx, &Tp_siz, &Tj_siz, &Tx_siz, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,1,0) &T_iso, #elif GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) NULL, #endif &T_jumbled, NULL)) ; // todo what is this phase doing? It is constructing a matrix T that // depends only on S, key, and V32. T contains a subset of the entries // in S, except that T (i,:) is empty if // The prior content of T is ignored; it is exported from the earlier // phase, only to reuse the allocated space for T. However, T_jumbled // is preserved from the prior matrix T, which doesn't make sense. // This parallel loop is badly load balanced. Each thread operates on // the same number of rows of S, regardless of how many entries appear // in each set of rows. It uses one thread per task, statically // scheduled. #pragma omp parallel for num_threads(nthreads) schedule(static) for (int tid = 0 ; tid < nthreads ; tid++) { GrB_Index ptr = Sp [range [tid]] ; // thread tid scans S (range [tid]:range [tid+1]-1,:), // and constructs T(i,:) for all rows in this range. for (int32_t i = range [tid] ; i < range [tid+1] ; i++) { int32_t pv = V32 [i] ; // what is pv? Tp [i] = ptr ; // start the construction of T(i,:) // T(i,:) is empty if pv == key if (pv != key) { // scan S(i,:) for (GrB_Index p = Sp [i] ; p < Sp [i+1] ; p++) { // get S(i,j) int32_t j = Sj [p] ; if (V32 [j] != key) { // add the entry T(i,j) to T, but skip it if // V32 [j] is equal to key Tj [ptr++] = j ; } } // add the entry T(i,key) if there is room for it in T(i,:) if (ptr - Tp [i] < Sp [i+1] - Sp [i]) { Tj [ptr++] = key ; } } } // count the number of entries inserted into T by this thread? count [tid] = ptr - Tp [range [tid]] ; } // Compact empty space out of Tj not filled in from the above phase. // This is a lot of work and should be done in parallel. GrB_Index offset = 0 ; for (int tid = 0 ; tid < nthreads ; tid++) { memcpy (Tj + offset, Tj + Tp [range [tid]], sizeof (GrB_Index) * count [tid]) ; offset += count [tid] ; count [tid] = offset - count [tid] ; } // Compact empty space out of Tp #pragma omp parallel for num_threads(nthreads) schedule(static) for (int tid = 0 ; tid < nthreads ; tid++) { GrB_Index ptr = Tp [range [tid]] ; for (int32_t i = range [tid] ; i < range [tid+1] ; i++) { Tp [i] -= ptr - count [tid] ; } } // finalize T Tp [n] = offset ; // free workspace LAGraph_Free ((void **) &count) ; LAGraph_Free ((void **) &range) ; // import S (unchanged since last export) GrB_TRY (GxB_Matrix_import_CSR (&S, type, nrows, ncols, &Sp, &Sj, &Sx, Sp_size, Sj_size, Sx_size, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,1,0) S_iso, #elif GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) false, #endif S_jumbled, NULL)) ; // import T for the final phase GrB_TRY (GxB_Matrix_import_CSR (&T, type, nrows, ncols, &Tp, &Tj, &Tx, Tp_siz, Tj_siz, Tx_siz, #if GxB_IMPLEMENTATION >= GxB_VERSION (5,1,0) T_iso, #elif GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) false, #endif T_jumbled, NULL)) ; // restore G->A G->A = S ; } else { // no sampling; the final phase operates on the whole graph T = S ; } //-------------------------------------------------------------------------- // final phase //-------------------------------------------------------------------------- GrB_TRY (GrB_Matrix_nvals (&nnz, T)) ; bool change = true ; while (change && nnz > 0) { // hooking & shortcutting GrB_TRY (GrB_mxv (mngp, NULL, GrB_MIN_UINT32, GxB_MIN_SECOND_UINT32, T, gp, NULL)) ; GrB_TRY (Reduce_assign32 (&f, &mngp, V32, n, nthreads, ht_key, ht_val, &seed, msg)) ; GrB_TRY (GrB_eWiseAdd (f, NULL, GrB_MIN_UINT32, GrB_MIN_UINT32, mngp, gp, NULL)) ; // calculate grandparent // fixme: NULL parameter is SS:GrB extension GrB_TRY (GrB_Vector_extractTuples (NULL, V32, &n, f)) ; // fixme #pragma omp parallel for num_threads(nthreads2) schedule(static) for (uint32_t k = 0 ; k < n ; k++) { I [k] = (GrB_Index) V32 [k] ; } GrB_TRY (GrB_extract (gp_new, NULL, NULL, f, I, n, NULL)) ; // check termination GrB_TRY (GrB_eWiseMult (mod, NULL, NULL, GrB_NE_UINT32, gp_new, gp, NULL)) ; GrB_TRY (GrB_reduce (&change, NULL, GxB_LOR_BOOL_MONOID, mod, NULL)) ; // swap gp and gp_new GrB_Vector t = gp ; gp = gp_new ; gp_new = t ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- (*component) = f ; f = NULL ; if (sampling) { GrB_free (&T) ; } LAGraph_FREE_ALL ; return (0) ; }
geo_normal_3d_omp.h
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ /* * Modified by Xin Wang * Email : ericrussell@zju.edu.cn */ #pragma once #include "geo_normal_3d.h" /** \brief GeoNormalEstimationOMP estimates local surface properties at each 3D point, such as surface normals and * curvatures, in parallel, using the OpenMP standard. * \author Radu Bogdan Rusu * \ingroup features */ template <typename PointInT, typename PointOutT> class GeoNormalEstimationOMP: public GeoNormalEstimation<PointInT, PointOutT> { public: using GeoNormalEstimation<PointInT, PointOutT>::feature_name_; using GeoNormalEstimation<PointInT, PointOutT>::getClassName; using GeoNormalEstimation<PointInT, PointOutT>::indices_; using GeoNormalEstimation<PointInT, PointOutT>::input_; using GeoNormalEstimation<PointInT, PointOutT>::k_; using GeoNormalEstimation<PointInT, PointOutT>::search_parameter_; using GeoNormalEstimation<PointInT, PointOutT>::surface_; using GeoNormalEstimation<PointInT, PointOutT>::getViewPoint; typedef typename GeoNormalEstimation<PointInT, PointOutT>::PointCloudOut PointCloudOut; public: /** \brief Empty constructor. */ GeoNormalEstimationOMP () : threads_ (1) { feature_name_ = "GeoNormalEstimationOMP"; }; /** \brief Initialize the scheduler and set the number of threads to use. * \param nr_threads the number of hardware threads to use (-1 sets the value back to automatic) */ GeoNormalEstimationOMP (unsigned int nr_threads) : threads_ (1) { setNumberOfThreads (nr_threads); feature_name_ = "GeoNormalEstimationOMP"; } /** \brief Initialize the scheduler and set the number of threads to use. * \param nr_threads the number of hardware threads to use (-1 sets the value back to automatic) */ inline void setNumberOfThreads (unsigned int nr_threads) { if (nr_threads == 0) nr_threads = 1; threads_ = nr_threads; } protected: /** \brief The number of threads the scheduler should use. */ unsigned int threads_; private: /** \brief Estimate normals for all points given in <setInputCloud (), setIndices ()> using the surface in * setSearchSurface () and the spatial locator in setSearchMethod () * \param output the resultant point cloud model dataset that contains surface normals and curvatures */ void computeFeature (PointCloudOut &output); /** \brief Make the computeFeature (&Eigen::MatrixXf); inaccessible from outside the class * \param[out] output the output point cloud */ void computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &) {} }; /** \brief GeoNormalEstimationOMP estimates local surface properties at each 3D point, such as surface normals and * curvatures, in parallel, using the OpenMP standard. * \author Radu Bogdan Rusu * \ingroup features */ template <typename PointInT> class GeoNormalEstimationOMP<PointInT, Eigen::MatrixXf>: public GeoNormalEstimationOMP<PointInT, pcl::Normal> { public: using GeoNormalEstimationOMP<PointInT, pcl::Normal>::indices_; using GeoNormalEstimationOMP<PointInT, pcl::Normal>::search_parameter_; using GeoNormalEstimationOMP<PointInT, pcl::Normal>::k_; using GeoNormalEstimationOMP<PointInT, pcl::Normal>::input_; using GeoNormalEstimationOMP<PointInT, pcl::Normal>::surface_; using GeoNormalEstimationOMP<PointInT, pcl::Normal>::getViewPoint; using GeoNormalEstimationOMP<PointInT, pcl::Normal>::threads_; using GeoNormalEstimationOMP<PointInT, pcl::Normal>::compute; /** \brief Default constructor. */ GeoNormalEstimationOMP () : GeoNormalEstimationOMP<PointInT, pcl::Normal> () {} /** \brief Initialize the scheduler and set the number of threads to use. * \param nr_threads the number of hardware threads to use (-1 sets the value back to automatic) */ GeoNormalEstimationOMP (unsigned int nr_threads) : GeoNormalEstimationOMP<PointInT, pcl::Normal> (nr_threads) {} private: /** \brief Estimate normals for all points given in <setInputCloud (), setIndices ()> using the surface in * setSearchSurface () and the spatial locator in setSearchMethod () * \param output the resultant point cloud model dataset that contains surface normals and curvatures */ void computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output); /** \brief Make the compute (&PointCloudOut); inaccessible from outside the class * \param[out] output the output point cloud */ void compute (pcl::PointCloud<pcl::Normal> &) {} }; ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT> void GeoNormalEstimationOMP<PointInT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output) { float vpx, vpy, vpz; getViewPoint (vpx, vpy, vpz); output.is_dense = true; // Resize the output dataset output.points.resize (indices_->size (), 4); // GCC 4.2.x seems to segfault with "internal compiler error" on MacOS X here #if defined(_WIN32) || ((__GNUC__ > 4) && (__GNUC_MINOR__ > 2)) #pragma omp parallel for schedule (dynamic, threads_) #endif // Iterating over the entire index vector for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); if (!isFinite ((*input_)[(*indices_)[idx]]) || this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points (idx, 0) = output.points (idx, 1) = output.points (idx, 2) = output.points (idx, 3) = std::numeric_limits<float>::quiet_NaN (); output.is_dense = false; continue; } // 16-bytes aligned placeholder for the XYZ centroid of a surface patch Eigen::Vector4f xyz_centroid; // Estimate the XYZ centroid compute3DCentroid (*surface_, nn_indices, xyz_centroid); // Placeholder for the 3x3 covariance matrix at each surface patch EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix; // Compute the 3x3 covariance matrix computeCovarianceMatrix (*surface_, nn_indices, xyz_centroid, covariance_matrix); // Get the plane normal and surface curvature pcl::solvePlaneParameters (covariance_matrix, output.points (idx, 0), output.points (idx, 1), output.points (idx, 2), output.points (idx, 3)); flipNormalTowardsViewpoint (input_->points[(*indices_)[idx]], vpx, vpy, vpz, output.points (idx, 0), output.points (idx, 1), output.points (idx, 2)); } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointOutT> void GeoNormalEstimationOMP<PointInT, PointOutT>::computeFeature (PointCloudOut &output) { float vpx, vpy, vpz; getViewPoint (vpx, vpy, vpz); output.is_dense = true; // Iterating over the entire index vector #pragma omp parallel for schedule (dynamic, threads_) for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); if (!isFinite ((*input_)[(*indices_)[idx]]) || this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points[idx].normal[0] = output.points[idx].normal[1] = output.points[idx].normal[2] = output.points[idx].curvature = std::numeric_limits<float>::quiet_NaN (); output.is_dense = false; continue; } // 16-bytes aligned placeholder for the XYZ centroid of a surface patch Eigen::Vector4f xyz_centroid; // Estimate the XYZ centroid compute3DCentroid (*surface_, nn_indices, xyz_centroid); // Placeholder for the 3x3 covariance matrix at each surface patch EIGEN_ALIGN16 Eigen::Matrix3f covariance_matrix; // Compute the 3x3 covariance matrix computeCovarianceMatrix (*surface_, nn_indices, xyz_centroid, covariance_matrix); // Get the plane normal and surface curvature pcl::solvePlaneParameters (covariance_matrix, output.points[idx].normal[0], output.points[idx].normal[1], output.points[idx].normal[2], output.points[idx].curvature); flipNormalTowardsViewpoint (input_->points[(*indices_)[idx]], vpx, vpy, vpz, output.points[idx].normal[0], output.points[idx].normal[1], output.points[idx].normal[2]); } }
cpunetworkexecutor.h
#pragma once #include "cpunetwork.h" namespace NEAT { //Don't need any special qualifiers for CPU #define __net_eval_decl //--- //--- CLASS CpuNetworkExecutor //--- template<typename Evaluator> class CpuNetworkExecutor : public NetworkExecutor<Evaluator> { public: const typename Evaluator::Config *config; CpuNetworkExecutor() { config = NULL; } virtual ~CpuNetworkExecutor() { delete config; } virtual void configure(const typename Evaluator::Config *config_, size_t len) { void *buf = malloc(len); memcpy(buf, config_, len); config = (const typename Evaluator::Config *)buf; } virtual void execute(class Network **nets_, OrganismEvaluation *results, size_t nnets) { CpuNetwork **nets = (CpuNetwork **)nets_; node_size_t nsensors = nets[0]->get_dims().nnodes.sensor; #pragma omp parallel for for(size_t inet = 0; inet < nnets; inet++) { CpuNetwork *net = nets[inet]; Evaluator eval(config); while(eval.next_step()) { if(eval.clear_noninput()) { net->clear_noninput(); } for(node_size_t isensor = 0; isensor < nsensors; isensor++) { net->load_sensor(isensor, eval.get_sensor(isensor)); } net->activate(NACTIVATES_PER_INPUT); eval.evaluate(net->get_outputs()); } results[inet] = eval.result(); } } }; //--- //--- FUNC NetworkExecutor<Evaluator>::create() //--- template<typename Evaluator> inline NetworkExecutor<Evaluator> *NetworkExecutor<Evaluator>::create() { return new CpuNetworkExecutor<Evaluator>(); } }
mixed_tentusscher_myo_epi_2004_S2_11.c
// Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S2_11.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5878770431026,0.00128467644044377,0.780190776060102,0.780031768712007,0.000174269347293292,0.485294334096334,0.00293619530930145,0.999998354577283,1.92718333358183e-08,1.88612615371809e-05,0.999770487779485,1.00715530958520,0.999996174757918,4.37641258651731e-05,0.481810864796698,10.5215306150078,139.090426708925}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={14.4067656911232,0.000251423214660846,0.000138644400006808,0.000171348168255836,0.271363539920663,0.152533735596316,0.167802952974848,4.50982141647208,0.0182925907891570,1.32742805103830,1087.64330176885,0.000521118477931967,0.130358693810526,0.0198787620687159,0.00477679600041959,4.82656795411010e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
declare-variant-12.c
/* { dg-do compile } */ /* { dg-additional-options "-foffload=disable -fdump-tree-gimple" } */ /* { dg-additional-options "-mavx512bw -mavx512vl" { target { i?86-*-* x86_64-*-* } } } */ #pragma omp requires atomic_default_mem_order(seq_cst) void f01 (void); void f02 (void); void f03 (void); #pragma omp declare variant (f01) match (device={isa("avx512f","avx512vl")}) /* 16 */ #pragma omp declare variant (f02) match (implementation={vendor(score(15):gnu)}) #pragma omp declare variant (f03) match (user={condition(score(11):1)}) void f04 (void); void f05 (void); void f06 (void); void f07 (void); #pragma omp declare variant (f05) match (device={isa(avx512f,avx512vl)}) /* 16 */ #pragma omp declare variant (f06) match (implementation={vendor(score(15):gnu)}) #pragma omp declare variant (f07) match (user={condition(score(17):1)}) void f08 (void); void f09 (void); void f10 (void); void f11 (void); void f12 (void); #pragma omp declare variant (f09) match (device={arch(x86_64)},user={condition(score(65):1)}) /* 64+65 */ #pragma omp declare variant (f10) match (implementation={vendor(score(127):"gnu")}) #pragma omp declare variant (f11) match (device={isa(ssse3)}) /* 128 */ #pragma omp declare variant (f12) match (implementation={atomic_default_mem_order(score(126):seq_cst)}) void f13 (void); void f14 (void); void f15 (void); void f16 (void); #pragma omp declare variant (f14) match (construct={teams,parallel,for}) /* 16+8+4 */ #pragma omp declare variant (f15) match (construct={parallel},user={condition(score(19):1)}) /* 8+19 */ #pragma omp declare variant (f16) match (implementation={atomic_default_mem_order(score(27):seq_cst)}) void f17 (void); void f18 (void); void f19 (void); void f20 (void); #pragma omp declare variant (f18) match (construct={teams,parallel,for}) /* 16+8+4 */ #pragma omp declare variant (f19) match (construct={for},user={condition(score(25):1)}) /* 4+25 */ #pragma omp declare variant (f20) match (implementation={atomic_default_mem_order(score(28):seq_cst)}) void f21 (void); void f22 (void); void f23 (void); void f24 (void); #pragma omp declare variant (f22) match (construct={parallel,for}) /* 2+1 */ #pragma omp declare variant (f23) match (construct={for}) /* 0 */ #pragma omp declare variant (f24) match (implementation={atomic_default_mem_order(score(2):seq_cst)}) void f25 (void); void f26 (void); void f27 (void); void f28 (void); #pragma omp declare variant (f26) match (construct={parallel,for}) /* 2+1 */ #pragma omp declare variant (f27) match (construct={for},user={condition(1)}) /* 4 */ #pragma omp declare variant (f28) match (implementation={atomic_default_mem_order(score(3):seq_cst)}) void f29 (void); void test1 (void) { int i, j; #pragma omp parallel for /* 2 constructs in OpenMP context, isa has score 2^4. */ for (i = 0; i < 1; i++) f04 (); /* { dg-final { scan-tree-dump-times "f01 \\\(\\\);" 1 "gimple" { target i?86-*-* x86_64-*-* } } } */ /* { dg-final { scan-tree-dump-times "f02 \\\(\\\);" 1 "gimple" { target { ! { i?86-*-* x86_64-*-* } } } } } */ #pragma omp target teams /* 2 constructs in OpenMP context, isa has score 2^4. */ f08 (); /* { dg-final { scan-tree-dump-times "f07 \\\(\\\);" 1 "gimple" } } */ #pragma omp teams #pragma omp parallel for for (i = 0; i < 1; i++) #pragma omp parallel for /* 5 constructs in OpenMP context, arch is 2^6, isa 2^7. */ for (j = 0; j < 1; j++) { f13 (); /* { dg-final { scan-tree-dump-times "f09 \\\(\\\);" 1 "gimple" { target { { i?86-*-* x86_64-*-* } && lp64 } } } } */ /* { dg-final { scan-tree-dump-times "f11 \\\(\\\);" 1 "gimple" { target { { i?86-*-* x86_64-*-* } && { ! lp64 } } } } } */ /* { dg-final { scan-tree-dump-times "f10 \\\(\\\);" 1 "gimple" { target { ! { i?86-*-* x86_64-*-* } } } } } */ f17 (); /* { dg-final { scan-tree-dump-times "f14 \\\(\\\);" 1 "gimple" } } */ f21 (); /* { dg-final { scan-tree-dump-times "f19 \\\(\\\);" 1 "gimple" } } */ } #pragma omp for for (i = 0; i < 1; i++) #pragma omp parallel for for (j = 0; j < 1; j++) { f25 (); /* { dg-final { scan-tree-dump-times "f22 \\\(\\\);" 1 "gimple" } } */ f29 (); /* { dg-final { scan-tree-dump-times "f27 \\\(\\\);" 1 "gimple" } } */ } }
BIN.h
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <immintrin.h> #include <algorithm> #include "utility.h" /* * Manage the group * prepare hash table for each group */ template <class IT, class NT> class BIN { public: BIN(): total_intprod(0), max_intprod(0), max_nz(0), thread_num(omp_get_max_threads()) { } BIN(IT rows): total_intprod(0), max_intprod(0), max_nz(0), thread_num(omp_get_max_threads()), min_ht_size(8) { assert(rows != 0); row_nz = my_malloc<IT>(rows); rows_offset = my_malloc<IT>(thread_num + 1); bin_id = my_malloc<char>(rows); local_hash_table_id = my_malloc<IT*>(thread_num); local_hash_table_val = my_malloc<NT*>(thread_num); } BIN(IT rows, IT ht_size): total_intprod(0), max_intprod(0), max_nz(0), thread_num(omp_get_max_threads()), min_ht_size(ht_size) { assert(rows != 0); row_nz = my_malloc<IT>(rows); rows_offset = my_malloc<IT>(thread_num + 1); bin_id = my_malloc<char>(rows); local_hash_table_id = my_malloc<IT*>(thread_num); local_hash_table_val = my_malloc<NT*>(thread_num); } ~BIN() { my_free<IT>(row_nz); my_free<IT>(rows_offset); my_free<char>(bin_id); #pragma omp parallel { int tid = omp_get_thread_num(); my_free<IT>(local_hash_table_id[tid]); my_free<NT>(local_hash_table_val[tid]); } my_free<IT*>(local_hash_table_id); my_free<NT*>(local_hash_table_val); } void set_max_bin(const IT *arpt, const IT *acol, const IT *brpt, const IT rows, const IT cols); void set_min_bin(const IT rows, const IT cols); void create_local_hash_table(const IT cols); void set_intprod_num(const IT *arpt, const IT *acol, const IT *brpt, const IT rows); void set_rows_offset(const IT rows); void set_bin_id(const IT rows, const IT cols, const IT min); long long int total_intprod; IT max_intprod; IT max_nz; IT thread_num; IT min_ht_size; IT *row_nz; // the number of flop or non-zero elements of output matrix IT *rows_offset; // offset for row_nz char *bin_id; IT **local_hash_table_id; NT **local_hash_table_val; }; /* Count the number of intermediate products per row (= flop / 2) */ template <class IT, class NT> inline void BIN<IT, NT>::set_intprod_num(const IT *arpt, const IT *acol, const IT *brpt, const IT rows) { #pragma omp parallel { IT each_int_prod = 0; #pragma omp for for (IT i = 0; i < rows; ++i) { IT nz_per_row = 0; for (IT j = arpt[i]; j < arpt[i + 1]; ++j) { nz_per_row += brpt[acol[j] + 1] - brpt[acol[j]]; } row_nz[i] = nz_per_row; each_int_prod += nz_per_row; } #pragma omp atomic total_intprod += each_int_prod; } } /* Get total number of floating operations and average * then, use it for assigning rows to thread as the amount of work is equally distributed */ template <class IT, class NT> inline void BIN<IT, NT>::set_rows_offset(const IT rows) { IT *ps_row_nz = my_malloc<IT>(rows + 1); /* Prefix sum of #intermediate products */ scan(row_nz, ps_row_nz, rows + 1); IT average_intprod = (total_intprod + thread_num - 1) / thread_num; // long long int average_intprod = total_intprod / thread_num; /* Search end point of each range */ rows_offset[0] = 0; #pragma omp parallel { int tid = omp_get_thread_num(); long long int end_itr = (lower_bound(ps_row_nz, ps_row_nz + rows + 1, average_intprod * (tid + 1))) - ps_row_nz; rows_offset[tid + 1] = end_itr; // if (tid == thread_num - 1) rows_offset[tid + 1] = rows; } rows_offset[thread_num] = rows; my_free<IT>(ps_row_nz); } /* * Prepare hash table for each thread_num * once allocate memory space for hash table, the thread reuse it for each row */ template <class IT, class NT> inline void BIN<IT, NT>::create_local_hash_table(const IT cols) { #pragma omp parallel { int tid = omp_get_thread_num(); IT ht_size = 0; /* Get max size of hash table */ for (IT j = rows_offset[tid]; j < rows_offset[tid + 1]; ++j) { if (ht_size < row_nz[j]) ht_size = row_nz[j]; } /* the size of hash table is aligned as 2^n */ if (ht_size > 0) { if (ht_size > cols) ht_size = cols; int k = min_ht_size; while (k < ht_size) { k <<= 1; } ht_size = k; } local_hash_table_id[tid] = my_malloc<IT>(ht_size); local_hash_table_val[tid] = my_malloc<NT>(ht_size); } } /* * Precompute how many entries each row requires for the hash table * the size is 2^bin_id */ template <class IT, class NT> inline void BIN<IT, NT>::set_bin_id(const IT rows, const IT cols, const IT min) { IT i; #pragma omp parallel for for (i = 0; i < rows; ++i) { IT j; IT nz_per_row = row_nz[i]; if (nz_per_row > cols) nz_per_row = cols; if (nz_per_row == 0) { bin_id[i] = 0; } else { j = 0; while (nz_per_row > (min << j)) { j++; } bin_id[i] = j + 1; } } } /* grouping and preparing hash table based on the number of floating operations */ template <class IT, class NT> inline void BIN<IT, NT>::set_max_bin(const IT *arpt, const IT *acol, const IT *brpt, const IT rows, const IT cols) { set_intprod_num(arpt, acol, brpt, rows); set_rows_offset(rows); set_bin_id(rows, cols, min_ht_size); } /* Reset the size of hash table which each row requires */ template <class IT, class NT> inline void BIN<IT, NT>::set_min_bin(const IT rows, const IT cols) { set_bin_id(rows, cols, min_ht_size); }
GB_unaryop__abs_fp64_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_fp64_int64 // op(A') function: GB_tran__abs_fp64_int64 // C type: double // A type: int64_t // cast: double cij = (double) aij // unaryop: cij = fabs (aij) #define GB_ATYPE \ int64_t #define GB_CTYPE \ double // 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 = fabs (x) ; // casting #define GB_CASTING(z, aij) \ double z = (double) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_FP64 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_fp64_int64 ( double *Cx, // Cx and Ax may be aliased 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++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_fp64_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_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
tinyexr.h
/* Copyright (c) 2014 - 2019, Syoyo Fujita and many contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Syoyo Fujita nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // TinyEXR contains some OpenEXR code, which is licensed under ------------ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// // End of OpenEXR license ------------------------------------------------- #ifndef TINYEXR_H_ #define TINYEXR_H_ // // // Do this: // #define TINYEXR_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the // implementation. // // // i.e. it should look like this: // #include ... // #include ... // #include ... // #define TINYEXR_IMPLEMENTATION // #include "tinyexr.h" // // #include <stddef.h> // for size_t #include <stdint.h> // guess stdint.h is available(C99) #ifdef __cplusplus extern "C" { #endif // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib // required if this flas is 0. #ifndef TINYEXR_USE_MINIZ #define TINYEXR_USE_MINIZ (1) #endif // Disable PIZ comporession when applying cpplint. #ifndef TINYEXR_USE_PIZ #define TINYEXR_USE_PIZ (1) #endif #ifndef TINYEXR_USE_ZFP #define TINYEXR_USE_ZFP (0) // TinyEXR extension. // http://computation.llnl.gov/projects/floating-point-compression #endif #define TINYEXR_SUCCESS (0) #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1) #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2) #define TINYEXR_ERROR_INVALID_ARGUMENT (-3) #define TINYEXR_ERROR_INVALID_DATA (-4) #define TINYEXR_ERROR_INVALID_FILE (-5) #define TINYEXR_ERROR_INVALID_PARAMETER (-6) #define TINYEXR_ERROR_CANT_OPEN_FILE (-7) #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8) #define TINYEXR_ERROR_INVALID_HEADER (-9) #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10) #define TINYEXR_ERROR_CANT_WRITE_FILE (-11) #define TINYEXR_ERROR_SERIALZATION_FAILED (-12) // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf } // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2 #define TINYEXR_PIXELTYPE_UINT (0) #define TINYEXR_PIXELTYPE_HALF (1) #define TINYEXR_PIXELTYPE_FLOAT (2) #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024) #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128) #define TINYEXR_COMPRESSIONTYPE_NONE (0) #define TINYEXR_COMPRESSIONTYPE_RLE (1) #define TINYEXR_COMPRESSIONTYPE_ZIPS (2) #define TINYEXR_COMPRESSIONTYPE_ZIP (3) #define TINYEXR_COMPRESSIONTYPE_PIZ (4) #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0) #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1) #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2) #define TINYEXR_TILE_ONE_LEVEL (0) #define TINYEXR_TILE_MIPMAP_LEVELS (1) #define TINYEXR_TILE_RIPMAP_LEVELS (2) #define TINYEXR_TILE_ROUND_DOWN (0) #define TINYEXR_TILE_ROUND_UP (1) typedef struct _EXRVersion { int version; // this must be 2 int tiled; // tile format image int long_name; // long name attribute int non_image; // deep image(EXR 2.0) int multipart; // multi-part(EXR 2.0) } EXRVersion; typedef struct _EXRAttribute { char name[256]; // name and type are up to 255 chars long. char type[256]; unsigned char *value; // uint8_t* int size; int pad0; } EXRAttribute; typedef struct _EXRChannelInfo { char name[256]; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } EXRChannelInfo; typedef struct _EXRTile { int offset_x; int offset_y; int level_x; int level_y; int width; // actual width in a tile. int height; // actual height int a tile. unsigned char **images; // image[channels][pixels] } EXRTile; typedef struct _EXRHeader { float pixel_aspect_ratio; int line_order; int data_window[4]; int display_window[4]; float screen_window_center[2]; float screen_window_width; int chunk_count; // Properties for tiled format(`tiledesc`). int tiled; int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; int long_name; int non_image; int multipart; unsigned int header_len; // Custom attributes(exludes required attributes(e.g. `channels`, // `compression`, etc) int num_custom_attributes; EXRAttribute *custom_attributes; // array of EXRAttribute. size = // `num_custom_attributes`. EXRChannelInfo *channels; // [num_channels] int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for // each channel. This is overwritten with `requested_pixel_types` when // loading. int num_channels; int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*) int *requested_pixel_types; // Filled initially by // ParseEXRHeaderFrom(Meomory|File), then users // can edit it(only valid for HALF pixel type // channel) } EXRHeader; typedef struct _EXRMultiPartHeader { int num_headers; EXRHeader *headers; } EXRMultiPartHeader; typedef struct _EXRImage { EXRTile *tiles; // Tiled pixel data. The application must reconstruct image // from tiles manually. NULL if scanline format. unsigned char **images; // image[channels][pixels]. NULL if tiled format. int width; int height; int num_channels; // Properties for tile format. int num_tiles; } EXRImage; typedef struct _EXRMultiPartImage { int num_images; EXRImage *images; } EXRMultiPartImage; typedef struct _DeepImage { const char **channel_names; float ***image; // image[channels][scanlines][samples] int **offset_table; // offset_table[scanline][offsets] int num_channels; int width; int height; int pad0; } DeepImage; // @deprecated { to be removed. } // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err); // @deprecated { to be removed. } // Simple wrapper API for ParseEXRHeaderFromFile. // checking given file is a EXR file(by just look up header) // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for // others extern int IsEXR(const char *filename); // @deprecated { to be removed. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. // Use ZIP compression by default. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Free's internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Free's internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Free's error message extern void FreeEXRErrorMessage(const char *msg); // Parse EXR version header of a file. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename); // Parse EXR version header from memory-mapped EXR data. extern int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size); // Parse single-part OpenEXR header from a file and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err); // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*` // array. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err); // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*` // array // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Loads single-part OpenEXR image from a file. // Application must setup `ParseEXRHeaderFromFile` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err); // Loads single-part OpenEXR image from a memory. // Application must setup `EXRHeader` with // `ParseEXRHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err); // Loads multi-part OpenEXR image from a file. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this // function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err); // Loads multi-part OpenEXR image from a memory. // Application must setup `EXRHeader*` array with // `ParseEXRMultipartHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err); // Saves multi-channel, single-frame OpenEXR image to a file. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err); // Saves multi-channel, single-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err); // Loads single-frame OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err); // NOT YET IMPLEMENTED: // Saves single-frame OpenEXR deep image. // Returns negative value and may set error string in `err` when there's an // error // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename, // const char **err); // NOT YET IMPLEMENTED: // Loads multi-part OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const // char *filename, // const char **err); // For emscripten. // Loads single-frame OpenEXR image from memory. Assume EXR image contains // RGB(A) channels. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err); #ifdef __cplusplus } #endif #endif // TINYEXR_H_ #ifdef TINYEXR_IMPLEMENTATION #ifndef TINYEXR_IMPLEMENTATION_DEIFNED #define TINYEXR_IMPLEMENTATION_DEIFNED #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> //#include <iostream> // debug #include <limits> #include <string> #include <vector> #if __cplusplus > 199711L // C++11 #include <cstdint> #endif // __cplusplus > 199711L #ifdef _OPENMP #include <omp.h> #endif #if TINYEXR_USE_MINIZ #else // Issue #46. Please include your own zlib-compatible API header before // including `tinyexr.h` //#include "zlib.h" #endif #if TINYEXR_USE_ZFP #include "zfp.h" #endif namespace tinyexr { #if __cplusplus > 199711L // C++11 typedef uint64_t tinyexr_uint64; typedef int64_t tinyexr_int64; #else // Although `long long` is not a standard type pre C++11, assume it is defined // as a compiler's extension. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif typedef unsigned long long tinyexr_uint64; typedef long long tinyexr_int64; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #if TINYEXR_USE_MINIZ namespace miniz { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wundef" #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wmacro-redefined") #pragma clang diagnostic ignored "-Wmacro-redefined" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wtautological-constant-compare") #pragma clang diagnostic ignored "-Wtautological-constant-compare" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED //#include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be // CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on // stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able // to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be // called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive // API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression // API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent // conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom // user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's // which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and // tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc // on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) //#include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient // integer loads and stores from unaligned addresses. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \ 0 // disable to suppress compiler warnings #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are // reasonably fast (and don't involve compiler generated calls to helper // functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() // unless you've modified the MZ_MALLOC macro) to release a block allocated from // the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with // ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with // ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: // items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The // other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best // possible compression (not zlib compatible, and may be very slow), // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been // optimized purely for performance, not ratio. // (This special func. is currently only enabled when // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no // header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input // and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or // MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not // available, and/or there's more output to be written but the output buffer // is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been // written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or // output buffers are empty. (Fill up the input buffer or free up some output // space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of // data that could be generated by deflate(), assuming flush is set to only // MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on // failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of // data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that // controls the window size and whether or not the stream has been wrapped with // a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or // -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the // input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output // buffers are both sized large enough to decompress the entire stream in a // single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside // what's already in the input buffer, and that the output buffer is large // enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or // there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes // have been written. For zlib streams, the adler-32 of the decompressed data // has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is // empty but the inflater needs more input to continue, or if the output // buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when // using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on // failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the // error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used // as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you // use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional // expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is // 0 this function returns the number of bytes needed to fully store the // filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and // modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive // file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient // in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the // archive's filename so it can be reopened for writing. If the file can't be // reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be // growable using the realloc callback (which defaults to realloc unless you've // overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's // user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what // you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record // the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a // forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records // the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no // recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by // the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive // struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be // valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if // mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) // appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the // input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available // beyond the end of the supplied input buffer. If clear, the input buffer // contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large // enough to hold the entire decompressed stream. If clear, the output buffer is // at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the // decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data // to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer // needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block // in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes // written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an // internal 32KB buffer, and a user provided callback function will be called to // flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) \ do { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function // actually needed for decompression. All the other functions are just // high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any // desired higher level decompression API. In the limit case, it can be called // once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly // slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain // the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap // compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before // the deflate data, and the Adler-32 of the source data at the end. Otherwise, // you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even // when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more // efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's // initialization time to the minimum, but the output may vary from run to run // given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per // dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against // the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in // memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be // 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost // pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL // apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be // larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The // above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed // output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper // functions aren't flexible enough. The low-level functions don't make any heap // allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not // dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified // callback. In this case, the user should call the tdefl_compress_buffer() API // for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() // API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, // etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer // as possible, and writing as much compressed data to the specified output // buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a // non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't // defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be // much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, // MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want // the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; //#include <assert.h> //#include <string.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C // implementation that balances processor cache usage against speed": // http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, // size_t size) { // (void)opaque, (void)address, (void)items, (void)size; // return MZ_REALLOC(address, items * size); //} const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty // tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some // uncompressed data left in the output dictionary - // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress // without supplying more input or by setting flush // to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data // when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's // at least 1 more byte on the way. If there's no more room left in the // output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = {{MZ_OK, ""}, {MZ_STREAM_END, "stream end"}, {MZ_NEED_DICT, "need dictionary"}, {MZ_ERRNO, "file error"}, {MZ_STREAM_ERROR, "stream error"}, {MZ_DATA_ERROR, "data error"}, {MZ_MEM_ERROR, "out of memory"}, {MZ_BUF_ERROR, "buf error"}, {MZ_VERSION_ERROR, "version error"}, {MZ_PARAM_ERROR, "parameter error"}}; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif // MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all // compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do { \ for (;;) { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt // to read beyond the input buf, then something is wrong with the input because // the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of // the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) \ do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for (;;) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes // remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode // the next Huffman code (and absolutely no more). It works by trying to fully // decode a // Huffman code by using whatever bits are currently present in the bit buffer. // If this fails, it reads another byte, and tries again until it succeeds or // until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex // than you would initially expect because the zlib API expects the decompressor // to never read // beyond the final byte of the deflate stream. (In other words, when this macro // wants to read another byte from the input, it REALLY needs another byte in // order to fully // decode the next Huffman code.) Handling this properly is particularly // important on raw deflate (non-zlib) streams, which aren't followed by a byte // aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const int s_min_table_sizes[3] = {257, 1, 4}; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer // is large enough to hold the entire output file (in which case it doesn't // matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression // API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285}; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted // values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = \ (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && // MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output // buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS( d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed // block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && \ (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better // register utilization. Intended for applications where raw throughput is // valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to // TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output // buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; // level may actually range from [0,10] (10 is a "hidden" max level, where we // want a bit more compression and it's fine if throughput to fall off a cliff // on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public // domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files // generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was // defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41, 0x54}; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's // where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #error "No arvhive APIs" #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler // alignment and platform endian issues, miniz.c doesn't use structs for any of // this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), // but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename( mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (;;) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end // towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another // heap block to hold the unsorted central dir file record offsets, and // another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some // basic sanity checking on each record, and check for zip64 entries (which // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh( mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, // which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the // low 16-bits, so check for the DOS directory flag and ignore the source OS // ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare( const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input // buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input // buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32( file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback( pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc( pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max // size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir( mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header( pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start // with a forward slash, cannot contain a drive letter, and cannot use // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment( mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an // allocation fails the file remains unmodified. (A good idea if we're doing // an in-place modification.) if ((!mz_zip_array_ensure_room( pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32( uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer( pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back( pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */ // ---------------------- end of miniz ---------------------------------------- #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef _MSC_VER #pragma warning(pop) #endif } // namespace miniz #else // Reuse MINIZ_LITTE_ENDIAN macro #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #endif // TINYEXR_USE_MINIZ // static bool IsBigEndian(void) { // union { // unsigned int i; // char c[4]; // } bint = {0x01020304}; // // return bint.c[0] == 1; //} static void SetErrorMessage(const std::string &msg, const char **err) { if (err) { #ifdef _WIN32 (*err) = _strdup(msg.c_str()); #else (*err) = strdup(msg.c_str()); #endif } } static const int kEXRVersionSize = 8; static void cpy2(unsigned short *dst_val, const unsigned short *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; } static void swap2(unsigned short *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned short tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[1]; dst[1] = src[0]; #endif } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif static void cpy4(int *dst_val, const int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(unsigned int *dst_val, const unsigned int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(float *dst_val, const float *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif static void swap4(unsigned int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } #if 0 static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; } #endif static void swap8(tinyexr::tinyexr_uint64 *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else tinyexr::tinyexr_uint64 tmp = (*val); unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; #endif } // https://gist.github.com/rygorous/2156668 // Reuse MINIZ_LITTLE_ENDIAN flag from miniz. union FP32 { unsigned int u; float f; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif union FP16 { unsigned short u; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic pop #endif static FP32 half_to_float(FP16 h) { static const FP32 magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32 o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o; } static FP16 float_to_half_full(FP32 f) { FP16 o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; return o; } // NOTE: From OpenEXR code // #define IMF_INCREASING_Y 0 // #define IMF_DECREASING_Y 1 // #define IMF_RAMDOM_Y 2 // // #define IMF_NO_COMPRESSION 0 // #define IMF_RLE_COMPRESSION 1 // #define IMF_ZIPS_COMPRESSION 2 // #define IMF_ZIP_COMPRESSION 3 // #define IMF_PIZ_COMPRESSION 4 // #define IMF_PXR24_COMPRESSION 5 // #define IMF_B44_COMPRESSION 6 // #define IMF_B44A_COMPRESSION 7 #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif static const char *ReadString(std::string *s, const char *ptr, size_t len) { // Read untile NULL(\0). const char *p = ptr; const char *q = ptr; while ((size_t(q - ptr) < len) && (*q) != 0) { q++; } if (size_t(q - ptr) >= len) { (*s) = std::string(); return NULL; } (*s) = std::string(p, q); return q + 1; // skip '\0' } static bool ReadAttribute(std::string *name, std::string *type, std::vector<unsigned char> *data, size_t *marker_size, const char *marker, size_t size) { size_t name_len = strnlen(marker, size); if (name_len == size) { // String does not have a terminating character. return false; } *name = std::string(marker, name_len); marker += name_len + 1; size -= name_len + 1; size_t type_len = strnlen(marker, size); if (type_len == size) { return false; } *type = std::string(marker, type_len); marker += type_len + 1; size -= type_len + 1; if (size < sizeof(uint32_t)) { return false; } uint32_t data_len; memcpy(&data_len, marker, sizeof(uint32_t)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len == 0) { if ((*type).compare("string") == 0) { // Accept empty string attribute. marker += sizeof(uint32_t); size -= sizeof(uint32_t); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t); data->resize(1); (*data)[0] = '\0'; return true; } else { return false; } } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen)); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; typedef struct { std::vector<tinyexr::ChannelInfo> channels; std::vector<EXRAttribute> attributes; int data_window[4]; int line_order; int display_window[4]; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; void clear() { channels.clear(); attributes.clear(); data_window[0] = 0; data_window[1] = 0; data_window[2] = 0; data_window[3] = 0; line_order = 0; display_window[0] = 0; display_window[1] = 0; display_window[2] = 0; display_window[3] = 0; screen_window_center[0] = 0.0f; screen_window_center[1] = 0.0f; screen_window_width = 0.0f; pixel_aspect_ratio = 0.0f; chunk_count = 0; // Tiled format tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; } } HeaderInfo; static bool ReadChannelInfo(std::vector<ChannelInfo> &channels, const std::vector<unsigned char> &data) { const char *p = reinterpret_cast<const char *>(&data.at(0)); for (;;) { if ((*p) == 0) { break; } ChannelInfo info; tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char *>(data.data())); if (data_len < 0) { return false; } p = ReadString(&info.name, p, size_t(data_len)); if ((p == NULL) && (info.name.empty())) { // Buffer overrun. Issue #51. return false; } const unsigned char *data_end = reinterpret_cast<const unsigned char *>(p) + 16; if (data_end >= (data.data() + data.size())) { return false; } memcpy(&info.pixel_type, p, sizeof(int)); p += 4; info.p_linear = static_cast<unsigned char>(p[0]); // uchar p += 1 + 3; // reserved: uchar[3] memcpy(&info.x_sampling, p, sizeof(int)); // int p += 4; memcpy(&info.y_sampling, p, sizeof(int)); // int p += 4; tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling)); channels.push_back(info); } return true; } static void WriteChannelInfo(std::vector<unsigned char> &data, const std::vector<ChannelInfo> &channels) { size_t sz = 0; // Calculate total size. for (size_t c = 0; c < channels.size(); c++) { sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0 sz += 16; // 4 * int } data.resize(sz + 1); unsigned char *p = &data.at(0); for (size_t c = 0; c < channels.size(); c++) { memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str())); p += strlen(channels[c].name.c_str()); (*p) = '\0'; p++; int pixel_type = channels[c].pixel_type; int x_sampling = channels[c].x_sampling; int y_sampling = channels[c].y_sampling; tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling)); memcpy(p, &pixel_type, sizeof(int)); p += sizeof(int); (*p) = channels[c].p_linear; p += 4; memcpy(p, &x_sampling, sizeof(int)); p += sizeof(int); memcpy(p, &y_sampling, sizeof(int)); p += sizeof(int); } (*p) = '\0'; } static void CompressZip(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } #if TINYEXR_USE_MINIZ // // Compress the data using miniz // miniz::mz_ulong outSize = miniz::mz_compressBound(src_size); int ret = miniz::mz_compress( dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)), src_size); assert(ret == miniz::MZ_OK); (void)ret; compressedSize = outSize; #else uLong outSize = compressBound(static_cast<uLong>(src_size)); int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)), src_size); assert(ret == Z_OK); compressedSize = outSize; #endif // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressZip(unsigned char *dst, unsigned long *uncompressed_size /* inout */, const unsigned char *src, unsigned long src_size) { if ((*uncompressed_size) == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } std::vector<unsigned char> tmpBuf(*uncompressed_size); #if TINYEXR_USE_MINIZ int ret = miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (miniz::MZ_OK != ret) { return false; } #else int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (Z_OK != ret) { return false; } #endif // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size); while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + (*uncompressed_size); for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } // RLE code from OpenEXR -------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif const int MIN_RUN_LENGTH = 3; const int MAX_RUN_LENGTH = 127; // // Compress an array of bytes, using run-length encoding, // and return the length of the compressed data. // static int rleCompress(int inLength, const char in[], signed char out[]) { const char *inEnd = in + inLength; const char *runStart = in; const char *runEnd = in + 1; signed char *outWrite = out; while (runStart < inEnd) { while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) { ++runEnd; } if (runEnd - runStart >= MIN_RUN_LENGTH) { // // Compressable run // *outWrite++ = static_cast<char>(runEnd - runStart) - 1; *outWrite++ = *(reinterpret_cast<const signed char *>(runStart)); runStart = runEnd; } else { // // Uncompressable run // while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) { ++runEnd; } *outWrite++ = static_cast<char>(runStart - runEnd); while (runStart < runEnd) { *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++)); } } ++runEnd; } return static_cast<int>(outWrite - out); } // // Uncompress an array of bytes compressed with rleCompress(). // Returns the length of the oncompressed data, or 0 if the // length of the uncompressed data would be more than maxLength. // static int rleUncompress(int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -(static_cast<int>(*in++)); inLength -= count + 1; // Fixes #116: Add bounds check to in buffer. if ((0 > (maxLength -= count)) || (inLength < 0)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } // Workaround for issue #112. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`. if (src_size <= 2) { return false; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); if (ret != static_cast<int>(uncompressed_size)) { return false; } // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierachical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- int len : 8; // code length 0 int lit : 24; // lit p size int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // std::vector<int> hlink(HUF_ENCSIZE); std::vector<long long *> fHeap(HUF_ENCSIZE); *im = 0; while (!frq[*im]) (*im)++; int nf = 0; for (int i = *im; i < HUF_ENCSIZE; i++) { hlink[i] = i; if (frq[i]) { fHeap[nf] = &frq[i]; nf++; *iM = i; } } // // Add a pseudo-symbol, with a frequency count of 1, to frq; // adjust the fHeap and hlink array accordingly. Function // hufEncode() uses the pseudo-symbol for run-length encoding. // (*iM)++; frq[*iM] = 1; fHeap[nf] = &frq[*iM]; nf++; // // Build an array, scode, such that scode[i] contains the number // of bits assigned to symbol i. Conceptually this is done by // constructing a tree whose leaves are the symbols with non-zero // frequency: // // Make a heap that contains all symbols with a non-zero frequency, // with the least frequent symbol on top. // // Repeat until only one symbol is left on the heap: // // Take the two least frequent symbols off the top of the heap. // Create a new node that has first two nodes as children, and // whose frequency is the sum of the frequencies of the first // two nodes. Put the new node back into the heap. // // The last node left on the heap is the root of the tree. For each // leaf node, the distance between the root and the leaf is the length // of the code for the corresponding symbol. // // The loop below doesn't actually build the tree; instead we compute // the distances of the leaves from the root on the fly. When a new // node is added to the heap, then that node's descendants are linked // into a single linear list that starts at the new node, and the code // lengths of the descendants (that is, their distance from the root // of the tree) are incremented by one. // std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); std::vector<long long> scode(HUF_ENCSIZE); memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE); while (nf > 1) { // // Find the indices, mm and m, of the two smallest non-zero frq // values in fHeap, add the smallest frq to the second-smallest // frq, and remove the smallest frq value from fHeap. // int mm = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); --nf; int m = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); frq[m] += frq[mm]; std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); // // The entries in scode are linked into lists with the // entries in hlink serving as "next" pointers and with // the end of a list marked by hlink[j] == j. // // Traverse the lists that start at scode[m] and scode[mm]. // For each element visited, increment the length of the // corresponding code by one bit. (If we visit scode[j] // during the traversal, then the code for symbol j becomes // one bit longer.) // // Merge the lists that start at scode[m] and scode[mm] // into a single list that starts at scode[m]. // // // Add a bit to all codes in the first list. // for (int j = m;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) { // // Merge the two lists. // hlink[j] = mm; break; } } // // Add a bit to all codes in the second list // for (int j = mm;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) break; } } // // Build a canonical Huffman code table, replacing the code // lengths in scode with (code, code length) pairs. Copy the // code table from scode into frq. // hufCanonicalCodeTable(scode.data()); memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE); } // // Pack an encoding table: // - only code lengths, not actual codes, are stored // - runs of zeroes are compressed as follows: // // unpacked packed // -------------------------------- // 1 zero 0 (6 bits) // 2 zeroes 59 // 3 zeroes 60 // 4 zeroes 61 // 5 zeroes 62 // n zeroes (6 or more) 63 n-6 (6 + 8 bits) // const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN; static void hufPackEncTable( const long long *hcode, // i : encoding table [HUF_ENCSIZE] int im, // i : min hcode index int iM, // i : max hcode index char **pcode) // o: ptr to packed table (updated) { char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { int l = hufLength(hcode[im]); if (l == 0) { int zerun = 1; while ((im < iM) && (zerun < LONGEST_LONG_RUN)) { if (hufLength(hcode[im + 1]) > 0) break; im++; zerun++; } if (zerun >= 2) { if (zerun >= SHORTEST_LONG_RUN) { outputBits(6, LONG_ZEROCODE_RUN, c, lc, p); outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p); } else { outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p); } continue; } } outputBits(6, l, c, lc, p); } if (lc > 0) *p++ = (unsigned char)(c << (8 - lc)); *pcode = p; } // // Unpack an encoding table packed by hufPackEncTable(): // static bool hufUnpackEncTable( const char **pcode, // io: ptr to packed table (updated) int ni, // i : input size (in bytes) int im, // i : min hcode index int iM, // i : max hcode index long long *hcode) // o: encoding table [HUF_ENCSIZE] { memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE); const char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { if (p - *pcode >= ni) { return false; } long long l = hcode[im] = getBits(6, c, lc, p); // code length if (l == (long long)LONG_ZEROCODE_RUN) { if (p - *pcode > ni) { return false; } int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } else if (l >= (long long)SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } } *pcode = const_cast<char *>(p); hufCanonicalCodeTable(hcode); return true; } // // DECODING TABLE BUILDING // // // Clear a newly allocated decoding table so that it contains only zeroes. // static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller) // decoding table [HUF_DECSIZE] { for (int i = 0; i < HUF_DECSIZE; i++) { hdecod[i].len = 0; hdecod[i].lit = 0; hdecod[i].p = NULL; } // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE); } // // Build a decoding hash table based on the encoding table hcode: // - short codes (<= HUF_DECBITS) are resolved with a single table access; // - long code entry allocations are not optimized, because long codes are // unfrequent; // - decoding tables are used by hufDecode(); // static bool hufBuildDecTable(const long long *hcode, // i : encoding table int im, // i : min index in hcode int iM, // i : max index in hcode HufDec *hdecod) // o: (allocated by caller) // decoding table [HUF_DECSIZE] { // // Init hashtable & loop on all codes. // Assumes that hufClearDecTable(hdecod) has already been called. // for (; im <= iM; im++) { long long c = hufCode(hcode[im]); int l = hufLength(hcode[im]); if (c >> l) { // // Error: c is supposed to be an l-bit code, // but c contains a value that is greater // than the largest l-bit number. // // invalidTableEntry(); return false; } if (l > HUF_DECBITS) { // // Long code: add a secondary entry // HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) { // // Error: a short code has already // been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->lit++; if (pl->p) { int *p = pl->p; pl->p = new int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new int[1]; } pl->p[pl->lit - 1] = im; } else if (l) { // // Short code: init all primary entries // HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) { // // Error: a short code or a long code has // already been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->len = l; pl->lit = im; } } } return true; } // // Free the long code entries of a decoding table built by hufBuildDecTable() // static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table { for (int i = 0; i < HUF_DECSIZE; i++) { if (hdecod[i].p) { delete[] hdecod[i].p; hdecod[i].p = 0; } } } // // ENCODING // inline void outputCode(long long code, long long &c, int &lc, char *&out) { outputBits(hufLength(code), hufCode(code), c, lc, out); } inline void sendCode(long long sCode, int runCount, long long runCode, long long &c, int &lc, char *&out) { // // Output a run of runCount instances of the symbol sCount. // Output the symbols explicitly, or if that is shorter, output // the sCode symbol once followed by a runCode symbol and runCount // expressed as an 8-bit number. // if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) { outputCode(sCode, c, lc, out); outputCode(runCode, c, lc, out); outputBits(8, runCount, c, lc, out); } else { while (runCount-- >= 0) outputCode(sCode, c, lc, out); } } // // Encode (compress) ni values based on the Huffman encoding table hcode: // static int hufEncode // return: output size (in bits) (const long long *hcode, // i : encoding table const unsigned short *in, // i : uncompressed input buffer const int ni, // i : input buffer size (in bytes) int rlc, // i : rl code char *out) // o: compressed output buffer { char *outStart = out; long long c = 0; // bits not yet written to out int lc = 0; // number of valid bits in c (LSB) int s = in[0]; int cs = 0; // // Loop on input values // for (int i = 1; i < ni; i++) { // // Count same values or send code // if (s == in[i] && cs < 255) { cs++; } else { sendCode(hcode[s], cs, hcode[rlc], c, lc, out); cs = 0; } s = in[i]; } // // Send remaining code // sendCode(hcode[s], cs, hcode[rlc], c, lc, out); if (lc) *out = (c << (8 - lc)) & 0xff; return (out - outStart) * 8 + lc; } // // DECODING // // // In order to force the compiler to inline them, // getChar() and getCode() are implemented as macros // instead of "inline" functions. // #define getChar(c, lc, in) \ { \ c = (c << 8) | *(unsigned char *)(in++); \ lc += 8; \ } #if 0 #define getCode(po, rlc, c, lc, in, out, ob, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ /* TinyEXR issue 78 */ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } #else static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in, const char *in_end, unsigned short *&out, const unsigned short *ob, const unsigned short *oe) { (void)ob; if (po == rlc) { if (lc < 8) { /* TinyEXR issue 78 */ if ((in + 1) >= in_end) { return false; } getChar(c, lc, in); } lc -= 8; unsigned char cs = (c >> lc); if (out + cs > oe) return false; // Bounds check for safety // Issue 100. if ((out - 1) < ob) return false; unsigned short s = out[-1]; while (cs-- > 0) *out++ = s; } else if (out < oe) { *out++ = po; } else { return false; } return true; } #endif // // Decode (uncompress) ni bits based on encoding & decoding tables: // static bool hufDecode(const long long *hcode, // i : encoding table const HufDec *hdecod, // i : decoding table const char *in, // i : compressed input buffer int ni, // i : input size (in bits) int rlc, // i : run-length code int no, // i : expected output size (in bytes) unsigned short *out) // o: uncompressed output buffer { long long c = 0; int lc = 0; unsigned short *outb = out; // begin unsigned short *oe = out + no; // end const char *ie = in + (ni + 7) / 8; // input byte size // // Loop on input bytes // while (in < ie) { getChar(c, lc, in); // // Access decoding table // while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { // // Get short code // lc -= pl.len; // std::cout << "lit = " << pl.lit << std::endl; // std::cout << "rlc = " << rlc << std::endl; // std::cout << "c = " << c << std::endl; // std::cout << "lc = " << lc << std::endl; // std::cout << "in = " << in << std::endl; // std::cout << "out = " << out << std::endl; // std::cout << "oe = " << oe << std::endl; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { if (!pl.p) { return false; } // invalidCode(); // wrong code // // Search long code // int j; for (j = 0; j < pl.lit; j++) { int l = hufLength(hcode[pl.p[j]]); while (lc < l && in < ie) // get more bits getChar(c, lc, in); if (lc >= l) { if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & (((long long)(1) << l) - 1))) { // // Found : get long code // lc -= l; if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) { return false; } break; } } } if (j == pl.lit) { return false; // invalidCode(); // Not found } } } } // // Get remaining (short) codes // int i = (8 - ni) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(std::vector<long long> &freq, const unsigned short data[/*n*/], int n) { for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0; for (int i = 0; i < n; ++i) ++freq[data[i]]; } static void writeUInt(char buf[4], unsigned int i) { unsigned char *b = (unsigned char *)buf; b[0] = i; b[1] = i >> 8; b[2] = i >> 16; b[3] = i >> 24; } static unsigned int readUInt(const char buf[4]) { const unsigned char *b = (const unsigned char *)buf; return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000); } // // EXTERNAL INTERFACE // static int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) { if (nRaw == 0) return 0; std::vector<long long> freq(HUF_ENCSIZE); countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq.data(), &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq.data(), im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart); int data_length = (nBits + 7) / 8; writeUInt(compressed, im); writeUInt(compressed + 4, iM); writeUInt(compressed + 8, tableLength); writeUInt(compressed + 12, nBits); writeUInt(compressed + 16, 0); // room for future extensions return dataStart + data_length - compressed; } static bool hufUncompress(const char compressed[], int nCompressed, std::vector<unsigned short> *raw) { if (nCompressed == 0) { if (raw->size() != 0) return false; return false; } int im = readUInt(compressed); int iM = readUInt(compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt(compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false; const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // // if (FastHufDecoder::enabled() && nBits > 128) //{ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); //} // else { std::vector<long long> freq(HUF_ENCSIZE); std::vector<HufDec> hdec(HUF_DECSIZE); hufClearDecTable(&hdec.at(0)); hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM, &freq.at(0)); { if (nBits > 8 * (nCompressed - (ptr - compressed))) { return false; } hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0)); hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(), raw->data()); } // catch (...) //{ // hufFreeDecTable (hdec); // throw; //} hufFreeDecTable(&hdec.at(0)); } return true; } // // Functions to compress the range of values in the pixel data // const int USHORT_RANGE = (1 << 16); const int BITMAP_SIZE = (USHORT_RANGE >> 3); static void bitmapFromData(const unsigned short data[/*nData*/], int nData, unsigned char bitmap[BITMAP_SIZE], unsigned short &minNonZero, unsigned short &maxNonZero) { for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0; for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); bitmap[0] &= ~1; // zero is not explicitly stored in // the bitmap; we assume that the // data always contain zeroes minNonZero = BITMAP_SIZE - 1; maxNonZero = 0; for (int i = 0; i < BITMAP_SIZE; ++i) { if (bitmap[i]) { if (minNonZero > i) minNonZero = i; if (maxNonZero < i) maxNonZero = i; } } } static unsigned short forwardLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[i] = k++; else lut[i] = 0; } return k - 1; // maximum value stored in lut[], } // i.e. number of ones in bitmap minus 1 static unsigned short reverseLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; } int n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; // maximum k where lut[k] is non-zero, } // i.e. number of ones in bitmap minus 1 static void applyLut(const unsigned short lut[USHORT_RANGE], unsigned short data[/*nData*/], int nData) { for (int i = 0; i < nData; ++i) data[i] = lut[data[i]]; } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _MSC_VER #pragma warning(pop) #endif static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize, const unsigned char *inPtr, size_t inSize, const std::vector<ChannelInfo> &channelInfo, int data_width, int num_lines) { std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif // Assume `inSize` is multiple of 2 or 4. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short)); std::vector<PIZChannelData> channelData(channelInfo.size()); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t c = 0; c < channelData.size(); c++) { PIZChannelData &cd = channelData[c]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = data_width; cd.ny = num_lines; // cd.ys = c.channel().ySampling; size_t pixelSize = sizeof(int); // UINT and FLOAT if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } cd.size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += cd.nx * cd.ny * cd.size; } const unsigned char *ptr = inPtr; for (int y = 0; y < num_lines; ++y) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(cd.end, ptr, n * sizeof(unsigned short)); ptr += n * sizeof(unsigned short); cd.end += n; } } bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), bitmap.data(), minNonZero, maxNonZero); std::vector<unsigned short> lut(USHORT_RANGE); unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data()); applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size())); // // Store range compression info in _outBuffer // char *buf = reinterpret_cast<char *>(outPtr); memcpy(buf, &minNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); memcpy(buf, &maxNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); if (minNonZero <= maxNonZero) { memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero), maxNonZero - minNonZero + 1); buf += maxNonZero - minNonZero + 1; } // // Apply wavelet encoding // for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Apply Huffman encoding; append the result to _outBuffer // // length header(4byte), then huff data. Initialize length header with zero, // then later fill it by `length`. char *lengthPtr = buf; int zero = 0; memcpy(buf, &zero, sizeof(int)); buf += sizeof(int); int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf); memcpy(lengthPtr, &length, sizeof(int)); (*outSize) = static_cast<unsigned int>( (reinterpret_cast<unsigned char *>(buf) - outPtr) + static_cast<unsigned int>(length)); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if ((*outSize) >= inSize) { (*outSize) = static_cast<unsigned int>(inSize); memcpy(outPtr, inPtr, inSize); } return true; } static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize, size_t inLen, int num_channels, const EXRChannelInfo *channels, int data_width, int num_lines) { if (inLen == tmpBufSize) { // Data is not compressed(Issue 40). memcpy(outPtr, inPtr, inLen); return true; } std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif memset(bitmap.data(), 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr)); // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2)); ptr += 4; if (maxNonZero >= BITMAP_SIZE) { return false; } if (minNonZero <= maxNonZero) { memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr, maxNonZero - minNonZero + 1); ptr += maxNonZero - minNonZero + 1; } std::vector<unsigned short> lut(USHORT_RANGE); memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data()); // // Huffman decoding // int length; // length = *(reinterpret_cast<const int *>(ptr)); tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); if (size_t((ptr - inPtr) + length) > inLen) { return false; } std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer); // // Wavelet decoding // std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels)); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) { const EXRChannelInfo &chan = channels[i]; size_t pixelSize = sizeof(int); // UINT and FLOAT if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } channelData[i].start = tmpBufferEnd; channelData[i].end = channelData[i].start; channelData[i].nx = data_width; channelData[i].ny = num_lines; // channelData[i].ys = 1; channelData[i].size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size; } for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); for (int y = 0; y < num_lines; y++) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short))); outPtr += n * sizeof(unsigned short); cd.end += n; } } return true; } #endif // TINYEXR_USE_PIZ #if TINYEXR_USE_ZFP struct ZFPCompressionParam { double rate; int precision; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0f; } }; bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) && (attributes[i].size == 1)) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; } } if (!foundType) { return false; } if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) { param->rate = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) { param->rate = *(reinterpret_cast<int *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) { param->tolerance = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else { assert(0); } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, int num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = dst_width * dst_num_lines * num_channels; if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); } zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((dst_width % 4) == 0); assert((dst_num_lines % 4) == 0); if ((dst_width & 3U) || (dst_num_lines & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, dst_width, dst_num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); std::vector<unsigned char> buf(buf_size); memcpy(&buf.at(0), src, src_size); bitstream *stream = stream_open(&buf.at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); size_t image_size = dst_width * dst_num_lines; for (int c = 0; c < num_channels; c++) { // decompress 4x4 pixel block. for (int y = 0; y < dst_num_lines; y += 4) { for (int x = 0; x < dst_width; x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * dst_width + (x + i))] = fblock[j * 4 + i]; } } } } } zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); return true; } // Assume pixel format is FLOAT for all channels. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize, const float *inPtr, int width, int num_lines, int num_channels, const ZFPCompressionParam &param) { zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((width % 4) == 0); assert((num_lines % 4) == 0); if ((width & 3U) || (num_lines & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, width, num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); outBuf->resize(buf_size); bitstream *stream = stream_open(&outBuf->at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_field_free(field); size_t image_size = width * num_lines; for (int c = 0; c < num_channels; c++) { // compress 4x4 pixel block. for (int y = 0; y < num_lines; y += 4) { for (int x = 0; x < width; x += 4) { float fblock[16]; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * width + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = zfp_stream_compressed_size(zfp); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // // TODO(syoyo): Refactor function arguments. static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) { // Invalid input #90 return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); if (!ret) { return false; } // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; // hf.u = line_ptr[u]; // use `cpy` to avoid unaligned memory access when compiler's // optimization is on. tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>(&outBuf.at( v * pixel_data_size * static_cast<size_t>(x_stride) + channel_offset_list[c] * static_cast<size_t>(x_stride))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); } } #else assert(0 && "PIZ is enabled in this build"); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For ZIP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); if (dstLen == 0) { return false; } if (!tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; if (!FindZFPCompressionParam(&zfp_compression_param, attributes, num_attributes)) { assert(0); return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = outBuf.size(); assert(dstLen > 0); tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width, num_lines, num_channels, data_ptr, static_cast<unsigned long>(data_len), zfp_compression_param); // For ZFP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } #else (void)attributes; (void)num_attributes; (void)num_channels; assert(0); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { for (size_t c = 0; c < num_channels; c++) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); outLine[u] = hf.u; } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // address may not be aliged. use byte-wise copy for safety.#76 // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); tinyexr::FP32 f32 = half_to_float(hf); outLine[u] = f32.f; } } else { assert(0); return false; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { const float *line_ptr = reinterpret_cast<const float *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { if (reinterpret_cast<const unsigned char *>(line_ptr + u) >= (data_ptr + data_len)) { // Corrupsed data? return false; } unsigned int val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } } } } return true; } static void DecodeTiledPixelData( unsigned char **out_images, int *width, int *height, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int data_width, int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x, int tile_size_y, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { assert(tile_offset_x * tile_size_x < data_width); assert(tile_offset_y * tile_size_y < data_height); // Compute actual image size in a tile. if ((tile_offset_x + 1) * tile_size_x >= data_width) { (*width) = data_width - (tile_offset_x * tile_size_x); } else { (*width) = tile_size_x; } if ((tile_offset_y + 1) * tile_size_y >= data_height) { (*height) = data_height - (tile_offset_y * tile_size_y); } else { (*height) = tile_size_y; } // Image size = tile size. DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len, compression_type, line_order, (*width), tile_size_y, /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0, (*height), pixel_data_size, num_attributes, attributes, num_channels, channels, channel_offset_list); } static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { // ??? return false; } } return true; } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; info->data_window[0] = 0; info->data_window[1] = 0; info->data_window[2] = 0; info->data_window[3] = 0; info->line_order = 0; // @fixme info->display_window[0] = 0; info->display_window[1] = 0; info->display_window[2] = 0; info->display_window[3] = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { if (err) { (*err) += "Insufficient data size for attributes.\n"; } return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { if (err) { (*err) += "Failed to read attribute.\n"; } return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (version->tiled && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) += "Failed to parse channel info.\n"; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) += "# of channels is zero.\n"; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window[0], &data.at(0), sizeof(int)); memcpy(&info->data_window[1], &data.at(4), sizeof(int)); memcpy(&info->data_window[2], &data.at(8), sizeof(int)); memcpy(&info->data_window[3], &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3])); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window[0], &data.at(0), sizeof(int)); memcpy(&info->display_window[1], &data.at(4), sizeof(int)); memcpy(&info->display_window[2], &data.at(8), sizeof(int)); memcpy(&info->display_window[3], &data.at(12), sizeof(int)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[3])); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio)); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[1])); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_width)); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count)); } } else { // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) { EXRAttribute attrib; #ifdef _MSC_VER strncpy_s(attrib.name, attr_name.c_str(), 255); strncpy_s(attrib.type, attr_type.c_str(), 255); #else strncpy(attrib.name, attr_name.c_str(), 255); strncpy(attrib.type, attr_type.c_str(), 255); #endif attrib.name[255] = '\0'; attrib.type[255] = '\0'; attrib.size = static_cast<int>(data.size()); attrib.value = static_cast<unsigned char *>(malloc(data.size())); memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0), data.size()); info->attributes.push_back(attrib); } } } // Check if required attributes exist { std::stringstream ss_err; if (!has_compression) { ss_err << "\"compression\" attribute not found in the header." << std::endl; } if (!has_channels) { ss_err << "\"channels\" attribute not found in the header." << std::endl; } if (!has_line_order) { ss_err << "\"lineOrder\" attribute not found in the header." << std::endl; } if (!has_display_window) { ss_err << "\"displayWindow\" attribute not found in the header." << std::endl; } if (!has_data_window) { ss_err << "\"dataWindow\" attribute not found in the header or invalid." << std::endl; } if (!has_pixel_aspect_ratio) { ss_err << "\"pixelAspectRatio\" attribute not found in the header." << std::endl; } if (!has_screen_window_width) { ss_err << "\"screenWindowWidth\" attribute not found in the header." << std::endl; } if (!has_screen_window_center) { ss_err << "\"screenWindowCenter\" attribute not found in the header." << std::endl; } if (!(ss_err.str().empty())) { if (err) { (*err) += ss_err.str(); } return TINYEXR_ERROR_INVALID_HEADER; } } info->header_len = static_cast<unsigned int>(orig_size - size); return TINYEXR_SUCCESS; } // C++ HeaderInfo to C EXRHeader conversion. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) { exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio; exr_header->screen_window_center[0] = info.screen_window_center[0]; exr_header->screen_window_center[1] = info.screen_window_center[1]; exr_header->screen_window_width = info.screen_window_width; exr_header->chunk_count = info.chunk_count; exr_header->display_window[0] = info.display_window[0]; exr_header->display_window[1] = info.display_window[1]; exr_header->display_window[2] = info.display_window[2]; exr_header->display_window[3] = info.display_window[3]; exr_header->data_window[0] = info.data_window[0]; exr_header->data_window[1] = info.data_window[1]; exr_header->data_window[2] = info.data_window[2]; exr_header->data_window[3] = info.data_window[3]; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; exr_header->tile_size_x = info.tile_size_x; exr_header->tile_size_y = info.tile_size_y; exr_header->tile_level_mode = info.tile_level_mode; exr_header->tile_rounding_mode = info.tile_rounding_mode; exr_header->num_channels = static_cast<int>(info.channels.size()); exr_header->channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { #ifdef _MSC_VER strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #else strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #endif // manually add '\0' for safety. exr_header->channels[c].name[255] = '\0'; exr_header->channels[c].pixel_type = info.channels[c].pixel_type; exr_header->channels[c].p_linear = info.channels[c].p_linear; exr_header->channels[c].x_sampling = info.channels[c].x_sampling; exr_header->channels[c].y_sampling = info.channels[c].y_sampling; } exr_header->pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->pixel_types[c] = info.channels[c].pixel_type; } // Initially fill with values of `pixel_types` exr_header->requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->requested_pixel_types[c] = info.channels[c].pixel_type; } exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); if (exr_header->num_custom_attributes > 0) { // TODO(syoyo): Report warning when # of attributes exceeds // `TINYEXR_MAX_CUSTOM_ATTRIBUTES` if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) { exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES; } exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc( sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes))); for (size_t i = 0; i < info.attributes.size(); i++) { memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name, 256); memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type, 256); exr_header->custom_attributes[i].size = info.attributes[i].size; // Just copy poiner exr_header->custom_attributes[i].value = info.attributes[i].value; } } else { exr_header->custom_attributes = NULL; } exr_header->header_len = info.header_len; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const std::vector<tinyexr::tinyexr_uint64> &offsets, const unsigned char *head, const size_t size, std::string *err) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; if ((data_width < 0) || (data_height < 0)) { if (err) { std::stringstream ss; ss << "Invalid data width or data height: " << data_width << ", " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if ((data_width > threshold) || (data_height > threshold)) { if (err) { std::stringstream ss; ss << "data_with or data_height too large. data_width: " << data_width << ", " << "data_height = " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } } size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { // value check if (exr_header->tile_size_x < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_size_y < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) { // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, exr_header->tile_size_x, exr_header->tile_size_y); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { if (err) { (*err) += "Insufficient data size.\n"; } return TINYEXR_ERROR_INVALID_DATA; } size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[3])); // @todo{ LoD } if (tile_coordinates[2] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } if (tile_coordinates[3] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len < 4 || size_t(data_len) > data_size) { if (err) { (*err) += "Insufficient data length.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; exr_image->num_tiles = static_cast<int>(num_tiles); } } else { // scanline format // Don't allow too large image(256GB * pixel_data_size or more). Workaround // for #104. size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels); const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false; if ((total_data_len == 0) || total_data_len_overflown ) { if (err) { std::stringstream ss; ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #ifdef _OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (size_t(data_len) > data_size) { invalid_data = true; } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) { // Too large value. Assume this is invalid // 2**20 = 1048576 = heuristic value. invalid_data = true; } else if (data_len == 0) { // TODO(syoyo): May be ok to raise the threshold for example `data_len // < 4` invalid_data = true; } else { // line_no may be negative. int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window[3] + 1)); int num_lines = end_line_no - line_no; if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y // overflow check tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window[1]); if (lno > std::numeric_limits<int>::max()) { line_no = -1; // invalid } else if (lno < -std::numeric_limits<int>::max()) { line_no = -1; // invalid } else { line_no -= exr_header->data_window[1]; } if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } } // omp parallel } if (invalid_data) { if (err) { std::stringstream ss; (*err) += "Invalid data found when decoding pixels.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0]; if (data_width >= std::numeric_limits<int>::max()) { // Issue 63 tinyexr::SetErrorMessage("Invalid data width value", err); return TINYEXR_ERROR_INVALID_DATA; } data_width++; int data_height = exr_header->data_window[3] - exr_header->data_window[1]; if (data_height >= std::numeric_limits<int>::max()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } data_height++; if ((data_width < 0) || (data_height < 0)) { tinyexr::SetErrorMessage("data width or data height is negative.", err); return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if (data_width > threshold) { tinyexr::SetErrorMessage("data width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (data_height > threshold) { tinyexr::SetErrorMessage("data height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } // Read offset tables. size_t num_blocks = 0; if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); } else if (exr_header->tiled) { // @todo { LoD } size_t num_x_tiles = static_cast<size_t>(data_width) / static_cast<size_t>(exr_header->tile_size_x); if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) < static_cast<size_t>(data_width)) { num_x_tiles++; } size_t num_y_tiles = static_cast<size_t>(data_height) / static_cast<size_t>(exr_header->tile_size_y); if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) < static_cast<size_t>(data_height)) { num_y_tiles++; } num_blocks = num_x_tiles * num_y_tiles; } else { num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks); if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) { num_blocks++; } } std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks); for (size_t y = 0; y < num_blocks; y++) { tinyexr::tinyexr_uint64 offset; // Issue #81 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offsets[y] = offset; } // If line offsets are invalid, we try to reconstruct it. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details. for (size_t y = 0; y < num_blocks; y++) { if (offsets[y] <= 0) { // TODO(syoyo) Report as warning? // if (err) { // stringstream ss; // ss << "Incomplete lineOffsets." << std::endl; // (*err) += ss.str(); //} bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size); if (ret) { // OK break; } else { tinyexr::SetErrorMessage( "Cannot reconstruct lineOffset table in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } } } { std::string e; int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } // release memory(if exists) if ((exr_header->num_channels > 0) && exr_image && exr_image->images) { for (size_t c = 0; c < size_t(exr_header->num_channels); c++) { if (exr_image->images[c]) { free(exr_image->images[c]); exr_image->images[c] = NULL; } } free(exr_image->images); exr_image->images = NULL; } } return ret; } } } // namespace tinyexr int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { if (out_rgba == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); InitEXRImage(&exr_image); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Invalid EXR header.", err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } { int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } if (exr_header.num_channels == 1) { // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // Assume RGB(A) if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int IsEXR(const char *filename) { EXRVersion exr_version; int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { return TINYEXR_ERROR_INVALID_HEADER; } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_header == NULL) { tinyexr::SetErrorMessage( "Invalid argument. `memory` or `exr_header` argument is null in " "ParseEXRHeaderFromMemory()", err); // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Insufficient header/data size.\n", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; tinyexr::HeaderInfo info; info.clear(); std::string err_str; int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err && !err_str.empty()) { tinyexr::SetErrorMessage(err_str, err); } } ConvertHeader(exr_header, info); // transfoer `tiled` from version. exr_header->tiled = version->tiled; return ret; } int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err) { if (out_rgba == NULL || memory == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); int ret = ParseEXRVersionFromMemory(&exr_version, memory, size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Failed to parse EXR version", err); return ret; } ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } InitEXRImage(&exr_image); ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } // TODO(syoyo): Refactor removing same code as used in LoadEXR(). if (exr_header.num_channels == 1) { // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // TODO(syoyo): Support non RGBA image. if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize < 16) { tinyexr::SetErrorMessage("File size too short " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize, err); } int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *memory, const size_t size, const char **err) { if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } const unsigned char *head = memory; const unsigned char *marker = reinterpret_cast<const unsigned char *>( memory + exr_header->header_len + 8); // +8 for magic number + version header. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size, err); } size_t SaveEXRImageToMemory(const EXRImage *exr_image, const EXRHeader *exr_header, unsigned char **memory_out, const char **err) { if (exr_image == NULL || memory_out == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return 0; } #endif #if TINYEXR_USE_ZFP for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) { if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) { tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression", err); return 0; } } #endif std::vector<unsigned char> memory; // Header { const char header[] = {0x76, 0x2f, 0x31, 0x01}; memory.insert(memory.end(), header, header + 4); } // Version, scanline. { char marker[] = {2, 0, 0, 0}; /* @todo if (exr_header->tiled) { marker[1] |= 0x2; } if (exr_header->long_name) { marker[1] |= 0x4; } if (exr_header->non_image) { marker[1] |= 0x8; } if (exr_header->multipart) { marker[1] |= 0x10; } */ memory.insert(memory.end(), marker, marker + 4); } int num_scanlines = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } // Write attributes. std::vector<tinyexr::ChannelInfo> channels; { std::vector<unsigned char> data; for (int c = 0; c < exr_header->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_header->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_header->channels[c].name); channels.push_back(info); } tinyexr::WriteChannelInfo(data, channels); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_header->compression_type; tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp)); tinyexr::WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char *>(&comp), 1); } { int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3])); tinyexr::WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); tinyexr::WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { float aspectRatio = 1.0f; tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio)); tinyexr::WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float)); } { float center[2] = {0.0f, 0.0f}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1])); tinyexr::WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float)); } { float w = static_cast<float>(exr_image->width); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char *>(&w), sizeof(float)); } // Custom attributes if (exr_header->num_custom_attributes > 0) { for (int i = 0; i < exr_header->num_custom_attributes; i++) { tinyexr::WriteAttributeToMemory( &memory, exr_header->custom_attributes[i].name, exr_header->custom_attributes[i].type, reinterpret_cast<const unsigned char *>( exr_header->custom_attributes[i].value), exr_header->custom_attributes[i].size); } } { // end of header unsigned char e = 0; memory.push_back(e); } int num_blocks = exr_image->height / num_scanlines; if (num_blocks * num_scanlines < exr_image->height) { num_blocks++; } std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks)); size_t headerSize = memory.size(); tinyexr::tinyexr_uint64 offset = headerSize + static_cast<size_t>(num_blocks) * sizeof( tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable) std::vector<std::vector<unsigned char> > data_list( static_cast<size_t>(num_blocks)); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } } #endif // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { size_t ii = static_cast<size_t>(i); int start_y = num_scanlines * i; int endY = (std::min)(num_scanlines * (i + 1), exr_image->height); int h = endY - start_y; std::vector<unsigned char> buf( static_cast<size_t>(exr_image->width * h * pixel_data_size)); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f)); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned short val = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap2(&val); // line_ptr[x] = val; tinyexr::cpy2(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP16 h16; h16 = float_to_half_full(f32); tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u)); // line_ptr[x] = h16.u; tinyexr::cpy2(line_ptr + x, &(h16.u)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { float val = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned int val = reinterpret_cast<unsigned int **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } } if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(buf.size()); memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), buf.begin(), buf.begin() + data_len); } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #if TINYEXR_USE_MINIZ std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound( static_cast<unsigned long>(buf.size()))); #else std::vector<unsigned char> block( compressBound(static_cast<uLong>(buf.size()))); #endif tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressZip(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // (buf.size() * 3) / 2 would be enough. std::vector<unsigned char> block((buf.size() * 3) / 2); tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressRle(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ unsigned int bufLen = 8192 + static_cast<unsigned int>( 2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, exr_image->width, h); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), exr_image->width, h, exr_header->num_channels, zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); } } // omp parallel for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size(); } size_t totalSize = static_cast<size_t>(offset); { memory.insert( memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)), reinterpret_cast<unsigned char *>(&offsets.at(0)) + sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks)); } if (memory.size() == 0) { tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char *>(malloc(totalSize)); memcpy((*memory_out), &memory.at(0), memory.size()); unsigned char *memory_ptr = *memory_out + memory.size(); for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size()); memory_ptr += data_list[i].size(); } return totalSize; // OK } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "wb"); #else FILE *fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _MSC_VER FILE *fp = NULL; errno_t errcode = fopen_s(&fp, filename, "rb"); if ((0 != errcode) || (!fp)) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #endif size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize == 0) { fclose(fp); tinyexr::SetErrorMessage("File size is zero : " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); (void)ret; } fclose(fp); const char *head = &buf[0]; const char *marker = &buf[0]; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { tinyexr::SetErrorMessage("Invalid magic number", err); return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } // Version, scanline. { // ver 2.0, scanline, deep bit on(0x800) // must be [2, 0, 0, 0] if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) { tinyexr::SetErrorMessage("Unsupported version or scanline", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } marker += 4; } int dx = -1; int dy = -1; int dw = -1; int dh = -1; int num_scanline_blocks = 1; // 16 for ZIP compression. int compression_type = -1; int num_channels = -1; std::vector<tinyexr::ChannelInfo> channels; // Read attributes size_t size = filesize - tinyexr::kEXRVersionSize; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { marker++; size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { std::stringstream ss; ss << "Failed to parse attribute\n"; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (attr_name.compare("compression") == 0) { compression_type = data[0]; if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) { std::stringstream ss; ss << "Unsupported compression type : " << compression_type; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!tinyexr::ReadChannelInfo(channels, data)) { tinyexr::SetErrorMessage("Failed to parse channel info", err); return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { tinyexr::SetErrorMessage("Invalid channels format", err); return TINYEXR_ERROR_INVALID_DATA; } } else if (attr_name.compare("dataWindow") == 0) { memcpy(&dx, &data.at(0), sizeof(int)); memcpy(&dy, &data.at(4), sizeof(int)); memcpy(&dw, &data.at(8), sizeof(int)); memcpy(&dh, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh)); } else if (attr_name.compare("displayWindow") == 0) { int x; int y; int w; int h; memcpy(&x, &data.at(0), sizeof(int)); memcpy(&y, &data.at(4), sizeof(int)); memcpy(&w, &data.at(8), sizeof(int)); memcpy(&h, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&h)); } } assert(dx >= 0); assert(dy >= 0); assert(dw >= 0); assert(dh >= 0); assert(num_channels >= 1); int data_width = dw - dx + 1; int data_height = dh - dy + 1; std::vector<float> image( static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA // Read offset tables. int num_blocks = data_height / num_scanline_blocks; if (num_blocks * num_scanline_blocks < data_height) { num_blocks++; } std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks)); for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { tinyexr::tinyexr_int64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset)); marker += sizeof(tinyexr::tinyexr_int64); // = 8 offsets[y] = offset; } #if TINYEXR_USE_PIZ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) { #else if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #endif // OK } else { tinyexr::SetErrorMessage("Unsupported compression format", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } deep_image->image = static_cast<float ***>( malloc(sizeof(float **) * static_cast<size_t>(num_channels))); for (int c = 0; c < num_channels; c++) { deep_image->image[c] = static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { } } deep_image->offset_table = static_cast<int **>( malloc(sizeof(int *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { deep_image->offset_table[y] = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(data_width))); } for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y]); // int: y coordinate // int64: packed size of pixel offset table // int64: packed size of sample data // int64: unpacked size of sample data // compressed pixel offset table // compressed sample data int line_no; tinyexr::tinyexr_int64 packedOffsetTableSize; tinyexr::tinyexr_int64 packedSampleDataSize; tinyexr::tinyexr_int64 unpackedSampleDataSize; memcpy(&line_no, data_ptr, sizeof(int)); memcpy(&packedOffsetTableSize, data_ptr + 4, sizeof(tinyexr::tinyexr_int64)); memcpy(&packedSampleDataSize, data_ptr + 12, sizeof(tinyexr::tinyexr_int64)); memcpy(&unpackedSampleDataSize, data_ptr + 20, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize)); std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width)); // decode pixel offset table. { unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int)); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)), &dstLen, data_ptr + 28, static_cast<unsigned long>(packedOffsetTableSize))) { return false; } assert(dstLen == pixelOffsetTable.size() * sizeof(int)); for (size_t i = 0; i < static_cast<size_t>(data_width); i++) { deep_image->offset_table[y][i] = pixelOffsetTable[i]; } } std::vector<unsigned char> sample_data( static_cast<size_t>(unpackedSampleDataSize)); // decode sample data. { unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize); if (dstLen) { if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen, data_ptr + 28 + packedOffsetTableSize, static_cast<unsigned long>(packedSampleDataSize))) { return false; } assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize)); } } // decode sample int sampleSize = -1; std::vector<int> channel_offset_list(static_cast<size_t>(num_channels)); { int channel_offset = 0; for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) { channel_offset_list[i] = channel_offset; if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT channel_offset += 4; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half channel_offset += 2; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float channel_offset += 4; } else { assert(0); } } sampleSize = channel_offset; } assert(sampleSize >= 2); assert(static_cast<size_t>( pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize) == sample_data.size()); int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize; // // Alloc memory // // // pixel data is stored as image[channels][pixel_samples] // { tinyexr::tinyexr_uint64 data_offset = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { deep_image->image[c][y] = static_cast<float *>( malloc(sizeof(float) * static_cast<size_t>(samples_per_line))); if (channels[c].pixel_type == 0) { // UINT for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { unsigned int ui; unsigned int *src_ptr = reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); tinyexr::cpy4(&ui, src_ptr); deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme } data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line); } else if (channels[c].pixel_type == 1) { // half for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { tinyexr::FP16 f16; const unsigned short *src_ptr = reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::cpy2(&(f16.u), src_ptr); tinyexr::FP32 f32 = half_to_float(f16); deep_image->image[c][y][x] = f32.f; } data_offset += sizeof(short) * static_cast<size_t>(samples_per_line); } else { // float for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { float f; const float *src_ptr = reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); tinyexr::cpy4(&f, src_ptr); deep_image->image[c][y][x] = f; } data_offset += sizeof(float) * static_cast<size_t>(samples_per_line); } } } } // y deep_image->width = data_width; deep_image->height = data_height; deep_image->channel_names = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(num_channels))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { #ifdef _WIN32 deep_image->channel_names[c] = _strdup(channels[c].name.c_str()); #else deep_image->channel_names[c] = strdup(channels[c].name.c_str()); #endif } deep_image->num_channels = num_channels; return TINYEXR_SUCCESS; } void InitEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return; } exr_image->width = 0; exr_image->height = 0; exr_image->num_channels = 0; exr_image->images = NULL; exr_image->tiles = NULL; exr_image->num_tiles = 0; } void FreeEXRErrorMessage(const char *msg) { if (msg) { free(reinterpret_cast<void *>(const_cast<char *>(msg))); } return; } void InitEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return; } memset(exr_header, 0, sizeof(EXRHeader)); } int FreeEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->channels) { free(exr_header->channels); } if (exr_header->pixel_types) { free(exr_header->pixel_types); } if (exr_header->requested_pixel_types) { free(exr_header->requested_pixel_types); } for (int i = 0; i < exr_header->num_custom_attributes; i++) { if (exr_header->custom_attributes[i].value) { free(exr_header->custom_attributes[i].value); } } if (exr_header->custom_attributes) { free(exr_header->custom_attributes); } return TINYEXR_SUCCESS; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->images && exr_image->images[i]) { free(exr_image->images[i]); } } if (exr_image->images) { free(exr_image->images); } if (exr_image->tiles) { for (int tid = 0; tid < exr_image->num_tiles; tid++) { for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) { free(exr_image->tiles[tid].images[i]); } } if (exr_image->tiles[tid].images) { free(exr_image->tiles[tid].images); } } free(exr_image->tiles); } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_header == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("fread() error on " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize, err); } int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) { // Invalid argument tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Data size too short", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; std::vector<tinyexr::HeaderInfo> infos; for (;;) { tinyexr::HeaderInfo info; info.clear(); std::string err_str; bool empty_header = false; int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage(err_str, err); return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { tinyexr::SetErrorMessage( "`chunkCount' attribute is not found in the header.", err); return TINYEXR_ERROR_INVALID_DATA; } infos.push_back(info); // move to next header. marker += info.header_len; size -= info.header_len; } // allocate memory for EXRHeader and create array of EXRHeader pointers. (*exr_headers) = static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size())); for (size_t i = 0; i < infos.size(); i++) { EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader))); ConvertHeader(exr_header, infos[i]); // transfoer `tiled` from version. exr_header->tiled = exr_version->tiled; (*exr_headers)[i] = exr_header; } (*num_headers) = static_cast<int>(infos.size()); return TINYEXR_SUCCESS; } int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromFile()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRMultipartHeaderFromMemory( exr_headers, num_headers, exr_version, &buf.at(0), filesize, err); } int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size) { if (version == NULL || memory == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } version->tiled = false; version->long_name = false; version->non_image = false; version->multipart = false; // Parse version header. { // must be 2 if (marker[0] != 2) { return TINYEXR_ERROR_INVALID_EXR_VERSION; } if (version == NULL) { return TINYEXR_SUCCESS; // May OK } version->version = 2; if (marker[1] & 0x2) { // 9th bit version->tiled = true; } if (marker[1] & 0x4) { // 10th bit version->long_name = true; } if (marker[1] & 0x8) { // 11th bit version->non_image = true; // (deep image) } if (marker[1] & 0x10) { // 12th bit version->multipart = true; } } return TINYEXR_SUCCESS; } int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) { if (filename == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t file_size; // Compute size fseek(fp, 0, SEEK_END); file_size = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (file_size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } unsigned char buf[tinyexr::kEXRVersionSize]; size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp); fclose(fp); if (ret != tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize); } int LoadEXRMultipartImageFromMemory(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromMemory()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } // compute total header size. size_t total_header_size = 0; for (unsigned int i = 0; i < num_parts; i++) { if (exr_headers[i]->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } total_header_size += exr_headers[i]->header_len; } const char *marker = reinterpret_cast<const char *>( memory + total_header_size + 4 + 4); // +8 for magic number and version header. marker += 1; // Skip empty header. // NOTE 1: // In multipart image, There is 'part number' before chunk data. // 4 byte : part number // 4+ : chunk // // NOTE 2: // EXR spec says 'part number' is 'unsigned long' but actually this is // 'unsigned int(4 bytes)' in OpenEXR implementation... // http://www.openexr.com/openexrfilelayout.pdf // Load chunk offset table. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list; for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> offset_table( static_cast<size_t>(exr_headers[i]->chunk_count)); for (size_t c = 0; c < offset_table.size(); c++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, 8); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_table[c] = offset + 4; // +4 to skip 'part number' marker += 8; } chunk_offset_table_list.push_back(offset_table); } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> &offset_table = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (size_t c = 0; c < offset_table.size(); c++) { const unsigned char *part_number_addr = memory + offset_table[c] - 4; // -4 to move to 'part number' field. unsigned int part_no; memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4 tinyexr::swap4(&part_no); if (part_no != i) { tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } } std::string e; int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table, memory, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return ret; } } return TINYEXR_SUCCESS; } int LoadEXRMultipartImageFromFile(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts, &buf.at(0), filesize, err); } int SaveEXR(const float *data, int width, int height, int components, const int save_as_fp16, const char *outfilename, const char **err) { if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } int ret = SaveEXRImageToFile(&image, &header, outfilename, err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEIFNED #endif // TINYEXR_IMPLEMENTATION
turtle_json_number_parsing.c
#include "turtle_json.h" //Place to put various # parsing algorithms ... //https://github.com/miloyip/rapidjson/blob/03a73910498d784a3a9429202a90d2fb67be910b/include/rapidjson/reader.h#L1118 //=================== Number parsing errors =========================== // We observed only a '-' #define NO_NUMBER_ERROR 0 //# We observed a period with no fraction ... #define NO_FRACTION_ERROR 1 #define NO_EXPONENT_ERROR 2 void string_to_double_v2(double *value_p, char *p, int i, int *error_p, int *error_value) { double value = 0; double fraction = 0; double exponent_value; bool negate; if (*p == '-'){ ++p; negate = true; }else{ negate = false; } //Verify at least one number - technically we could put this in the '-' //case above, as otherwise this was triggered based on observing a # if (isdigit(*p)){ value = 10*value + (double)(*p-'0'); ++p; }else{ *error_p = i+1; *error_value = NO_NUMBER_ERROR; return; } while (isdigit(*p)){ value = 10*value + (double)(*p-'0'); ++p; } //Fraction //-------------------------------------------------------- if (*p == '.') { ++p; if (isdigit(*p)){ value = value + 0.1*((*p) - '0'); fraction = 0.01; ++p; }else{ *error_p = i+1; *error_value = NO_FRACTION_ERROR; return; } while (isdigit(*p)){ value = value + fraction * ((*p) - '0'); fraction *= 0.1; ++p; } } if (negate){ value = -1*value; } //Exponent //---------------------- if (*p == 'E' || *p == 'e') { ++p; switch (*p){ case '-': ++p; negate = true; break; case '+': ++p; default: negate = false; } exponent_value = 0; while (isdigit(*p)) { exponent_value = 10*exponent_value + (double)((*p) - '0'); ++p; } if (negate){ exponent_value = -exponent_value; } value *= pow(10.0, exponent_value); } //TODO: We could still have: //(so '.' , '-', 'e', and 'E') (numbers would just be parsed) //- note, with no e or E, we only need to check '.' and '-' *value_p = value; } void string_to_double_v3(double *value_p, char *p, int i, int *error_p, int *error_value) { double value = 0; double fraction = 0; double exponent_value = 0; bool negate = (*p == '-'); if (negate){ ++p; } //Integer parsing //------------------------------------------------------- if (isdigit(*p)){ value = 10*value + (double)(*p-'0'); ++p; }else{ *error_p = i+1; *error_value = NO_NUMBER_ERROR; return; } while (isdigit(*p)){ value = 10*value + (double)(*p-'0'); ++p; } //Fraction //-------------------------------------------------------- if (*p == '.') { ++p; if (isdigit(*p)){ value = value + 0.1 * ((*p) - '0'); fraction = 0.01; ++p; }else{ *error_p = i+1; *error_value = NO_FRACTION_ERROR; return; } while (isdigit(*p)){ value = value + fraction * ((*p) - '0'); fraction *= 0.1; ++p; } } if (negate){ value = -1*value; } //Exponent //---------------------- if (*p == 'E' || *p == 'e') { ++p; if (*p == '-'){ negate = true; ++p; if (isdigit(*p)){ exponent_value = 10*exponent_value + (double)((*p) - '0'); ++p; }else{ *error_p = i+1; *error_value = NO_EXPONENT_ERROR; } }else if (isdigit(*p)){ negate = false; }else if (*p == '+'){ negate = false; ++p; if (isdigit(*p)){ exponent_value = 10*exponent_value + (double)((*p) - '0'); ++p; }else{ *error_p = i+1; *error_value = NO_EXPONENT_ERROR; } }else{ *error_p = i+1; *error_value = NO_EXPONENT_ERROR; return; } while (isdigit(*p)) { exponent_value = 10*exponent_value + (double)((*p) - '0'); ++p; } if (negate){ exponent_value = -exponent_value; } value *= pow(10.0, exponent_value); //Test ('.' , '-', 'e', and 'E') }else{ //Test '.' , '-', } *value_p = value; } //========================================================================= //========================================================================= void parse_numbers(unsigned char *js,mxArray *plhs[]) { // // numeric_p - this array starts as a set of pointers // to locations in the json_string that contain numbers. // For example, we might have numeric_p[0] point to the following // location: // // {"my_value": 1.2345} // ^ // // Some of these pointers may be null, indicating that a "null" // JSON value occurred at that index in the array. // // I am currently assuming that a pointer is 64 bits, which means // that I recycle the memory to store the array of doubles //--------------------------------------------------------------------- //The same memory is used twice. A value currently points to the start //of a number to parse. After parsing the same location holds a double. mxArray *temp = mxGetFieldByNumber(plhs[0],0,E_numeric_p); int n_numbers = mxGetN(temp); if (n_numbers == 0){ return; } //mexPrintf("%d %d\n",n_numbers,N_NUMBERS_FOR_PARALLEL); //Casting for input handling unsigned char **numeric_p = (unsigned char **)mxGetData(temp); //Casting for output handling (recycling of memory) double *numeric_p_double = (double *)mxGetData(temp); //--------------------------------------------------------------------- int error_locations[MAX_OPENMP_THREADS]; int error_values[MAX_OPENMP_THREADS]; int n_threads = 1; if (n_numbers >= N_NUMBERS_FOR_PARALLEL){ n_threads = omp_get_max_threads(); } if (n_threads > MAX_OPENMP_THREADS){ mexErrMsgIdAndTxt("turtle_json:max_thread_errors","stack allocation exceeded by # of threads"); } const double MX_NAN = mxGetNaN(); //https://stackoverflow.com/questions/39116329/enable-disable-openmp-locally-at-runtime #pragma omp parallel if (n_numbers >= N_NUMBERS_FOR_PARALLEL) { int tid = omp_get_thread_num(); int error_location; int error_value = 0; #pragma omp for for (int i = 0; i < n_numbers; i++){ //NaN values occupy an index space in numeric_p but have a null //value to indicate that they are NaN if (numeric_p[i]){ string_to_double_v3(&numeric_p_double[i],numeric_p[i],i,&error_location,&error_value); }else{ numeric_p_double[i] = MX_NAN; } } error_locations[tid] = error_location; error_values[tid] = error_value; } //Error processing //-------------------------------------- for (int i = 0; i < n_threads; i++){ if (error_values[i]){ int error_index = error_locations[i]; //Note that we hold onto the pointer in cases of an error //It is not overidden with a double unsigned char *first_char_of_bad_number = numeric_p[error_index]; //TODO: This is a bit confusing since this pointer doesn't //move but the other one does ... //TODO: Ideally we would pass these error messages into //a handler that would handle the last bit of formatting //and also provide context in the string //We would need the string length ... switch (error_values[i]) { case NO_NUMBER_ERROR: //TODO: This needs to be clarified ... mexErrMsgIdAndTxt("turtle_json:no_numeric_component", \ "No integer component was found for a number (#%d in the file, at position %d)", \ error_index+1,first_char_of_bad_number-js+1); break; case NO_FRACTION_ERROR: mexErrMsgIdAndTxt("turtle_json:no_fractional_numbers", "A number had a period, followed by no numbers (#%d in the file, at position %d)",error_index+1,first_char_of_bad_number-js+1); case NO_EXPONENT_ERROR: mexErrMsgIdAndTxt("turtle_json:no_exponent_numbers", "A number had an 'e' or 'E', followed by no numbers (#%d in the file, at position %d)",error_index+1,first_char_of_bad_number-js+1); default: mexErrMsgIdAndTxt("turtle_json:internal_code_error", "Internal code error"); } } } } //===================== END OF NUMBER PARSING ==========================
GB_unop__identity_uint32_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_uint32_fp64 // op(A') function: GB_unop_tran__identity_uint32_fp64 // C type: uint32_t // A type: double // cast: uint32_t cij = GB_cast_to_uint32_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ double #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint32_t z = GB_cast_to_uint32_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = GB_cast_to_uint32_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint32_fp64 ( uint32_t *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (double), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; uint32_t z = GB_cast_to_uint32_t ((double) (aij)) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; uint32_t z = GB_cast_to_uint32_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_uint32_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
c-typeck.c
/* Build expressions with type checking for C compiler. Copyright (C) 1987-2020 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ /* This file is part of the C front end. It contains routines to build C expressions given their operands, including computing the types of the result, C-specific error checks, and some optimization. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "memmodel.h" #include "target.h" #include "function.h" #include "bitmap.h" #include "c-tree.h" #include "gimple-expr.h" #include "predict.h" #include "stor-layout.h" #include "trans-mem.h" #include "varasm.h" #include "stmt.h" #include "langhooks.h" #include "c-lang.h" #include "intl.h" #include "tree-iterator.h" #include "gimplify.h" #include "tree-inline.h" #include "omp-general.h" #include "c-family/c-objc.h" #include "c-family/c-ubsan.h" #include "gomp-constants.h" #include "spellcheck-tree.h" #include "gcc-rich-location.h" #include "stringpool.h" #include "attribs.h" #include "asan.h" /* Possible cases of implicit bad conversions. Used to select diagnostic messages in convert_for_assignment. */ enum impl_conv { ic_argpass, ic_assign, ic_init, ic_return }; /* The level of nesting inside "__alignof__". */ int in_alignof; /* The level of nesting inside "sizeof". */ int in_sizeof; /* The level of nesting inside "typeof". */ int in_typeof; /* True when parsing OpenMP loop expressions. */ bool c_in_omp_for; /* The argument of last parsed sizeof expression, only to be tested if expr.original_code == SIZEOF_EXPR. */ tree c_last_sizeof_arg; location_t c_last_sizeof_loc; /* Nonzero if we might need to print a "missing braces around initializer" message within this initializer. */ static int found_missing_braces; static int require_constant_value; static int require_constant_elements; static bool null_pointer_constant_p (const_tree); static tree qualify_type (tree, tree); static int tagged_types_tu_compatible_p (const_tree, const_tree, bool *, bool *); static int comp_target_types (location_t, tree, tree); static int function_types_compatible_p (const_tree, const_tree, bool *, bool *); static int type_lists_compatible_p (const_tree, const_tree, bool *, bool *); static tree lookup_field (tree, tree); static int convert_arguments (location_t, vec<location_t>, tree, vec<tree, va_gc> *, vec<tree, va_gc> *, tree, tree); static tree pointer_diff (location_t, tree, tree, tree *); static tree convert_for_assignment (location_t, location_t, tree, tree, tree, enum impl_conv, bool, tree, tree, int, int = 0); static tree valid_compound_expr_initializer (tree, tree); static void push_string (const char *); static void push_member_name (tree); static int spelling_length (void); static char *print_spelling (char *); static void warning_init (location_t, int, const char *); static tree digest_init (location_t, tree, tree, tree, bool, bool, int); static void output_init_element (location_t, tree, tree, bool, tree, tree, bool, bool, struct obstack *); static void output_pending_init_elements (int, struct obstack *); static bool set_designator (location_t, bool, struct obstack *); static void push_range_stack (tree, struct obstack *); static void add_pending_init (location_t, tree, tree, tree, bool, struct obstack *); static void set_nonincremental_init (struct obstack *); static void set_nonincremental_init_from_string (tree, struct obstack *); static tree find_init_member (tree, struct obstack *); static void readonly_warning (tree, enum lvalue_use); static int lvalue_or_else (location_t, const_tree, enum lvalue_use); static void record_maybe_used_decl (tree); static int comptypes_internal (const_tree, const_tree, bool *, bool *); /* Return true if EXP is a null pointer constant, false otherwise. */ static bool null_pointer_constant_p (const_tree expr) { /* This should really operate on c_expr structures, but they aren't yet available everywhere required. */ tree type = TREE_TYPE (expr); return (TREE_CODE (expr) == INTEGER_CST && !TREE_OVERFLOW (expr) && integer_zerop (expr) && (INTEGRAL_TYPE_P (type) || (TREE_CODE (type) == POINTER_TYPE && VOID_TYPE_P (TREE_TYPE (type)) && TYPE_QUALS (TREE_TYPE (type)) == TYPE_UNQUALIFIED))); } /* EXPR may appear in an unevaluated part of an integer constant expression, but not in an evaluated part. Wrap it in a C_MAYBE_CONST_EXPR, or mark it with TREE_OVERFLOW if it is just an INTEGER_CST and we cannot create a C_MAYBE_CONST_EXPR. */ static tree note_integer_operands (tree expr) { tree ret; if (TREE_CODE (expr) == INTEGER_CST && in_late_binary_op) { ret = copy_node (expr); TREE_OVERFLOW (ret) = 1; } else { ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL_TREE, expr); C_MAYBE_CONST_EXPR_INT_OPERANDS (ret) = 1; } return ret; } /* Having checked whether EXPR may appear in an unevaluated part of an integer constant expression and found that it may, remove any C_MAYBE_CONST_EXPR noting this fact and return the resulting expression. */ static inline tree remove_c_maybe_const_expr (tree expr) { if (TREE_CODE (expr) == C_MAYBE_CONST_EXPR) return C_MAYBE_CONST_EXPR_EXPR (expr); else return expr; } /* This is a cache to hold if two types are compatible or not. */ struct tagged_tu_seen_cache { const struct tagged_tu_seen_cache * next; const_tree t1; const_tree t2; /* The return value of tagged_types_tu_compatible_p if we had seen these two types already. */ int val; }; static const struct tagged_tu_seen_cache * tagged_tu_seen_base; static void free_all_tagged_tu_seen_up_to (const struct tagged_tu_seen_cache *); /* Do `exp = require_complete_type (loc, exp);' to make sure exp does not have an incomplete type. (That includes void types.) LOC is the location of the use. */ tree require_complete_type (location_t loc, tree value) { tree type = TREE_TYPE (value); if (error_operand_p (value)) return error_mark_node; /* First, detect a valid value with a complete type. */ if (COMPLETE_TYPE_P (type)) return value; c_incomplete_type_error (loc, value, type); return error_mark_node; } /* Print an error message for invalid use of an incomplete type. VALUE is the expression that was used (or 0 if that isn't known) and TYPE is the type that was invalid. LOC is the location for the error. */ void c_incomplete_type_error (location_t loc, const_tree value, const_tree type) { /* Avoid duplicate error message. */ if (TREE_CODE (type) == ERROR_MARK) return; if (value != NULL_TREE && (VAR_P (value) || TREE_CODE (value) == PARM_DECL)) error_at (loc, "%qD has an incomplete type %qT", value, type); else { retry: /* We must print an error message. Be clever about what it says. */ switch (TREE_CODE (type)) { case RECORD_TYPE: case UNION_TYPE: case ENUMERAL_TYPE: break; case VOID_TYPE: error_at (loc, "invalid use of void expression"); return; case ARRAY_TYPE: if (TYPE_DOMAIN (type)) { if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL) { error_at (loc, "invalid use of flexible array member"); return; } type = TREE_TYPE (type); goto retry; } error_at (loc, "invalid use of array with unspecified bounds"); return; default: gcc_unreachable (); } if (TREE_CODE (TYPE_NAME (type)) == IDENTIFIER_NODE) error_at (loc, "invalid use of undefined type %qT", type); else /* If this type has a typedef-name, the TYPE_NAME is a TYPE_DECL. */ error_at (loc, "invalid use of incomplete typedef %qT", type); } } /* Given a type, apply default promotions wrt unnamed function arguments and return the new type. */ tree c_type_promotes_to (tree type) { tree ret = NULL_TREE; if (TYPE_MAIN_VARIANT (type) == float_type_node) ret = double_type_node; else if (c_promoting_integer_type_p (type)) { /* Preserve unsignedness if not really getting any wider. */ if (TYPE_UNSIGNED (type) && (TYPE_PRECISION (type) == TYPE_PRECISION (integer_type_node))) ret = unsigned_type_node; else ret = integer_type_node; } if (ret != NULL_TREE) return (TYPE_ATOMIC (type) ? c_build_qualified_type (ret, TYPE_QUAL_ATOMIC) : ret); return type; } /* Return true if between two named address spaces, whether there is a superset named address space that encompasses both address spaces. If there is a superset, return which address space is the superset. */ static bool addr_space_superset (addr_space_t as1, addr_space_t as2, addr_space_t *common) { if (as1 == as2) { *common = as1; return true; } else if (targetm.addr_space.subset_p (as1, as2)) { *common = as2; return true; } else if (targetm.addr_space.subset_p (as2, as1)) { *common = as1; return true; } else return false; } /* Return a variant of TYPE which has all the type qualifiers of LIKE as well as those of TYPE. */ static tree qualify_type (tree type, tree like) { addr_space_t as_type = TYPE_ADDR_SPACE (type); addr_space_t as_like = TYPE_ADDR_SPACE (like); addr_space_t as_common; /* If the two named address spaces are different, determine the common superset address space. If there isn't one, raise an error. */ if (!addr_space_superset (as_type, as_like, &as_common)) { as_common = as_type; error ("%qT and %qT are in disjoint named address spaces", type, like); } return c_build_qualified_type (type, TYPE_QUALS_NO_ADDR_SPACE (type) | TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (like) | ENCODE_QUAL_ADDR_SPACE (as_common)); } /* Return true iff the given tree T is a variable length array. */ bool c_vla_type_p (const_tree t) { if (TREE_CODE (t) == ARRAY_TYPE && C_TYPE_VARIABLE_SIZE (t)) return true; return false; } /* If NTYPE is a type of a non-variadic function with a prototype and OTYPE is a type of a function without a prototype and ATTRS contains attribute format, diagnosess and removes it from ATTRS. Returns the result of build_type_attribute_variant of NTYPE and the (possibly) modified ATTRS. */ static tree build_functype_attribute_variant (tree ntype, tree otype, tree attrs) { if (!prototype_p (otype) && prototype_p (ntype) && lookup_attribute ("format", attrs)) { warning_at (input_location, OPT_Wattributes, "%qs attribute cannot be applied to a function that " "does not take variable arguments", "format"); attrs = remove_attribute ("format", attrs); } return build_type_attribute_variant (ntype, attrs); } /* Return the composite type of two compatible types. We assume that comptypes has already been done and returned nonzero; if that isn't so, this may crash. In particular, we assume that qualifiers match. */ tree composite_type (tree t1, tree t2) { enum tree_code code1; enum tree_code code2; tree attributes; /* Save time if the two types are the same. */ if (t1 == t2) return t1; /* If one type is nonsense, use the other. */ if (t1 == error_mark_node) return t2; if (t2 == error_mark_node) return t1; code1 = TREE_CODE (t1); code2 = TREE_CODE (t2); /* Merge the attributes. */ attributes = targetm.merge_type_attributes (t1, t2); /* If one is an enumerated type and the other is the compatible integer type, the composite type might be either of the two (DR#013 question 3). For consistency, use the enumerated type as the composite type. */ if (code1 == ENUMERAL_TYPE && code2 == INTEGER_TYPE) return t1; if (code2 == ENUMERAL_TYPE && code1 == INTEGER_TYPE) return t2; gcc_assert (code1 == code2); switch (code1) { case POINTER_TYPE: /* For two pointers, do this recursively on the target type. */ { tree pointed_to_1 = TREE_TYPE (t1); tree pointed_to_2 = TREE_TYPE (t2); tree target = composite_type (pointed_to_1, pointed_to_2); t1 = build_pointer_type_for_mode (target, TYPE_MODE (t1), false); t1 = build_type_attribute_variant (t1, attributes); return qualify_type (t1, t2); } case ARRAY_TYPE: { tree elt = composite_type (TREE_TYPE (t1), TREE_TYPE (t2)); int quals; tree unqual_elt; tree d1 = TYPE_DOMAIN (t1); tree d2 = TYPE_DOMAIN (t2); bool d1_variable, d2_variable; bool d1_zero, d2_zero; bool t1_complete, t2_complete; /* We should not have any type quals on arrays at all. */ gcc_assert (!TYPE_QUALS_NO_ADDR_SPACE (t1) && !TYPE_QUALS_NO_ADDR_SPACE (t2)); t1_complete = COMPLETE_TYPE_P (t1); t2_complete = COMPLETE_TYPE_P (t2); d1_zero = d1 == NULL_TREE || !TYPE_MAX_VALUE (d1); d2_zero = d2 == NULL_TREE || !TYPE_MAX_VALUE (d2); d1_variable = (!d1_zero && (TREE_CODE (TYPE_MIN_VALUE (d1)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d1)) != INTEGER_CST)); d2_variable = (!d2_zero && (TREE_CODE (TYPE_MIN_VALUE (d2)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d2)) != INTEGER_CST)); d1_variable = d1_variable || (d1_zero && c_vla_type_p (t1)); d2_variable = d2_variable || (d2_zero && c_vla_type_p (t2)); /* Save space: see if the result is identical to one of the args. */ if (elt == TREE_TYPE (t1) && TYPE_DOMAIN (t1) && (d2_variable || d2_zero || !d1_variable)) return build_type_attribute_variant (t1, attributes); if (elt == TREE_TYPE (t2) && TYPE_DOMAIN (t2) && (d1_variable || d1_zero || !d2_variable)) return build_type_attribute_variant (t2, attributes); if (elt == TREE_TYPE (t1) && !TYPE_DOMAIN (t2) && !TYPE_DOMAIN (t1)) return build_type_attribute_variant (t1, attributes); if (elt == TREE_TYPE (t2) && !TYPE_DOMAIN (t2) && !TYPE_DOMAIN (t1)) return build_type_attribute_variant (t2, attributes); /* Merge the element types, and have a size if either arg has one. We may have qualifiers on the element types. To set up TYPE_MAIN_VARIANT correctly, we need to form the composite of the unqualified types and add the qualifiers back at the end. */ quals = TYPE_QUALS (strip_array_types (elt)); unqual_elt = c_build_qualified_type (elt, TYPE_UNQUALIFIED); t1 = build_array_type (unqual_elt, TYPE_DOMAIN ((TYPE_DOMAIN (t1) && (d2_variable || d2_zero || !d1_variable)) ? t1 : t2)); /* Ensure a composite type involving a zero-length array type is a zero-length type not an incomplete type. */ if (d1_zero && d2_zero && (t1_complete || t2_complete) && !COMPLETE_TYPE_P (t1)) { TYPE_SIZE (t1) = bitsize_zero_node; TYPE_SIZE_UNIT (t1) = size_zero_node; } t1 = c_build_qualified_type (t1, quals); return build_type_attribute_variant (t1, attributes); } case ENUMERAL_TYPE: case RECORD_TYPE: case UNION_TYPE: if (attributes != NULL) { /* Try harder not to create a new aggregate type. */ if (attribute_list_equal (TYPE_ATTRIBUTES (t1), attributes)) return t1; if (attribute_list_equal (TYPE_ATTRIBUTES (t2), attributes)) return t2; } return build_type_attribute_variant (t1, attributes); case FUNCTION_TYPE: /* Function types: prefer the one that specified arg types. If both do, merge the arg types. Also merge the return types. */ { tree valtype = composite_type (TREE_TYPE (t1), TREE_TYPE (t2)); tree p1 = TYPE_ARG_TYPES (t1); tree p2 = TYPE_ARG_TYPES (t2); int len; tree newargs, n; int i; /* Save space: see if the result is identical to one of the args. */ if (valtype == TREE_TYPE (t1) && !TYPE_ARG_TYPES (t2)) return build_functype_attribute_variant (t1, t2, attributes); if (valtype == TREE_TYPE (t2) && !TYPE_ARG_TYPES (t1)) return build_functype_attribute_variant (t2, t1, attributes); /* Simple way if one arg fails to specify argument types. */ if (TYPE_ARG_TYPES (t1) == NULL_TREE) { t1 = build_function_type (valtype, TYPE_ARG_TYPES (t2)); t1 = build_type_attribute_variant (t1, attributes); return qualify_type (t1, t2); } if (TYPE_ARG_TYPES (t2) == NULL_TREE) { t1 = build_function_type (valtype, TYPE_ARG_TYPES (t1)); t1 = build_type_attribute_variant (t1, attributes); return qualify_type (t1, t2); } /* If both args specify argument types, we must merge the two lists, argument by argument. */ for (len = 0, newargs = p1; newargs && newargs != void_list_node; len++, newargs = TREE_CHAIN (newargs)) ; for (i = 0; i < len; i++) newargs = tree_cons (NULL_TREE, NULL_TREE, newargs); n = newargs; for (; p1 && p1 != void_list_node; p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2), n = TREE_CHAIN (n)) { /* A null type means arg type is not specified. Take whatever the other function type has. */ if (TREE_VALUE (p1) == NULL_TREE) { TREE_VALUE (n) = TREE_VALUE (p2); goto parm_done; } if (TREE_VALUE (p2) == NULL_TREE) { TREE_VALUE (n) = TREE_VALUE (p1); goto parm_done; } /* Given wait (union {union wait *u; int *i} *) and wait (union wait *), prefer union wait * as type of parm. */ if (TREE_CODE (TREE_VALUE (p1)) == UNION_TYPE && TREE_VALUE (p1) != TREE_VALUE (p2)) { tree memb; tree mv2 = TREE_VALUE (p2); if (mv2 && mv2 != error_mark_node && TREE_CODE (mv2) != ARRAY_TYPE) mv2 = TYPE_MAIN_VARIANT (mv2); for (memb = TYPE_FIELDS (TREE_VALUE (p1)); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = TYPE_MAIN_VARIANT (mv3); if (comptypes (mv3, mv2)) { TREE_VALUE (n) = composite_type (TREE_TYPE (memb), TREE_VALUE (p2)); pedwarn (input_location, OPT_Wpedantic, "function types not truly compatible in ISO C"); goto parm_done; } } } if (TREE_CODE (TREE_VALUE (p2)) == UNION_TYPE && TREE_VALUE (p2) != TREE_VALUE (p1)) { tree memb; tree mv1 = TREE_VALUE (p1); if (mv1 && mv1 != error_mark_node && TREE_CODE (mv1) != ARRAY_TYPE) mv1 = TYPE_MAIN_VARIANT (mv1); for (memb = TYPE_FIELDS (TREE_VALUE (p2)); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = TYPE_MAIN_VARIANT (mv3); if (comptypes (mv3, mv1)) { TREE_VALUE (n) = composite_type (TREE_TYPE (memb), TREE_VALUE (p1)); pedwarn (input_location, OPT_Wpedantic, "function types not truly compatible in ISO C"); goto parm_done; } } } TREE_VALUE (n) = composite_type (TREE_VALUE (p1), TREE_VALUE (p2)); parm_done: ; } t1 = build_function_type (valtype, newargs); t1 = qualify_type (t1, t2); } /* FALLTHRU */ default: return build_type_attribute_variant (t1, attributes); } } /* Return the type of a conditional expression between pointers to possibly differently qualified versions of compatible types. We assume that comp_target_types has already been done and returned nonzero; if that isn't so, this may crash. */ static tree common_pointer_type (tree t1, tree t2) { tree attributes; tree pointed_to_1, mv1; tree pointed_to_2, mv2; tree target; unsigned target_quals; addr_space_t as1, as2, as_common; int quals1, quals2; /* Save time if the two types are the same. */ if (t1 == t2) return t1; /* If one type is nonsense, use the other. */ if (t1 == error_mark_node) return t2; if (t2 == error_mark_node) return t1; gcc_assert (TREE_CODE (t1) == POINTER_TYPE && TREE_CODE (t2) == POINTER_TYPE); /* Merge the attributes. */ attributes = targetm.merge_type_attributes (t1, t2); /* Find the composite type of the target types, and combine the qualifiers of the two types' targets. Do not lose qualifiers on array element types by taking the TYPE_MAIN_VARIANT. */ mv1 = pointed_to_1 = TREE_TYPE (t1); mv2 = pointed_to_2 = TREE_TYPE (t2); if (TREE_CODE (mv1) != ARRAY_TYPE) mv1 = TYPE_MAIN_VARIANT (pointed_to_1); if (TREE_CODE (mv2) != ARRAY_TYPE) mv2 = TYPE_MAIN_VARIANT (pointed_to_2); target = composite_type (mv1, mv2); /* Strip array types to get correct qualifier for pointers to arrays */ quals1 = TYPE_QUALS_NO_ADDR_SPACE (strip_array_types (pointed_to_1)); quals2 = TYPE_QUALS_NO_ADDR_SPACE (strip_array_types (pointed_to_2)); /* For function types do not merge const qualifiers, but drop them if used inconsistently. The middle-end uses these to mark const and noreturn functions. */ if (TREE_CODE (pointed_to_1) == FUNCTION_TYPE) target_quals = (quals1 & quals2); else target_quals = (quals1 | quals2); /* If the two named address spaces are different, determine the common superset address space. This is guaranteed to exist due to the assumption that comp_target_type returned non-zero. */ as1 = TYPE_ADDR_SPACE (pointed_to_1); as2 = TYPE_ADDR_SPACE (pointed_to_2); if (!addr_space_superset (as1, as2, &as_common)) gcc_unreachable (); target_quals |= ENCODE_QUAL_ADDR_SPACE (as_common); t1 = build_pointer_type (c_build_qualified_type (target, target_quals)); return build_type_attribute_variant (t1, attributes); } /* Return the common type for two arithmetic types under the usual arithmetic conversions. The default conversions have already been applied, and enumerated types converted to their compatible integer types. The resulting type is unqualified and has no attributes. This is the type for the result of most arithmetic operations if the operands have the given two types. */ static tree c_common_type (tree t1, tree t2) { enum tree_code code1; enum tree_code code2; /* If one type is nonsense, use the other. */ if (t1 == error_mark_node) return t2; if (t2 == error_mark_node) return t1; if (TYPE_QUALS (t1) != TYPE_UNQUALIFIED) t1 = TYPE_MAIN_VARIANT (t1); if (TYPE_QUALS (t2) != TYPE_UNQUALIFIED) t2 = TYPE_MAIN_VARIANT (t2); if (TYPE_ATTRIBUTES (t1) != NULL_TREE) t1 = build_type_attribute_variant (t1, NULL_TREE); if (TYPE_ATTRIBUTES (t2) != NULL_TREE) t2 = build_type_attribute_variant (t2, NULL_TREE); /* Save time if the two types are the same. */ if (t1 == t2) return t1; code1 = TREE_CODE (t1); code2 = TREE_CODE (t2); gcc_assert (code1 == VECTOR_TYPE || code1 == COMPLEX_TYPE || code1 == FIXED_POINT_TYPE || code1 == REAL_TYPE || code1 == INTEGER_TYPE); gcc_assert (code2 == VECTOR_TYPE || code2 == COMPLEX_TYPE || code2 == FIXED_POINT_TYPE || code2 == REAL_TYPE || code2 == INTEGER_TYPE); /* When one operand is a decimal float type, the other operand cannot be a generic float type or a complex type. We also disallow vector types here. */ if ((DECIMAL_FLOAT_TYPE_P (t1) || DECIMAL_FLOAT_TYPE_P (t2)) && !(DECIMAL_FLOAT_TYPE_P (t1) && DECIMAL_FLOAT_TYPE_P (t2))) { if (code1 == VECTOR_TYPE || code2 == VECTOR_TYPE) { error ("cannot mix operands of decimal floating and vector types"); return error_mark_node; } if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE) { error ("cannot mix operands of decimal floating and complex types"); return error_mark_node; } if (code1 == REAL_TYPE && code2 == REAL_TYPE) { error ("cannot mix operands of decimal floating " "and other floating types"); return error_mark_node; } } /* If one type is a vector type, return that type. (How the usual arithmetic conversions apply to the vector types extension is not precisely specified.) */ if (code1 == VECTOR_TYPE) return t1; if (code2 == VECTOR_TYPE) return t2; /* If one type is complex, form the common type of the non-complex components, then make that complex. Use T1 or T2 if it is the required type. */ if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE) { tree subtype1 = code1 == COMPLEX_TYPE ? TREE_TYPE (t1) : t1; tree subtype2 = code2 == COMPLEX_TYPE ? TREE_TYPE (t2) : t2; tree subtype = c_common_type (subtype1, subtype2); if (code1 == COMPLEX_TYPE && TREE_TYPE (t1) == subtype) return t1; else if (code2 == COMPLEX_TYPE && TREE_TYPE (t2) == subtype) return t2; else return build_complex_type (subtype); } /* If only one is real, use it as the result. */ if (code1 == REAL_TYPE && code2 != REAL_TYPE) return t1; if (code2 == REAL_TYPE && code1 != REAL_TYPE) return t2; /* If both are real and either are decimal floating point types, use the decimal floating point type with the greater precision. */ if (code1 == REAL_TYPE && code2 == REAL_TYPE) { if (TYPE_MAIN_VARIANT (t1) == dfloat128_type_node || TYPE_MAIN_VARIANT (t2) == dfloat128_type_node) return dfloat128_type_node; else if (TYPE_MAIN_VARIANT (t1) == dfloat64_type_node || TYPE_MAIN_VARIANT (t2) == dfloat64_type_node) return dfloat64_type_node; else if (TYPE_MAIN_VARIANT (t1) == dfloat32_type_node || TYPE_MAIN_VARIANT (t2) == dfloat32_type_node) return dfloat32_type_node; } /* Deal with fixed-point types. */ if (code1 == FIXED_POINT_TYPE || code2 == FIXED_POINT_TYPE) { unsigned int unsignedp = 0, satp = 0; scalar_mode m1, m2; unsigned int fbit1, ibit1, fbit2, ibit2, max_fbit, max_ibit; m1 = SCALAR_TYPE_MODE (t1); m2 = SCALAR_TYPE_MODE (t2); /* If one input type is saturating, the result type is saturating. */ if (TYPE_SATURATING (t1) || TYPE_SATURATING (t2)) satp = 1; /* If both fixed-point types are unsigned, the result type is unsigned. When mixing fixed-point and integer types, follow the sign of the fixed-point type. Otherwise, the result type is signed. */ if ((TYPE_UNSIGNED (t1) && TYPE_UNSIGNED (t2) && code1 == FIXED_POINT_TYPE && code2 == FIXED_POINT_TYPE) || (code1 == FIXED_POINT_TYPE && code2 != FIXED_POINT_TYPE && TYPE_UNSIGNED (t1)) || (code1 != FIXED_POINT_TYPE && code2 == FIXED_POINT_TYPE && TYPE_UNSIGNED (t2))) unsignedp = 1; /* The result type is signed. */ if (unsignedp == 0) { /* If the input type is unsigned, we need to convert to the signed type. */ if (code1 == FIXED_POINT_TYPE && TYPE_UNSIGNED (t1)) { enum mode_class mclass = (enum mode_class) 0; if (GET_MODE_CLASS (m1) == MODE_UFRACT) mclass = MODE_FRACT; else if (GET_MODE_CLASS (m1) == MODE_UACCUM) mclass = MODE_ACCUM; else gcc_unreachable (); m1 = as_a <scalar_mode> (mode_for_size (GET_MODE_PRECISION (m1), mclass, 0)); } if (code2 == FIXED_POINT_TYPE && TYPE_UNSIGNED (t2)) { enum mode_class mclass = (enum mode_class) 0; if (GET_MODE_CLASS (m2) == MODE_UFRACT) mclass = MODE_FRACT; else if (GET_MODE_CLASS (m2) == MODE_UACCUM) mclass = MODE_ACCUM; else gcc_unreachable (); m2 = as_a <scalar_mode> (mode_for_size (GET_MODE_PRECISION (m2), mclass, 0)); } } if (code1 == FIXED_POINT_TYPE) { fbit1 = GET_MODE_FBIT (m1); ibit1 = GET_MODE_IBIT (m1); } else { fbit1 = 0; /* Signed integers need to subtract one sign bit. */ ibit1 = TYPE_PRECISION (t1) - (!TYPE_UNSIGNED (t1)); } if (code2 == FIXED_POINT_TYPE) { fbit2 = GET_MODE_FBIT (m2); ibit2 = GET_MODE_IBIT (m2); } else { fbit2 = 0; /* Signed integers need to subtract one sign bit. */ ibit2 = TYPE_PRECISION (t2) - (!TYPE_UNSIGNED (t2)); } max_ibit = ibit1 >= ibit2 ? ibit1 : ibit2; max_fbit = fbit1 >= fbit2 ? fbit1 : fbit2; return c_common_fixed_point_type_for_size (max_ibit, max_fbit, unsignedp, satp); } /* Both real or both integers; use the one with greater precision. */ if (TYPE_PRECISION (t1) > TYPE_PRECISION (t2)) return t1; else if (TYPE_PRECISION (t2) > TYPE_PRECISION (t1)) return t2; /* Same precision. Prefer long longs to longs to ints when the same precision, following the C99 rules on integer type rank (which are equivalent to the C90 rules for C90 types). */ if (TYPE_MAIN_VARIANT (t1) == long_long_unsigned_type_node || TYPE_MAIN_VARIANT (t2) == long_long_unsigned_type_node) return long_long_unsigned_type_node; if (TYPE_MAIN_VARIANT (t1) == long_long_integer_type_node || TYPE_MAIN_VARIANT (t2) == long_long_integer_type_node) { if (TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2)) return long_long_unsigned_type_node; else return long_long_integer_type_node; } if (TYPE_MAIN_VARIANT (t1) == long_unsigned_type_node || TYPE_MAIN_VARIANT (t2) == long_unsigned_type_node) return long_unsigned_type_node; if (TYPE_MAIN_VARIANT (t1) == long_integer_type_node || TYPE_MAIN_VARIANT (t2) == long_integer_type_node) { /* But preserve unsignedness from the other type, since long cannot hold all the values of an unsigned int. */ if (TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2)) return long_unsigned_type_node; else return long_integer_type_node; } /* For floating types of the same TYPE_PRECISION (which we here assume means either the same set of values, or sets of values neither a subset of the other, with behavior being undefined in the latter case), follow the rules from TS 18661-3: prefer interchange types _FloatN, then standard types long double, double, float, then extended types _FloatNx. For extended types, check them starting with _Float128x as that seems most consistent in spirit with preferring long double to double; for interchange types, also check in that order for consistency although it's not possible for more than one of them to have the same precision. */ tree mv1 = TYPE_MAIN_VARIANT (t1); tree mv2 = TYPE_MAIN_VARIANT (t2); for (int i = NUM_FLOATN_TYPES - 1; i >= 0; i--) if (mv1 == FLOATN_TYPE_NODE (i) || mv2 == FLOATN_TYPE_NODE (i)) return FLOATN_TYPE_NODE (i); /* Likewise, prefer long double to double even if same size. */ if (mv1 == long_double_type_node || mv2 == long_double_type_node) return long_double_type_node; /* Likewise, prefer double to float even if same size. We got a couple of embedded targets with 32 bit doubles, and the pdp11 might have 64 bit floats. */ if (mv1 == double_type_node || mv2 == double_type_node) return double_type_node; if (mv1 == float_type_node || mv2 == float_type_node) return float_type_node; for (int i = NUM_FLOATNX_TYPES - 1; i >= 0; i--) if (mv1 == FLOATNX_TYPE_NODE (i) || mv2 == FLOATNX_TYPE_NODE (i)) return FLOATNX_TYPE_NODE (i); /* Otherwise prefer the unsigned one. */ if (TYPE_UNSIGNED (t1)) return t1; else return t2; } /* Wrapper around c_common_type that is used by c-common.c and other front end optimizations that remove promotions. ENUMERAL_TYPEs are allowed here and are converted to their compatible integer types. BOOLEAN_TYPEs are allowed here and return either boolean_type_node or preferably a non-Boolean type as the common type. */ tree common_type (tree t1, tree t2) { if (TREE_CODE (t1) == ENUMERAL_TYPE) t1 = c_common_type_for_size (TYPE_PRECISION (t1), 1); if (TREE_CODE (t2) == ENUMERAL_TYPE) t2 = c_common_type_for_size (TYPE_PRECISION (t2), 1); /* If both types are BOOLEAN_TYPE, then return boolean_type_node. */ if (TREE_CODE (t1) == BOOLEAN_TYPE && TREE_CODE (t2) == BOOLEAN_TYPE) return boolean_type_node; /* If either type is BOOLEAN_TYPE, then return the other. */ if (TREE_CODE (t1) == BOOLEAN_TYPE) return t2; if (TREE_CODE (t2) == BOOLEAN_TYPE) return t1; return c_common_type (t1, t2); } /* Return 1 if TYPE1 and TYPE2 are compatible types for assignment or various other operations. Return 2 if they are compatible but a warning may be needed if you use them together. */ int comptypes (tree type1, tree type2) { const struct tagged_tu_seen_cache * tagged_tu_seen_base1 = tagged_tu_seen_base; int val; val = comptypes_internal (type1, type2, NULL, NULL); free_all_tagged_tu_seen_up_to (tagged_tu_seen_base1); return val; } /* Like comptypes, but if it returns non-zero because enum and int are compatible, it sets *ENUM_AND_INT_P to true. */ static int comptypes_check_enum_int (tree type1, tree type2, bool *enum_and_int_p) { const struct tagged_tu_seen_cache * tagged_tu_seen_base1 = tagged_tu_seen_base; int val; val = comptypes_internal (type1, type2, enum_and_int_p, NULL); free_all_tagged_tu_seen_up_to (tagged_tu_seen_base1); return val; } /* Like comptypes, but if it returns nonzero for different types, it sets *DIFFERENT_TYPES_P to true. */ int comptypes_check_different_types (tree type1, tree type2, bool *different_types_p) { const struct tagged_tu_seen_cache * tagged_tu_seen_base1 = tagged_tu_seen_base; int val; val = comptypes_internal (type1, type2, NULL, different_types_p); free_all_tagged_tu_seen_up_to (tagged_tu_seen_base1); return val; } /* Return 1 if TYPE1 and TYPE2 are compatible types for assignment or various other operations. Return 2 if they are compatible but a warning may be needed if you use them together. If ENUM_AND_INT_P is not NULL, and one type is an enum and the other a compatible integer type, then this sets *ENUM_AND_INT_P to true; *ENUM_AND_INT_P is never set to false. If DIFFERENT_TYPES_P is not NULL, and the types are compatible but different enough not to be permitted in C11 typedef redeclarations, then this sets *DIFFERENT_TYPES_P to true; *DIFFERENT_TYPES_P is never set to false, but may or may not be set if the types are incompatible. This differs from comptypes, in that we don't free the seen types. */ static int comptypes_internal (const_tree type1, const_tree type2, bool *enum_and_int_p, bool *different_types_p) { const_tree t1 = type1; const_tree t2 = type2; int attrval, val; /* Suppress errors caused by previously reported errors. */ if (t1 == t2 || !t1 || !t2 || TREE_CODE (t1) == ERROR_MARK || TREE_CODE (t2) == ERROR_MARK) return 1; /* Enumerated types are compatible with integer types, but this is not transitive: two enumerated types in the same translation unit are compatible with each other only if they are the same type. */ if (TREE_CODE (t1) == ENUMERAL_TYPE && TREE_CODE (t2) != ENUMERAL_TYPE) { t1 = c_common_type_for_size (TYPE_PRECISION (t1), TYPE_UNSIGNED (t1)); if (TREE_CODE (t2) != VOID_TYPE) { if (enum_and_int_p != NULL) *enum_and_int_p = true; if (different_types_p != NULL) *different_types_p = true; } } else if (TREE_CODE (t2) == ENUMERAL_TYPE && TREE_CODE (t1) != ENUMERAL_TYPE) { t2 = c_common_type_for_size (TYPE_PRECISION (t2), TYPE_UNSIGNED (t2)); if (TREE_CODE (t1) != VOID_TYPE) { if (enum_and_int_p != NULL) *enum_and_int_p = true; if (different_types_p != NULL) *different_types_p = true; } } if (t1 == t2) return 1; /* Different classes of types can't be compatible. */ if (TREE_CODE (t1) != TREE_CODE (t2)) return 0; /* Qualifiers must match. C99 6.7.3p9 */ if (TYPE_QUALS (t1) != TYPE_QUALS (t2)) return 0; /* Allow for two different type nodes which have essentially the same definition. Note that we already checked for equality of the type qualifiers (just above). */ if (TREE_CODE (t1) != ARRAY_TYPE && TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2)) return 1; /* 1 if no need for warning yet, 2 if warning cause has been seen. */ if (!(attrval = comp_type_attributes (t1, t2))) return 0; /* 1 if no need for warning yet, 2 if warning cause has been seen. */ val = 0; switch (TREE_CODE (t1)) { case INTEGER_TYPE: case FIXED_POINT_TYPE: case REAL_TYPE: /* With these nodes, we can't determine type equivalence by looking at what is stored in the nodes themselves, because two nodes might have different TYPE_MAIN_VARIANTs but still represent the same type. For example, wchar_t and int could have the same properties (TYPE_PRECISION, TYPE_MIN_VALUE, TYPE_MAX_VALUE, etc.), but have different TYPE_MAIN_VARIANTs and are distinct types. On the other hand, int and the following typedef typedef int INT __attribute((may_alias)); have identical properties, different TYPE_MAIN_VARIANTs, but represent the same type. The canonical type system keeps track of equivalence in this case, so we fall back on it. */ return TYPE_CANONICAL (t1) == TYPE_CANONICAL (t2); case POINTER_TYPE: /* Do not remove mode information. */ if (TYPE_MODE (t1) != TYPE_MODE (t2)) break; val = (TREE_TYPE (t1) == TREE_TYPE (t2) ? 1 : comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2), enum_and_int_p, different_types_p)); break; case FUNCTION_TYPE: val = function_types_compatible_p (t1, t2, enum_and_int_p, different_types_p); break; case ARRAY_TYPE: { tree d1 = TYPE_DOMAIN (t1); tree d2 = TYPE_DOMAIN (t2); bool d1_variable, d2_variable; bool d1_zero, d2_zero; val = 1; /* Target types must match incl. qualifiers. */ if (TREE_TYPE (t1) != TREE_TYPE (t2) && (val = comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2), enum_and_int_p, different_types_p)) == 0) return 0; if (different_types_p != NULL && (d1 == NULL_TREE) != (d2 == NULL_TREE)) *different_types_p = true; /* Sizes must match unless one is missing or variable. */ if (d1 == NULL_TREE || d2 == NULL_TREE || d1 == d2) break; d1_zero = !TYPE_MAX_VALUE (d1); d2_zero = !TYPE_MAX_VALUE (d2); d1_variable = (!d1_zero && (TREE_CODE (TYPE_MIN_VALUE (d1)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d1)) != INTEGER_CST)); d2_variable = (!d2_zero && (TREE_CODE (TYPE_MIN_VALUE (d2)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d2)) != INTEGER_CST)); d1_variable = d1_variable || (d1_zero && c_vla_type_p (t1)); d2_variable = d2_variable || (d2_zero && c_vla_type_p (t2)); if (different_types_p != NULL && d1_variable != d2_variable) *different_types_p = true; if (d1_variable || d2_variable) break; if (d1_zero && d2_zero) break; if (d1_zero || d2_zero || !tree_int_cst_equal (TYPE_MIN_VALUE (d1), TYPE_MIN_VALUE (d2)) || !tree_int_cst_equal (TYPE_MAX_VALUE (d1), TYPE_MAX_VALUE (d2))) val = 0; break; } case ENUMERAL_TYPE: case RECORD_TYPE: case UNION_TYPE: if (val != 1 && !same_translation_unit_p (t1, t2)) { tree a1 = TYPE_ATTRIBUTES (t1); tree a2 = TYPE_ATTRIBUTES (t2); if (! attribute_list_contained (a1, a2) && ! attribute_list_contained (a2, a1)) break; if (attrval != 2) return tagged_types_tu_compatible_p (t1, t2, enum_and_int_p, different_types_p); val = tagged_types_tu_compatible_p (t1, t2, enum_and_int_p, different_types_p); } break; case VECTOR_TYPE: val = (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2)) && comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2), enum_and_int_p, different_types_p)); break; default: break; } return attrval == 2 && val == 1 ? 2 : val; } /* Return 1 if TTL and TTR are pointers to types that are equivalent, ignoring their qualifiers, except for named address spaces. If the pointers point to different named addresses, then we must determine if one address space is a subset of the other. */ static int comp_target_types (location_t location, tree ttl, tree ttr) { int val; int val_ped; tree mvl = TREE_TYPE (ttl); tree mvr = TREE_TYPE (ttr); addr_space_t asl = TYPE_ADDR_SPACE (mvl); addr_space_t asr = TYPE_ADDR_SPACE (mvr); addr_space_t as_common; bool enum_and_int_p; /* Fail if pointers point to incompatible address spaces. */ if (!addr_space_superset (asl, asr, &as_common)) return 0; /* For pedantic record result of comptypes on arrays before losing qualifiers on the element type below. */ val_ped = 1; if (TREE_CODE (mvl) == ARRAY_TYPE && TREE_CODE (mvr) == ARRAY_TYPE) val_ped = comptypes (mvl, mvr); /* Qualifiers on element types of array types that are pointer targets are lost by taking their TYPE_MAIN_VARIANT. */ mvl = (TYPE_ATOMIC (strip_array_types (mvl)) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvl), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvl)); mvr = (TYPE_ATOMIC (strip_array_types (mvr)) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvr), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvr)); enum_and_int_p = false; val = comptypes_check_enum_int (mvl, mvr, &enum_and_int_p); if (val == 1 && val_ped != 1) pedwarn (location, OPT_Wpedantic, "pointers to arrays with different qualifiers " "are incompatible in ISO C"); if (val == 2) pedwarn (location, OPT_Wpedantic, "types are not quite compatible"); if (val == 1 && enum_and_int_p && warn_cxx_compat) warning_at (location, OPT_Wc___compat, "pointer target types incompatible in C++"); return val; } /* Subroutines of `comptypes'. */ /* Determine whether two trees derive from the same translation unit. If the CONTEXT chain ends in a null, that tree's context is still being parsed, so if two trees have context chains ending in null, they're in the same translation unit. */ bool same_translation_unit_p (const_tree t1, const_tree t2) { while (t1 && TREE_CODE (t1) != TRANSLATION_UNIT_DECL) switch (TREE_CODE_CLASS (TREE_CODE (t1))) { case tcc_declaration: t1 = DECL_CONTEXT (t1); break; case tcc_type: t1 = TYPE_CONTEXT (t1); break; case tcc_exceptional: t1 = BLOCK_SUPERCONTEXT (t1); break; /* assume block */ default: gcc_unreachable (); } while (t2 && TREE_CODE (t2) != TRANSLATION_UNIT_DECL) switch (TREE_CODE_CLASS (TREE_CODE (t2))) { case tcc_declaration: t2 = DECL_CONTEXT (t2); break; case tcc_type: t2 = TYPE_CONTEXT (t2); break; case tcc_exceptional: t2 = BLOCK_SUPERCONTEXT (t2); break; /* assume block */ default: gcc_unreachable (); } return t1 == t2; } /* Allocate the seen two types, assuming that they are compatible. */ static struct tagged_tu_seen_cache * alloc_tagged_tu_seen_cache (const_tree t1, const_tree t2) { struct tagged_tu_seen_cache *tu = XNEW (struct tagged_tu_seen_cache); tu->next = tagged_tu_seen_base; tu->t1 = t1; tu->t2 = t2; tagged_tu_seen_base = tu; /* The C standard says that two structures in different translation units are compatible with each other only if the types of their fields are compatible (among other things). We assume that they are compatible until proven otherwise when building the cache. An example where this can occur is: struct a { struct a *next; }; If we are comparing this against a similar struct in another TU, and did not assume they were compatible, we end up with an infinite loop. */ tu->val = 1; return tu; } /* Free the seen types until we get to TU_TIL. */ static void free_all_tagged_tu_seen_up_to (const struct tagged_tu_seen_cache *tu_til) { const struct tagged_tu_seen_cache *tu = tagged_tu_seen_base; while (tu != tu_til) { const struct tagged_tu_seen_cache *const tu1 = (const struct tagged_tu_seen_cache *) tu; tu = tu1->next; free (CONST_CAST (struct tagged_tu_seen_cache *, tu1)); } tagged_tu_seen_base = tu_til; } /* Return 1 if two 'struct', 'union', or 'enum' types T1 and T2 are compatible. If the two types are not the same (which has been checked earlier), this can only happen when multiple translation units are being compiled. See C99 6.2.7 paragraph 1 for the exact rules. ENUM_AND_INT_P and DIFFERENT_TYPES_P are as in comptypes_internal. */ static int tagged_types_tu_compatible_p (const_tree t1, const_tree t2, bool *enum_and_int_p, bool *different_types_p) { tree s1, s2; bool needs_warning = false; /* We have to verify that the tags of the types are the same. This is harder than it looks because this may be a typedef, so we have to go look at the original type. It may even be a typedef of a typedef... In the case of compiler-created builtin structs the TYPE_DECL may be a dummy, with no DECL_ORIGINAL_TYPE. Don't fault. */ while (TYPE_NAME (t1) && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL && DECL_ORIGINAL_TYPE (TYPE_NAME (t1))) t1 = DECL_ORIGINAL_TYPE (TYPE_NAME (t1)); while (TYPE_NAME (t2) && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL && DECL_ORIGINAL_TYPE (TYPE_NAME (t2))) t2 = DECL_ORIGINAL_TYPE (TYPE_NAME (t2)); /* C90 didn't have the requirement that the two tags be the same. */ if (flag_isoc99 && TYPE_NAME (t1) != TYPE_NAME (t2)) return 0; /* C90 didn't say what happened if one or both of the types were incomplete; we choose to follow C99 rules here, which is that they are compatible. */ if (TYPE_SIZE (t1) == NULL || TYPE_SIZE (t2) == NULL) return 1; { const struct tagged_tu_seen_cache * tts_i; for (tts_i = tagged_tu_seen_base; tts_i != NULL; tts_i = tts_i->next) if (tts_i->t1 == t1 && tts_i->t2 == t2) return tts_i->val; } switch (TREE_CODE (t1)) { case ENUMERAL_TYPE: { struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2); /* Speed up the case where the type values are in the same order. */ tree tv1 = TYPE_VALUES (t1); tree tv2 = TYPE_VALUES (t2); if (tv1 == tv2) { return 1; } for (;tv1 && tv2; tv1 = TREE_CHAIN (tv1), tv2 = TREE_CHAIN (tv2)) { if (TREE_PURPOSE (tv1) != TREE_PURPOSE (tv2)) break; if (simple_cst_equal (TREE_VALUE (tv1), TREE_VALUE (tv2)) != 1) { tu->val = 0; return 0; } } if (tv1 == NULL_TREE && tv2 == NULL_TREE) { return 1; } if (tv1 == NULL_TREE || tv2 == NULL_TREE) { tu->val = 0; return 0; } if (list_length (TYPE_VALUES (t1)) != list_length (TYPE_VALUES (t2))) { tu->val = 0; return 0; } for (s1 = TYPE_VALUES (t1); s1; s1 = TREE_CHAIN (s1)) { s2 = purpose_member (TREE_PURPOSE (s1), TYPE_VALUES (t2)); if (s2 == NULL || simple_cst_equal (TREE_VALUE (s1), TREE_VALUE (s2)) != 1) { tu->val = 0; return 0; } } return 1; } case UNION_TYPE: { struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2); if (list_length (TYPE_FIELDS (t1)) != list_length (TYPE_FIELDS (t2))) { tu->val = 0; return 0; } /* Speed up the common case where the fields are in the same order. */ for (s1 = TYPE_FIELDS (t1), s2 = TYPE_FIELDS (t2); s1 && s2; s1 = DECL_CHAIN (s1), s2 = DECL_CHAIN (s2)) { int result; if (DECL_NAME (s1) != DECL_NAME (s2)) break; result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2), enum_and_int_p, different_types_p); if (result != 1 && !DECL_NAME (s1)) break; if (result == 0) { tu->val = 0; return 0; } if (result == 2) needs_warning = true; if (TREE_CODE (s1) == FIELD_DECL && simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1), DECL_FIELD_BIT_OFFSET (s2)) != 1) { tu->val = 0; return 0; } } if (!s1 && !s2) { tu->val = needs_warning ? 2 : 1; return tu->val; } for (s1 = TYPE_FIELDS (t1); s1; s1 = DECL_CHAIN (s1)) { bool ok = false; for (s2 = TYPE_FIELDS (t2); s2; s2 = DECL_CHAIN (s2)) if (DECL_NAME (s1) == DECL_NAME (s2)) { int result; result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2), enum_and_int_p, different_types_p); if (result != 1 && !DECL_NAME (s1)) continue; if (result == 0) { tu->val = 0; return 0; } if (result == 2) needs_warning = true; if (TREE_CODE (s1) == FIELD_DECL && simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1), DECL_FIELD_BIT_OFFSET (s2)) != 1) break; ok = true; break; } if (!ok) { tu->val = 0; return 0; } } tu->val = needs_warning ? 2 : 10; return tu->val; } case RECORD_TYPE: { struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2); for (s1 = TYPE_FIELDS (t1), s2 = TYPE_FIELDS (t2); s1 && s2; s1 = DECL_CHAIN (s1), s2 = DECL_CHAIN (s2)) { int result; if (TREE_CODE (s1) != TREE_CODE (s2) || DECL_NAME (s1) != DECL_NAME (s2)) break; result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2), enum_and_int_p, different_types_p); if (result == 0) break; if (result == 2) needs_warning = true; if (TREE_CODE (s1) == FIELD_DECL && simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1), DECL_FIELD_BIT_OFFSET (s2)) != 1) break; } if (s1 && s2) tu->val = 0; else tu->val = needs_warning ? 2 : 1; return tu->val; } default: gcc_unreachable (); } } /* Return 1 if two function types F1 and F2 are compatible. If either type specifies no argument types, the other must specify a fixed number of self-promoting arg types. Otherwise, if one type specifies only the number of arguments, the other must specify that number of self-promoting arg types. Otherwise, the argument types must match. ENUM_AND_INT_P and DIFFERENT_TYPES_P are as in comptypes_internal. */ static int function_types_compatible_p (const_tree f1, const_tree f2, bool *enum_and_int_p, bool *different_types_p) { tree args1, args2; /* 1 if no need for warning yet, 2 if warning cause has been seen. */ int val = 1; int val1; tree ret1, ret2; ret1 = TREE_TYPE (f1); ret2 = TREE_TYPE (f2); /* 'volatile' qualifiers on a function's return type used to mean the function is noreturn. */ if (TYPE_VOLATILE (ret1) != TYPE_VOLATILE (ret2)) pedwarn (input_location, 0, "function return types not compatible due to %<volatile%>"); if (TYPE_VOLATILE (ret1)) ret1 = build_qualified_type (TYPE_MAIN_VARIANT (ret1), TYPE_QUALS (ret1) & ~TYPE_QUAL_VOLATILE); if (TYPE_VOLATILE (ret2)) ret2 = build_qualified_type (TYPE_MAIN_VARIANT (ret2), TYPE_QUALS (ret2) & ~TYPE_QUAL_VOLATILE); val = comptypes_internal (ret1, ret2, enum_and_int_p, different_types_p); if (val == 0) return 0; args1 = TYPE_ARG_TYPES (f1); args2 = TYPE_ARG_TYPES (f2); if (different_types_p != NULL && (args1 == NULL_TREE) != (args2 == NULL_TREE)) *different_types_p = true; /* An unspecified parmlist matches any specified parmlist whose argument types don't need default promotions. */ if (args1 == NULL_TREE) { if (!self_promoting_args_p (args2)) return 0; /* If one of these types comes from a non-prototype fn definition, compare that with the other type's arglist. If they don't match, ask for a warning (but no error). */ if (TYPE_ACTUAL_ARG_TYPES (f1) && type_lists_compatible_p (args2, TYPE_ACTUAL_ARG_TYPES (f1), enum_and_int_p, different_types_p) != 1) val = 2; return val; } if (args2 == NULL_TREE) { if (!self_promoting_args_p (args1)) return 0; if (TYPE_ACTUAL_ARG_TYPES (f2) && type_lists_compatible_p (args1, TYPE_ACTUAL_ARG_TYPES (f2), enum_and_int_p, different_types_p) != 1) val = 2; return val; } /* Both types have argument lists: compare them and propagate results. */ val1 = type_lists_compatible_p (args1, args2, enum_and_int_p, different_types_p); return val1 != 1 ? val1 : val; } /* Check two lists of types for compatibility, returning 0 for incompatible, 1 for compatible, or 2 for compatible with warning. ENUM_AND_INT_P and DIFFERENT_TYPES_P are as in comptypes_internal. */ static int type_lists_compatible_p (const_tree args1, const_tree args2, bool *enum_and_int_p, bool *different_types_p) { /* 1 if no need for warning yet, 2 if warning cause has been seen. */ int val = 1; int newval = 0; while (1) { tree a1, mv1, a2, mv2; if (args1 == NULL_TREE && args2 == NULL_TREE) return val; /* If one list is shorter than the other, they fail to match. */ if (args1 == NULL_TREE || args2 == NULL_TREE) return 0; mv1 = a1 = TREE_VALUE (args1); mv2 = a2 = TREE_VALUE (args2); if (mv1 && mv1 != error_mark_node && TREE_CODE (mv1) != ARRAY_TYPE) mv1 = (TYPE_ATOMIC (mv1) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv1), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv1)); if (mv2 && mv2 != error_mark_node && TREE_CODE (mv2) != ARRAY_TYPE) mv2 = (TYPE_ATOMIC (mv2) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv2), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv2)); /* A null pointer instead of a type means there is supposed to be an argument but nothing is specified about what type it has. So match anything that self-promotes. */ if (different_types_p != NULL && (a1 == NULL_TREE) != (a2 == NULL_TREE)) *different_types_p = true; if (a1 == NULL_TREE) { if (c_type_promotes_to (a2) != a2) return 0; } else if (a2 == NULL_TREE) { if (c_type_promotes_to (a1) != a1) return 0; } /* If one of the lists has an error marker, ignore this arg. */ else if (TREE_CODE (a1) == ERROR_MARK || TREE_CODE (a2) == ERROR_MARK) ; else if (!(newval = comptypes_internal (mv1, mv2, enum_and_int_p, different_types_p))) { if (different_types_p != NULL) *different_types_p = true; /* Allow wait (union {union wait *u; int *i} *) and wait (union wait *) to be compatible. */ if (TREE_CODE (a1) == UNION_TYPE && (TYPE_NAME (a1) == NULL_TREE || TYPE_TRANSPARENT_AGGR (a1)) && TREE_CODE (TYPE_SIZE (a1)) == INTEGER_CST && tree_int_cst_equal (TYPE_SIZE (a1), TYPE_SIZE (a2))) { tree memb; for (memb = TYPE_FIELDS (a1); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = (TYPE_ATOMIC (mv3) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv3), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv3)); if (comptypes_internal (mv3, mv2, enum_and_int_p, different_types_p)) break; } if (memb == NULL_TREE) return 0; } else if (TREE_CODE (a2) == UNION_TYPE && (TYPE_NAME (a2) == NULL_TREE || TYPE_TRANSPARENT_AGGR (a2)) && TREE_CODE (TYPE_SIZE (a2)) == INTEGER_CST && tree_int_cst_equal (TYPE_SIZE (a2), TYPE_SIZE (a1))) { tree memb; for (memb = TYPE_FIELDS (a2); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = (TYPE_ATOMIC (mv3) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv3), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv3)); if (comptypes_internal (mv3, mv1, enum_and_int_p, different_types_p)) break; } if (memb == NULL_TREE) return 0; } else return 0; } /* comptypes said ok, but record if it said to warn. */ if (newval > val) val = newval; args1 = TREE_CHAIN (args1); args2 = TREE_CHAIN (args2); } } /* Compute the size to increment a pointer by. When a function type or void type or incomplete type is passed, size_one_node is returned. This function does not emit any diagnostics; the caller is responsible for that. */ static tree c_size_in_bytes (const_tree type) { enum tree_code code = TREE_CODE (type); if (code == FUNCTION_TYPE || code == VOID_TYPE || code == ERROR_MARK || !COMPLETE_TYPE_P (type)) return size_one_node; /* Convert in case a char is more than one unit. */ return size_binop_loc (input_location, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type), size_int (TYPE_PRECISION (char_type_node) / BITS_PER_UNIT)); } /* Return either DECL or its known constant value (if it has one). */ tree decl_constant_value_1 (tree decl, bool in_init) { if (/* Note that DECL_INITIAL isn't valid for a PARM_DECL. */ TREE_CODE (decl) != PARM_DECL && !TREE_THIS_VOLATILE (decl) && TREE_READONLY (decl) && DECL_INITIAL (decl) != NULL_TREE && !error_operand_p (DECL_INITIAL (decl)) /* This is invalid if initial value is not constant. If it has either a function call, a memory reference, or a variable, then re-evaluating it could give different results. */ && TREE_CONSTANT (DECL_INITIAL (decl)) /* Check for cases where this is sub-optimal, even though valid. */ && (in_init || TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)) return DECL_INITIAL (decl); return decl; } /* Return either DECL or its known constant value (if it has one). Like the above, but always return decl outside of functions. */ tree decl_constant_value (tree decl) { /* Don't change a variable array bound or initial value to a constant in a place where a variable is invalid. */ return current_function_decl ? decl_constant_value_1 (decl, false) : decl; } /* Convert the array expression EXP to a pointer. */ static tree array_to_pointer_conversion (location_t loc, tree exp) { tree orig_exp = exp; tree type = TREE_TYPE (exp); tree adr; tree restype = TREE_TYPE (type); tree ptrtype; gcc_assert (TREE_CODE (type) == ARRAY_TYPE); STRIP_TYPE_NOPS (exp); if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp) = 1; ptrtype = build_pointer_type (restype); if (INDIRECT_REF_P (exp)) return convert (ptrtype, TREE_OPERAND (exp, 0)); /* In C++ array compound literals are temporary objects unless they are const or appear in namespace scope, so they are destroyed too soon to use them for much of anything (c++/53220). */ if (warn_cxx_compat && TREE_CODE (exp) == COMPOUND_LITERAL_EXPR) { tree decl = TREE_OPERAND (TREE_OPERAND (exp, 0), 0); if (!TREE_READONLY (decl) && !TREE_STATIC (decl)) warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wc___compat, "converting an array compound literal to a pointer " "is ill-formed in C++"); } adr = build_unary_op (loc, ADDR_EXPR, exp, true); return convert (ptrtype, adr); } /* Convert the function expression EXP to a pointer. */ static tree function_to_pointer_conversion (location_t loc, tree exp) { tree orig_exp = exp; gcc_assert (TREE_CODE (TREE_TYPE (exp)) == FUNCTION_TYPE); STRIP_TYPE_NOPS (exp); if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp) = 1; return build_unary_op (loc, ADDR_EXPR, exp, false); } /* Mark EXP as read, not just set, for set but not used -Wunused warning purposes. */ void mark_exp_read (tree exp) { switch (TREE_CODE (exp)) { case VAR_DECL: case PARM_DECL: DECL_READ_P (exp) = 1; break; case ARRAY_REF: case COMPONENT_REF: case MODIFY_EXPR: case REALPART_EXPR: case IMAGPART_EXPR: CASE_CONVERT: case ADDR_EXPR: case VIEW_CONVERT_EXPR: mark_exp_read (TREE_OPERAND (exp, 0)); break; case COMPOUND_EXPR: case C_MAYBE_CONST_EXPR: mark_exp_read (TREE_OPERAND (exp, 1)); break; default: break; } } /* Perform the default conversion of arrays and functions to pointers. Return the result of converting EXP. For any other expression, just return EXP. LOC is the location of the expression. */ struct c_expr default_function_array_conversion (location_t loc, struct c_expr exp) { tree orig_exp = exp.value; tree type = TREE_TYPE (exp.value); enum tree_code code = TREE_CODE (type); switch (code) { case ARRAY_TYPE: { bool not_lvalue = false; bool lvalue_array_p; while ((TREE_CODE (exp.value) == NON_LVALUE_EXPR || CONVERT_EXPR_P (exp.value)) && TREE_TYPE (TREE_OPERAND (exp.value, 0)) == type) { if (TREE_CODE (exp.value) == NON_LVALUE_EXPR) not_lvalue = true; exp.value = TREE_OPERAND (exp.value, 0); } if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp.value) = 1; lvalue_array_p = !not_lvalue && lvalue_p (exp.value); if (!flag_isoc99 && !lvalue_array_p) { /* Before C99, non-lvalue arrays do not decay to pointers. Normally, using such an array would be invalid; but it can be used correctly inside sizeof or as a statement expression. Thus, do not give an error here; an error will result later. */ return exp; } exp.value = array_to_pointer_conversion (loc, exp.value); } break; case FUNCTION_TYPE: exp.value = function_to_pointer_conversion (loc, exp.value); break; default: break; } return exp; } struct c_expr default_function_array_read_conversion (location_t loc, struct c_expr exp) { mark_exp_read (exp.value); return default_function_array_conversion (loc, exp); } /* Return whether EXPR should be treated as an atomic lvalue for the purposes of load and store handling. */ static bool really_atomic_lvalue (tree expr) { if (error_operand_p (expr)) return false; if (!TYPE_ATOMIC (TREE_TYPE (expr))) return false; if (!lvalue_p (expr)) return false; /* Ignore _Atomic on register variables, since their addresses can't be taken so (a) atomicity is irrelevant and (b) the normal atomic sequences wouldn't work. Ignore _Atomic on structures containing bit-fields, since accessing elements of atomic structures or unions is undefined behavior (C11 6.5.2.3#5), but it's unclear if it's undefined at translation time or execution time, and the normal atomic sequences again wouldn't work. */ while (handled_component_p (expr)) { if (TREE_CODE (expr) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1))) return false; expr = TREE_OPERAND (expr, 0); } if (DECL_P (expr) && C_DECL_REGISTER (expr)) return false; return true; } /* Convert expression EXP (location LOC) from lvalue to rvalue, including converting functions and arrays to pointers if CONVERT_P. If READ_P, also mark the expression as having been read. */ struct c_expr convert_lvalue_to_rvalue (location_t loc, struct c_expr exp, bool convert_p, bool read_p) { if (read_p) mark_exp_read (exp.value); if (convert_p) exp = default_function_array_conversion (loc, exp); if (!VOID_TYPE_P (TREE_TYPE (exp.value))) exp.value = require_complete_type (loc, exp.value); if (really_atomic_lvalue (exp.value)) { vec<tree, va_gc> *params; tree nonatomic_type, tmp, tmp_addr, fndecl, func_call; tree expr_type = TREE_TYPE (exp.value); tree expr_addr = build_unary_op (loc, ADDR_EXPR, exp.value, false); tree seq_cst = build_int_cst (integer_type_node, MEMMODEL_SEQ_CST); gcc_assert (TYPE_ATOMIC (expr_type)); /* Expansion of a generic atomic load may require an addition element, so allocate enough to prevent a resize. */ vec_alloc (params, 4); /* Remove the qualifiers for the rest of the expressions and create the VAL temp variable to hold the RHS. */ nonatomic_type = build_qualified_type (expr_type, TYPE_UNQUALIFIED); tmp = create_tmp_var_raw (nonatomic_type); tmp_addr = build_unary_op (loc, ADDR_EXPR, tmp, false); TREE_ADDRESSABLE (tmp) = 1; TREE_NO_WARNING (tmp) = 1; /* Issue __atomic_load (&expr, &tmp, SEQ_CST); */ fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_LOAD); params->quick_push (expr_addr); params->quick_push (tmp_addr); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); /* EXPR is always read. */ mark_exp_read (exp.value); /* Return tmp which contains the value loaded. */ exp.value = build4 (TARGET_EXPR, nonatomic_type, tmp, func_call, NULL_TREE, NULL_TREE); } return exp; } /* EXP is an expression of integer type. Apply the integer promotions to it and return the promoted value. */ tree perform_integral_promotions (tree exp) { tree type = TREE_TYPE (exp); enum tree_code code = TREE_CODE (type); gcc_assert (INTEGRAL_TYPE_P (type)); /* Normally convert enums to int, but convert wide enums to something wider. */ if (code == ENUMERAL_TYPE) { type = c_common_type_for_size (MAX (TYPE_PRECISION (type), TYPE_PRECISION (integer_type_node)), ((TYPE_PRECISION (type) >= TYPE_PRECISION (integer_type_node)) && TYPE_UNSIGNED (type))); return convert (type, exp); } /* ??? This should no longer be needed now bit-fields have their proper types. */ if (TREE_CODE (exp) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (exp, 1)) /* If it's thinner than an int, promote it like a c_promoting_integer_type_p, otherwise leave it alone. */ && compare_tree_int (DECL_SIZE (TREE_OPERAND (exp, 1)), TYPE_PRECISION (integer_type_node)) < 0) return convert (integer_type_node, exp); if (c_promoting_integer_type_p (type)) { /* Preserve unsignedness if not really getting any wider. */ if (TYPE_UNSIGNED (type) && TYPE_PRECISION (type) == TYPE_PRECISION (integer_type_node)) return convert (unsigned_type_node, exp); return convert (integer_type_node, exp); } return exp; } /* Perform default promotions for C data used in expressions. Enumeral types or short or char are converted to int. In addition, manifest constants symbols are replaced by their values. */ tree default_conversion (tree exp) { tree orig_exp; tree type = TREE_TYPE (exp); enum tree_code code = TREE_CODE (type); tree promoted_type; mark_exp_read (exp); /* Functions and arrays have been converted during parsing. */ gcc_assert (code != FUNCTION_TYPE); if (code == ARRAY_TYPE) return exp; /* Constants can be used directly unless they're not loadable. */ if (TREE_CODE (exp) == CONST_DECL) exp = DECL_INITIAL (exp); /* Strip no-op conversions. */ orig_exp = exp; STRIP_TYPE_NOPS (exp); if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp) = 1; if (code == VOID_TYPE) { error_at (EXPR_LOC_OR_LOC (exp, input_location), "void value not ignored as it ought to be"); return error_mark_node; } exp = require_complete_type (EXPR_LOC_OR_LOC (exp, input_location), exp); if (exp == error_mark_node) return error_mark_node; promoted_type = targetm.promoted_type (type); if (promoted_type) return convert (promoted_type, exp); if (INTEGRAL_TYPE_P (type)) return perform_integral_promotions (exp); return exp; } /* Look up COMPONENT in a structure or union TYPE. If the component name is not found, returns NULL_TREE. Otherwise, the return value is a TREE_LIST, with each TREE_VALUE a FIELD_DECL stepping down the chain to the component, which is in the last TREE_VALUE of the list. Normally the list is of length one, but if the component is embedded within (nested) anonymous structures or unions, the list steps down the chain to the component. */ static tree lookup_field (tree type, tree component) { tree field; /* If TYPE_LANG_SPECIFIC is set, then it is a sorted array of pointers to the field elements. Use a binary search on this array to quickly find the element. Otherwise, do a linear search. TYPE_LANG_SPECIFIC will always be set for structures which have many elements. Duplicate field checking replaces duplicates with NULL_TREE so TYPE_LANG_SPECIFIC arrays are potentially no longer sorted. In that case just iterate using DECL_CHAIN. */ if (TYPE_LANG_SPECIFIC (type) && TYPE_LANG_SPECIFIC (type)->s && !seen_error ()) { int bot, top, half; tree *field_array = &TYPE_LANG_SPECIFIC (type)->s->elts[0]; field = TYPE_FIELDS (type); bot = 0; top = TYPE_LANG_SPECIFIC (type)->s->len; while (top - bot > 1) { half = (top - bot + 1) >> 1; field = field_array[bot+half]; if (DECL_NAME (field) == NULL_TREE) { /* Step through all anon unions in linear fashion. */ while (DECL_NAME (field_array[bot]) == NULL_TREE) { field = field_array[bot++]; if (RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))) { tree anon = lookup_field (TREE_TYPE (field), component); if (anon) return tree_cons (NULL_TREE, field, anon); /* The Plan 9 compiler permits referring directly to an anonymous struct/union field using a typedef name. */ if (flag_plan9_extensions && TYPE_NAME (TREE_TYPE (field)) != NULL_TREE && (TREE_CODE (TYPE_NAME (TREE_TYPE (field))) == TYPE_DECL) && (DECL_NAME (TYPE_NAME (TREE_TYPE (field))) == component)) break; } } /* Entire record is only anon unions. */ if (bot > top) return NULL_TREE; /* Restart the binary search, with new lower bound. */ continue; } if (DECL_NAME (field) == component) break; if (DECL_NAME (field) < component) bot += half; else top = bot + half; } if (DECL_NAME (field_array[bot]) == component) field = field_array[bot]; else if (DECL_NAME (field) != component) return NULL_TREE; } else { for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field)) { if (DECL_NAME (field) == NULL_TREE && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))) { tree anon = lookup_field (TREE_TYPE (field), component); if (anon) return tree_cons (NULL_TREE, field, anon); /* The Plan 9 compiler permits referring directly to an anonymous struct/union field using a typedef name. */ if (flag_plan9_extensions && TYPE_NAME (TREE_TYPE (field)) != NULL_TREE && TREE_CODE (TYPE_NAME (TREE_TYPE (field))) == TYPE_DECL && (DECL_NAME (TYPE_NAME (TREE_TYPE (field))) == component)) break; } if (DECL_NAME (field) == component) break; } if (field == NULL_TREE) return NULL_TREE; } return tree_cons (NULL_TREE, field, NULL_TREE); } /* Recursively append candidate IDENTIFIER_NODEs to CANDIDATES. */ static void lookup_field_fuzzy_find_candidates (tree type, tree component, vec<tree> *candidates) { tree field; for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field)) { if (DECL_NAME (field) == NULL_TREE && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))) lookup_field_fuzzy_find_candidates (TREE_TYPE (field), component, candidates); if (DECL_NAME (field)) candidates->safe_push (DECL_NAME (field)); } } /* Like "lookup_field", but find the closest matching IDENTIFIER_NODE, rather than returning a TREE_LIST for an exact match. */ static tree lookup_field_fuzzy (tree type, tree component) { gcc_assert (TREE_CODE (component) == IDENTIFIER_NODE); /* First, gather a list of candidates. */ auto_vec <tree> candidates; lookup_field_fuzzy_find_candidates (type, component, &candidates); return find_closest_identifier (component, &candidates); } /* Support function for build_component_ref's error-handling. Given DATUM_TYPE, and "DATUM.COMPONENT", where DATUM is *not* a struct or union, should we suggest "DATUM->COMPONENT" as a hint? */ static bool should_suggest_deref_p (tree datum_type) { /* We don't do it for Objective-C, since Objective-C 2.0 dot-syntax allows "." for ptrs; we could be handling a failed attempt to access a property. */ if (c_dialect_objc ()) return false; /* Only suggest it for pointers... */ if (TREE_CODE (datum_type) != POINTER_TYPE) return false; /* ...to structs/unions. */ tree underlying_type = TREE_TYPE (datum_type); enum tree_code code = TREE_CODE (underlying_type); if (code == RECORD_TYPE || code == UNION_TYPE) return true; else return false; } /* Make an expression to refer to the COMPONENT field of structure or union value DATUM. COMPONENT is an IDENTIFIER_NODE. LOC is the location of the COMPONENT_REF. COMPONENT_LOC is the location of COMPONENT. */ tree build_component_ref (location_t loc, tree datum, tree component, location_t component_loc) { tree type = TREE_TYPE (datum); enum tree_code code = TREE_CODE (type); tree field = NULL; tree ref; bool datum_lvalue = lvalue_p (datum); if (!objc_is_public (datum, component)) return error_mark_node; /* Detect Objective-C property syntax object.property. */ if (c_dialect_objc () && (ref = objc_maybe_build_component_ref (datum, component))) return ref; /* See if there is a field or component with name COMPONENT. */ if (code == RECORD_TYPE || code == UNION_TYPE) { if (!COMPLETE_TYPE_P (type)) { c_incomplete_type_error (loc, NULL_TREE, type); return error_mark_node; } field = lookup_field (type, component); if (!field) { tree guessed_id = lookup_field_fuzzy (type, component); if (guessed_id) { /* Attempt to provide a fixit replacement hint, if we have a valid range for the component. */ location_t reported_loc = (component_loc != UNKNOWN_LOCATION) ? component_loc : loc; gcc_rich_location rich_loc (reported_loc); if (component_loc != UNKNOWN_LOCATION) rich_loc.add_fixit_misspelled_id (component_loc, guessed_id); error_at (&rich_loc, "%qT has no member named %qE; did you mean %qE?", type, component, guessed_id); } else error_at (loc, "%qT has no member named %qE", type, component); return error_mark_node; } /* Accessing elements of atomic structures or unions is undefined behavior (C11 6.5.2.3#5). */ if (TYPE_ATOMIC (type) && c_inhibit_evaluation_warnings == 0) { if (code == RECORD_TYPE) warning_at (loc, 0, "accessing a member %qE of an atomic " "structure %qE", component, datum); else warning_at (loc, 0, "accessing a member %qE of an atomic " "union %qE", component, datum); } /* Chain the COMPONENT_REFs if necessary down to the FIELD. This might be better solved in future the way the C++ front end does it - by giving the anonymous entities each a separate name and type, and then have build_component_ref recursively call itself. We can't do that here. */ do { tree subdatum = TREE_VALUE (field); int quals; tree subtype; bool use_datum_quals; if (TREE_TYPE (subdatum) == error_mark_node) return error_mark_node; /* If this is an rvalue, it does not have qualifiers in C standard terms and we must avoid propagating such qualifiers down to a non-lvalue array that is then converted to a pointer. */ use_datum_quals = (datum_lvalue || TREE_CODE (TREE_TYPE (subdatum)) != ARRAY_TYPE); quals = TYPE_QUALS (strip_array_types (TREE_TYPE (subdatum))); if (use_datum_quals) quals |= TYPE_QUALS (TREE_TYPE (datum)); subtype = c_build_qualified_type (TREE_TYPE (subdatum), quals); ref = build3 (COMPONENT_REF, subtype, datum, subdatum, NULL_TREE); SET_EXPR_LOCATION (ref, loc); if (TREE_READONLY (subdatum) || (use_datum_quals && TREE_READONLY (datum))) TREE_READONLY (ref) = 1; if (TREE_THIS_VOLATILE (subdatum) || (use_datum_quals && TREE_THIS_VOLATILE (datum))) TREE_THIS_VOLATILE (ref) = 1; if (TREE_DEPRECATED (subdatum)) warn_deprecated_use (subdatum, NULL_TREE); datum = ref; field = TREE_CHAIN (field); } while (field); return ref; } else if (should_suggest_deref_p (type)) { /* Special-case the error message for "ptr.field" for the case where the user has confused "." vs "->". */ rich_location richloc (line_table, loc); /* "loc" should be the "." token. */ richloc.add_fixit_replace ("->"); error_at (&richloc, "%qE is a pointer; did you mean to use %<->%>?", datum); return error_mark_node; } else if (code != ERROR_MARK) error_at (loc, "request for member %qE in something not a structure or union", component); return error_mark_node; } /* Given an expression PTR for a pointer, return an expression for the value pointed to. ERRORSTRING is the name of the operator to appear in error messages. LOC is the location to use for the generated tree. */ tree build_indirect_ref (location_t loc, tree ptr, ref_operator errstring) { tree pointer = default_conversion (ptr); tree type = TREE_TYPE (pointer); tree ref; if (TREE_CODE (type) == POINTER_TYPE) { if (CONVERT_EXPR_P (pointer) || TREE_CODE (pointer) == VIEW_CONVERT_EXPR) { /* If a warning is issued, mark it to avoid duplicates from the backend. This only needs to be done at warn_strict_aliasing > 2. */ if (warn_strict_aliasing > 2) if (strict_aliasing_warning (EXPR_LOCATION (pointer), type, TREE_OPERAND (pointer, 0))) TREE_NO_WARNING (pointer) = 1; } if (TREE_CODE (pointer) == ADDR_EXPR && (TREE_TYPE (TREE_OPERAND (pointer, 0)) == TREE_TYPE (type))) { ref = TREE_OPERAND (pointer, 0); protected_set_expr_location (ref, loc); return ref; } else { tree t = TREE_TYPE (type); ref = build1 (INDIRECT_REF, t, pointer); if (VOID_TYPE_P (t) && c_inhibit_evaluation_warnings == 0) warning_at (loc, 0, "dereferencing %<void *%> pointer"); /* We *must* set TREE_READONLY when dereferencing a pointer to const, so that we get the proper error message if the result is used to assign to. Also, &* is supposed to be a no-op. And ANSI C seems to specify that the type of the result should be the const type. */ /* A de-reference of a pointer to const is not a const. It is valid to change it via some other pointer. */ TREE_READONLY (ref) = TYPE_READONLY (t); TREE_SIDE_EFFECTS (ref) = TYPE_VOLATILE (t) || TREE_SIDE_EFFECTS (pointer); TREE_THIS_VOLATILE (ref) = TYPE_VOLATILE (t); protected_set_expr_location (ref, loc); return ref; } } else if (TREE_CODE (pointer) != ERROR_MARK) invalid_indirection_error (loc, type, errstring); return error_mark_node; } /* This handles expressions of the form "a[i]", which denotes an array reference. This is logically equivalent in C to *(a+i), but we may do it differently. If A is a variable or a member, we generate a primitive ARRAY_REF. This avoids forcing the array out of registers, and can work on arrays that are not lvalues (for example, members of structures returned by functions). For vector types, allow vector[i] but not i[vector], and create *(((type*)&vectortype) + i) for the expression. LOC is the location to use for the returned expression. */ tree build_array_ref (location_t loc, tree array, tree index) { tree ret; bool swapped = false; if (TREE_TYPE (array) == error_mark_node || TREE_TYPE (index) == error_mark_node) return error_mark_node; if (TREE_CODE (TREE_TYPE (array)) != ARRAY_TYPE && TREE_CODE (TREE_TYPE (array)) != POINTER_TYPE /* Allow vector[index] but not index[vector]. */ && !gnu_vector_type_p (TREE_TYPE (array))) { if (TREE_CODE (TREE_TYPE (index)) != ARRAY_TYPE && TREE_CODE (TREE_TYPE (index)) != POINTER_TYPE) { error_at (loc, "subscripted value is neither array nor pointer nor vector"); return error_mark_node; } std::swap (array, index); swapped = true; } if (!INTEGRAL_TYPE_P (TREE_TYPE (index))) { error_at (loc, "array subscript is not an integer"); return error_mark_node; } if (TREE_CODE (TREE_TYPE (TREE_TYPE (array))) == FUNCTION_TYPE) { error_at (loc, "subscripted value is pointer to function"); return error_mark_node; } /* ??? Existing practice has been to warn only when the char index is syntactically the index, not for char[array]. */ if (!swapped) warn_array_subscript_with_type_char (loc, index); /* Apply default promotions *after* noticing character types. */ index = default_conversion (index); if (index == error_mark_node) return error_mark_node; gcc_assert (TREE_CODE (TREE_TYPE (index)) == INTEGER_TYPE); bool was_vector = VECTOR_TYPE_P (TREE_TYPE (array)); bool non_lvalue = convert_vector_to_array_for_subscript (loc, &array, index); if (TREE_CODE (TREE_TYPE (array)) == ARRAY_TYPE) { tree rval, type; /* An array that is indexed by a non-constant cannot be stored in a register; we must be able to do address arithmetic on its address. Likewise an array of elements of variable size. */ if (TREE_CODE (index) != INTEGER_CST || (COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (array))) && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (array)))) != INTEGER_CST)) { if (!c_mark_addressable (array, true)) return error_mark_node; } /* An array that is indexed by a constant value which is not within the array bounds cannot be stored in a register either; because we would get a crash in store_bit_field/extract_bit_field when trying to access a non-existent part of the register. */ if (TREE_CODE (index) == INTEGER_CST && TYPE_DOMAIN (TREE_TYPE (array)) && !int_fits_type_p (index, TYPE_DOMAIN (TREE_TYPE (array)))) { if (!c_mark_addressable (array)) return error_mark_node; } if ((pedantic || warn_c90_c99_compat) && ! was_vector) { tree foo = array; while (TREE_CODE (foo) == COMPONENT_REF) foo = TREE_OPERAND (foo, 0); if (VAR_P (foo) && C_DECL_REGISTER (foo)) pedwarn (loc, OPT_Wpedantic, "ISO C forbids subscripting %<register%> array"); else if (!lvalue_p (foo)) pedwarn_c90 (loc, OPT_Wpedantic, "ISO C90 forbids subscripting non-lvalue " "array"); } type = TREE_TYPE (TREE_TYPE (array)); rval = build4 (ARRAY_REF, type, array, index, NULL_TREE, NULL_TREE); /* Array ref is const/volatile if the array elements are or if the array is. */ TREE_READONLY (rval) |= (TYPE_READONLY (TREE_TYPE (TREE_TYPE (array))) | TREE_READONLY (array)); TREE_SIDE_EFFECTS (rval) |= (TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (array))) | TREE_SIDE_EFFECTS (array)); TREE_THIS_VOLATILE (rval) |= (TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (array))) /* This was added by rms on 16 Nov 91. It fixes vol struct foo *a; a->elts[1] in an inline function. Hope it doesn't break something else. */ | TREE_THIS_VOLATILE (array)); ret = require_complete_type (loc, rval); protected_set_expr_location (ret, loc); if (non_lvalue) ret = non_lvalue_loc (loc, ret); return ret; } else { tree ar = default_conversion (array); if (ar == error_mark_node) return ar; gcc_assert (TREE_CODE (TREE_TYPE (ar)) == POINTER_TYPE); gcc_assert (TREE_CODE (TREE_TYPE (TREE_TYPE (ar))) != FUNCTION_TYPE); ret = build_indirect_ref (loc, build_binary_op (loc, PLUS_EXPR, ar, index, false), RO_ARRAY_INDEXING); if (non_lvalue) ret = non_lvalue_loc (loc, ret); return ret; } } /* Build an external reference to identifier ID. FUN indicates whether this will be used for a function call. LOC is the source location of the identifier. This sets *TYPE to the type of the identifier, which is not the same as the type of the returned value for CONST_DECLs defined as enum constants. If the type of the identifier is not available, *TYPE is set to NULL. */ tree build_external_ref (location_t loc, tree id, bool fun, tree *type) { tree ref; tree decl = lookup_name (id); /* In Objective-C, an instance variable (ivar) may be preferred to whatever lookup_name() found. */ decl = objc_lookup_ivar (decl, id); *type = NULL; if (decl && decl != error_mark_node) { ref = decl; *type = TREE_TYPE (ref); } else if (fun) /* Implicit function declaration. */ ref = implicitly_declare (loc, id); else if (decl == error_mark_node) /* Don't complain about something that's already been complained about. */ return error_mark_node; else { undeclared_variable (loc, id); return error_mark_node; } if (TREE_TYPE (ref) == error_mark_node) return error_mark_node; if (TREE_DEPRECATED (ref)) warn_deprecated_use (ref, NULL_TREE); /* Recursive call does not count as usage. */ if (ref != current_function_decl) { TREE_USED (ref) = 1; } if (TREE_CODE (ref) == FUNCTION_DECL && !in_alignof) { if (!in_sizeof && !in_typeof) C_DECL_USED (ref) = 1; else if (DECL_INITIAL (ref) == NULL_TREE && DECL_EXTERNAL (ref) && !TREE_PUBLIC (ref)) record_maybe_used_decl (ref); } if (TREE_CODE (ref) == CONST_DECL) { used_types_insert (TREE_TYPE (ref)); if (warn_cxx_compat && TREE_CODE (TREE_TYPE (ref)) == ENUMERAL_TYPE && C_TYPE_DEFINED_IN_STRUCT (TREE_TYPE (ref))) { warning_at (loc, OPT_Wc___compat, ("enum constant defined in struct or union " "is not visible in C++")); inform (DECL_SOURCE_LOCATION (ref), "enum constant defined here"); } ref = DECL_INITIAL (ref); TREE_CONSTANT (ref) = 1; } else if (current_function_decl != NULL_TREE && !DECL_FILE_SCOPE_P (current_function_decl) && (VAR_OR_FUNCTION_DECL_P (ref) || TREE_CODE (ref) == PARM_DECL)) { tree context = decl_function_context (ref); if (context != NULL_TREE && context != current_function_decl) DECL_NONLOCAL (ref) = 1; } /* C99 6.7.4p3: An inline definition of a function with external linkage ... shall not contain a reference to an identifier with internal linkage. */ else if (current_function_decl != NULL_TREE && DECL_DECLARED_INLINE_P (current_function_decl) && DECL_EXTERNAL (current_function_decl) && VAR_OR_FUNCTION_DECL_P (ref) && (!VAR_P (ref) || TREE_STATIC (ref)) && ! TREE_PUBLIC (ref) && DECL_CONTEXT (ref) != current_function_decl) record_inline_static (loc, current_function_decl, ref, csi_internal); return ref; } /* Record details of decls possibly used inside sizeof or typeof. */ struct maybe_used_decl { /* The decl. */ tree decl; /* The level seen at (in_sizeof + in_typeof). */ int level; /* The next one at this level or above, or NULL. */ struct maybe_used_decl *next; }; static struct maybe_used_decl *maybe_used_decls; /* Record that DECL, an undefined static function reference seen inside sizeof or typeof, might be used if the operand of sizeof is a VLA type or the operand of typeof is a variably modified type. */ static void record_maybe_used_decl (tree decl) { struct maybe_used_decl *t = XOBNEW (&parser_obstack, struct maybe_used_decl); t->decl = decl; t->level = in_sizeof + in_typeof; t->next = maybe_used_decls; maybe_used_decls = t; } /* Pop the stack of decls possibly used inside sizeof or typeof. If USED is false, just discard them. If it is true, mark them used (if no longer inside sizeof or typeof) or move them to the next level up (if still inside sizeof or typeof). */ void pop_maybe_used (bool used) { struct maybe_used_decl *p = maybe_used_decls; int cur_level = in_sizeof + in_typeof; while (p && p->level > cur_level) { if (used) { if (cur_level == 0) C_DECL_USED (p->decl) = 1; else p->level = cur_level; } p = p->next; } if (!used || cur_level == 0) maybe_used_decls = p; } /* Return the result of sizeof applied to EXPR. */ struct c_expr c_expr_sizeof_expr (location_t loc, struct c_expr expr) { struct c_expr ret; if (expr.value == error_mark_node) { ret.value = error_mark_node; ret.original_code = ERROR_MARK; ret.original_type = NULL; pop_maybe_used (false); } else { bool expr_const_operands = true; if (TREE_CODE (expr.value) == PARM_DECL && C_ARRAY_PARAMETER (expr.value)) { auto_diagnostic_group d; if (warning_at (loc, OPT_Wsizeof_array_argument, "%<sizeof%> on array function parameter %qE will " "return size of %qT", expr.value, TREE_TYPE (expr.value))) inform (DECL_SOURCE_LOCATION (expr.value), "declared here"); } tree folded_expr = c_fully_fold (expr.value, require_constant_value, &expr_const_operands); ret.value = c_sizeof (loc, TREE_TYPE (folded_expr)); c_last_sizeof_arg = expr.value; c_last_sizeof_loc = loc; ret.original_code = SIZEOF_EXPR; ret.original_type = NULL; if (c_vla_type_p (TREE_TYPE (folded_expr))) { /* sizeof is evaluated when given a vla (C99 6.5.3.4p2). */ ret.value = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (ret.value), folded_expr, ret.value); C_MAYBE_CONST_EXPR_NON_CONST (ret.value) = !expr_const_operands; SET_EXPR_LOCATION (ret.value, loc); } pop_maybe_used (C_TYPE_VARIABLE_SIZE (TREE_TYPE (folded_expr))); } return ret; } /* Return the result of sizeof applied to T, a structure for the type name passed to sizeof (rather than the type itself). LOC is the location of the original expression. */ struct c_expr c_expr_sizeof_type (location_t loc, struct c_type_name *t) { tree type; struct c_expr ret; tree type_expr = NULL_TREE; bool type_expr_const = true; type = groktypename (t, &type_expr, &type_expr_const); ret.value = c_sizeof (loc, type); c_last_sizeof_arg = type; c_last_sizeof_loc = loc; ret.original_code = SIZEOF_EXPR; ret.original_type = NULL; if ((type_expr || TREE_CODE (ret.value) == INTEGER_CST) && c_vla_type_p (type)) { /* If the type is a [*] array, it is a VLA but is represented as having a size of zero. In such a case we must ensure that the result of sizeof does not get folded to a constant by c_fully_fold, because if the size is evaluated the result is not constant and so constraints on zero or negative size arrays must not be applied when this sizeof call is inside another array declarator. */ if (!type_expr) type_expr = integer_zero_node; ret.value = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (ret.value), type_expr, ret.value); C_MAYBE_CONST_EXPR_NON_CONST (ret.value) = !type_expr_const; } pop_maybe_used (type != error_mark_node ? C_TYPE_VARIABLE_SIZE (type) : false); return ret; } /* Build a function call to function FUNCTION with parameters PARAMS. The function call is at LOC. PARAMS is a list--a chain of TREE_LIST nodes--in which the TREE_VALUE of each node is a parameter-expression. FUNCTION's data type may be a function type or a pointer-to-function. */ tree build_function_call (location_t loc, tree function, tree params) { vec<tree, va_gc> *v; tree ret; vec_alloc (v, list_length (params)); for (; params; params = TREE_CHAIN (params)) v->quick_push (TREE_VALUE (params)); ret = c_build_function_call_vec (loc, vNULL, function, v, NULL); vec_free (v); return ret; } /* Give a note about the location of the declaration of DECL. */ static void inform_declaration (tree decl) { if (decl && (TREE_CODE (decl) != FUNCTION_DECL || !DECL_IS_BUILTIN (decl))) inform (DECL_SOURCE_LOCATION (decl), "declared here"); } /* Build a function call to function FUNCTION with parameters PARAMS. If FUNCTION is the result of resolving an overloaded target built-in, ORIG_FUNDECL is the original function decl, otherwise it is null. ORIGTYPES, if not NULL, is a vector of types; each element is either NULL or the original type of the corresponding element in PARAMS. The original type may differ from TREE_TYPE of the parameter for enums. FUNCTION's data type may be a function type or pointer-to-function. This function changes the elements of PARAMS. */ tree build_function_call_vec (location_t loc, vec<location_t> arg_loc, tree function, vec<tree, va_gc> *params, vec<tree, va_gc> *origtypes, tree orig_fundecl) { tree fntype, fundecl = NULL_TREE; tree name = NULL_TREE, result; tree tem; int nargs; tree *argarray; /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */ STRIP_TYPE_NOPS (function); /* Convert anything with function type to a pointer-to-function. */ if (TREE_CODE (function) == FUNCTION_DECL) { name = DECL_NAME (function); if (flag_tm) tm_malloc_replacement (function); fundecl = function; if (!orig_fundecl) orig_fundecl = fundecl; /* Atomic functions have type checking/casting already done. They are often rewritten and don't match the original parameter list. */ if (name && !strncmp (IDENTIFIER_POINTER (name), "__atomic_", 9)) origtypes = NULL; } if (TREE_CODE (TREE_TYPE (function)) == FUNCTION_TYPE) function = function_to_pointer_conversion (loc, function); /* For Objective-C, convert any calls via a cast to OBJC_TYPE_REF expressions, like those used for ObjC messenger dispatches. */ if (params && !params->is_empty ()) function = objc_rewrite_function_call (function, (*params)[0]); function = c_fully_fold (function, false, NULL); fntype = TREE_TYPE (function); if (TREE_CODE (fntype) == ERROR_MARK) return error_mark_node; if (!(TREE_CODE (fntype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (fntype)) == FUNCTION_TYPE)) { if (!flag_diagnostics_show_caret && !STATEMENT_CLASS_P (function)) error_at (loc, "called object %qE is not a function or function pointer", function); else if (DECL_P (function)) { error_at (loc, "called object %qD is not a function or function pointer", function); inform_declaration (function); } else error_at (loc, "called object is not a function or function pointer"); return error_mark_node; } if (fundecl && TREE_THIS_VOLATILE (fundecl)) current_function_returns_abnormally = 1; /* fntype now gets the type of function pointed to. */ fntype = TREE_TYPE (fntype); /* Convert the parameters to the types declared in the function prototype, or apply default promotions. */ nargs = convert_arguments (loc, arg_loc, TYPE_ARG_TYPES (fntype), params, origtypes, function, fundecl); if (nargs < 0) return error_mark_node; /* Check that the function is called through a compatible prototype. If it is not, warn. */ if (CONVERT_EXPR_P (function) && TREE_CODE (tem = TREE_OPERAND (function, 0)) == ADDR_EXPR && TREE_CODE (tem = TREE_OPERAND (tem, 0)) == FUNCTION_DECL && !comptypes (fntype, TREE_TYPE (tem))) { tree return_type = TREE_TYPE (fntype); /* This situation leads to run-time undefined behavior. We can't, therefore, simply error unless we can prove that all possible executions of the program must execute the code. */ warning_at (loc, 0, "function called through a non-compatible type"); if (VOID_TYPE_P (return_type) && TYPE_QUALS (return_type) != TYPE_UNQUALIFIED) pedwarn (loc, 0, "function with qualified void return type called"); } argarray = vec_safe_address (params); /* Check that arguments to builtin functions match the expectations. */ if (fundecl && fndecl_built_in_p (fundecl) && !check_builtin_function_arguments (loc, arg_loc, fundecl, orig_fundecl, nargs, argarray)) return error_mark_node; /* Check that the arguments to the function are valid. */ bool warned_p = check_function_arguments (loc, fundecl, fntype, nargs, argarray, &arg_loc); if (name != NULL_TREE && !strncmp (IDENTIFIER_POINTER (name), "__builtin_", 10)) { if (require_constant_value) result = fold_build_call_array_initializer_loc (loc, TREE_TYPE (fntype), function, nargs, argarray); else result = fold_build_call_array_loc (loc, TREE_TYPE (fntype), function, nargs, argarray); if (TREE_CODE (result) == NOP_EXPR && TREE_CODE (TREE_OPERAND (result, 0)) == INTEGER_CST) STRIP_TYPE_NOPS (result); } else result = build_call_array_loc (loc, TREE_TYPE (fntype), function, nargs, argarray); /* If -Wnonnull warning has been diagnosed, avoid diagnosing it again later. */ if (warned_p && TREE_CODE (result) == CALL_EXPR) TREE_NO_WARNING (result) = 1; /* In this improbable scenario, a nested function returns a VM type. Create a TARGET_EXPR so that the call always has a LHS, much as what the C++ FE does for functions returning non-PODs. */ if (variably_modified_type_p (TREE_TYPE (fntype), NULL_TREE)) { tree tmp = create_tmp_var_raw (TREE_TYPE (fntype)); result = build4 (TARGET_EXPR, TREE_TYPE (fntype), tmp, result, NULL_TREE, NULL_TREE); } if (VOID_TYPE_P (TREE_TYPE (result))) { if (TYPE_QUALS (TREE_TYPE (result)) != TYPE_UNQUALIFIED) pedwarn (loc, 0, "function with qualified void return type called"); return result; } return require_complete_type (loc, result); } /* Like build_function_call_vec, but call also resolve_overloaded_builtin. */ tree c_build_function_call_vec (location_t loc, vec<location_t> arg_loc, tree function, vec<tree, va_gc> *params, vec<tree, va_gc> *origtypes) { /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */ STRIP_TYPE_NOPS (function); /* Convert anything with function type to a pointer-to-function. */ if (TREE_CODE (function) == FUNCTION_DECL) { /* Implement type-directed function overloading for builtins. resolve_overloaded_builtin and targetm.resolve_overloaded_builtin handle all the type checking. The result is a complete expression that implements this function call. */ tree tem = resolve_overloaded_builtin (loc, function, params); if (tem) return tem; } return build_function_call_vec (loc, arg_loc, function, params, origtypes); } /* Helper for convert_arguments called to convert the VALue of argument number ARGNUM from ORIGTYPE to the corresponding parameter number PARMNUM and TYPE. PLOC is the location where the conversion is being performed. FUNCTION and FUNDECL are the same as in convert_arguments. VALTYPE is the original type of VAL before the conversion and, for EXCESS_PRECISION_EXPR, the operand of the expression. NPC is true if VAL represents the null pointer constant (VAL itself will have been folded to an integer constant). RNAME is the same as FUNCTION except in Objective C when it's the function selector. EXCESS_PRECISION is true when VAL was originally represented as EXCESS_PRECISION_EXPR. WARNOPT is the same as in convert_for_assignment. */ static tree convert_argument (location_t ploc, tree function, tree fundecl, tree type, tree origtype, tree val, tree valtype, bool npc, tree rname, int parmnum, int argnum, bool excess_precision, int warnopt) { /* Formal parm type is specified by a function prototype. */ if (type == error_mark_node || !COMPLETE_TYPE_P (type)) { error_at (ploc, "type of formal parameter %d is incomplete", parmnum + 1); return val; } /* Optionally warn about conversions that differ from the default conversions. */ if (warn_traditional_conversion || warn_traditional) { unsigned int formal_prec = TYPE_PRECISION (type); if (INTEGRAL_TYPE_P (type) && TREE_CODE (valtype) == REAL_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as integer rather " "than floating due to prototype", argnum, rname); if (INTEGRAL_TYPE_P (type) && TREE_CODE (valtype) == COMPLEX_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as integer rather " "than complex due to prototype", argnum, rname); else if (TREE_CODE (type) == COMPLEX_TYPE && TREE_CODE (valtype) == REAL_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as complex rather " "than floating due to prototype", argnum, rname); else if (TREE_CODE (type) == REAL_TYPE && INTEGRAL_TYPE_P (valtype)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as floating rather " "than integer due to prototype", argnum, rname); else if (TREE_CODE (type) == COMPLEX_TYPE && INTEGRAL_TYPE_P (valtype)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as complex rather " "than integer due to prototype", argnum, rname); else if (TREE_CODE (type) == REAL_TYPE && TREE_CODE (valtype) == COMPLEX_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as floating rather " "than complex due to prototype", argnum, rname); /* ??? At some point, messages should be written about conversions between complex types, but that's too messy to do now. */ else if (TREE_CODE (type) == REAL_TYPE && TREE_CODE (valtype) == REAL_TYPE) { /* Warn if any argument is passed as `float', since without a prototype it would be `double'. */ if (formal_prec == TYPE_PRECISION (float_type_node) && type != dfloat32_type_node) warning_at (ploc, 0, "passing argument %d of %qE as %<float%> " "rather than %<double%> due to prototype", argnum, rname); /* Warn if mismatch between argument and prototype for decimal float types. Warn of conversions with binary float types and of precision narrowing due to prototype. */ else if (type != valtype && (type == dfloat32_type_node || type == dfloat64_type_node || type == dfloat128_type_node || valtype == dfloat32_type_node || valtype == dfloat64_type_node || valtype == dfloat128_type_node) && (formal_prec <= TYPE_PRECISION (valtype) || (type == dfloat128_type_node && (valtype != dfloat64_type_node && (valtype != dfloat32_type_node))) || (type == dfloat64_type_node && (valtype != dfloat32_type_node)))) warning_at (ploc, 0, "passing argument %d of %qE as %qT " "rather than %qT due to prototype", argnum, rname, type, valtype); } /* Detect integer changing in width or signedness. These warnings are only activated with -Wtraditional-conversion, not with -Wtraditional. */ else if (warn_traditional_conversion && INTEGRAL_TYPE_P (type) && INTEGRAL_TYPE_P (valtype)) { tree would_have_been = default_conversion (val); tree type1 = TREE_TYPE (would_have_been); if (val == error_mark_node) /* VAL could have been of incomplete type. */; else if (TREE_CODE (type) == ENUMERAL_TYPE && (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (valtype))) /* No warning if function asks for enum and the actual arg is that enum type. */ ; else if (formal_prec != TYPE_PRECISION (type1)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE " "with different width due to prototype", argnum, rname); else if (TYPE_UNSIGNED (type) == TYPE_UNSIGNED (type1)) ; /* Don't complain if the formal parameter type is an enum, because we can't tell now whether the value was an enum--even the same enum. */ else if (TREE_CODE (type) == ENUMERAL_TYPE) ; else if (TREE_CODE (val) == INTEGER_CST && int_fits_type_p (val, type)) /* Change in signedness doesn't matter if a constant value is unaffected. */ ; /* If the value is extended from a narrower unsigned type, it doesn't matter whether we pass it as signed or unsigned; the value certainly is the same either way. */ else if (TYPE_PRECISION (valtype) < TYPE_PRECISION (type) && TYPE_UNSIGNED (valtype)) ; else if (TYPE_UNSIGNED (type)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE " "as unsigned due to prototype", argnum, rname); else warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE " "as signed due to prototype", argnum, rname); } } /* Possibly restore an EXCESS_PRECISION_EXPR for the sake of better warnings from convert_and_check. */ if (excess_precision) val = build1 (EXCESS_PRECISION_EXPR, valtype, val); tree parmval = convert_for_assignment (ploc, ploc, type, val, origtype, ic_argpass, npc, fundecl, function, parmnum + 1, warnopt); if (targetm.calls.promote_prototypes (fundecl ? TREE_TYPE (fundecl) : 0) && INTEGRAL_TYPE_P (type) && (TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))) parmval = default_conversion (parmval); return parmval; } /* Convert the argument expressions in the vector VALUES to the types in the list TYPELIST. If TYPELIST is exhausted, or when an element has NULL as its type, perform the default conversions. ORIGTYPES is the original types of the expressions in VALUES. This holds the type of enum values which have been converted to integral types. It may be NULL. FUNCTION is a tree for the called function. It is used only for error messages, where it is formatted with %qE. This is also where warnings about wrong number of args are generated. ARG_LOC are locations of function arguments (if any). Returns the actual number of arguments processed (which may be less than the length of VALUES in some error situations), or -1 on failure. */ static int convert_arguments (location_t loc, vec<location_t> arg_loc, tree typelist, vec<tree, va_gc> *values, vec<tree, va_gc> *origtypes, tree function, tree fundecl) { unsigned int parmnum; bool error_args = false; const bool type_generic = fundecl && lookup_attribute ("type generic", TYPE_ATTRIBUTES (TREE_TYPE (fundecl))); bool type_generic_remove_excess_precision = false; bool type_generic_overflow_p = false; tree selector; /* Change pointer to function to the function itself for diagnostics. */ if (TREE_CODE (function) == ADDR_EXPR && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL) function = TREE_OPERAND (function, 0); /* Handle an ObjC selector specially for diagnostics. */ selector = objc_message_selector (); /* For a call to a built-in function declared without a prototype, set to the built-in function's argument list. */ tree builtin_typelist = NULL_TREE; /* For type-generic built-in functions, determine whether excess precision should be removed (classification) or not (comparison). */ if (fundecl && fndecl_built_in_p (fundecl, BUILT_IN_NORMAL)) { built_in_function code = DECL_FUNCTION_CODE (fundecl); if (C_DECL_BUILTIN_PROTOTYPE (fundecl)) { /* For a call to a built-in function declared without a prototype use the types of the parameters of the internal built-in to match those of the arguments to. */ if (tree bdecl = builtin_decl_explicit (code)) builtin_typelist = TYPE_ARG_TYPES (TREE_TYPE (bdecl)); } /* For type-generic built-in functions, determine whether excess precision should be removed (classification) or not (comparison). */ if (type_generic) switch (code) { case BUILT_IN_ISFINITE: case BUILT_IN_ISINF: case BUILT_IN_ISINF_SIGN: case BUILT_IN_ISNAN: case BUILT_IN_ISNORMAL: case BUILT_IN_FPCLASSIFY: type_generic_remove_excess_precision = true; break; case BUILT_IN_ADD_OVERFLOW_P: case BUILT_IN_SUB_OVERFLOW_P: case BUILT_IN_MUL_OVERFLOW_P: /* The last argument of these type-generic builtins should not be promoted. */ type_generic_overflow_p = true; break; default: break; } } /* Scan the given expressions (VALUES) and types (TYPELIST), producing individual converted arguments. */ tree typetail, builtin_typetail, val; for (typetail = typelist, builtin_typetail = builtin_typelist, parmnum = 0; values && values->iterate (parmnum, &val); ++parmnum) { /* The type of the function parameter (if it was declared with one). */ tree type = typetail ? TREE_VALUE (typetail) : NULL_TREE; /* The type of the built-in function parameter (if the function is a built-in). Used to detect type incompatibilities in calls to built-ins declared without a prototype. */ tree builtin_type = (builtin_typetail ? TREE_VALUE (builtin_typetail) : NULL_TREE); /* The original type of the argument being passed to the function. */ tree valtype = TREE_TYPE (val); /* The called function (or function selector in Objective C). */ tree rname = function; int argnum = parmnum + 1; const char *invalid_func_diag; /* Set for EXCESS_PRECISION_EXPR arguments. */ bool excess_precision = false; /* The value of the argument after conversion to the type of the function parameter it is passed to. */ tree parmval; /* Some __atomic_* builtins have additional hidden argument at position 0. */ location_t ploc = !arg_loc.is_empty () && values->length () == arg_loc.length () ? expansion_point_location_if_in_system_header (arg_loc[parmnum]) : input_location; if (type == void_type_node) { if (selector) error_at (loc, "too many arguments to method %qE", selector); else error_at (loc, "too many arguments to function %qE", function); inform_declaration (fundecl); return error_args ? -1 : (int) parmnum; } if (builtin_type == void_type_node) { if (warning_at (loc, OPT_Wbuiltin_declaration_mismatch, "too many arguments to built-in function %qE " "expecting %d", function, parmnum)) inform_declaration (fundecl); builtin_typetail = NULL_TREE; } if (selector && argnum > 2) { rname = selector; argnum -= 2; } /* Determine if VAL is a null pointer constant before folding it. */ bool npc = null_pointer_constant_p (val); /* If there is excess precision and a prototype, convert once to the required type rather than converting via the semantic type. Likewise without a prototype a float value represented as long double should be converted once to double. But for type-generic classification functions excess precision must be removed here. */ if (TREE_CODE (val) == EXCESS_PRECISION_EXPR && (type || !type_generic || !type_generic_remove_excess_precision)) { val = TREE_OPERAND (val, 0); excess_precision = true; } val = c_fully_fold (val, false, NULL); STRIP_TYPE_NOPS (val); val = require_complete_type (ploc, val); /* Some floating-point arguments must be promoted to double when no type is specified by a prototype. This applies to arguments of type float, and to architecture-specific types (ARM __fp16), but not to _FloatN or _FloatNx types. */ bool promote_float_arg = false; if (type == NULL_TREE && TREE_CODE (valtype) == REAL_TYPE && (TYPE_PRECISION (valtype) <= TYPE_PRECISION (double_type_node)) && TYPE_MAIN_VARIANT (valtype) != double_type_node && TYPE_MAIN_VARIANT (valtype) != long_double_type_node && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (valtype))) { /* Promote this argument, unless it has a _FloatN or _FloatNx type. */ promote_float_arg = true; for (int i = 0; i < NUM_FLOATN_NX_TYPES; i++) if (TYPE_MAIN_VARIANT (valtype) == FLOATN_NX_TYPE_NODE (i)) { promote_float_arg = false; break; } } if (type != NULL_TREE) { tree origtype = (!origtypes) ? NULL_TREE : (*origtypes)[parmnum]; parmval = convert_argument (ploc, function, fundecl, type, origtype, val, valtype, npc, rname, parmnum, argnum, excess_precision, 0); } else if (promote_float_arg) { if (type_generic) parmval = val; else { /* Convert `float' to `double'. */ if (warn_double_promotion && !c_inhibit_evaluation_warnings) warning_at (ploc, OPT_Wdouble_promotion, "implicit conversion from %qT to %qT when passing " "argument to function", valtype, double_type_node); parmval = convert (double_type_node, val); } } else if ((excess_precision && !type_generic) || (type_generic_overflow_p && parmnum == 2)) /* A "double" argument with excess precision being passed without a prototype or in variable arguments. The last argument of __builtin_*_overflow_p should not be promoted. */ parmval = convert (valtype, val); else if ((invalid_func_diag = targetm.calls.invalid_arg_for_unprototyped_fn (typelist, fundecl, val))) { error (invalid_func_diag); return -1; } else if (TREE_CODE (val) == ADDR_EXPR && reject_gcc_builtin (val)) { return -1; } else /* Convert `short' and `char' to full-size `int'. */ parmval = default_conversion (val); (*values)[parmnum] = parmval; if (parmval == error_mark_node) error_args = true; if (!type && builtin_type && TREE_CODE (builtin_type) != VOID_TYPE) { /* For a call to a built-in function declared without a prototype, perform the conversions from the argument to the expected type but issue warnings rather than errors for any mismatches. Ignore the converted argument and use the PARMVAL obtained above by applying default conversions instead. */ tree origtype = (!origtypes) ? NULL_TREE : (*origtypes)[parmnum]; convert_argument (ploc, function, fundecl, builtin_type, origtype, val, valtype, npc, rname, parmnum, argnum, excess_precision, OPT_Wbuiltin_declaration_mismatch); } if (typetail) typetail = TREE_CHAIN (typetail); if (builtin_typetail) builtin_typetail = TREE_CHAIN (builtin_typetail); } gcc_assert (parmnum == vec_safe_length (values)); if (typetail != NULL_TREE && TREE_VALUE (typetail) != void_type_node) { error_at (loc, "too few arguments to function %qE", function); inform_declaration (fundecl); return -1; } if (builtin_typetail && TREE_VALUE (builtin_typetail) != void_type_node) { unsigned nargs = parmnum; for (tree t = builtin_typetail; t; t = TREE_CHAIN (t)) ++nargs; if (warning_at (loc, OPT_Wbuiltin_declaration_mismatch, "too few arguments to built-in function %qE " "expecting %u", function, nargs - 1)) inform_declaration (fundecl); } return error_args ? -1 : (int) parmnum; } /* This is the entry point used by the parser to build unary operators in the input. CODE, a tree_code, specifies the unary operator, and ARG is the operand. For unary plus, the C parser currently uses CONVERT_EXPR for code. LOC is the location to use for the tree generated. */ struct c_expr parser_build_unary_op (location_t loc, enum tree_code code, struct c_expr arg) { struct c_expr result; result.original_code = code; result.original_type = NULL; if (reject_gcc_builtin (arg.value)) { result.value = error_mark_node; } else { result.value = build_unary_op (loc, code, arg.value, false); if (TREE_OVERFLOW_P (result.value) && !TREE_OVERFLOW_P (arg.value)) overflow_warning (loc, result.value, arg.value); } /* We are typically called when parsing a prefix token at LOC acting on ARG. Reflect this by updating the source range of the result to start at LOC and end at the end of ARG. */ set_c_expr_source_range (&result, loc, arg.get_finish ()); return result; } /* Returns true if TYPE is a character type, *not* including wchar_t. */ static bool char_type_p (tree type) { return (type == char_type_node || type == unsigned_char_type_node || type == signed_char_type_node || type == char16_type_node || type == char32_type_node); } /* This is the entry point used by the parser to build binary operators in the input. CODE, a tree_code, specifies the binary operator, and ARG1 and ARG2 are the operands. In addition to constructing the expression, we check for operands that were written with other binary operators in a way that is likely to confuse the user. LOCATION is the location of the binary operator. */ struct c_expr parser_build_binary_op (location_t location, enum tree_code code, struct c_expr arg1, struct c_expr arg2) { struct c_expr result; enum tree_code code1 = arg1.original_code; enum tree_code code2 = arg2.original_code; tree type1 = (arg1.original_type ? arg1.original_type : TREE_TYPE (arg1.value)); tree type2 = (arg2.original_type ? arg2.original_type : TREE_TYPE (arg2.value)); result.value = build_binary_op (location, code, arg1.value, arg2.value, true); result.original_code = code; result.original_type = NULL; if (TREE_CODE (result.value) == ERROR_MARK) { set_c_expr_source_range (&result, arg1.get_start (), arg2.get_finish ()); return result; } if (location != UNKNOWN_LOCATION) protected_set_expr_location (result.value, location); set_c_expr_source_range (&result, arg1.get_start (), arg2.get_finish ()); /* Check for cases such as x+y<<z which users are likely to misinterpret. */ if (warn_parentheses) warn_about_parentheses (location, code, code1, arg1.value, code2, arg2.value); if (warn_logical_op) warn_logical_operator (location, code, TREE_TYPE (result.value), code1, arg1.value, code2, arg2.value); if (warn_tautological_compare) { tree lhs = arg1.value; tree rhs = arg2.value; if (TREE_CODE (lhs) == C_MAYBE_CONST_EXPR) { if (C_MAYBE_CONST_EXPR_PRE (lhs) != NULL_TREE && TREE_SIDE_EFFECTS (C_MAYBE_CONST_EXPR_PRE (lhs))) lhs = NULL_TREE; else lhs = C_MAYBE_CONST_EXPR_EXPR (lhs); } if (TREE_CODE (rhs) == C_MAYBE_CONST_EXPR) { if (C_MAYBE_CONST_EXPR_PRE (rhs) != NULL_TREE && TREE_SIDE_EFFECTS (C_MAYBE_CONST_EXPR_PRE (rhs))) rhs = NULL_TREE; else rhs = C_MAYBE_CONST_EXPR_EXPR (rhs); } if (lhs != NULL_TREE && rhs != NULL_TREE) warn_tautological_cmp (location, code, lhs, rhs); } if (warn_logical_not_paren && TREE_CODE_CLASS (code) == tcc_comparison && code1 == TRUTH_NOT_EXPR && code2 != TRUTH_NOT_EXPR /* Avoid warning for !!x == y. */ && (TREE_CODE (arg1.value) != NE_EXPR || !integer_zerop (TREE_OPERAND (arg1.value, 1)))) { /* Avoid warning for !b == y where b has _Bool type. */ tree t = integer_zero_node; if (TREE_CODE (arg1.value) == EQ_EXPR && integer_zerop (TREE_OPERAND (arg1.value, 1)) && TREE_TYPE (TREE_OPERAND (arg1.value, 0)) == integer_type_node) { t = TREE_OPERAND (arg1.value, 0); do { if (TREE_TYPE (t) != integer_type_node) break; if (TREE_CODE (t) == C_MAYBE_CONST_EXPR) t = C_MAYBE_CONST_EXPR_EXPR (t); else if (CONVERT_EXPR_P (t)) t = TREE_OPERAND (t, 0); else break; } while (1); } if (TREE_CODE (TREE_TYPE (t)) != BOOLEAN_TYPE) warn_logical_not_parentheses (location, code, arg1.value, arg2.value); } /* Warn about comparisons against string literals, with the exception of testing for equality or inequality of a string literal with NULL. */ if (code == EQ_EXPR || code == NE_EXPR) { if ((code1 == STRING_CST && !integer_zerop (tree_strip_nop_conversions (arg2.value))) || (code2 == STRING_CST && !integer_zerop (tree_strip_nop_conversions (arg1.value)))) warning_at (location, OPT_Waddress, "comparison with string literal results in unspecified behavior"); /* Warn for ptr == '\0', it's likely that it should've been ptr[0]. */ if (POINTER_TYPE_P (type1) && null_pointer_constant_p (arg2.value) && char_type_p (type2)) { auto_diagnostic_group d; if (warning_at (location, OPT_Wpointer_compare, "comparison between pointer and zero character " "constant")) inform (arg1.get_start (), "did you mean to dereference the pointer?"); } else if (POINTER_TYPE_P (type2) && null_pointer_constant_p (arg1.value) && char_type_p (type1)) { auto_diagnostic_group d; if (warning_at (location, OPT_Wpointer_compare, "comparison between pointer and zero character " "constant")) inform (arg2.get_start (), "did you mean to dereference the pointer?"); } } else if (TREE_CODE_CLASS (code) == tcc_comparison && (code1 == STRING_CST || code2 == STRING_CST)) warning_at (location, OPT_Waddress, "comparison with string literal results in unspecified behavior"); if (TREE_OVERFLOW_P (result.value) && !TREE_OVERFLOW_P (arg1.value) && !TREE_OVERFLOW_P (arg2.value)) overflow_warning (location, result.value); /* Warn about comparisons of different enum types. */ if (warn_enum_compare && TREE_CODE_CLASS (code) == tcc_comparison && TREE_CODE (type1) == ENUMERAL_TYPE && TREE_CODE (type2) == ENUMERAL_TYPE && TYPE_MAIN_VARIANT (type1) != TYPE_MAIN_VARIANT (type2)) warning_at (location, OPT_Wenum_compare, "comparison between %qT and %qT", type1, type2); return result; } /* Return a tree for the difference of pointers OP0 and OP1. The resulting tree has type ptrdiff_t. If POINTER_SUBTRACT sanitization is enabled, assign to INSTRUMENT_EXPR call to libsanitizer. */ static tree pointer_diff (location_t loc, tree op0, tree op1, tree *instrument_expr) { tree restype = ptrdiff_type_node; tree result, inttype; addr_space_t as0 = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (op0))); addr_space_t as1 = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (op1))); tree target_type = TREE_TYPE (TREE_TYPE (op0)); tree orig_op0 = op0; tree orig_op1 = op1; /* If the operands point into different address spaces, we need to explicitly convert them to pointers into the common address space before we can subtract the numerical address values. */ if (as0 != as1) { addr_space_t as_common; tree common_type; /* Determine the common superset address space. This is guaranteed to exist because the caller verified that comp_target_types returned non-zero. */ if (!addr_space_superset (as0, as1, &as_common)) gcc_unreachable (); common_type = common_pointer_type (TREE_TYPE (op0), TREE_TYPE (op1)); op0 = convert (common_type, op0); op1 = convert (common_type, op1); } /* Determine integer type result of the subtraction. This will usually be the same as the result type (ptrdiff_t), but may need to be a wider type if pointers for the address space are wider than ptrdiff_t. */ if (TYPE_PRECISION (restype) < TYPE_PRECISION (TREE_TYPE (op0))) inttype = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op0)), 0); else inttype = restype; if (TREE_CODE (target_type) == VOID_TYPE) pedwarn (loc, OPT_Wpointer_arith, "pointer of type %<void *%> used in subtraction"); if (TREE_CODE (target_type) == FUNCTION_TYPE) pedwarn (loc, OPT_Wpointer_arith, "pointer to a function used in subtraction"); if (sanitize_flags_p (SANITIZE_POINTER_SUBTRACT)) { gcc_assert (current_function_decl != NULL_TREE); op0 = save_expr (op0); op1 = save_expr (op1); tree tt = builtin_decl_explicit (BUILT_IN_ASAN_POINTER_SUBTRACT); *instrument_expr = build_call_expr_loc (loc, tt, 2, op0, op1); } /* First do the subtraction, then build the divide operator and only convert at the very end. Do not do default conversions in case restype is a short type. */ /* POINTER_DIFF_EXPR requires a signed integer type of the same size as pointers. If some platform cannot provide that, or has a larger ptrdiff_type to support differences larger than half the address space, cast the pointers to some larger integer type and do the computations in that type. */ if (TYPE_PRECISION (inttype) > TYPE_PRECISION (TREE_TYPE (op0))) op0 = build_binary_op (loc, MINUS_EXPR, convert (inttype, op0), convert (inttype, op1), false); else { /* Cast away qualifiers. */ op0 = convert (c_common_type (TREE_TYPE (op0), TREE_TYPE (op0)), op0); op1 = convert (c_common_type (TREE_TYPE (op1), TREE_TYPE (op1)), op1); op0 = build2_loc (loc, POINTER_DIFF_EXPR, inttype, op0, op1); } /* This generates an error if op1 is pointer to incomplete type. */ if (!COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (TREE_TYPE (orig_op1)))) error_at (loc, "arithmetic on pointer to an incomplete type"); else if (verify_type_context (loc, TCTX_POINTER_ARITH, TREE_TYPE (TREE_TYPE (orig_op0)))) verify_type_context (loc, TCTX_POINTER_ARITH, TREE_TYPE (TREE_TYPE (orig_op1))); op1 = c_size_in_bytes (target_type); if (pointer_to_zero_sized_aggr_p (TREE_TYPE (orig_op1))) error_at (loc, "arithmetic on pointer to an empty aggregate"); /* Divide by the size, in easiest possible way. */ result = fold_build2_loc (loc, EXACT_DIV_EXPR, inttype, op0, convert (inttype, op1)); /* Convert to final result type if necessary. */ return convert (restype, result); } /* Expand atomic compound assignments into an appropriate sequence as specified by the C11 standard section 6.5.16.2. _Atomic T1 E1 T2 E2 E1 op= E2 This sequence is used for all types for which these operations are supported. In addition, built-in versions of the 'fe' prefixed routines may need to be invoked for floating point (real, complex or vector) when floating-point exceptions are supported. See 6.5.16.2 footnote 113. T1 newval; T1 old; T1 *addr T2 val fenv_t fenv addr = &E1; val = (E2); __atomic_load (addr, &old, SEQ_CST); feholdexcept (&fenv); loop: newval = old op val; if (__atomic_compare_exchange_strong (addr, &old, &newval, SEQ_CST, SEQ_CST)) goto done; feclearexcept (FE_ALL_EXCEPT); goto loop: done: feupdateenv (&fenv); The compiler will issue the __atomic_fetch_* built-in when possible, otherwise it will generate the generic form of the atomic operations. This requires temp(s) and has their address taken. The atomic processing is smart enough to figure out when the size of an object can utilize a lock-free version, and convert the built-in call to the appropriate lock-free routine. The optimizers will then dispose of any temps that are no longer required, and lock-free implementations are utilized as long as there is target support for the required size. If the operator is NOP_EXPR, then this is a simple assignment, and an __atomic_store is issued to perform the assignment rather than the above loop. */ /* Build an atomic assignment at LOC, expanding into the proper sequence to store LHS MODIFYCODE= RHS. Return a value representing the result of the operation, unless RETURN_OLD_P, in which case return the old value of LHS (this is only for postincrement and postdecrement). */ static tree build_atomic_assign (location_t loc, tree lhs, enum tree_code modifycode, tree rhs, bool return_old_p) { tree fndecl, func_call; vec<tree, va_gc> *params; tree val, nonatomic_lhs_type, nonatomic_rhs_type, newval, newval_addr; tree old, old_addr; tree compound_stmt; tree stmt, goto_stmt; tree loop_label, loop_decl, done_label, done_decl; tree lhs_type = TREE_TYPE (lhs); tree lhs_addr = build_unary_op (loc, ADDR_EXPR, lhs, false); tree seq_cst = build_int_cst (integer_type_node, MEMMODEL_SEQ_CST); tree rhs_semantic_type = TREE_TYPE (rhs); tree nonatomic_rhs_semantic_type; tree rhs_type; gcc_assert (TYPE_ATOMIC (lhs_type)); if (return_old_p) gcc_assert (modifycode == PLUS_EXPR || modifycode == MINUS_EXPR); /* Allocate enough vector items for a compare_exchange. */ vec_alloc (params, 6); /* Create a compound statement to hold the sequence of statements with a loop. */ compound_stmt = c_begin_compound_stmt (false); /* Remove any excess precision (which is only present here in the case of compound assignments). */ if (TREE_CODE (rhs) == EXCESS_PRECISION_EXPR) { gcc_assert (modifycode != NOP_EXPR); rhs = TREE_OPERAND (rhs, 0); } rhs_type = TREE_TYPE (rhs); /* Fold the RHS if it hasn't already been folded. */ if (modifycode != NOP_EXPR) rhs = c_fully_fold (rhs, false, NULL); /* Remove the qualifiers for the rest of the expressions and create the VAL temp variable to hold the RHS. */ nonatomic_lhs_type = build_qualified_type (lhs_type, TYPE_UNQUALIFIED); nonatomic_rhs_type = build_qualified_type (rhs_type, TYPE_UNQUALIFIED); nonatomic_rhs_semantic_type = build_qualified_type (rhs_semantic_type, TYPE_UNQUALIFIED); val = create_tmp_var_raw (nonatomic_rhs_type); TREE_ADDRESSABLE (val) = 1; TREE_NO_WARNING (val) = 1; rhs = build4 (TARGET_EXPR, nonatomic_rhs_type, val, rhs, NULL_TREE, NULL_TREE); SET_EXPR_LOCATION (rhs, loc); add_stmt (rhs); /* NOP_EXPR indicates it's a straight store of the RHS. Simply issue an atomic_store. */ if (modifycode == NOP_EXPR) { /* Build __atomic_store (&lhs, &val, SEQ_CST) */ rhs = build_unary_op (loc, ADDR_EXPR, val, false); fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_STORE); params->quick_push (lhs_addr); params->quick_push (rhs); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); add_stmt (func_call); /* Finish the compound statement. */ compound_stmt = c_end_compound_stmt (loc, compound_stmt, false); /* VAL is the value which was stored, return a COMPOUND_STMT of the statement and that value. */ return build2 (COMPOUND_EXPR, nonatomic_lhs_type, compound_stmt, val); } /* Attempt to implement the atomic operation as an __atomic_fetch_* or __atomic_*_fetch built-in rather than a CAS loop. atomic_bool type isn't applicable for such builtins. ??? Do we want to handle enums? */ if ((TREE_CODE (lhs_type) == INTEGER_TYPE || POINTER_TYPE_P (lhs_type)) && TREE_CODE (rhs_type) == INTEGER_TYPE) { built_in_function fncode; switch (modifycode) { case PLUS_EXPR: case POINTER_PLUS_EXPR: fncode = (return_old_p ? BUILT_IN_ATOMIC_FETCH_ADD_N : BUILT_IN_ATOMIC_ADD_FETCH_N); break; case MINUS_EXPR: fncode = (return_old_p ? BUILT_IN_ATOMIC_FETCH_SUB_N : BUILT_IN_ATOMIC_SUB_FETCH_N); break; case BIT_AND_EXPR: fncode = (return_old_p ? BUILT_IN_ATOMIC_FETCH_AND_N : BUILT_IN_ATOMIC_AND_FETCH_N); break; case BIT_IOR_EXPR: fncode = (return_old_p ? BUILT_IN_ATOMIC_FETCH_OR_N : BUILT_IN_ATOMIC_OR_FETCH_N); break; case BIT_XOR_EXPR: fncode = (return_old_p ? BUILT_IN_ATOMIC_FETCH_XOR_N : BUILT_IN_ATOMIC_XOR_FETCH_N); break; default: goto cas_loop; } /* We can only use "_1" through "_16" variants of the atomic fetch built-ins. */ unsigned HOST_WIDE_INT size = tree_to_uhwi (TYPE_SIZE_UNIT (lhs_type)); if (size != 1 && size != 2 && size != 4 && size != 8 && size != 16) goto cas_loop; /* If this is a pointer type, we need to multiply by the size of the pointer target type. */ if (POINTER_TYPE_P (lhs_type)) { if (!COMPLETE_TYPE_P (TREE_TYPE (lhs_type)) /* ??? This would introduce -Wdiscarded-qualifiers warning: __atomic_fetch_* expect volatile void * type as the first argument. (Assignments between atomic and non-atomic objects are OK.) */ || TYPE_RESTRICT (lhs_type)) goto cas_loop; tree sz = TYPE_SIZE_UNIT (TREE_TYPE (lhs_type)); rhs = fold_build2_loc (loc, MULT_EXPR, ptrdiff_type_node, convert (ptrdiff_type_node, rhs), convert (ptrdiff_type_node, sz)); } /* Build __atomic_fetch_* (&lhs, &val, SEQ_CST), or __atomic_*_fetch (&lhs, &val, SEQ_CST). */ fndecl = builtin_decl_explicit (fncode); params->quick_push (lhs_addr); params->quick_push (rhs); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); newval = create_tmp_var_raw (nonatomic_lhs_type); TREE_ADDRESSABLE (newval) = 1; TREE_NO_WARNING (newval) = 1; rhs = build4 (TARGET_EXPR, nonatomic_lhs_type, newval, func_call, NULL_TREE, NULL_TREE); SET_EXPR_LOCATION (rhs, loc); add_stmt (rhs); /* Finish the compound statement. */ compound_stmt = c_end_compound_stmt (loc, compound_stmt, false); /* NEWVAL is the value which was stored, return a COMPOUND_STMT of the statement and that value. */ return build2 (COMPOUND_EXPR, nonatomic_lhs_type, compound_stmt, newval); } cas_loop: /* Create the variables and labels required for the op= form. */ old = create_tmp_var_raw (nonatomic_lhs_type); old_addr = build_unary_op (loc, ADDR_EXPR, old, false); TREE_ADDRESSABLE (old) = 1; TREE_NO_WARNING (old) = 1; newval = create_tmp_var_raw (nonatomic_lhs_type); newval_addr = build_unary_op (loc, ADDR_EXPR, newval, false); TREE_ADDRESSABLE (newval) = 1; TREE_NO_WARNING (newval) = 1; loop_decl = create_artificial_label (loc); loop_label = build1 (LABEL_EXPR, void_type_node, loop_decl); done_decl = create_artificial_label (loc); done_label = build1 (LABEL_EXPR, void_type_node, done_decl); /* __atomic_load (addr, &old, SEQ_CST). */ fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_LOAD); params->quick_push (lhs_addr); params->quick_push (old_addr); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); old = build4 (TARGET_EXPR, nonatomic_lhs_type, old, func_call, NULL_TREE, NULL_TREE); add_stmt (old); params->truncate (0); /* Create the expressions for floating-point environment manipulation, if required. */ bool need_fenv = (flag_trapping_math && (FLOAT_TYPE_P (lhs_type) || FLOAT_TYPE_P (rhs_type))); tree hold_call = NULL_TREE, clear_call = NULL_TREE, update_call = NULL_TREE; if (need_fenv) targetm.atomic_assign_expand_fenv (&hold_call, &clear_call, &update_call); if (hold_call) add_stmt (hold_call); /* loop: */ add_stmt (loop_label); /* newval = old + val; */ if (rhs_type != rhs_semantic_type) val = build1 (EXCESS_PRECISION_EXPR, nonatomic_rhs_semantic_type, val); rhs = build_binary_op (loc, modifycode, old, val, true); if (TREE_CODE (rhs) == EXCESS_PRECISION_EXPR) { tree eptype = TREE_TYPE (rhs); rhs = c_fully_fold (TREE_OPERAND (rhs, 0), false, NULL); rhs = build1 (EXCESS_PRECISION_EXPR, eptype, rhs); } else rhs = c_fully_fold (rhs, false, NULL); rhs = convert_for_assignment (loc, UNKNOWN_LOCATION, nonatomic_lhs_type, rhs, NULL_TREE, ic_assign, false, NULL_TREE, NULL_TREE, 0); if (rhs != error_mark_node) { rhs = build4 (TARGET_EXPR, nonatomic_lhs_type, newval, rhs, NULL_TREE, NULL_TREE); SET_EXPR_LOCATION (rhs, loc); add_stmt (rhs); } /* if (__atomic_compare_exchange (addr, &old, &new, false, SEQ_CST, SEQ_CST)) goto done; */ fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_COMPARE_EXCHANGE); params->quick_push (lhs_addr); params->quick_push (old_addr); params->quick_push (newval_addr); params->quick_push (integer_zero_node); params->quick_push (seq_cst); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); goto_stmt = build1 (GOTO_EXPR, void_type_node, done_decl); SET_EXPR_LOCATION (goto_stmt, loc); stmt = build3 (COND_EXPR, void_type_node, func_call, goto_stmt, NULL_TREE); SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); if (clear_call) add_stmt (clear_call); /* goto loop; */ goto_stmt = build1 (GOTO_EXPR, void_type_node, loop_decl); SET_EXPR_LOCATION (goto_stmt, loc); add_stmt (goto_stmt); /* done: */ add_stmt (done_label); if (update_call) add_stmt (update_call); /* Finish the compound statement. */ compound_stmt = c_end_compound_stmt (loc, compound_stmt, false); /* NEWVAL is the value that was successfully stored, return a COMPOUND_EXPR of the statement and the appropriate value. */ return build2 (COMPOUND_EXPR, nonatomic_lhs_type, compound_stmt, return_old_p ? old : newval); } /* Construct and perhaps optimize a tree representation for a unary operation. CODE, a tree_code, specifies the operation and XARG is the operand. For any CODE other than ADDR_EXPR, NOCONVERT suppresses the default promotions (such as from short to int). For ADDR_EXPR, the default promotions are not applied; NOCONVERT allows non-lvalues; this is only used to handle conversion of non-lvalue arrays to pointers in C99. LOCATION is the location of the operator. */ tree build_unary_op (location_t location, enum tree_code code, tree xarg, bool noconvert) { /* No default_conversion here. It causes trouble for ADDR_EXPR. */ tree arg = xarg; tree argtype = NULL_TREE; enum tree_code typecode; tree val; tree ret = error_mark_node; tree eptype = NULL_TREE; const char *invalid_op_diag; bool int_operands; int_operands = EXPR_INT_CONST_OPERANDS (xarg); if (int_operands) arg = remove_c_maybe_const_expr (arg); if (code != ADDR_EXPR) arg = require_complete_type (location, arg); typecode = TREE_CODE (TREE_TYPE (arg)); if (typecode == ERROR_MARK) return error_mark_node; if (typecode == ENUMERAL_TYPE || typecode == BOOLEAN_TYPE) typecode = INTEGER_TYPE; if ((invalid_op_diag = targetm.invalid_unary_op (code, TREE_TYPE (xarg)))) { error_at (location, invalid_op_diag); return error_mark_node; } if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR) { eptype = TREE_TYPE (arg); arg = TREE_OPERAND (arg, 0); } switch (code) { case CONVERT_EXPR: /* This is used for unary plus, because a CONVERT_EXPR is enough to prevent anybody from looking inside for associativity, but won't generate any code. */ if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE || typecode == FIXED_POINT_TYPE || typecode == COMPLEX_TYPE || gnu_vector_type_p (TREE_TYPE (arg)))) { error_at (location, "wrong type argument to unary plus"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); arg = non_lvalue_loc (location, arg); break; case NEGATE_EXPR: if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE || typecode == FIXED_POINT_TYPE || typecode == COMPLEX_TYPE || gnu_vector_type_p (TREE_TYPE (arg)))) { error_at (location, "wrong type argument to unary minus"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); break; case BIT_NOT_EXPR: /* ~ works on integer types and non float vectors. */ if (typecode == INTEGER_TYPE || (gnu_vector_type_p (TREE_TYPE (arg)) && !VECTOR_FLOAT_TYPE_P (TREE_TYPE (arg)))) { tree e = arg; /* Warn if the expression has boolean value. */ while (TREE_CODE (e) == COMPOUND_EXPR) e = TREE_OPERAND (e, 1); if ((TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (e)))) { auto_diagnostic_group d; if (warning_at (location, OPT_Wbool_operation, "%<~%> on a boolean expression")) { gcc_rich_location richloc (location); richloc.add_fixit_insert_before (location, "!"); inform (&richloc, "did you mean to use logical not?"); } } if (!noconvert) arg = default_conversion (arg); } else if (typecode == COMPLEX_TYPE) { code = CONJ_EXPR; pedwarn (location, OPT_Wpedantic, "ISO C does not support %<~%> for complex conjugation"); if (!noconvert) arg = default_conversion (arg); } else { error_at (location, "wrong type argument to bit-complement"); return error_mark_node; } break; case ABS_EXPR: if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE)) { error_at (location, "wrong type argument to abs"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); break; case ABSU_EXPR: if (!(typecode == INTEGER_TYPE)) { error_at (location, "wrong type argument to absu"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); break; case CONJ_EXPR: /* Conjugating a real value is a no-op, but allow it anyway. */ if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE || typecode == COMPLEX_TYPE)) { error_at (location, "wrong type argument to conjugation"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); break; case TRUTH_NOT_EXPR: if (typecode != INTEGER_TYPE && typecode != FIXED_POINT_TYPE && typecode != REAL_TYPE && typecode != POINTER_TYPE && typecode != COMPLEX_TYPE) { error_at (location, "wrong type argument to unary exclamation mark"); return error_mark_node; } if (int_operands) { arg = c_objc_common_truthvalue_conversion (location, xarg); arg = remove_c_maybe_const_expr (arg); } else arg = c_objc_common_truthvalue_conversion (location, arg); ret = invert_truthvalue_loc (location, arg); /* If the TRUTH_NOT_EXPR has been folded, reset the location. */ if (EXPR_P (ret) && EXPR_HAS_LOCATION (ret)) location = EXPR_LOCATION (ret); goto return_build_unary_op; case REALPART_EXPR: case IMAGPART_EXPR: ret = build_real_imag_expr (location, code, arg); if (ret == error_mark_node) return error_mark_node; if (eptype && TREE_CODE (eptype) == COMPLEX_TYPE) eptype = TREE_TYPE (eptype); goto return_build_unary_op; case PREINCREMENT_EXPR: case POSTINCREMENT_EXPR: case PREDECREMENT_EXPR: case POSTDECREMENT_EXPR: if (TREE_CODE (arg) == C_MAYBE_CONST_EXPR) { tree inner = build_unary_op (location, code, C_MAYBE_CONST_EXPR_EXPR (arg), noconvert); if (inner == error_mark_node) return error_mark_node; ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (inner), C_MAYBE_CONST_EXPR_PRE (arg), inner); gcc_assert (!C_MAYBE_CONST_EXPR_INT_OPERANDS (arg)); C_MAYBE_CONST_EXPR_NON_CONST (ret) = 1; goto return_build_unary_op; } /* Complain about anything that is not a true lvalue. In Objective-C, skip this check for property_refs. */ if (!objc_is_property_ref (arg) && !lvalue_or_else (location, arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? lv_increment : lv_decrement))) return error_mark_node; if (warn_cxx_compat && TREE_CODE (TREE_TYPE (arg)) == ENUMERAL_TYPE) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) warning_at (location, OPT_Wc___compat, "increment of enumeration value is invalid in C++"); else warning_at (location, OPT_Wc___compat, "decrement of enumeration value is invalid in C++"); } if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) warning_at (location, OPT_Wbool_operation, "increment of a boolean expression"); else warning_at (location, OPT_Wbool_operation, "decrement of a boolean expression"); } /* Ensure the argument is fully folded inside any SAVE_EXPR. */ arg = c_fully_fold (arg, false, NULL, true); bool atomic_op; atomic_op = really_atomic_lvalue (arg); /* Increment or decrement the real part of the value, and don't change the imaginary part. */ if (typecode == COMPLEX_TYPE) { tree real, imag; pedwarn (location, OPT_Wpedantic, "ISO C does not support %<++%> and %<--%> on complex types"); if (!atomic_op) { arg = stabilize_reference (arg); real = build_unary_op (EXPR_LOCATION (arg), REALPART_EXPR, arg, true); imag = build_unary_op (EXPR_LOCATION (arg), IMAGPART_EXPR, arg, true); real = build_unary_op (EXPR_LOCATION (arg), code, real, true); if (real == error_mark_node || imag == error_mark_node) return error_mark_node; ret = build2 (COMPLEX_EXPR, TREE_TYPE (arg), real, imag); goto return_build_unary_op; } } /* Report invalid types. */ if (typecode != POINTER_TYPE && typecode != FIXED_POINT_TYPE && typecode != INTEGER_TYPE && typecode != REAL_TYPE && typecode != COMPLEX_TYPE && !gnu_vector_type_p (TREE_TYPE (arg))) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) error_at (location, "wrong type argument to increment"); else error_at (location, "wrong type argument to decrement"); return error_mark_node; } { tree inc; argtype = TREE_TYPE (arg); /* Compute the increment. */ if (typecode == POINTER_TYPE) { /* If pointer target is an incomplete type, we just cannot know how to do the arithmetic. */ if (!COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (argtype))) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) error_at (location, "increment of pointer to an incomplete type %qT", TREE_TYPE (argtype)); else error_at (location, "decrement of pointer to an incomplete type %qT", TREE_TYPE (argtype)); } else if (TREE_CODE (TREE_TYPE (argtype)) == FUNCTION_TYPE || TREE_CODE (TREE_TYPE (argtype)) == VOID_TYPE) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) pedwarn (location, OPT_Wpointer_arith, "wrong type argument to increment"); else pedwarn (location, OPT_Wpointer_arith, "wrong type argument to decrement"); } else verify_type_context (location, TCTX_POINTER_ARITH, TREE_TYPE (argtype)); inc = c_size_in_bytes (TREE_TYPE (argtype)); inc = convert_to_ptrofftype_loc (location, inc); } else if (FRACT_MODE_P (TYPE_MODE (argtype))) { /* For signed fract types, we invert ++ to -- or -- to ++, and change inc from 1 to -1, because it is not possible to represent 1 in signed fract constants. For unsigned fract types, the result always overflows and we get an undefined (original) or the maximum value. */ if (code == PREINCREMENT_EXPR) code = PREDECREMENT_EXPR; else if (code == PREDECREMENT_EXPR) code = PREINCREMENT_EXPR; else if (code == POSTINCREMENT_EXPR) code = POSTDECREMENT_EXPR; else /* code == POSTDECREMENT_EXPR */ code = POSTINCREMENT_EXPR; inc = integer_minus_one_node; inc = convert (argtype, inc); } else { inc = VECTOR_TYPE_P (argtype) ? build_one_cst (argtype) : integer_one_node; inc = convert (argtype, inc); } /* If 'arg' is an Objective-C PROPERTY_REF expression, then we need to ask Objective-C to build the increment or decrement expression for it. */ if (objc_is_property_ref (arg)) return objc_build_incr_expr_for_property_ref (location, code, arg, inc); /* Report a read-only lvalue. */ if (TYPE_READONLY (argtype)) { readonly_error (location, arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? lv_increment : lv_decrement)); return error_mark_node; } else if (TREE_READONLY (arg)) readonly_warning (arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? lv_increment : lv_decrement)); /* If the argument is atomic, use the special code sequences for atomic compound assignment. */ if (atomic_op) { arg = stabilize_reference (arg); ret = build_atomic_assign (location, arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? PLUS_EXPR : MINUS_EXPR), (FRACT_MODE_P (TYPE_MODE (argtype)) ? inc : integer_one_node), (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)); goto return_build_unary_op; } if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE) val = boolean_increment (code, arg); else val = build2 (code, TREE_TYPE (arg), arg, inc); TREE_SIDE_EFFECTS (val) = 1; if (TREE_CODE (val) != code) TREE_NO_WARNING (val) = 1; ret = val; goto return_build_unary_op; } case ADDR_EXPR: /* Note that this operation never does default_conversion. */ /* The operand of unary '&' must be an lvalue (which excludes expressions of type void), or, in C99, the result of a [] or unary '*' operator. */ if (VOID_TYPE_P (TREE_TYPE (arg)) && TYPE_QUALS (TREE_TYPE (arg)) == TYPE_UNQUALIFIED && (!INDIRECT_REF_P (arg) || !flag_isoc99)) pedwarn (location, 0, "taking address of expression of type %<void%>"); /* Let &* cancel out to simplify resulting code. */ if (INDIRECT_REF_P (arg)) { /* Don't let this be an lvalue. */ if (lvalue_p (TREE_OPERAND (arg, 0))) return non_lvalue_loc (location, TREE_OPERAND (arg, 0)); ret = TREE_OPERAND (arg, 0); goto return_build_unary_op; } /* Anything not already handled and not a true memory reference or a non-lvalue array is an error. */ if (typecode != FUNCTION_TYPE && !noconvert && !lvalue_or_else (location, arg, lv_addressof)) return error_mark_node; /* Move address operations inside C_MAYBE_CONST_EXPR to simplify folding later. */ if (TREE_CODE (arg) == C_MAYBE_CONST_EXPR) { tree inner = build_unary_op (location, code, C_MAYBE_CONST_EXPR_EXPR (arg), noconvert); ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (inner), C_MAYBE_CONST_EXPR_PRE (arg), inner); gcc_assert (!C_MAYBE_CONST_EXPR_INT_OPERANDS (arg)); C_MAYBE_CONST_EXPR_NON_CONST (ret) = C_MAYBE_CONST_EXPR_NON_CONST (arg); goto return_build_unary_op; } /* Ordinary case; arg is a COMPONENT_REF or a decl. */ argtype = TREE_TYPE (arg); /* If the lvalue is const or volatile, merge that into the type to which the address will point. This is only needed for function types. */ if ((DECL_P (arg) || REFERENCE_CLASS_P (arg)) && (TREE_READONLY (arg) || TREE_THIS_VOLATILE (arg)) && TREE_CODE (argtype) == FUNCTION_TYPE) { int orig_quals = TYPE_QUALS (strip_array_types (argtype)); int quals = orig_quals; if (TREE_READONLY (arg)) quals |= TYPE_QUAL_CONST; if (TREE_THIS_VOLATILE (arg)) quals |= TYPE_QUAL_VOLATILE; argtype = c_build_qualified_type (argtype, quals); } switch (TREE_CODE (arg)) { case COMPONENT_REF: if (DECL_C_BIT_FIELD (TREE_OPERAND (arg, 1))) { error_at (location, "cannot take address of bit-field %qD", TREE_OPERAND (arg, 1)); return error_mark_node; } /* fall through */ case ARRAY_REF: if (TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_OPERAND (arg, 0)))) { if (!AGGREGATE_TYPE_P (TREE_TYPE (arg)) && !VECTOR_TYPE_P (TREE_TYPE (arg))) { error_at (location, "cannot take address of scalar with " "reverse storage order"); return error_mark_node; } if (TREE_CODE (TREE_TYPE (arg)) == ARRAY_TYPE && TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (arg))) warning_at (location, OPT_Wscalar_storage_order, "address of array with reverse scalar storage " "order requested"); } default: break; } if (!c_mark_addressable (arg)) return error_mark_node; gcc_assert (TREE_CODE (arg) != COMPONENT_REF || !DECL_C_BIT_FIELD (TREE_OPERAND (arg, 1))); argtype = build_pointer_type (argtype); /* ??? Cope with user tricks that amount to offsetof. Delete this when we have proper support for integer constant expressions. */ val = get_base_address (arg); if (val && INDIRECT_REF_P (val) && TREE_CONSTANT (TREE_OPERAND (val, 0))) { ret = fold_offsetof (arg, argtype); goto return_build_unary_op; } val = build1 (ADDR_EXPR, argtype, arg); ret = val; goto return_build_unary_op; default: gcc_unreachable (); } if (argtype == NULL_TREE) argtype = TREE_TYPE (arg); if (TREE_CODE (arg) == INTEGER_CST) ret = (require_constant_value ? fold_build1_initializer_loc (location, code, argtype, arg) : fold_build1_loc (location, code, argtype, arg)); else ret = build1 (code, argtype, arg); return_build_unary_op: gcc_assert (ret != error_mark_node); if (TREE_CODE (ret) == INTEGER_CST && !TREE_OVERFLOW (ret) && !(TREE_CODE (xarg) == INTEGER_CST && !TREE_OVERFLOW (xarg))) ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret); else if (TREE_CODE (ret) != INTEGER_CST && int_operands) ret = note_integer_operands (ret); if (eptype) ret = build1 (EXCESS_PRECISION_EXPR, eptype, ret); protected_set_expr_location (ret, location); return ret; } /* Return nonzero if REF is an lvalue valid for this language. Lvalues can be assigned, unless their type has TYPE_READONLY. Lvalues can have their address taken, unless they have C_DECL_REGISTER. */ bool lvalue_p (const_tree ref) { const enum tree_code code = TREE_CODE (ref); switch (code) { case REALPART_EXPR: case IMAGPART_EXPR: case COMPONENT_REF: return lvalue_p (TREE_OPERAND (ref, 0)); case C_MAYBE_CONST_EXPR: return lvalue_p (TREE_OPERAND (ref, 1)); case COMPOUND_LITERAL_EXPR: case STRING_CST: return true; case INDIRECT_REF: case ARRAY_REF: case VAR_DECL: case PARM_DECL: case RESULT_DECL: case ERROR_MARK: return (TREE_CODE (TREE_TYPE (ref)) != FUNCTION_TYPE && TREE_CODE (TREE_TYPE (ref)) != METHOD_TYPE); case BIND_EXPR: return TREE_CODE (TREE_TYPE (ref)) == ARRAY_TYPE; default: return false; } } /* Give a warning for storing in something that is read-only in GCC terms but not const in ISO C terms. */ static void readonly_warning (tree arg, enum lvalue_use use) { switch (use) { case lv_assign: warning (0, "assignment of read-only location %qE", arg); break; case lv_increment: warning (0, "increment of read-only location %qE", arg); break; case lv_decrement: warning (0, "decrement of read-only location %qE", arg); break; default: gcc_unreachable (); } return; } /* Return nonzero if REF is an lvalue valid for this language; otherwise, print an error message and return zero. USE says how the lvalue is being used and so selects the error message. LOCATION is the location at which any error should be reported. */ static int lvalue_or_else (location_t loc, const_tree ref, enum lvalue_use use) { int win = lvalue_p (ref); if (!win) lvalue_error (loc, use); return win; } /* Mark EXP saying that we need to be able to take the address of it; it should not be allocated in a register. Returns true if successful. ARRAY_REF_P is true if this is for ARRAY_REF construction - in that case we don't want to look through VIEW_CONVERT_EXPR from VECTOR_TYPE to ARRAY_TYPE, it is fine to use ARRAY_REFs for vector subscripts on vector register variables. */ bool c_mark_addressable (tree exp, bool array_ref_p) { tree x = exp; while (1) switch (TREE_CODE (x)) { case VIEW_CONVERT_EXPR: if (array_ref_p && TREE_CODE (TREE_TYPE (x)) == ARRAY_TYPE && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (x, 0)))) return true; /* FALLTHRU */ case COMPONENT_REF: case ADDR_EXPR: case ARRAY_REF: case REALPART_EXPR: case IMAGPART_EXPR: x = TREE_OPERAND (x, 0); break; case COMPOUND_LITERAL_EXPR: TREE_ADDRESSABLE (x) = 1; TREE_ADDRESSABLE (COMPOUND_LITERAL_EXPR_DECL (x)) = 1; return true; case CONSTRUCTOR: TREE_ADDRESSABLE (x) = 1; return true; case VAR_DECL: case CONST_DECL: case PARM_DECL: case RESULT_DECL: if (C_DECL_REGISTER (x) && DECL_NONLOCAL (x)) { if (TREE_PUBLIC (x) || is_global_var (x)) { error ("global register variable %qD used in nested function", x); return false; } pedwarn (input_location, 0, "register variable %qD used in nested function", x); } else if (C_DECL_REGISTER (x)) { if (TREE_PUBLIC (x) || is_global_var (x)) error ("address of global register variable %qD requested", x); else error ("address of register variable %qD requested", x); return false; } /* FALLTHRU */ case FUNCTION_DECL: TREE_ADDRESSABLE (x) = 1; /* FALLTHRU */ default: return true; } } /* Convert EXPR to TYPE, warning about conversion problems with constants. SEMANTIC_TYPE is the type this conversion would use without excess precision. If SEMANTIC_TYPE is NULL, this function is equivalent to convert_and_check. This function is a wrapper that handles conversions that may be different than the usual ones because of excess precision. */ static tree ep_convert_and_check (location_t loc, tree type, tree expr, tree semantic_type) { if (TREE_TYPE (expr) == type) return expr; /* For C11, integer conversions may have results with excess precision. */ if (flag_isoc11 || !semantic_type) return convert_and_check (loc, type, expr); if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE && TREE_TYPE (expr) != semantic_type) { /* For integers, we need to check the real conversion, not the conversion to the excess precision type. */ expr = convert_and_check (loc, semantic_type, expr); } /* Result type is the excess precision type, which should be large enough, so do not check. */ return convert (type, expr); } /* If EXPR refers to a built-in declared without a prototype returns the actual type of the built-in and, if non-null, set *BLTIN to a pointer to the built-in. Otherwise return the type of EXPR and clear *BLTIN if non-null. */ static tree type_or_builtin_type (tree expr, tree *bltin = NULL) { tree dummy; if (!bltin) bltin = &dummy; *bltin = NULL_TREE; tree type = TREE_TYPE (expr); if (TREE_CODE (expr) != ADDR_EXPR) return type; tree oper = TREE_OPERAND (expr, 0); if (!DECL_P (oper) || TREE_CODE (oper) != FUNCTION_DECL || !fndecl_built_in_p (oper, BUILT_IN_NORMAL)) return type; built_in_function code = DECL_FUNCTION_CODE (oper); if (!C_DECL_BUILTIN_PROTOTYPE (oper)) return type; if ((*bltin = builtin_decl_implicit (code))) type = build_pointer_type (TREE_TYPE (*bltin)); return type; } /* Build and return a conditional expression IFEXP ? OP1 : OP2. If IFEXP_BCP then the condition is a call to __builtin_constant_p, and if folded to an integer constant then the unselected half may contain arbitrary operations not normally permitted in constant expressions. Set the location of the expression to LOC. */ tree build_conditional_expr (location_t colon_loc, tree ifexp, bool ifexp_bcp, tree op1, tree op1_original_type, location_t op1_loc, tree op2, tree op2_original_type, location_t op2_loc) { tree type1; tree type2; enum tree_code code1; enum tree_code code2; tree result_type = NULL; tree semantic_result_type = NULL; tree orig_op1 = op1, orig_op2 = op2; bool int_const, op1_int_operands, op2_int_operands, int_operands; bool ifexp_int_operands; tree ret; op1_int_operands = EXPR_INT_CONST_OPERANDS (orig_op1); if (op1_int_operands) op1 = remove_c_maybe_const_expr (op1); op2_int_operands = EXPR_INT_CONST_OPERANDS (orig_op2); if (op2_int_operands) op2 = remove_c_maybe_const_expr (op2); ifexp_int_operands = EXPR_INT_CONST_OPERANDS (ifexp); if (ifexp_int_operands) ifexp = remove_c_maybe_const_expr (ifexp); /* Promote both alternatives. */ if (TREE_CODE (TREE_TYPE (op1)) != VOID_TYPE) op1 = default_conversion (op1); if (TREE_CODE (TREE_TYPE (op2)) != VOID_TYPE) op2 = default_conversion (op2); if (TREE_CODE (ifexp) == ERROR_MARK || TREE_CODE (TREE_TYPE (op1)) == ERROR_MARK || TREE_CODE (TREE_TYPE (op2)) == ERROR_MARK) return error_mark_node; tree bltin1 = NULL_TREE; tree bltin2 = NULL_TREE; type1 = type_or_builtin_type (op1, &bltin1); code1 = TREE_CODE (type1); type2 = type_or_builtin_type (op2, &bltin2); code2 = TREE_CODE (type2); if (code1 == POINTER_TYPE && reject_gcc_builtin (op1)) return error_mark_node; if (code2 == POINTER_TYPE && reject_gcc_builtin (op2)) return error_mark_node; /* C90 does not permit non-lvalue arrays in conditional expressions. In C99 they will be pointers by now. */ if (code1 == ARRAY_TYPE || code2 == ARRAY_TYPE) { error_at (colon_loc, "non-lvalue array in conditional expression"); return error_mark_node; } if ((TREE_CODE (op1) == EXCESS_PRECISION_EXPR || TREE_CODE (op2) == EXCESS_PRECISION_EXPR) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE) && (code2 == INTEGER_TYPE || code2 == REAL_TYPE || code2 == COMPLEX_TYPE)) { semantic_result_type = c_common_type (type1, type2); if (TREE_CODE (op1) == EXCESS_PRECISION_EXPR) { op1 = TREE_OPERAND (op1, 0); type1 = TREE_TYPE (op1); gcc_assert (TREE_CODE (type1) == code1); } if (TREE_CODE (op2) == EXCESS_PRECISION_EXPR) { op2 = TREE_OPERAND (op2, 0); type2 = TREE_TYPE (op2); gcc_assert (TREE_CODE (type2) == code2); } } if (warn_cxx_compat) { tree t1 = op1_original_type ? op1_original_type : TREE_TYPE (orig_op1); tree t2 = op2_original_type ? op2_original_type : TREE_TYPE (orig_op2); if (TREE_CODE (t1) == ENUMERAL_TYPE && TREE_CODE (t2) == ENUMERAL_TYPE && TYPE_MAIN_VARIANT (t1) != TYPE_MAIN_VARIANT (t2)) warning_at (colon_loc, OPT_Wc___compat, ("different enum types in conditional is " "invalid in C++: %qT vs %qT"), t1, t2); } /* Quickly detect the usual case where op1 and op2 have the same type after promotion. */ if (TYPE_MAIN_VARIANT (type1) == TYPE_MAIN_VARIANT (type2)) { if (type1 == type2) result_type = type1; else result_type = TYPE_MAIN_VARIANT (type1); } else if ((code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE) && (code2 == INTEGER_TYPE || code2 == REAL_TYPE || code2 == COMPLEX_TYPE)) { /* In C11, a conditional expression between a floating-point type and an integer type should convert the integer type to the evaluation format of the floating-point type, with possible excess precision. */ tree eptype1 = type1; tree eptype2 = type2; if (flag_isoc11) { tree eptype; if (ANY_INTEGRAL_TYPE_P (type1) && (eptype = excess_precision_type (type2)) != NULL_TREE) { eptype2 = eptype; if (!semantic_result_type) semantic_result_type = c_common_type (type1, type2); } else if (ANY_INTEGRAL_TYPE_P (type2) && (eptype = excess_precision_type (type1)) != NULL_TREE) { eptype1 = eptype; if (!semantic_result_type) semantic_result_type = c_common_type (type1, type2); } } result_type = c_common_type (eptype1, eptype2); if (result_type == error_mark_node) return error_mark_node; do_warn_double_promotion (result_type, type1, type2, "implicit conversion from %qT to %qT to " "match other result of conditional", colon_loc); /* If -Wsign-compare, warn here if type1 and type2 have different signedness. We'll promote the signed to unsigned and later code won't know it used to be different. Do this check on the original types, so that explicit casts will be considered, but default promotions won't. */ if (c_inhibit_evaluation_warnings == 0) { int unsigned_op1 = TYPE_UNSIGNED (TREE_TYPE (orig_op1)); int unsigned_op2 = TYPE_UNSIGNED (TREE_TYPE (orig_op2)); if (unsigned_op1 ^ unsigned_op2) { bool ovf; /* Do not warn if the result type is signed, since the signed type will only be chosen if it can represent all the values of the unsigned type. */ if (!TYPE_UNSIGNED (result_type)) /* OK */; else { bool op1_maybe_const = true; bool op2_maybe_const = true; /* Do not warn if the signed quantity is an unsuffixed integer literal (or some static constant expression involving such literals) and it is non-negative. This warning requires the operands to be folded for best results, so do that folding in this case even without warn_sign_compare to avoid warning options possibly affecting code generation. */ c_inhibit_evaluation_warnings += (ifexp == truthvalue_false_node); op1 = c_fully_fold (op1, require_constant_value, &op1_maybe_const); c_inhibit_evaluation_warnings -= (ifexp == truthvalue_false_node); c_inhibit_evaluation_warnings += (ifexp == truthvalue_true_node); op2 = c_fully_fold (op2, require_constant_value, &op2_maybe_const); c_inhibit_evaluation_warnings -= (ifexp == truthvalue_true_node); if (warn_sign_compare) { if ((unsigned_op2 && tree_expr_nonnegative_warnv_p (op1, &ovf)) || (unsigned_op1 && tree_expr_nonnegative_warnv_p (op2, &ovf))) /* OK */; else if (unsigned_op2) warning_at (op1_loc, OPT_Wsign_compare, "operand of %<?:%> changes signedness from " "%qT to %qT due to unsignedness of other " "operand", TREE_TYPE (orig_op1), TREE_TYPE (orig_op2)); else warning_at (op2_loc, OPT_Wsign_compare, "operand of %<?:%> changes signedness from " "%qT to %qT due to unsignedness of other " "operand", TREE_TYPE (orig_op2), TREE_TYPE (orig_op1)); } if (!op1_maybe_const || TREE_CODE (op1) != INTEGER_CST) op1 = c_wrap_maybe_const (op1, !op1_maybe_const); if (!op2_maybe_const || TREE_CODE (op2) != INTEGER_CST) op2 = c_wrap_maybe_const (op2, !op2_maybe_const); } } } } else if (code1 == VOID_TYPE || code2 == VOID_TYPE) { if (code1 != VOID_TYPE || code2 != VOID_TYPE) pedwarn (colon_loc, OPT_Wpedantic, "ISO C forbids conditional expr with only one void side"); result_type = void_type_node; } else if (code1 == POINTER_TYPE && code2 == POINTER_TYPE) { addr_space_t as1 = TYPE_ADDR_SPACE (TREE_TYPE (type1)); addr_space_t as2 = TYPE_ADDR_SPACE (TREE_TYPE (type2)); addr_space_t as_common; if (comp_target_types (colon_loc, type1, type2)) result_type = common_pointer_type (type1, type2); else if (null_pointer_constant_p (orig_op1)) result_type = type2; else if (null_pointer_constant_p (orig_op2)) result_type = type1; else if (!addr_space_superset (as1, as2, &as_common)) { error_at (colon_loc, "pointers to disjoint address spaces " "used in conditional expression"); return error_mark_node; } else if (VOID_TYPE_P (TREE_TYPE (type1)) && !TYPE_ATOMIC (TREE_TYPE (type1))) { if ((TREE_CODE (TREE_TYPE (type2)) == ARRAY_TYPE) && (TYPE_QUALS (strip_array_types (TREE_TYPE (type2))) & ~TYPE_QUALS (TREE_TYPE (type1)))) warning_at (colon_loc, OPT_Wdiscarded_array_qualifiers, "pointer to array loses qualifier " "in conditional expression"); if (TREE_CODE (TREE_TYPE (type2)) == FUNCTION_TYPE) pedwarn (colon_loc, OPT_Wpedantic, "ISO C forbids conditional expr between " "%<void *%> and function pointer"); result_type = build_pointer_type (qualify_type (TREE_TYPE (type1), TREE_TYPE (type2))); } else if (VOID_TYPE_P (TREE_TYPE (type2)) && !TYPE_ATOMIC (TREE_TYPE (type2))) { if ((TREE_CODE (TREE_TYPE (type1)) == ARRAY_TYPE) && (TYPE_QUALS (strip_array_types (TREE_TYPE (type1))) & ~TYPE_QUALS (TREE_TYPE (type2)))) warning_at (colon_loc, OPT_Wdiscarded_array_qualifiers, "pointer to array loses qualifier " "in conditional expression"); if (TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE) pedwarn (colon_loc, OPT_Wpedantic, "ISO C forbids conditional expr between " "%<void *%> and function pointer"); result_type = build_pointer_type (qualify_type (TREE_TYPE (type2), TREE_TYPE (type1))); } /* Objective-C pointer comparisons are a bit more lenient. */ else if (objc_have_common_type (type1, type2, -3, NULL_TREE)) result_type = objc_common_type (type1, type2); else { int qual = ENCODE_QUAL_ADDR_SPACE (as_common); if (bltin1 && bltin2) warning_at (colon_loc, OPT_Wincompatible_pointer_types, "pointer type mismatch between %qT and %qT " "of %qD and %qD in conditional expression", type1, type2, bltin1, bltin2); else pedwarn (colon_loc, 0, "pointer type mismatch in conditional expression"); result_type = build_pointer_type (build_qualified_type (void_type_node, qual)); } } else if (code1 == POINTER_TYPE && code2 == INTEGER_TYPE) { if (!null_pointer_constant_p (orig_op2)) pedwarn (colon_loc, 0, "pointer/integer type mismatch in conditional expression"); else { op2 = null_pointer_node; } result_type = type1; } else if (code2 == POINTER_TYPE && code1 == INTEGER_TYPE) { if (!null_pointer_constant_p (orig_op1)) pedwarn (colon_loc, 0, "pointer/integer type mismatch in conditional expression"); else { op1 = null_pointer_node; } result_type = type2; } if (!result_type) { if (flag_cond_mismatch) result_type = void_type_node; else { error_at (colon_loc, "type mismatch in conditional expression"); return error_mark_node; } } /* Merge const and volatile flags of the incoming types. */ result_type = build_type_variant (result_type, TYPE_READONLY (type1) || TYPE_READONLY (type2), TYPE_VOLATILE (type1) || TYPE_VOLATILE (type2)); op1 = ep_convert_and_check (colon_loc, result_type, op1, semantic_result_type); op2 = ep_convert_and_check (colon_loc, result_type, op2, semantic_result_type); if (ifexp_bcp && ifexp == truthvalue_true_node) { op2_int_operands = true; op1 = c_fully_fold (op1, require_constant_value, NULL); } if (ifexp_bcp && ifexp == truthvalue_false_node) { op1_int_operands = true; op2 = c_fully_fold (op2, require_constant_value, NULL); } int_const = int_operands = (ifexp_int_operands && op1_int_operands && op2_int_operands); if (int_operands) { int_const = ((ifexp == truthvalue_true_node && TREE_CODE (orig_op1) == INTEGER_CST && !TREE_OVERFLOW (orig_op1)) || (ifexp == truthvalue_false_node && TREE_CODE (orig_op2) == INTEGER_CST && !TREE_OVERFLOW (orig_op2))); } /* Need to convert condition operand into a vector mask. */ if (VECTOR_TYPE_P (TREE_TYPE (ifexp))) { tree vectype = TREE_TYPE (ifexp); tree elem_type = TREE_TYPE (vectype); tree zero = build_int_cst (elem_type, 0); tree zero_vec = build_vector_from_val (vectype, zero); tree cmp_type = truth_type_for (vectype); ifexp = build2 (NE_EXPR, cmp_type, ifexp, zero_vec); } if (int_const || (ifexp_bcp && TREE_CODE (ifexp) == INTEGER_CST)) ret = fold_build3_loc (colon_loc, COND_EXPR, result_type, ifexp, op1, op2); else { if (int_operands) { /* Use c_fully_fold here, since C_MAYBE_CONST_EXPR might be nested inside of the expression. */ op1 = c_fully_fold (op1, false, NULL); op2 = c_fully_fold (op2, false, NULL); } ret = build3 (COND_EXPR, result_type, ifexp, op1, op2); if (int_operands) ret = note_integer_operands (ret); } if (semantic_result_type) ret = build1 (EXCESS_PRECISION_EXPR, semantic_result_type, ret); protected_set_expr_location (ret, colon_loc); /* If the OP1 and OP2 are the same and don't have side-effects, warn here, because the COND_EXPR will be turned into OP1. */ if (warn_duplicated_branches && TREE_CODE (ret) == COND_EXPR && (op1 == op2 || operand_equal_p (op1, op2, 0))) warning_at (EXPR_LOCATION (ret), OPT_Wduplicated_branches, "this condition has identical branches"); return ret; } /* Return a compound expression that performs two expressions and returns the value of the second of them. LOC is the location of the COMPOUND_EXPR. */ tree build_compound_expr (location_t loc, tree expr1, tree expr2) { bool expr1_int_operands, expr2_int_operands; tree eptype = NULL_TREE; tree ret; expr1_int_operands = EXPR_INT_CONST_OPERANDS (expr1); if (expr1_int_operands) expr1 = remove_c_maybe_const_expr (expr1); expr2_int_operands = EXPR_INT_CONST_OPERANDS (expr2); if (expr2_int_operands) expr2 = remove_c_maybe_const_expr (expr2); if (TREE_CODE (expr1) == EXCESS_PRECISION_EXPR) expr1 = TREE_OPERAND (expr1, 0); if (TREE_CODE (expr2) == EXCESS_PRECISION_EXPR) { eptype = TREE_TYPE (expr2); expr2 = TREE_OPERAND (expr2, 0); } if (!TREE_SIDE_EFFECTS (expr1)) { /* The left-hand operand of a comma expression is like an expression statement: with -Wunused, we should warn if it doesn't have any side-effects, unless it was explicitly cast to (void). */ if (warn_unused_value) { if (VOID_TYPE_P (TREE_TYPE (expr1)) && CONVERT_EXPR_P (expr1)) ; /* (void) a, b */ else if (VOID_TYPE_P (TREE_TYPE (expr1)) && TREE_CODE (expr1) == COMPOUND_EXPR && CONVERT_EXPR_P (TREE_OPERAND (expr1, 1))) ; /* (void) a, (void) b, c */ else warning_at (loc, OPT_Wunused_value, "left-hand operand of comma expression has no effect"); } } else if (TREE_CODE (expr1) == COMPOUND_EXPR && warn_unused_value) { tree r = expr1; location_t cloc = loc; while (TREE_CODE (r) == COMPOUND_EXPR) { if (EXPR_HAS_LOCATION (r)) cloc = EXPR_LOCATION (r); r = TREE_OPERAND (r, 1); } if (!TREE_SIDE_EFFECTS (r) && !VOID_TYPE_P (TREE_TYPE (r)) && !CONVERT_EXPR_P (r)) warning_at (cloc, OPT_Wunused_value, "right-hand operand of comma expression has no effect"); } /* With -Wunused, we should also warn if the left-hand operand does have side-effects, but computes a value which is not used. For example, in `foo() + bar(), baz()' the result of the `+' operator is not used, so we should issue a warning. */ else if (warn_unused_value) warn_if_unused_value (expr1, loc); if (expr2 == error_mark_node) return error_mark_node; ret = build2 (COMPOUND_EXPR, TREE_TYPE (expr2), expr1, expr2); if (flag_isoc99 && expr1_int_operands && expr2_int_operands) ret = note_integer_operands (ret); if (eptype) ret = build1 (EXCESS_PRECISION_EXPR, eptype, ret); protected_set_expr_location (ret, loc); return ret; } /* Issue -Wcast-qual warnings when appropriate. TYPE is the type to which we are casting. OTYPE is the type of the expression being cast. Both TYPE and OTYPE are pointer types. LOC is the location of the cast. -Wcast-qual appeared on the command line. Named address space qualifiers are not handled here, because they result in different warnings. */ static void handle_warn_cast_qual (location_t loc, tree type, tree otype) { tree in_type = type; tree in_otype = otype; int added = 0; int discarded = 0; bool is_const; /* Check that the qualifiers on IN_TYPE are a superset of the qualifiers of IN_OTYPE. The outermost level of POINTER_TYPE nodes is uninteresting and we stop as soon as we hit a non-POINTER_TYPE node on either type. */ do { in_otype = TREE_TYPE (in_otype); in_type = TREE_TYPE (in_type); /* GNU C allows cv-qualified function types. 'const' means the function is very pure, 'volatile' means it can't return. We need to warn when such qualifiers are added, not when they're taken away. */ if (TREE_CODE (in_otype) == FUNCTION_TYPE && TREE_CODE (in_type) == FUNCTION_TYPE) added |= (TYPE_QUALS_NO_ADDR_SPACE (in_type) & ~TYPE_QUALS_NO_ADDR_SPACE (in_otype)); else discarded |= (TYPE_QUALS_NO_ADDR_SPACE (in_otype) & ~TYPE_QUALS_NO_ADDR_SPACE (in_type)); } while (TREE_CODE (in_type) == POINTER_TYPE && TREE_CODE (in_otype) == POINTER_TYPE); if (added) warning_at (loc, OPT_Wcast_qual, "cast adds %q#v qualifier to function type", added); if (discarded) /* There are qualifiers present in IN_OTYPE that are not present in IN_TYPE. */ warning_at (loc, OPT_Wcast_qual, "cast discards %qv qualifier from pointer target type", discarded); if (added || discarded) return; /* A cast from **T to const **T is unsafe, because it can cause a const value to be changed with no additional warning. We only issue this warning if T is the same on both sides, and we only issue the warning if there are the same number of pointers on both sides, as otherwise the cast is clearly unsafe anyhow. A cast is unsafe when a qualifier is added at one level and const is not present at all outer levels. To issue this warning, we check at each level whether the cast adds new qualifiers not already seen. We don't need to special case function types, as they won't have the same TYPE_MAIN_VARIANT. */ if (TYPE_MAIN_VARIANT (in_type) != TYPE_MAIN_VARIANT (in_otype)) return; if (TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE) return; in_type = type; in_otype = otype; is_const = TYPE_READONLY (TREE_TYPE (in_type)); do { in_type = TREE_TYPE (in_type); in_otype = TREE_TYPE (in_otype); if ((TYPE_QUALS (in_type) &~ TYPE_QUALS (in_otype)) != 0 && !is_const) { warning_at (loc, OPT_Wcast_qual, "to be safe all intermediate pointers in cast from " "%qT to %qT must be %<const%> qualified", otype, type); break; } if (is_const) is_const = TYPE_READONLY (in_type); } while (TREE_CODE (in_type) == POINTER_TYPE); } /* Heuristic check if two parameter types can be considered ABI-equivalent. */ static bool c_safe_arg_type_equiv_p (tree t1, tree t2) { t1 = TYPE_MAIN_VARIANT (t1); t2 = TYPE_MAIN_VARIANT (t2); if (TREE_CODE (t1) == POINTER_TYPE && TREE_CODE (t2) == POINTER_TYPE) return true; /* The signedness of the parameter matters only when an integral type smaller than int is promoted to int, otherwise only the precision of the parameter matters. This check should make sure that the callee does not see undefined values in argument registers. */ if (INTEGRAL_TYPE_P (t1) && INTEGRAL_TYPE_P (t2) && TYPE_PRECISION (t1) == TYPE_PRECISION (t2) && (TYPE_UNSIGNED (t1) == TYPE_UNSIGNED (t2) || !targetm.calls.promote_prototypes (NULL_TREE) || TYPE_PRECISION (t1) >= TYPE_PRECISION (integer_type_node))) return true; return comptypes (t1, t2); } /* Check if a type cast between two function types can be considered safe. */ static bool c_safe_function_type_cast_p (tree t1, tree t2) { if (TREE_TYPE (t1) == void_type_node && TYPE_ARG_TYPES (t1) == void_list_node) return true; if (TREE_TYPE (t2) == void_type_node && TYPE_ARG_TYPES (t2) == void_list_node) return true; if (!c_safe_arg_type_equiv_p (TREE_TYPE (t1), TREE_TYPE (t2))) return false; for (t1 = TYPE_ARG_TYPES (t1), t2 = TYPE_ARG_TYPES (t2); t1 && t2; t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2)) if (!c_safe_arg_type_equiv_p (TREE_VALUE (t1), TREE_VALUE (t2))) return false; return true; } /* Build an expression representing a cast to type TYPE of expression EXPR. LOC is the location of the cast-- typically the open paren of the cast. */ tree build_c_cast (location_t loc, tree type, tree expr) { tree value; bool int_operands = EXPR_INT_CONST_OPERANDS (expr); if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR) expr = TREE_OPERAND (expr, 0); value = expr; if (int_operands) value = remove_c_maybe_const_expr (value); if (type == error_mark_node || expr == error_mark_node) return error_mark_node; /* The ObjC front-end uses TYPE_MAIN_VARIANT to tie together types differing only in <protocol> qualifications. But when constructing cast expressions, the protocols do matter and must be kept around. */ if (objc_is_object_ptr (type) && objc_is_object_ptr (TREE_TYPE (expr))) return build1 (NOP_EXPR, type, expr); type = TYPE_MAIN_VARIANT (type); if (TREE_CODE (type) == ARRAY_TYPE) { error_at (loc, "cast specifies array type"); return error_mark_node; } if (TREE_CODE (type) == FUNCTION_TYPE) { error_at (loc, "cast specifies function type"); return error_mark_node; } if (!VOID_TYPE_P (type)) { value = require_complete_type (loc, value); if (value == error_mark_node) return error_mark_node; } if (type == TYPE_MAIN_VARIANT (TREE_TYPE (value))) { if (RECORD_OR_UNION_TYPE_P (type)) pedwarn (loc, OPT_Wpedantic, "ISO C forbids casting nonscalar to the same type"); /* Convert to remove any qualifiers from VALUE's type. */ value = convert (type, value); } else if (TREE_CODE (type) == UNION_TYPE) { tree field; for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field)) if (TREE_TYPE (field) != error_mark_node && comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (field)), TYPE_MAIN_VARIANT (TREE_TYPE (value)))) break; if (field) { tree t; bool maybe_const = true; pedwarn (loc, OPT_Wpedantic, "ISO C forbids casts to union type"); t = c_fully_fold (value, false, &maybe_const); t = build_constructor_single (type, field, t); if (!maybe_const) t = c_wrap_maybe_const (t, true); t = digest_init (loc, type, t, NULL_TREE, false, true, 0); TREE_CONSTANT (t) = TREE_CONSTANT (value); return t; } error_at (loc, "cast to union type from type not present in union"); return error_mark_node; } else { tree otype, ovalue; if (type == void_type_node) { tree t = build1 (CONVERT_EXPR, type, value); SET_EXPR_LOCATION (t, loc); return t; } otype = TREE_TYPE (value); /* Optionally warn about potentially worrisome casts. */ if (warn_cast_qual && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE) handle_warn_cast_qual (loc, type, otype); /* Warn about conversions between pointers to disjoint address spaces. */ if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && !null_pointer_constant_p (value)) { addr_space_t as_to = TYPE_ADDR_SPACE (TREE_TYPE (type)); addr_space_t as_from = TYPE_ADDR_SPACE (TREE_TYPE (otype)); addr_space_t as_common; if (!addr_space_superset (as_to, as_from, &as_common)) { if (ADDR_SPACE_GENERIC_P (as_from)) warning_at (loc, 0, "cast to %s address space pointer " "from disjoint generic address space pointer", c_addr_space_name (as_to)); else if (ADDR_SPACE_GENERIC_P (as_to)) warning_at (loc, 0, "cast to generic address space pointer " "from disjoint %s address space pointer", c_addr_space_name (as_from)); else warning_at (loc, 0, "cast to %s address space pointer " "from disjoint %s address space pointer", c_addr_space_name (as_to), c_addr_space_name (as_from)); } } /* Warn about possible alignment problems. */ if ((STRICT_ALIGNMENT || warn_cast_align == 2) && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (otype)) != VOID_TYPE && TREE_CODE (TREE_TYPE (otype)) != FUNCTION_TYPE /* Don't warn about opaque types, where the actual alignment restriction is unknown. */ && !(RECORD_OR_UNION_TYPE_P (TREE_TYPE (otype)) && TYPE_MODE (TREE_TYPE (otype)) == VOIDmode) && min_align_of_type (TREE_TYPE (type)) > min_align_of_type (TREE_TYPE (otype))) warning_at (loc, OPT_Wcast_align, "cast increases required alignment of target type"); if (TREE_CODE (type) == INTEGER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TYPE_PRECISION (type) != TYPE_PRECISION (otype)) /* Unlike conversion of integers to pointers, where the warning is disabled for converting constants because of cases such as SIG_*, warn about converting constant pointers to integers. In some cases it may cause unwanted sign extension, and a warning is appropriate. */ warning_at (loc, OPT_Wpointer_to_int_cast, "cast from pointer to integer of different size"); if (TREE_CODE (value) == CALL_EXPR && TREE_CODE (type) != TREE_CODE (otype)) warning_at (loc, OPT_Wbad_function_cast, "cast from function call of type %qT " "to non-matching type %qT", otype, type); if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == INTEGER_TYPE && TYPE_PRECISION (type) != TYPE_PRECISION (otype) /* Don't warn about converting any constant. */ && !TREE_CONSTANT (value)) warning_at (loc, OPT_Wint_to_pointer_cast, "cast to pointer from integer " "of different size"); if (warn_strict_aliasing <= 2) strict_aliasing_warning (EXPR_LOCATION (value), type, expr); /* If pedantic, warn for conversions between function and object pointer types, except for converting a null pointer constant to function pointer type. */ if (pedantic && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (otype)) == FUNCTION_TYPE && TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE) pedwarn (loc, OPT_Wpedantic, "ISO C forbids " "conversion of function pointer to object pointer type"); if (pedantic && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE && TREE_CODE (TREE_TYPE (otype)) != FUNCTION_TYPE && !null_pointer_constant_p (value)) pedwarn (loc, OPT_Wpedantic, "ISO C forbids " "conversion of object pointer to function pointer type"); if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE && TREE_CODE (TREE_TYPE (otype)) == FUNCTION_TYPE && !c_safe_function_type_cast_p (TREE_TYPE (type), TREE_TYPE (otype))) warning_at (loc, OPT_Wcast_function_type, "cast between incompatible function types" " from %qT to %qT", otype, type); ovalue = value; value = convert (type, value); /* Ignore any integer overflow caused by the cast. */ if (TREE_CODE (value) == INTEGER_CST && !FLOAT_TYPE_P (otype)) { if (CONSTANT_CLASS_P (ovalue) && TREE_OVERFLOW (ovalue)) { if (!TREE_OVERFLOW (value)) { /* Avoid clobbering a shared constant. */ value = copy_node (value); TREE_OVERFLOW (value) = TREE_OVERFLOW (ovalue); } } else if (TREE_OVERFLOW (value)) /* Reset VALUE's overflow flags, ensuring constant sharing. */ value = wide_int_to_tree (TREE_TYPE (value), wi::to_wide (value)); } } /* Don't let a cast be an lvalue. */ if (lvalue_p (value)) value = non_lvalue_loc (loc, value); /* Don't allow the results of casting to floating-point or complex types be confused with actual constants, or casts involving integer and pointer types other than direct integer-to-integer and integer-to-pointer be confused with integer constant expressions and null pointer constants. */ if (TREE_CODE (value) == REAL_CST || TREE_CODE (value) == COMPLEX_CST || (TREE_CODE (value) == INTEGER_CST && !((TREE_CODE (expr) == INTEGER_CST && INTEGRAL_TYPE_P (TREE_TYPE (expr))) || TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == COMPLEX_CST))) value = build1 (NOP_EXPR, type, value); /* If the expression has integer operands and so can occur in an unevaluated part of an integer constant expression, ensure the return value reflects this. */ if (int_operands && INTEGRAL_TYPE_P (type) && !EXPR_INT_CONST_OPERANDS (value)) value = note_integer_operands (value); protected_set_expr_location (value, loc); return value; } /* Interpret a cast of expression EXPR to type TYPE. LOC is the location of the open paren of the cast, or the position of the cast expr. */ tree c_cast_expr (location_t loc, struct c_type_name *type_name, tree expr) { tree type; tree type_expr = NULL_TREE; bool type_expr_const = true; tree ret; int saved_wsp = warn_strict_prototypes; /* This avoids warnings about unprototyped casts on integers. E.g. "#define SIG_DFL (void(*)())0". */ if (TREE_CODE (expr) == INTEGER_CST) warn_strict_prototypes = 0; type = groktypename (type_name, &type_expr, &type_expr_const); warn_strict_prototypes = saved_wsp; if (TREE_CODE (expr) == ADDR_EXPR && !VOID_TYPE_P (type) && reject_gcc_builtin (expr)) return error_mark_node; ret = build_c_cast (loc, type, expr); if (type_expr) { bool inner_expr_const = true; ret = c_fully_fold (ret, require_constant_value, &inner_expr_const); ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (ret), type_expr, ret); C_MAYBE_CONST_EXPR_NON_CONST (ret) = !(type_expr_const && inner_expr_const); SET_EXPR_LOCATION (ret, loc); } if (!EXPR_HAS_LOCATION (ret)) protected_set_expr_location (ret, loc); /* C++ does not permits types to be defined in a cast, but it allows references to incomplete types. */ if (warn_cxx_compat && type_name->specs->typespec_kind == ctsk_tagdef) warning_at (loc, OPT_Wc___compat, "defining a type in a cast is invalid in C++"); return ret; } /* Build an assignment expression of lvalue LHS from value RHS. If LHS_ORIGTYPE is not NULL, it is the original type of LHS, which may differ from TREE_TYPE (LHS) for an enum bitfield. MODIFYCODE is the code for a binary operator that we use to combine the old value of LHS with RHS to get the new value. Or else MODIFYCODE is NOP_EXPR meaning do a simple assignment. If RHS_ORIGTYPE is not NULL_TREE, it is the original type of RHS, which may differ from TREE_TYPE (RHS) for an enum value. LOCATION is the location of the MODIFYCODE operator. RHS_LOC is the location of the RHS. */ tree build_modify_expr (location_t location, tree lhs, tree lhs_origtype, enum tree_code modifycode, location_t rhs_loc, tree rhs, tree rhs_origtype) { tree result; tree newrhs; tree rhseval = NULL_TREE; tree lhstype = TREE_TYPE (lhs); tree olhstype = lhstype; bool npc; bool is_atomic_op; /* Types that aren't fully specified cannot be used in assignments. */ lhs = require_complete_type (location, lhs); /* Avoid duplicate error messages from operands that had errors. */ if (TREE_CODE (lhs) == ERROR_MARK || TREE_CODE (rhs) == ERROR_MARK) return error_mark_node; /* Ensure an error for assigning a non-lvalue array to an array in C90. */ if (TREE_CODE (lhstype) == ARRAY_TYPE) { error_at (location, "assignment to expression with array type"); return error_mark_node; } /* For ObjC properties, defer this check. */ if (!objc_is_property_ref (lhs) && !lvalue_or_else (location, lhs, lv_assign)) return error_mark_node; is_atomic_op = really_atomic_lvalue (lhs); newrhs = rhs; if (TREE_CODE (lhs) == C_MAYBE_CONST_EXPR) { tree inner = build_modify_expr (location, C_MAYBE_CONST_EXPR_EXPR (lhs), lhs_origtype, modifycode, rhs_loc, rhs, rhs_origtype); if (inner == error_mark_node) return error_mark_node; result = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (inner), C_MAYBE_CONST_EXPR_PRE (lhs), inner); gcc_assert (!C_MAYBE_CONST_EXPR_INT_OPERANDS (lhs)); C_MAYBE_CONST_EXPR_NON_CONST (result) = 1; protected_set_expr_location (result, location); return result; } /* If a binary op has been requested, combine the old LHS value with the RHS producing the value we should actually store into the LHS. */ if (modifycode != NOP_EXPR) { lhs = c_fully_fold (lhs, false, NULL, true); lhs = stabilize_reference (lhs); /* Construct the RHS for any non-atomic compound assignemnt. */ if (!is_atomic_op) { /* If in LHS op= RHS the RHS has side-effects, ensure they are preevaluated before the rest of the assignment expression's side-effects, because RHS could contain e.g. function calls that modify LHS. */ if (TREE_SIDE_EFFECTS (rhs)) { if (TREE_CODE (rhs) == EXCESS_PRECISION_EXPR) newrhs = save_expr (TREE_OPERAND (rhs, 0)); else newrhs = save_expr (rhs); rhseval = newrhs; if (TREE_CODE (rhs) == EXCESS_PRECISION_EXPR) newrhs = build1 (EXCESS_PRECISION_EXPR, TREE_TYPE (rhs), newrhs); } newrhs = build_binary_op (location, modifycode, lhs, newrhs, true); /* The original type of the right hand side is no longer meaningful. */ rhs_origtype = NULL_TREE; } } if (c_dialect_objc ()) { /* Check if we are modifying an Objective-C property reference; if so, we need to generate setter calls. */ if (TREE_CODE (newrhs) == EXCESS_PRECISION_EXPR) result = objc_maybe_build_modify_expr (lhs, TREE_OPERAND (newrhs, 0)); else result = objc_maybe_build_modify_expr (lhs, newrhs); if (result) goto return_result; /* Else, do the check that we postponed for Objective-C. */ if (!lvalue_or_else (location, lhs, lv_assign)) return error_mark_node; } /* Give an error for storing in something that is 'const'. */ if (TYPE_READONLY (lhstype) || (RECORD_OR_UNION_TYPE_P (lhstype) && C_TYPE_FIELDS_READONLY (lhstype))) { readonly_error (location, lhs, lv_assign); return error_mark_node; } else if (TREE_READONLY (lhs)) readonly_warning (lhs, lv_assign); /* If storing into a structure or union member, it has probably been given type `int'. Compute the type that would go with the actual amount of storage the member occupies. */ if (TREE_CODE (lhs) == COMPONENT_REF && (TREE_CODE (lhstype) == INTEGER_TYPE || TREE_CODE (lhstype) == BOOLEAN_TYPE || TREE_CODE (lhstype) == REAL_TYPE || TREE_CODE (lhstype) == ENUMERAL_TYPE)) lhstype = TREE_TYPE (get_unwidened (lhs, 0)); /* If storing in a field that is in actuality a short or narrower than one, we must store in the field in its actual type. */ if (lhstype != TREE_TYPE (lhs)) { lhs = copy_node (lhs); TREE_TYPE (lhs) = lhstype; } /* Issue -Wc++-compat warnings about an assignment to an enum type when LHS does not have its original type. This happens for, e.g., an enum bitfield in a struct. */ if (warn_cxx_compat && lhs_origtype != NULL_TREE && lhs_origtype != lhstype && TREE_CODE (lhs_origtype) == ENUMERAL_TYPE) { tree checktype = (rhs_origtype != NULL_TREE ? rhs_origtype : TREE_TYPE (rhs)); if (checktype != error_mark_node && (TYPE_MAIN_VARIANT (checktype) != TYPE_MAIN_VARIANT (lhs_origtype) || (is_atomic_op && modifycode != NOP_EXPR))) warning_at (location, OPT_Wc___compat, "enum conversion in assignment is invalid in C++"); } /* If the lhs is atomic, remove that qualifier. */ if (is_atomic_op) { lhstype = build_qualified_type (lhstype, (TYPE_QUALS (lhstype) & ~TYPE_QUAL_ATOMIC)); olhstype = build_qualified_type (olhstype, (TYPE_QUALS (lhstype) & ~TYPE_QUAL_ATOMIC)); } /* Convert new value to destination type. Fold it first, then restore any excess precision information, for the sake of conversion warnings. */ if (!(is_atomic_op && modifycode != NOP_EXPR)) { tree rhs_semantic_type = NULL_TREE; if (!c_in_omp_for) { if (TREE_CODE (newrhs) == EXCESS_PRECISION_EXPR) { rhs_semantic_type = TREE_TYPE (newrhs); newrhs = TREE_OPERAND (newrhs, 0); } npc = null_pointer_constant_p (newrhs); newrhs = c_fully_fold (newrhs, false, NULL); if (rhs_semantic_type) newrhs = build1 (EXCESS_PRECISION_EXPR, rhs_semantic_type, newrhs); } else npc = null_pointer_constant_p (newrhs); newrhs = convert_for_assignment (location, rhs_loc, lhstype, newrhs, rhs_origtype, ic_assign, npc, NULL_TREE, NULL_TREE, 0); if (TREE_CODE (newrhs) == ERROR_MARK) return error_mark_node; } /* Emit ObjC write barrier, if necessary. */ if (c_dialect_objc () && flag_objc_gc) { result = objc_generate_write_barrier (lhs, modifycode, newrhs); if (result) { protected_set_expr_location (result, location); goto return_result; } } /* Scan operands. */ if (is_atomic_op) result = build_atomic_assign (location, lhs, modifycode, newrhs, false); else { result = build2 (MODIFY_EXPR, lhstype, lhs, newrhs); TREE_SIDE_EFFECTS (result) = 1; protected_set_expr_location (result, location); } /* If we got the LHS in a different type for storing in, convert the result back to the nominal type of LHS so that the value we return always has the same type as the LHS argument. */ if (olhstype == TREE_TYPE (result)) goto return_result; result = convert_for_assignment (location, rhs_loc, olhstype, result, rhs_origtype, ic_assign, false, NULL_TREE, NULL_TREE, 0); protected_set_expr_location (result, location); return_result: if (rhseval) result = build2 (COMPOUND_EXPR, TREE_TYPE (result), rhseval, result); return result; } /* Return whether STRUCT_TYPE has an anonymous field with type TYPE. This is used to implement -fplan9-extensions. */ static bool find_anonymous_field_with_type (tree struct_type, tree type) { tree field; bool found; gcc_assert (RECORD_OR_UNION_TYPE_P (struct_type)); found = false; for (field = TYPE_FIELDS (struct_type); field != NULL_TREE; field = TREE_CHAIN (field)) { tree fieldtype = (TYPE_ATOMIC (TREE_TYPE (field)) ? c_build_qualified_type (TREE_TYPE (field), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (field))); if (DECL_NAME (field) == NULL && comptypes (type, fieldtype)) { if (found) return false; found = true; } else if (DECL_NAME (field) == NULL && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field)) && find_anonymous_field_with_type (TREE_TYPE (field), type)) { if (found) return false; found = true; } } return found; } /* RHS is an expression whose type is pointer to struct. If there is an anonymous field in RHS with type TYPE, then return a pointer to that field in RHS. This is used with -fplan9-extensions. This returns NULL if no conversion could be found. */ static tree convert_to_anonymous_field (location_t location, tree type, tree rhs) { tree rhs_struct_type, lhs_main_type; tree field, found_field; bool found_sub_field; tree ret; gcc_assert (POINTER_TYPE_P (TREE_TYPE (rhs))); rhs_struct_type = TREE_TYPE (TREE_TYPE (rhs)); gcc_assert (RECORD_OR_UNION_TYPE_P (rhs_struct_type)); gcc_assert (POINTER_TYPE_P (type)); lhs_main_type = (TYPE_ATOMIC (TREE_TYPE (type)) ? c_build_qualified_type (TREE_TYPE (type), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (type))); found_field = NULL_TREE; found_sub_field = false; for (field = TYPE_FIELDS (rhs_struct_type); field != NULL_TREE; field = TREE_CHAIN (field)) { if (DECL_NAME (field) != NULL_TREE || !RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))) continue; tree fieldtype = (TYPE_ATOMIC (TREE_TYPE (field)) ? c_build_qualified_type (TREE_TYPE (field), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (field))); if (comptypes (lhs_main_type, fieldtype)) { if (found_field != NULL_TREE) return NULL_TREE; found_field = field; } else if (find_anonymous_field_with_type (TREE_TYPE (field), lhs_main_type)) { if (found_field != NULL_TREE) return NULL_TREE; found_field = field; found_sub_field = true; } } if (found_field == NULL_TREE) return NULL_TREE; ret = fold_build3_loc (location, COMPONENT_REF, TREE_TYPE (found_field), build_fold_indirect_ref (rhs), found_field, NULL_TREE); ret = build_fold_addr_expr_loc (location, ret); if (found_sub_field) { ret = convert_to_anonymous_field (location, type, ret); gcc_assert (ret != NULL_TREE); } return ret; } /* Issue an error message for a bad initializer component. GMSGID identifies the message. The component name is taken from the spelling stack. */ static void ATTRIBUTE_GCC_DIAG (2,0) error_init (location_t loc, const char *gmsgid, ...) { char *ofwhat; auto_diagnostic_group d; /* The gmsgid may be a format string with %< and %>. */ va_list ap; va_start (ap, gmsgid); bool warned = emit_diagnostic_valist (DK_ERROR, loc, -1, gmsgid, &ap); va_end (ap); ofwhat = print_spelling ((char *) alloca (spelling_length () + 1)); if (*ofwhat && warned) inform (loc, "(near initialization for %qs)", ofwhat); } /* Issue a pedantic warning for a bad initializer component. OPT is the option OPT_* (from options.h) controlling this warning or 0 if it is unconditionally given. GMSGID identifies the message. The component name is taken from the spelling stack. */ static void ATTRIBUTE_GCC_DIAG (3,0) pedwarn_init (location_t loc, int opt, const char *gmsgid, ...) { /* Use the location where a macro was expanded rather than where it was defined to make sure macros defined in system headers but used incorrectly elsewhere are diagnosed. */ location_t exploc = expansion_point_location_if_in_system_header (loc); auto_diagnostic_group d; va_list ap; va_start (ap, gmsgid); bool warned = emit_diagnostic_valist (DK_PEDWARN, exploc, opt, gmsgid, &ap); va_end (ap); char *ofwhat = print_spelling ((char *) alloca (spelling_length () + 1)); if (*ofwhat && warned) inform (exploc, "(near initialization for %qs)", ofwhat); } /* Issue a warning for a bad initializer component. OPT is the OPT_W* value corresponding to the warning option that controls this warning. GMSGID identifies the message. The component name is taken from the spelling stack. */ static void warning_init (location_t loc, int opt, const char *gmsgid) { char *ofwhat; bool warned; auto_diagnostic_group d; /* Use the location where a macro was expanded rather than where it was defined to make sure macros defined in system headers but used incorrectly elsewhere are diagnosed. */ location_t exploc = expansion_point_location_if_in_system_header (loc); /* The gmsgid may be a format string with %< and %>. */ warned = warning_at (exploc, opt, gmsgid); ofwhat = print_spelling ((char *) alloca (spelling_length () + 1)); if (*ofwhat && warned) inform (exploc, "(near initialization for %qs)", ofwhat); } /* If TYPE is an array type and EXPR is a parenthesized string constant, warn if pedantic that EXPR is being used to initialize an object of type TYPE. */ void maybe_warn_string_init (location_t loc, tree type, struct c_expr expr) { if (pedantic && TREE_CODE (type) == ARRAY_TYPE && TREE_CODE (expr.value) == STRING_CST && expr.original_code != STRING_CST) pedwarn_init (loc, OPT_Wpedantic, "array initialized from parenthesized string constant"); } /* Attempt to locate the parameter with the given index within FNDECL, returning DECL_SOURCE_LOCATION (FNDECL) if it can't be found. */ static location_t get_fndecl_argument_location (tree fndecl, int argnum) { int i; tree param; /* Locate param by index within DECL_ARGUMENTS (fndecl). */ for (i = 0, param = DECL_ARGUMENTS (fndecl); i < argnum && param; i++, param = TREE_CHAIN (param)) ; /* If something went wrong (e.g. if we have a builtin and thus no arguments), return DECL_SOURCE_LOCATION (FNDECL). */ if (param == NULL) return DECL_SOURCE_LOCATION (fndecl); return DECL_SOURCE_LOCATION (param); } /* Issue a note about a mismatching argument for parameter PARMNUM to FUNDECL, for types EXPECTED_TYPE and ACTUAL_TYPE. Attempt to issue the note at the pertinent parameter of the decl; failing that issue it at the location of FUNDECL; failing that issue it at PLOC. */ static void inform_for_arg (tree fundecl, location_t ploc, int parmnum, tree expected_type, tree actual_type) { location_t loc; if (fundecl && !DECL_IS_BUILTIN (fundecl)) loc = get_fndecl_argument_location (fundecl, parmnum - 1); else loc = ploc; inform (loc, "expected %qT but argument is of type %qT", expected_type, actual_type); } /* Issue a warning when an argument of ARGTYPE is passed to a built-in function FUNDECL declared without prototype to parameter PARMNUM of PARMTYPE when ARGTYPE does not promote to PARMTYPE. */ static void maybe_warn_builtin_no_proto_arg (location_t loc, tree fundecl, int parmnum, tree parmtype, tree argtype) { tree_code parmcode = TREE_CODE (parmtype); tree_code argcode = TREE_CODE (argtype); tree promoted = c_type_promotes_to (argtype); /* Avoid warning for enum arguments that promote to an integer type of the same size/mode. */ if (parmcode == INTEGER_TYPE && argcode == ENUMERAL_TYPE && TYPE_MODE (parmtype) == TYPE_MODE (argtype)) return; if ((parmcode == argcode || (parmcode == INTEGER_TYPE && argcode == ENUMERAL_TYPE)) && TYPE_MAIN_VARIANT (parmtype) == TYPE_MAIN_VARIANT (promoted)) return; /* This diagnoses even signed/unsigned mismatches. Those might be safe in many cases but GCC may emit suboptimal code for them so warning on those cases drives efficiency improvements. */ if (warning_at (loc, OPT_Wbuiltin_declaration_mismatch, TYPE_MAIN_VARIANT (promoted) == argtype ? G_("%qD argument %d type is %qT where %qT is expected " "in a call to built-in function declared without " "prototype") : G_("%qD argument %d promotes to %qT where %qT is expected " "in a call to built-in function declared without " "prototype"), fundecl, parmnum, promoted, parmtype)) inform (DECL_SOURCE_LOCATION (fundecl), "built-in %qD declared here", fundecl); } /* Convert value RHS to type TYPE as preparation for an assignment to an lvalue of type TYPE. If ORIGTYPE is not NULL_TREE, it is the original type of RHS; this differs from TREE_TYPE (RHS) for enum types. NULL_POINTER_CONSTANT says whether RHS was a null pointer constant before any folding. The real work of conversion is done by `convert'. The purpose of this function is to generate error messages for assignments that are not allowed in C. ERRTYPE says whether it is argument passing, assignment, initialization or return. In the following example, '~' denotes where EXPR_LOC and '^' where LOCATION point to: f (var); [ic_argpass] ^ ~~~ x = var; [ic_assign] ^ ~~~; int x = var; [ic_init] ^^^ return x; [ic_return] ^ FUNCTION is a tree for the function being called. PARMNUM is the number of the argument, for printing in error messages. WARNOPT may be set to a warning option to issue the corresponding warning rather than an error for invalid conversions. Used for calls to built-in functions declared without a prototype. */ static tree convert_for_assignment (location_t location, location_t expr_loc, tree type, tree rhs, tree origtype, enum impl_conv errtype, bool null_pointer_constant, tree fundecl, tree function, int parmnum, int warnopt /* = 0 */) { enum tree_code codel = TREE_CODE (type); tree orig_rhs = rhs; tree rhstype; enum tree_code coder; tree rname = NULL_TREE; bool objc_ok = false; /* Use the expansion point location to handle cases such as user's function returning a wrong-type macro defined in a system header. */ location = expansion_point_location_if_in_system_header (location); if (errtype == ic_argpass) { tree selector; /* Change pointer to function to the function itself for diagnostics. */ if (TREE_CODE (function) == ADDR_EXPR && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL) function = TREE_OPERAND (function, 0); /* Handle an ObjC selector specially for diagnostics. */ selector = objc_message_selector (); rname = function; if (selector && parmnum > 2) { rname = selector; parmnum -= 2; } } /* This macro is used to emit diagnostics to ensure that all format strings are complete sentences, visible to gettext and checked at compile time. */ #define PEDWARN_FOR_ASSIGNMENT(LOCATION, PLOC, OPT, AR, AS, IN, RE) \ do { \ switch (errtype) \ { \ case ic_argpass: \ { \ auto_diagnostic_group d; \ if (pedwarn (PLOC, OPT, AR, parmnum, rname)) \ inform_for_arg (fundecl, (PLOC), parmnum, type, rhstype); \ } \ break; \ case ic_assign: \ pedwarn (LOCATION, OPT, AS); \ break; \ case ic_init: \ pedwarn_init (LOCATION, OPT, IN); \ break; \ case ic_return: \ pedwarn (LOCATION, OPT, RE); \ break; \ default: \ gcc_unreachable (); \ } \ } while (0) /* This macro is used to emit diagnostics to ensure that all format strings are complete sentences, visible to gettext and checked at compile time. It is the same as PEDWARN_FOR_ASSIGNMENT but with an extra parameter to enumerate qualifiers. */ #define PEDWARN_FOR_QUALIFIERS(LOCATION, PLOC, OPT, AR, AS, IN, RE, QUALS) \ do { \ switch (errtype) \ { \ case ic_argpass: \ { \ auto_diagnostic_group d; \ if (pedwarn (PLOC, OPT, AR, parmnum, rname, QUALS)) \ inform_for_arg (fundecl, (PLOC), parmnum, type, rhstype); \ } \ break; \ case ic_assign: \ pedwarn (LOCATION, OPT, AS, QUALS); \ break; \ case ic_init: \ pedwarn (LOCATION, OPT, IN, QUALS); \ break; \ case ic_return: \ pedwarn (LOCATION, OPT, RE, QUALS); \ break; \ default: \ gcc_unreachable (); \ } \ } while (0) /* This macro is used to emit diagnostics to ensure that all format strings are complete sentences, visible to gettext and checked at compile time. It is the same as PEDWARN_FOR_QUALIFIERS but uses warning_at instead of pedwarn. */ #define WARNING_FOR_QUALIFIERS(LOCATION, PLOC, OPT, AR, AS, IN, RE, QUALS) \ do { \ switch (errtype) \ { \ case ic_argpass: \ { \ auto_diagnostic_group d; \ if (warning_at (PLOC, OPT, AR, parmnum, rname, QUALS)) \ inform_for_arg (fundecl, (PLOC), parmnum, type, rhstype); \ } \ break; \ case ic_assign: \ warning_at (LOCATION, OPT, AS, QUALS); \ break; \ case ic_init: \ warning_at (LOCATION, OPT, IN, QUALS); \ break; \ case ic_return: \ warning_at (LOCATION, OPT, RE, QUALS); \ break; \ default: \ gcc_unreachable (); \ } \ } while (0) if (TREE_CODE (rhs) == EXCESS_PRECISION_EXPR) rhs = TREE_OPERAND (rhs, 0); rhstype = TREE_TYPE (rhs); coder = TREE_CODE (rhstype); if (coder == ERROR_MARK) return error_mark_node; if (c_dialect_objc ()) { int parmno; switch (errtype) { case ic_return: parmno = 0; break; case ic_assign: parmno = -1; break; case ic_init: parmno = -2; break; default: parmno = parmnum; break; } objc_ok = objc_compare_types (type, rhstype, parmno, rname); } if (warn_cxx_compat) { tree checktype = origtype != NULL_TREE ? origtype : rhstype; if (checktype != error_mark_node && TREE_CODE (type) == ENUMERAL_TYPE && TYPE_MAIN_VARIANT (checktype) != TYPE_MAIN_VARIANT (type)) switch (errtype) { case ic_argpass: if (pedwarn (expr_loc, OPT_Wc___compat, "enum conversion when " "passing argument %d of %qE is invalid in C++", parmnum, rname)) inform ((fundecl && !DECL_IS_BUILTIN (fundecl)) ? DECL_SOURCE_LOCATION (fundecl) : expr_loc, "expected %qT but argument is of type %qT", type, rhstype); break; case ic_assign: pedwarn (location, OPT_Wc___compat, "enum conversion from %qT to " "%qT in assignment is invalid in C++", rhstype, type); break; case ic_init: pedwarn_init (location, OPT_Wc___compat, "enum conversion from " "%qT to %qT in initialization is invalid in C++", rhstype, type); break; case ic_return: pedwarn (location, OPT_Wc___compat, "enum conversion from %qT to " "%qT in return is invalid in C++", rhstype, type); break; default: gcc_unreachable (); } } if (warn_enum_conversion) { tree checktype = origtype != NULL_TREE ? origtype : rhstype; if (checktype != error_mark_node && TREE_CODE (checktype) == ENUMERAL_TYPE && TREE_CODE (type) == ENUMERAL_TYPE && TYPE_MAIN_VARIANT (checktype) != TYPE_MAIN_VARIANT (type)) { gcc_rich_location loc (location); warning_at (&loc, OPT_Wenum_conversion, "implicit conversion from %qT to %qT", checktype, type); } } if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (rhstype)) { warn_for_address_or_pointer_of_packed_member (type, orig_rhs); return rhs; } if (coder == VOID_TYPE) { /* Except for passing an argument to an unprototyped function, this is a constraint violation. When passing an argument to an unprototyped function, it is compile-time undefined; making it a constraint in that case was rejected in DR#252. */ const char msg[] = "void value not ignored as it ought to be"; if (warnopt) warning_at (location, warnopt, msg); else error_at (location, msg); return error_mark_node; } rhs = require_complete_type (location, rhs); if (rhs == error_mark_node) return error_mark_node; if (coder == POINTER_TYPE && reject_gcc_builtin (rhs)) return error_mark_node; /* A non-reference type can convert to a reference. This handles va_start, va_copy and possibly port built-ins. */ if (codel == REFERENCE_TYPE && coder != REFERENCE_TYPE) { if (!lvalue_p (rhs)) { const char msg[] = "cannot pass rvalue to reference parameter"; if (warnopt) warning_at (location, warnopt, msg); else error_at (location, msg); return error_mark_node; } if (!c_mark_addressable (rhs)) return error_mark_node; rhs = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (rhs)), rhs); SET_EXPR_LOCATION (rhs, location); rhs = convert_for_assignment (location, expr_loc, build_pointer_type (TREE_TYPE (type)), rhs, origtype, errtype, null_pointer_constant, fundecl, function, parmnum, warnopt); if (rhs == error_mark_node) return error_mark_node; rhs = build1 (NOP_EXPR, type, rhs); SET_EXPR_LOCATION (rhs, location); return rhs; } /* Some types can interconvert without explicit casts. */ else if (codel == VECTOR_TYPE && coder == VECTOR_TYPE && vector_types_convertible_p (type, TREE_TYPE (rhs), true)) return convert (type, rhs); /* Arithmetic types all interconvert, and enum is treated like int. */ else if ((codel == INTEGER_TYPE || codel == REAL_TYPE || codel == FIXED_POINT_TYPE || codel == ENUMERAL_TYPE || codel == COMPLEX_TYPE || codel == BOOLEAN_TYPE) && (coder == INTEGER_TYPE || coder == REAL_TYPE || coder == FIXED_POINT_TYPE || coder == ENUMERAL_TYPE || coder == COMPLEX_TYPE || coder == BOOLEAN_TYPE)) { if (warnopt && errtype == ic_argpass) maybe_warn_builtin_no_proto_arg (expr_loc, fundecl, parmnum, type, rhstype); bool save = in_late_binary_op; if (codel == BOOLEAN_TYPE || codel == COMPLEX_TYPE || (coder == REAL_TYPE && (codel == INTEGER_TYPE || codel == ENUMERAL_TYPE) && sanitize_flags_p (SANITIZE_FLOAT_CAST))) in_late_binary_op = true; tree ret = convert_and_check (expr_loc != UNKNOWN_LOCATION ? expr_loc : location, type, orig_rhs); in_late_binary_op = save; return ret; } /* Aggregates in different TUs might need conversion. */ if ((codel == RECORD_TYPE || codel == UNION_TYPE) && codel == coder && comptypes (type, rhstype)) return convert_and_check (expr_loc != UNKNOWN_LOCATION ? expr_loc : location, type, rhs); /* Conversion to a transparent union or record from its member types. This applies only to function arguments. */ if (((codel == UNION_TYPE || codel == RECORD_TYPE) && TYPE_TRANSPARENT_AGGR (type)) && errtype == ic_argpass) { tree memb, marginal_memb = NULL_TREE; for (memb = TYPE_FIELDS (type); memb ; memb = DECL_CHAIN (memb)) { tree memb_type = TREE_TYPE (memb); if (comptypes (TYPE_MAIN_VARIANT (memb_type), TYPE_MAIN_VARIANT (rhstype))) break; if (TREE_CODE (memb_type) != POINTER_TYPE) continue; if (coder == POINTER_TYPE) { tree ttl = TREE_TYPE (memb_type); tree ttr = TREE_TYPE (rhstype); /* Any non-function converts to a [const][volatile] void * and vice versa; otherwise, targets must be the same. Meanwhile, the lhs target must have all the qualifiers of the rhs. */ if ((VOID_TYPE_P (ttl) && !TYPE_ATOMIC (ttl)) || (VOID_TYPE_P (ttr) && !TYPE_ATOMIC (ttr)) || comp_target_types (location, memb_type, rhstype)) { int lquals = TYPE_QUALS (ttl) & ~TYPE_QUAL_ATOMIC; int rquals = TYPE_QUALS (ttr) & ~TYPE_QUAL_ATOMIC; /* If this type won't generate any warnings, use it. */ if (lquals == rquals || ((TREE_CODE (ttr) == FUNCTION_TYPE && TREE_CODE (ttl) == FUNCTION_TYPE) ? ((lquals | rquals) == rquals) : ((lquals | rquals) == lquals))) break; /* Keep looking for a better type, but remember this one. */ if (!marginal_memb) marginal_memb = memb; } } /* Can convert integer zero to any pointer type. */ if (null_pointer_constant) { rhs = null_pointer_node; break; } } if (memb || marginal_memb) { if (!memb) { /* We have only a marginally acceptable member type; it needs a warning. */ tree ttl = TREE_TYPE (TREE_TYPE (marginal_memb)); tree ttr = TREE_TYPE (rhstype); /* Const and volatile mean something different for function types, so the usual warnings are not appropriate. */ if (TREE_CODE (ttr) == FUNCTION_TYPE && TREE_CODE (ttl) == FUNCTION_TYPE) { /* Because const and volatile on functions are restrictions that say the function will not do certain things, it is okay to use a const or volatile function where an ordinary one is wanted, but not vice-versa. */ if (TYPE_QUALS_NO_ADDR_SPACE (ttl) & ~TYPE_QUALS_NO_ADDR_SPACE (ttr)) PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE " "makes %q#v qualified function " "pointer from unqualified"), G_("assignment makes %q#v qualified " "function pointer from " "unqualified"), G_("initialization makes %q#v qualified " "function pointer from " "unqualified"), G_("return makes %q#v qualified function " "pointer from unqualified"), TYPE_QUALS (ttl) & ~TYPE_QUALS (ttr)); } else if (TYPE_QUALS_NO_ADDR_SPACE (ttr) & ~TYPE_QUALS_NO_ADDR_SPACE (ttl)) PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE discards " "%qv qualifier from pointer target type"), G_("assignment discards %qv qualifier " "from pointer target type"), G_("initialization discards %qv qualifier " "from pointer target type"), G_("return discards %qv qualifier from " "pointer target type"), TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl)); memb = marginal_memb; } if (!fundecl || !DECL_IN_SYSTEM_HEADER (fundecl)) pedwarn (location, OPT_Wpedantic, "ISO C prohibits argument conversion to union type"); rhs = fold_convert_loc (location, TREE_TYPE (memb), rhs); return build_constructor_single (type, memb, rhs); } } /* Conversions among pointers */ else if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE) && (coder == codel)) { /* If RHS refers to a built-in declared without a prototype BLTIN is the declaration of the built-in with a prototype and RHSTYPE is set to the actual type of the built-in. */ tree bltin; rhstype = type_or_builtin_type (rhs, &bltin); tree ttl = TREE_TYPE (type); tree ttr = TREE_TYPE (rhstype); tree mvl = ttl; tree mvr = ttr; bool is_opaque_pointer; int target_cmp = 0; /* Cache comp_target_types () result. */ addr_space_t asl; addr_space_t asr; if (TREE_CODE (mvl) != ARRAY_TYPE) mvl = (TYPE_ATOMIC (mvl) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvl), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvl)); if (TREE_CODE (mvr) != ARRAY_TYPE) mvr = (TYPE_ATOMIC (mvr) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvr), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvr)); /* Opaque pointers are treated like void pointers. */ is_opaque_pointer = vector_targets_convertible_p (ttl, ttr); /* The Plan 9 compiler permits a pointer to a struct to be automatically converted into a pointer to an anonymous field within the struct. */ if (flag_plan9_extensions && RECORD_OR_UNION_TYPE_P (mvl) && RECORD_OR_UNION_TYPE_P (mvr) && mvl != mvr) { tree new_rhs = convert_to_anonymous_field (location, type, rhs); if (new_rhs != NULL_TREE) { rhs = new_rhs; rhstype = TREE_TYPE (rhs); coder = TREE_CODE (rhstype); ttr = TREE_TYPE (rhstype); mvr = TYPE_MAIN_VARIANT (ttr); } } /* C++ does not allow the implicit conversion void* -> T*. However, for the purpose of reducing the number of false positives, we tolerate the special case of int *p = NULL; where NULL is typically defined in C to be '(void *) 0'. */ if (VOID_TYPE_P (ttr) && rhs != null_pointer_node && !VOID_TYPE_P (ttl)) warning_at (errtype == ic_argpass ? expr_loc : location, OPT_Wc___compat, "request for implicit conversion " "from %qT to %qT not permitted in C++", rhstype, type); /* See if the pointers point to incompatible address spaces. */ asl = TYPE_ADDR_SPACE (ttl); asr = TYPE_ADDR_SPACE (ttr); if (!null_pointer_constant_p (rhs) && asr != asl && !targetm.addr_space.subset_p (asr, asl)) { switch (errtype) { case ic_argpass: { const char msg[] = G_("passing argument %d of %qE from " "pointer to non-enclosed address space"); if (warnopt) warning_at (expr_loc, warnopt, msg, parmnum, rname); else error_at (expr_loc, msg, parmnum, rname); break; } case ic_assign: { const char msg[] = G_("assignment from pointer to " "non-enclosed address space"); if (warnopt) warning_at (location, warnopt, msg); else error_at (location, msg); break; } case ic_init: { const char msg[] = G_("initialization from pointer to " "non-enclosed address space"); if (warnopt) warning_at (location, warnopt, msg); else error_at (location, msg); break; } case ic_return: { const char msg[] = G_("return from pointer to " "non-enclosed address space"); if (warnopt) warning_at (location, warnopt, msg); else error_at (location, msg); break; } default: gcc_unreachable (); } return error_mark_node; } /* Check if the right-hand side has a format attribute but the left-hand side doesn't. */ if (warn_suggest_attribute_format && check_missing_format_attribute (type, rhstype)) { switch (errtype) { case ic_argpass: warning_at (expr_loc, OPT_Wsuggest_attribute_format, "argument %d of %qE might be " "a candidate for a format attribute", parmnum, rname); break; case ic_assign: warning_at (location, OPT_Wsuggest_attribute_format, "assignment left-hand side might be " "a candidate for a format attribute"); break; case ic_init: warning_at (location, OPT_Wsuggest_attribute_format, "initialization left-hand side might be " "a candidate for a format attribute"); break; case ic_return: warning_at (location, OPT_Wsuggest_attribute_format, "return type might be " "a candidate for a format attribute"); break; default: gcc_unreachable (); } } /* See if the pointers point to incompatible scalar storage orders. */ if (warn_scalar_storage_order && (AGGREGATE_TYPE_P (ttl) && TYPE_REVERSE_STORAGE_ORDER (ttl)) != (AGGREGATE_TYPE_P (ttr) && TYPE_REVERSE_STORAGE_ORDER (ttr))) { switch (errtype) { case ic_argpass: /* Do not warn for built-in functions, for example memcpy, since we control how they behave and they can be useful in this area. */ if (TREE_CODE (rname) != FUNCTION_DECL || !DECL_IS_BUILTIN (rname)) warning_at (location, OPT_Wscalar_storage_order, "passing argument %d of %qE from incompatible " "scalar storage order", parmnum, rname); break; case ic_assign: warning_at (location, OPT_Wscalar_storage_order, "assignment to %qT from pointer type %qT with " "incompatible scalar storage order", type, rhstype); break; case ic_init: warning_at (location, OPT_Wscalar_storage_order, "initialization of %qT from pointer type %qT with " "incompatible scalar storage order", type, rhstype); break; case ic_return: warning_at (location, OPT_Wscalar_storage_order, "returning %qT from pointer type with incompatible " "scalar storage order %qT", rhstype, type); break; default: gcc_unreachable (); } } /* Any non-function converts to a [const][volatile] void * and vice versa; otherwise, targets must be the same. Meanwhile, the lhs target must have all the qualifiers of the rhs. */ if ((VOID_TYPE_P (ttl) && !TYPE_ATOMIC (ttl)) || (VOID_TYPE_P (ttr) && !TYPE_ATOMIC (ttr)) || (target_cmp = comp_target_types (location, type, rhstype)) || is_opaque_pointer || ((c_common_unsigned_type (mvl) == c_common_unsigned_type (mvr)) && (c_common_signed_type (mvl) == c_common_signed_type (mvr)) && TYPE_ATOMIC (mvl) == TYPE_ATOMIC (mvr))) { /* Warn about loss of qualifers from pointers to arrays with qualifiers on the element type. */ if (TREE_CODE (ttr) == ARRAY_TYPE) { ttr = strip_array_types (ttr); ttl = strip_array_types (ttl); if (TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttr) & ~TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttl)) WARNING_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_array_qualifiers, G_("passing argument %d of %qE discards " "%qv qualifier from pointer target type"), G_("assignment discards %qv qualifier " "from pointer target type"), G_("initialization discards %qv qualifier " "from pointer target type"), G_("return discards %qv qualifier from " "pointer target type"), TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl)); } else if (pedantic && ((VOID_TYPE_P (ttl) && TREE_CODE (ttr) == FUNCTION_TYPE) || (VOID_TYPE_P (ttr) && !null_pointer_constant && TREE_CODE (ttl) == FUNCTION_TYPE))) PEDWARN_FOR_ASSIGNMENT (location, expr_loc, OPT_Wpedantic, G_("ISO C forbids passing argument %d of " "%qE between function pointer " "and %<void *%>"), G_("ISO C forbids assignment between " "function pointer and %<void *%>"), G_("ISO C forbids initialization between " "function pointer and %<void *%>"), G_("ISO C forbids return between function " "pointer and %<void *%>")); /* Const and volatile mean something different for function types, so the usual warnings are not appropriate. */ else if (TREE_CODE (ttr) != FUNCTION_TYPE && TREE_CODE (ttl) != FUNCTION_TYPE) { /* Don't warn about loss of qualifier for conversions from qualified void* to pointers to arrays with corresponding qualifier on the element type. */ if (!pedantic) ttl = strip_array_types (ttl); /* Assignments between atomic and non-atomic objects are OK. */ if (TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttr) & ~TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttl)) { PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE discards " "%qv qualifier from pointer target type"), G_("assignment discards %qv qualifier " "from pointer target type"), G_("initialization discards %qv qualifier " "from pointer target type"), G_("return discards %qv qualifier from " "pointer target type"), TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl)); } /* If this is not a case of ignoring a mismatch in signedness, no warning. */ else if (VOID_TYPE_P (ttl) || VOID_TYPE_P (ttr) || target_cmp) ; /* If there is a mismatch, do warn. */ else if (warn_pointer_sign) switch (errtype) { case ic_argpass: { auto_diagnostic_group d; range_label_for_type_mismatch rhs_label (rhstype, type); gcc_rich_location richloc (expr_loc, &rhs_label); if (pedwarn (&richloc, OPT_Wpointer_sign, "pointer targets in passing argument %d of " "%qE differ in signedness", parmnum, rname)) inform_for_arg (fundecl, expr_loc, parmnum, type, rhstype); } break; case ic_assign: pedwarn (location, OPT_Wpointer_sign, "pointer targets in assignment from %qT to %qT " "differ in signedness", rhstype, type); break; case ic_init: pedwarn_init (location, OPT_Wpointer_sign, "pointer targets in initialization of %qT " "from %qT differ in signedness", type, rhstype); break; case ic_return: pedwarn (location, OPT_Wpointer_sign, "pointer targets in " "returning %qT from a function with return type " "%qT differ in signedness", rhstype, type); break; default: gcc_unreachable (); } } else if (TREE_CODE (ttl) == FUNCTION_TYPE && TREE_CODE (ttr) == FUNCTION_TYPE) { /* Because const and volatile on functions are restrictions that say the function will not do certain things, it is okay to use a const or volatile function where an ordinary one is wanted, but not vice-versa. */ if (TYPE_QUALS_NO_ADDR_SPACE (ttl) & ~TYPE_QUALS_NO_ADDR_SPACE (ttr)) PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE makes " "%q#v qualified function pointer " "from unqualified"), G_("assignment makes %q#v qualified function " "pointer from unqualified"), G_("initialization makes %q#v qualified " "function pointer from unqualified"), G_("return makes %q#v qualified function " "pointer from unqualified"), TYPE_QUALS (ttl) & ~TYPE_QUALS (ttr)); } } /* Avoid warning about the volatile ObjC EH puts on decls. */ else if (!objc_ok) { switch (errtype) { case ic_argpass: { auto_diagnostic_group d; range_label_for_type_mismatch rhs_label (rhstype, type); gcc_rich_location richloc (expr_loc, &rhs_label); if (pedwarn (&richloc, OPT_Wincompatible_pointer_types, "passing argument %d of %qE from incompatible " "pointer type", parmnum, rname)) inform_for_arg (fundecl, expr_loc, parmnum, type, rhstype); } break; case ic_assign: if (bltin) pedwarn (location, OPT_Wincompatible_pointer_types, "assignment to %qT from pointer to " "%qD with incompatible type %qT", type, bltin, rhstype); else pedwarn (location, OPT_Wincompatible_pointer_types, "assignment to %qT from incompatible pointer type %qT", type, rhstype); break; case ic_init: if (bltin) pedwarn_init (location, OPT_Wincompatible_pointer_types, "initialization of %qT from pointer to " "%qD with incompatible type %qT", type, bltin, rhstype); else pedwarn_init (location, OPT_Wincompatible_pointer_types, "initialization of %qT from incompatible " "pointer type %qT", type, rhstype); break; case ic_return: if (bltin) pedwarn (location, OPT_Wincompatible_pointer_types, "returning pointer to %qD of type %qT from " "a function with incompatible type %qT", bltin, rhstype, type); else pedwarn (location, OPT_Wincompatible_pointer_types, "returning %qT from a function with incompatible " "return type %qT", rhstype, type); break; default: gcc_unreachable (); } } /* If RHS isn't an address, check pointer or array of packed struct or union. */ warn_for_address_or_pointer_of_packed_member (type, orig_rhs); return convert (type, rhs); } else if (codel == POINTER_TYPE && coder == ARRAY_TYPE) { /* ??? This should not be an error when inlining calls to unprototyped functions. */ const char msg[] = "invalid use of non-lvalue array"; if (warnopt) warning_at (location, warnopt, msg); else error_at (location, msg); return error_mark_node; } else if (codel == POINTER_TYPE && coder == INTEGER_TYPE) { /* An explicit constant 0 can convert to a pointer, or one that results from arithmetic, even including a cast to integer type. */ if (!null_pointer_constant) switch (errtype) { case ic_argpass: { auto_diagnostic_group d; range_label_for_type_mismatch rhs_label (rhstype, type); gcc_rich_location richloc (expr_loc, &rhs_label); if (pedwarn (&richloc, OPT_Wint_conversion, "passing argument %d of %qE makes pointer from " "integer without a cast", parmnum, rname)) inform_for_arg (fundecl, expr_loc, parmnum, type, rhstype); } break; case ic_assign: pedwarn (location, OPT_Wint_conversion, "assignment to %qT from %qT makes pointer from integer " "without a cast", type, rhstype); break; case ic_init: pedwarn_init (location, OPT_Wint_conversion, "initialization of %qT from %qT makes pointer from " "integer without a cast", type, rhstype); break; case ic_return: pedwarn (location, OPT_Wint_conversion, "returning %qT from a " "function with return type %qT makes pointer from " "integer without a cast", rhstype, type); break; default: gcc_unreachable (); } return convert (type, rhs); } else if (codel == INTEGER_TYPE && coder == POINTER_TYPE) { switch (errtype) { case ic_argpass: { auto_diagnostic_group d; range_label_for_type_mismatch rhs_label (rhstype, type); gcc_rich_location richloc (expr_loc, &rhs_label); if (pedwarn (&richloc, OPT_Wint_conversion, "passing argument %d of %qE makes integer from " "pointer without a cast", parmnum, rname)) inform_for_arg (fundecl, expr_loc, parmnum, type, rhstype); } break; case ic_assign: pedwarn (location, OPT_Wint_conversion, "assignment to %qT from %qT makes integer from pointer " "without a cast", type, rhstype); break; case ic_init: pedwarn_init (location, OPT_Wint_conversion, "initialization of %qT from %qT makes integer from " "pointer without a cast", type, rhstype); break; case ic_return: pedwarn (location, OPT_Wint_conversion, "returning %qT from a " "function with return type %qT makes integer from " "pointer without a cast", rhstype, type); break; default: gcc_unreachable (); } return convert (type, rhs); } else if (codel == BOOLEAN_TYPE && coder == POINTER_TYPE) { tree ret; bool save = in_late_binary_op; in_late_binary_op = true; ret = convert (type, rhs); in_late_binary_op = save; return ret; } switch (errtype) { case ic_argpass: { auto_diagnostic_group d; range_label_for_type_mismatch rhs_label (rhstype, type); gcc_rich_location richloc (expr_loc, &rhs_label); const char msg[] = G_("incompatible type for argument %d of %qE"); if (warnopt) warning_at (expr_loc, warnopt, msg, parmnum, rname); else error_at (&richloc, msg, parmnum, rname); inform_for_arg (fundecl, expr_loc, parmnum, type, rhstype); } break; case ic_assign: { const char msg[] = G_("incompatible types when assigning to type %qT from type %qT"); if (warnopt) warning_at (expr_loc, 0, msg, type, rhstype); else error_at (expr_loc, msg, type, rhstype); break; } case ic_init: { const char msg[] = G_("incompatible types when initializing type %qT using type %qT"); if (warnopt) warning_at (location, 0, msg, type, rhstype); else error_at (location, msg, type, rhstype); break; } case ic_return: { const char msg[] = G_("incompatible types when returning type %qT but %qT was expected"); if (warnopt) warning_at (location, 0, msg, rhstype, type); else error_at (location, msg, rhstype, type); break; } default: gcc_unreachable (); } return error_mark_node; } /* If VALUE is a compound expr all of whose expressions are constant, then return its value. Otherwise, return error_mark_node. This is for handling COMPOUND_EXPRs as initializer elements which is allowed with a warning when -pedantic is specified. */ static tree valid_compound_expr_initializer (tree value, tree endtype) { if (TREE_CODE (value) == COMPOUND_EXPR) { if (valid_compound_expr_initializer (TREE_OPERAND (value, 0), endtype) == error_mark_node) return error_mark_node; return valid_compound_expr_initializer (TREE_OPERAND (value, 1), endtype); } else if (!initializer_constant_valid_p (value, endtype)) return error_mark_node; else return value; } /* Perform appropriate conversions on the initial value of a variable, store it in the declaration DECL, and print any error messages that are appropriate. If ORIGTYPE is not NULL_TREE, it is the original type of INIT. If the init is invalid, store an ERROR_MARK. INIT_LOC is the location of the initial value. */ void store_init_value (location_t init_loc, tree decl, tree init, tree origtype) { tree value, type; bool npc = false; /* If variable's type was invalidly declared, just ignore it. */ type = TREE_TYPE (decl); if (TREE_CODE (type) == ERROR_MARK) return; /* Digest the specified initializer into an expression. */ if (init) npc = null_pointer_constant_p (init); value = digest_init (init_loc, type, init, origtype, npc, true, TREE_STATIC (decl)); /* Store the expression if valid; else report error. */ if (!in_system_header_at (input_location) && AGGREGATE_TYPE_P (TREE_TYPE (decl)) && !TREE_STATIC (decl)) warning (OPT_Wtraditional, "traditional C rejects automatic " "aggregate initialization"); if (value != error_mark_node || TREE_CODE (decl) != FUNCTION_DECL) DECL_INITIAL (decl) = value; /* ANSI wants warnings about out-of-range constant initializers. */ STRIP_TYPE_NOPS (value); if (TREE_STATIC (decl)) constant_expression_warning (value); /* Check if we need to set array size from compound literal size. */ if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type) == NULL_TREE && value != error_mark_node) { tree inside_init = init; STRIP_TYPE_NOPS (inside_init); inside_init = fold (inside_init); if (TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR) { tree cldecl = COMPOUND_LITERAL_EXPR_DECL (inside_init); if (TYPE_DOMAIN (TREE_TYPE (cldecl))) { /* For int foo[] = (int [3]){1}; we need to set array size now since later on array initializer will be just the brace enclosed list of the compound literal. */ tree etype = strip_array_types (TREE_TYPE (decl)); type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type)); TYPE_DOMAIN (type) = TYPE_DOMAIN (TREE_TYPE (cldecl)); layout_type (type); layout_decl (cldecl, 0); TREE_TYPE (decl) = c_build_qualified_type (type, TYPE_QUALS (etype)); } } } } /* Methods for storing and printing names for error messages. */ /* Implement a spelling stack that allows components of a name to be pushed and popped. Each element on the stack is this structure. */ struct spelling { int kind; union { unsigned HOST_WIDE_INT i; const char *s; } u; }; #define SPELLING_STRING 1 #define SPELLING_MEMBER 2 #define SPELLING_BOUNDS 3 static struct spelling *spelling; /* Next stack element (unused). */ static struct spelling *spelling_base; /* Spelling stack base. */ static int spelling_size; /* Size of the spelling stack. */ /* Macros to save and restore the spelling stack around push_... functions. Alternative to SAVE_SPELLING_STACK. */ #define SPELLING_DEPTH() (spelling - spelling_base) #define RESTORE_SPELLING_DEPTH(DEPTH) (spelling = spelling_base + (DEPTH)) /* Push an element on the spelling stack with type KIND and assign VALUE to MEMBER. */ #define PUSH_SPELLING(KIND, VALUE, MEMBER) \ { \ int depth = SPELLING_DEPTH (); \ \ if (depth >= spelling_size) \ { \ spelling_size += 10; \ spelling_base = XRESIZEVEC (struct spelling, spelling_base, \ spelling_size); \ RESTORE_SPELLING_DEPTH (depth); \ } \ \ spelling->kind = (KIND); \ spelling->MEMBER = (VALUE); \ spelling++; \ } /* Push STRING on the stack. Printed literally. */ static void push_string (const char *string) { PUSH_SPELLING (SPELLING_STRING, string, u.s); } /* Push a member name on the stack. Printed as '.' STRING. */ static void push_member_name (tree decl) { const char *const string = (DECL_NAME (decl) ? identifier_to_locale (IDENTIFIER_POINTER (DECL_NAME (decl))) : _("<anonymous>")); PUSH_SPELLING (SPELLING_MEMBER, string, u.s); } /* Push an array bounds on the stack. Printed as [BOUNDS]. */ static void push_array_bounds (unsigned HOST_WIDE_INT bounds) { PUSH_SPELLING (SPELLING_BOUNDS, bounds, u.i); } /* Compute the maximum size in bytes of the printed spelling. */ static int spelling_length (void) { int size = 0; struct spelling *p; for (p = spelling_base; p < spelling; p++) { if (p->kind == SPELLING_BOUNDS) size += 25; else size += strlen (p->u.s) + 1; } return size; } /* Print the spelling to BUFFER and return it. */ static char * print_spelling (char *buffer) { char *d = buffer; struct spelling *p; for (p = spelling_base; p < spelling; p++) if (p->kind == SPELLING_BOUNDS) { sprintf (d, "[" HOST_WIDE_INT_PRINT_UNSIGNED "]", p->u.i); d += strlen (d); } else { const char *s; if (p->kind == SPELLING_MEMBER) *d++ = '.'; for (s = p->u.s; (*d = *s++); d++) ; } *d++ = '\0'; return buffer; } /* Digest the parser output INIT as an initializer for type TYPE. Return a C expression of type TYPE to represent the initial value. If ORIGTYPE is not NULL_TREE, it is the original type of INIT. NULL_POINTER_CONSTANT is true if INIT is a null pointer constant. If INIT is a string constant, STRICT_STRING is true if it is unparenthesized or we should not warn here for it being parenthesized. For other types of INIT, STRICT_STRING is not used. INIT_LOC is the location of the INIT. REQUIRE_CONSTANT requests an error if non-constant initializers or elements are seen. */ static tree digest_init (location_t init_loc, tree type, tree init, tree origtype, bool null_pointer_constant, bool strict_string, int require_constant) { enum tree_code code = TREE_CODE (type); tree inside_init = init; tree semantic_type = NULL_TREE; bool maybe_const = true; if (type == error_mark_node || !init || error_operand_p (init)) return error_mark_node; STRIP_TYPE_NOPS (inside_init); if (!c_in_omp_for) { if (TREE_CODE (inside_init) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (inside_init); inside_init = TREE_OPERAND (inside_init, 0); } inside_init = c_fully_fold (inside_init, require_constant, &maybe_const); } /* Initialization of an array of chars from a string constant optionally enclosed in braces. */ if (code == ARRAY_TYPE && inside_init && TREE_CODE (inside_init) == STRING_CST) { tree typ1 = (TYPE_ATOMIC (TREE_TYPE (type)) ? c_build_qualified_type (TYPE_MAIN_VARIANT (TREE_TYPE (type)), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (type))); /* Note that an array could be both an array of character type and an array of wchar_t if wchar_t is signed char or unsigned char. */ bool char_array = (typ1 == char_type_node || typ1 == signed_char_type_node || typ1 == unsigned_char_type_node); bool wchar_array = !!comptypes (typ1, wchar_type_node); bool char16_array = !!comptypes (typ1, char16_type_node); bool char32_array = !!comptypes (typ1, char32_type_node); if (char_array || wchar_array || char16_array || char32_array) { struct c_expr expr; tree typ2 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (inside_init))); bool incompat_string_cst = false; expr.value = inside_init; expr.original_code = (strict_string ? STRING_CST : ERROR_MARK); expr.original_type = NULL; maybe_warn_string_init (init_loc, type, expr); if (TYPE_DOMAIN (type) && !TYPE_MAX_VALUE (TYPE_DOMAIN (type))) pedwarn_init (init_loc, OPT_Wpedantic, "initialization of a flexible array member"); if (comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)), TYPE_MAIN_VARIANT (type))) return inside_init; if (char_array) { if (typ2 != char_type_node) incompat_string_cst = true; } else if (!comptypes (typ1, typ2)) incompat_string_cst = true; if (incompat_string_cst) { error_init (init_loc, "cannot initialize array of %qT from " "a string literal with type array of %qT", typ1, typ2); return error_mark_node; } if (TYPE_DOMAIN (type) != NULL_TREE && TYPE_SIZE (type) != NULL_TREE && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST) { unsigned HOST_WIDE_INT len = TREE_STRING_LENGTH (inside_init); unsigned unit = TYPE_PRECISION (typ1) / BITS_PER_UNIT; /* Subtract the size of a single (possibly wide) character because it's ok to ignore the terminating null char that is counted in the length of the constant. */ if (compare_tree_int (TYPE_SIZE_UNIT (type), len - unit) < 0) pedwarn_init (init_loc, 0, ("initializer-string for array of %qT " "is too long"), typ1); else if (warn_cxx_compat && compare_tree_int (TYPE_SIZE_UNIT (type), len) < 0) warning_at (init_loc, OPT_Wc___compat, ("initializer-string for array of %qT " "is too long for C++"), typ1); if (compare_tree_int (TYPE_SIZE_UNIT (type), len) < 0) { unsigned HOST_WIDE_INT size = tree_to_uhwi (TYPE_SIZE_UNIT (type)); const char *p = TREE_STRING_POINTER (inside_init); inside_init = build_string (size, p); } } TREE_TYPE (inside_init) = type; return inside_init; } else if (INTEGRAL_TYPE_P (typ1)) { error_init (init_loc, "array of inappropriate type initialized " "from string constant"); return error_mark_node; } } /* Build a VECTOR_CST from a *constant* vector constructor. If the vector constructor is not constant (e.g. {1,2,3,foo()}) then punt below and handle as a constructor. */ if (code == VECTOR_TYPE && VECTOR_TYPE_P (TREE_TYPE (inside_init)) && vector_types_convertible_p (TREE_TYPE (inside_init), type, true) && TREE_CONSTANT (inside_init)) { if (TREE_CODE (inside_init) == VECTOR_CST && comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)), TYPE_MAIN_VARIANT (type))) return inside_init; if (TREE_CODE (inside_init) == CONSTRUCTOR) { unsigned HOST_WIDE_INT ix; tree value; bool constant_p = true; /* Iterate through elements and check if all constructor elements are *_CSTs. */ FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (inside_init), ix, value) if (!CONSTANT_CLASS_P (value)) { constant_p = false; break; } if (constant_p) return build_vector_from_ctor (type, CONSTRUCTOR_ELTS (inside_init)); } } if (warn_sequence_point) verify_sequence_points (inside_init); /* Any type can be initialized from an expression of the same type, optionally with braces. */ if (inside_init && TREE_TYPE (inside_init) != NULL_TREE && (comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)), TYPE_MAIN_VARIANT (type)) || (code == ARRAY_TYPE && comptypes (TREE_TYPE (inside_init), type)) || (gnu_vector_type_p (type) && comptypes (TREE_TYPE (inside_init), type)) || (code == POINTER_TYPE && TREE_CODE (TREE_TYPE (inside_init)) == ARRAY_TYPE && comptypes (TREE_TYPE (TREE_TYPE (inside_init)), TREE_TYPE (type))))) { if (code == POINTER_TYPE) { if (TREE_CODE (TREE_TYPE (inside_init)) == ARRAY_TYPE) { if (TREE_CODE (inside_init) == STRING_CST || TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR) inside_init = array_to_pointer_conversion (init_loc, inside_init); else { error_init (init_loc, "invalid use of non-lvalue array"); return error_mark_node; } } } if (code == VECTOR_TYPE) /* Although the types are compatible, we may require a conversion. */ inside_init = convert (type, inside_init); if (require_constant && TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR) { /* As an extension, allow initializing objects with static storage duration with compound literals (which are then treated just as the brace enclosed list they contain). Also allow this for vectors, as we can only assign them with compound literals. */ if (flag_isoc99 && code != VECTOR_TYPE) pedwarn_init (init_loc, OPT_Wpedantic, "initializer element " "is not constant"); tree decl = COMPOUND_LITERAL_EXPR_DECL (inside_init); inside_init = DECL_INITIAL (decl); } if (code == ARRAY_TYPE && TREE_CODE (inside_init) != STRING_CST && TREE_CODE (inside_init) != CONSTRUCTOR) { error_init (init_loc, "array initialized from non-constant array " "expression"); return error_mark_node; } /* Compound expressions can only occur here if -Wpedantic or -pedantic-errors is specified. In the later case, we always want an error. In the former case, we simply want a warning. */ if (require_constant && pedantic && TREE_CODE (inside_init) == COMPOUND_EXPR) { inside_init = valid_compound_expr_initializer (inside_init, TREE_TYPE (inside_init)); if (inside_init == error_mark_node) error_init (init_loc, "initializer element is not constant"); else pedwarn_init (init_loc, OPT_Wpedantic, "initializer element is not constant"); if (flag_pedantic_errors) inside_init = error_mark_node; } else if (require_constant && !initializer_constant_valid_p (inside_init, TREE_TYPE (inside_init))) { error_init (init_loc, "initializer element is not constant"); inside_init = error_mark_node; } else if (require_constant && !maybe_const) pedwarn_init (init_loc, OPT_Wpedantic, "initializer element is not a constant expression"); /* Added to enable additional -Wsuggest-attribute=format warnings. */ if (TREE_CODE (TREE_TYPE (inside_init)) == POINTER_TYPE) inside_init = convert_for_assignment (init_loc, UNKNOWN_LOCATION, type, inside_init, origtype, ic_init, null_pointer_constant, NULL_TREE, NULL_TREE, 0); return inside_init; } /* Handle scalar types, including conversions. */ if (code == INTEGER_TYPE || code == REAL_TYPE || code == FIXED_POINT_TYPE || code == POINTER_TYPE || code == ENUMERAL_TYPE || code == BOOLEAN_TYPE || code == COMPLEX_TYPE || code == VECTOR_TYPE) { if (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE && (TREE_CODE (init) == STRING_CST || TREE_CODE (init) == COMPOUND_LITERAL_EXPR)) inside_init = init = array_to_pointer_conversion (init_loc, init); if (semantic_type) inside_init = build1 (EXCESS_PRECISION_EXPR, semantic_type, inside_init); inside_init = convert_for_assignment (init_loc, UNKNOWN_LOCATION, type, inside_init, origtype, ic_init, null_pointer_constant, NULL_TREE, NULL_TREE, 0); /* Check to see if we have already given an error message. */ if (inside_init == error_mark_node) ; else if (require_constant && !TREE_CONSTANT (inside_init)) { error_init (init_loc, "initializer element is not constant"); inside_init = error_mark_node; } else if (require_constant && !initializer_constant_valid_p (inside_init, TREE_TYPE (inside_init))) { error_init (init_loc, "initializer element is not computable at " "load time"); inside_init = error_mark_node; } else if (require_constant && !maybe_const) pedwarn_init (init_loc, OPT_Wpedantic, "initializer element is not a constant expression"); return inside_init; } /* Come here only for records and arrays. */ if (COMPLETE_TYPE_P (type) && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST) { error_init (init_loc, "variable-sized object may not be initialized"); return error_mark_node; } error_init (init_loc, "invalid initializer"); return error_mark_node; } /* Handle initializers that use braces. */ /* Type of object we are accumulating a constructor for. This type is always a RECORD_TYPE, UNION_TYPE or ARRAY_TYPE. */ static tree constructor_type; /* For a RECORD_TYPE or UNION_TYPE, this is the chain of fields left to fill. */ static tree constructor_fields; /* For an ARRAY_TYPE, this is the specified index at which to store the next element we get. */ static tree constructor_index; /* For an ARRAY_TYPE, this is the maximum index. */ static tree constructor_max_index; /* For a RECORD_TYPE, this is the first field not yet written out. */ static tree constructor_unfilled_fields; /* For an ARRAY_TYPE, this is the index of the first element not yet written out. */ static tree constructor_unfilled_index; /* In a RECORD_TYPE, the byte index of the next consecutive field. This is so we can generate gaps between fields, when appropriate. */ static tree constructor_bit_index; /* If we are saving up the elements rather than allocating them, this is the list of elements so far (in reverse order, most recent first). */ static vec<constructor_elt, va_gc> *constructor_elements; /* 1 if constructor should be incrementally stored into a constructor chain, 0 if all the elements should be kept in AVL tree. */ static int constructor_incremental; /* 1 if so far this constructor's elements are all compile-time constants. */ static int constructor_constant; /* 1 if so far this constructor's elements are all valid address constants. */ static int constructor_simple; /* 1 if this constructor has an element that cannot be part of a constant expression. */ static int constructor_nonconst; /* 1 if this constructor is erroneous so far. */ static int constructor_erroneous; /* 1 if this constructor is the universal zero initializer { 0 }. */ static int constructor_zeroinit; /* Structure for managing pending initializer elements, organized as an AVL tree. */ struct init_node { struct init_node *left, *right; struct init_node *parent; int balance; tree purpose; tree value; tree origtype; }; /* Tree of pending elements at this constructor level. These are elements encountered out of order which belong at places we haven't reached yet in actually writing the output. Will never hold tree nodes across GC runs. */ static struct init_node *constructor_pending_elts; /* The SPELLING_DEPTH of this constructor. */ static int constructor_depth; /* DECL node for which an initializer is being read. 0 means we are reading a constructor expression such as (struct foo) {...}. */ static tree constructor_decl; /* Nonzero if this is an initializer for a top-level decl. */ static int constructor_top_level; /* Nonzero if there were any member designators in this initializer. */ static int constructor_designated; /* Nesting depth of designator list. */ static int designator_depth; /* Nonzero if there were diagnosed errors in this designator list. */ static int designator_erroneous; /* This stack has a level for each implicit or explicit level of structuring in the initializer, including the outermost one. It saves the values of most of the variables above. */ struct constructor_range_stack; struct constructor_stack { struct constructor_stack *next; tree type; tree fields; tree index; tree max_index; tree unfilled_index; tree unfilled_fields; tree bit_index; vec<constructor_elt, va_gc> *elements; struct init_node *pending_elts; int offset; int depth; /* If value nonzero, this value should replace the entire constructor at this level. */ struct c_expr replacement_value; struct constructor_range_stack *range_stack; char constant; char simple; char nonconst; char implicit; char erroneous; char outer; char incremental; char designated; int designator_depth; }; static struct constructor_stack *constructor_stack; /* This stack represents designators from some range designator up to the last designator in the list. */ struct constructor_range_stack { struct constructor_range_stack *next, *prev; struct constructor_stack *stack; tree range_start; tree index; tree range_end; tree fields; }; static struct constructor_range_stack *constructor_range_stack; /* This stack records separate initializers that are nested. Nested initializers can't happen in ANSI C, but GNU C allows them in cases like { ... (struct foo) { ... } ... }. */ struct initializer_stack { struct initializer_stack *next; tree decl; struct constructor_stack *constructor_stack; struct constructor_range_stack *constructor_range_stack; vec<constructor_elt, va_gc> *elements; struct spelling *spelling; struct spelling *spelling_base; int spelling_size; char top_level; char require_constant_value; char require_constant_elements; rich_location *missing_brace_richloc; }; static struct initializer_stack *initializer_stack; /* Prepare to parse and output the initializer for variable DECL. */ void start_init (tree decl, tree asmspec_tree ATTRIBUTE_UNUSED, int top_level, rich_location *richloc) { const char *locus; struct initializer_stack *p = XNEW (struct initializer_stack); p->decl = constructor_decl; p->require_constant_value = require_constant_value; p->require_constant_elements = require_constant_elements; p->constructor_stack = constructor_stack; p->constructor_range_stack = constructor_range_stack; p->elements = constructor_elements; p->spelling = spelling; p->spelling_base = spelling_base; p->spelling_size = spelling_size; p->top_level = constructor_top_level; p->next = initializer_stack; p->missing_brace_richloc = richloc; initializer_stack = p; constructor_decl = decl; constructor_designated = 0; constructor_top_level = top_level; if (decl != NULL_TREE && decl != error_mark_node) { require_constant_value = TREE_STATIC (decl); require_constant_elements = ((TREE_STATIC (decl) || (pedantic && !flag_isoc99)) /* For a scalar, you can always use any value to initialize, even within braces. */ && AGGREGATE_TYPE_P (TREE_TYPE (decl))); locus = identifier_to_locale (IDENTIFIER_POINTER (DECL_NAME (decl))); } else { require_constant_value = 0; require_constant_elements = 0; locus = _("(anonymous)"); } constructor_stack = 0; constructor_range_stack = 0; found_missing_braces = 0; spelling_base = 0; spelling_size = 0; RESTORE_SPELLING_DEPTH (0); if (locus) push_string (locus); } void finish_init (void) { struct initializer_stack *p = initializer_stack; /* Free the whole constructor stack of this initializer. */ while (constructor_stack) { struct constructor_stack *q = constructor_stack; constructor_stack = q->next; free (q); } gcc_assert (!constructor_range_stack); /* Pop back to the data of the outer initializer (if any). */ free (spelling_base); constructor_decl = p->decl; require_constant_value = p->require_constant_value; require_constant_elements = p->require_constant_elements; constructor_stack = p->constructor_stack; constructor_range_stack = p->constructor_range_stack; constructor_elements = p->elements; spelling = p->spelling; spelling_base = p->spelling_base; spelling_size = p->spelling_size; constructor_top_level = p->top_level; initializer_stack = p->next; free (p); } /* Call here when we see the initializer is surrounded by braces. This is instead of a call to push_init_level; it is matched by a call to pop_init_level. TYPE is the type to initialize, for a constructor expression. For an initializer for a decl, TYPE is zero. */ void really_start_incremental_init (tree type) { struct constructor_stack *p = XNEW (struct constructor_stack); if (type == NULL_TREE) type = TREE_TYPE (constructor_decl); if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type)) error ("opaque vector types cannot be initialized"); p->type = constructor_type; p->fields = constructor_fields; p->index = constructor_index; p->max_index = constructor_max_index; p->unfilled_index = constructor_unfilled_index; p->unfilled_fields = constructor_unfilled_fields; p->bit_index = constructor_bit_index; p->elements = constructor_elements; p->constant = constructor_constant; p->simple = constructor_simple; p->nonconst = constructor_nonconst; p->erroneous = constructor_erroneous; p->pending_elts = constructor_pending_elts; p->depth = constructor_depth; p->replacement_value.value = 0; p->replacement_value.original_code = ERROR_MARK; p->replacement_value.original_type = NULL; p->implicit = 0; p->range_stack = 0; p->outer = 0; p->incremental = constructor_incremental; p->designated = constructor_designated; p->designator_depth = designator_depth; p->next = 0; constructor_stack = p; constructor_constant = 1; constructor_simple = 1; constructor_nonconst = 0; constructor_depth = SPELLING_DEPTH (); constructor_elements = NULL; constructor_pending_elts = 0; constructor_type = type; constructor_incremental = 1; constructor_designated = 0; constructor_zeroinit = 1; designator_depth = 0; designator_erroneous = 0; if (RECORD_OR_UNION_TYPE_P (constructor_type)) { constructor_fields = TYPE_FIELDS (constructor_type); /* Skip any nameless bit fields at the beginning. */ while (constructor_fields != NULL_TREE && DECL_UNNAMED_BIT_FIELD (constructor_fields)) constructor_fields = DECL_CHAIN (constructor_fields); constructor_unfilled_fields = constructor_fields; constructor_bit_index = bitsize_zero_node; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (TYPE_DOMAIN (constructor_type)) { constructor_max_index = TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type)); /* Detect non-empty initializations of zero-length arrays. */ if (constructor_max_index == NULL_TREE && TYPE_SIZE (constructor_type)) constructor_max_index = integer_minus_one_node; /* constructor_max_index needs to be an INTEGER_CST. Attempts to initialize VLAs will cause a proper error; avoid tree checking errors as well by setting a safe value. */ if (constructor_max_index && TREE_CODE (constructor_max_index) != INTEGER_CST) constructor_max_index = integer_minus_one_node; constructor_index = convert (bitsizetype, TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type))); } else { constructor_index = bitsize_zero_node; constructor_max_index = NULL_TREE; } constructor_unfilled_index = constructor_index; } else if (gnu_vector_type_p (constructor_type)) { /* Vectors are like simple fixed-size arrays. */ constructor_max_index = bitsize_int (TYPE_VECTOR_SUBPARTS (constructor_type) - 1); constructor_index = bitsize_zero_node; constructor_unfilled_index = constructor_index; } else { /* Handle the case of int x = {5}; */ constructor_fields = constructor_type; constructor_unfilled_fields = constructor_type; } } extern location_t last_init_list_comma; /* Called when we see an open brace for a nested initializer. Finish off any pending levels with implicit braces. */ void finish_implicit_inits (location_t loc, struct obstack *braced_init_obstack) { while (constructor_stack->implicit) { if (RECORD_OR_UNION_TYPE_P (constructor_type) && constructor_fields == NULL_TREE) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack, last_init_list_comma), true, braced_init_obstack); else if (TREE_CODE (constructor_type) == ARRAY_TYPE && constructor_max_index && tree_int_cst_lt (constructor_max_index, constructor_index)) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack, last_init_list_comma), true, braced_init_obstack); else break; } } /* Push down into a subobject, for initialization. If this is for an explicit set of braces, IMPLICIT is 0. If it is because the next element belongs at a lower level, IMPLICIT is 1 (or 2 if the push is because of designator list). */ void push_init_level (location_t loc, int implicit, struct obstack *braced_init_obstack) { struct constructor_stack *p; tree value = NULL_TREE; /* Unless this is an explicit brace, we need to preserve previous content if any. */ if (implicit) { if (RECORD_OR_UNION_TYPE_P (constructor_type) && constructor_fields) value = find_init_member (constructor_fields, braced_init_obstack); else if (TREE_CODE (constructor_type) == ARRAY_TYPE) value = find_init_member (constructor_index, braced_init_obstack); } p = XNEW (struct constructor_stack); p->type = constructor_type; p->fields = constructor_fields; p->index = constructor_index; p->max_index = constructor_max_index; p->unfilled_index = constructor_unfilled_index; p->unfilled_fields = constructor_unfilled_fields; p->bit_index = constructor_bit_index; p->elements = constructor_elements; p->constant = constructor_constant; p->simple = constructor_simple; p->nonconst = constructor_nonconst; p->erroneous = constructor_erroneous; p->pending_elts = constructor_pending_elts; p->depth = constructor_depth; p->replacement_value.value = NULL_TREE; p->replacement_value.original_code = ERROR_MARK; p->replacement_value.original_type = NULL; p->implicit = implicit; p->outer = 0; p->incremental = constructor_incremental; p->designated = constructor_designated; p->designator_depth = designator_depth; p->next = constructor_stack; p->range_stack = 0; constructor_stack = p; constructor_constant = 1; constructor_simple = 1; constructor_nonconst = 0; constructor_depth = SPELLING_DEPTH (); constructor_elements = NULL; constructor_incremental = 1; constructor_designated = 0; constructor_pending_elts = 0; if (!implicit) { p->range_stack = constructor_range_stack; constructor_range_stack = 0; designator_depth = 0; designator_erroneous = 0; } /* Don't die if an entire brace-pair level is superfluous in the containing level. */ if (constructor_type == NULL_TREE) ; else if (RECORD_OR_UNION_TYPE_P (constructor_type)) { /* Don't die if there are extra init elts at the end. */ if (constructor_fields == NULL_TREE) constructor_type = NULL_TREE; else { constructor_type = TREE_TYPE (constructor_fields); push_member_name (constructor_fields); constructor_depth++; } /* If upper initializer is designated, then mark this as designated too to prevent bogus warnings. */ constructor_designated = p->designated; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { constructor_type = TREE_TYPE (constructor_type); push_array_bounds (tree_to_uhwi (constructor_index)); constructor_depth++; } if (constructor_type == NULL_TREE) { error_init (loc, "extra brace group at end of initializer"); constructor_fields = NULL_TREE; constructor_unfilled_fields = NULL_TREE; return; } if (value && TREE_CODE (value) == CONSTRUCTOR) { constructor_constant = TREE_CONSTANT (value); constructor_simple = TREE_STATIC (value); constructor_nonconst = CONSTRUCTOR_NON_CONST (value); constructor_elements = CONSTRUCTOR_ELTS (value); if (!vec_safe_is_empty (constructor_elements) && (TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == ARRAY_TYPE)) set_nonincremental_init (braced_init_obstack); } if (implicit == 1) { found_missing_braces = 1; if (initializer_stack->missing_brace_richloc) initializer_stack->missing_brace_richloc->add_fixit_insert_before (loc, "{"); } if (RECORD_OR_UNION_TYPE_P (constructor_type)) { constructor_fields = TYPE_FIELDS (constructor_type); /* Skip any nameless bit fields at the beginning. */ while (constructor_fields != NULL_TREE && DECL_UNNAMED_BIT_FIELD (constructor_fields)) constructor_fields = DECL_CHAIN (constructor_fields); constructor_unfilled_fields = constructor_fields; constructor_bit_index = bitsize_zero_node; } else if (gnu_vector_type_p (constructor_type)) { /* Vectors are like simple fixed-size arrays. */ constructor_max_index = bitsize_int (TYPE_VECTOR_SUBPARTS (constructor_type) - 1); constructor_index = bitsize_int (0); constructor_unfilled_index = constructor_index; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (TYPE_DOMAIN (constructor_type)) { constructor_max_index = TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type)); /* Detect non-empty initializations of zero-length arrays. */ if (constructor_max_index == NULL_TREE && TYPE_SIZE (constructor_type)) constructor_max_index = integer_minus_one_node; /* constructor_max_index needs to be an INTEGER_CST. Attempts to initialize VLAs will cause a proper error; avoid tree checking errors as well by setting a safe value. */ if (constructor_max_index && TREE_CODE (constructor_max_index) != INTEGER_CST) constructor_max_index = integer_minus_one_node; constructor_index = convert (bitsizetype, TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type))); } else constructor_index = bitsize_zero_node; constructor_unfilled_index = constructor_index; if (value && TREE_CODE (value) == STRING_CST) { /* We need to split the char/wchar array into individual characters, so that we don't have to special case it everywhere. */ set_nonincremental_init_from_string (value, braced_init_obstack); } } else { if (constructor_type != error_mark_node) warning_init (input_location, 0, "braces around scalar initializer"); constructor_fields = constructor_type; constructor_unfilled_fields = constructor_type; } } /* At the end of an implicit or explicit brace level, finish up that level of constructor. If a single expression with redundant braces initialized that level, return the c_expr structure for that expression. Otherwise, the original_code element is set to ERROR_MARK. If we were outputting the elements as they are read, return 0 as the value from inner levels (process_init_element ignores that), but return error_mark_node as the value from the outermost level (that's what we want to put in DECL_INITIAL). Otherwise, return a CONSTRUCTOR expression as the value. */ struct c_expr pop_init_level (location_t loc, int implicit, struct obstack *braced_init_obstack, location_t insert_before) { struct constructor_stack *p; struct c_expr ret; ret.value = NULL_TREE; ret.original_code = ERROR_MARK; ret.original_type = NULL; if (implicit == 0) { /* When we come to an explicit close brace, pop any inner levels that didn't have explicit braces. */ while (constructor_stack->implicit) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack, insert_before), true, braced_init_obstack); gcc_assert (!constructor_range_stack); } else if (initializer_stack->missing_brace_richloc) initializer_stack->missing_brace_richloc->add_fixit_insert_before (insert_before, "}"); /* Now output all pending elements. */ constructor_incremental = 1; output_pending_init_elements (1, braced_init_obstack); p = constructor_stack; /* Error for initializing a flexible array member, or a zero-length array member in an inappropriate context. */ if (constructor_type && constructor_fields && TREE_CODE (constructor_type) == ARRAY_TYPE && TYPE_DOMAIN (constructor_type) && !TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type))) { /* Silently discard empty initializations. The parser will already have pedwarned for empty brackets. */ if (integer_zerop (constructor_unfilled_index)) constructor_type = NULL_TREE; else { gcc_assert (!TYPE_SIZE (constructor_type)); if (constructor_depth > 2) error_init (loc, "initialization of flexible array member in a nested context"); else pedwarn_init (loc, OPT_Wpedantic, "initialization of a flexible array member"); /* We have already issued an error message for the existence of a flexible array member not at the end of the structure. Discard the initializer so that we do not die later. */ if (DECL_CHAIN (constructor_fields) != NULL_TREE) constructor_type = NULL_TREE; } } switch (vec_safe_length (constructor_elements)) { case 0: /* Initialization with { } counts as zeroinit. */ constructor_zeroinit = 1; break; case 1: /* This might be zeroinit as well. */ if (integer_zerop ((*constructor_elements)[0].value)) constructor_zeroinit = 1; break; default: /* If the constructor has more than one element, it can't be { 0 }. */ constructor_zeroinit = 0; break; } /* Warn when some structs are initialized with direct aggregation. */ if (!implicit && found_missing_braces && warn_missing_braces && !constructor_zeroinit) { gcc_assert (initializer_stack->missing_brace_richloc); warning_at (initializer_stack->missing_brace_richloc, OPT_Wmissing_braces, "missing braces around initializer"); } /* Warn when some struct elements are implicitly initialized to zero. */ if (warn_missing_field_initializers && constructor_type && TREE_CODE (constructor_type) == RECORD_TYPE && constructor_unfilled_fields) { /* Do not warn for flexible array members or zero-length arrays. */ while (constructor_unfilled_fields && (!DECL_SIZE (constructor_unfilled_fields) || integer_zerop (DECL_SIZE (constructor_unfilled_fields)))) constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); if (constructor_unfilled_fields /* Do not warn if this level of the initializer uses member designators; it is likely to be deliberate. */ && !constructor_designated /* Do not warn about initializing with { 0 } or with { }. */ && !constructor_zeroinit) { if (warning_at (input_location, OPT_Wmissing_field_initializers, "missing initializer for field %qD of %qT", constructor_unfilled_fields, constructor_type)) inform (DECL_SOURCE_LOCATION (constructor_unfilled_fields), "%qD declared here", constructor_unfilled_fields); } } /* Pad out the end of the structure. */ if (p->replacement_value.value) /* If this closes a superfluous brace pair, just pass out the element between them. */ ret = p->replacement_value; else if (constructor_type == NULL_TREE) ; else if (!RECORD_OR_UNION_TYPE_P (constructor_type) && TREE_CODE (constructor_type) != ARRAY_TYPE && !gnu_vector_type_p (constructor_type)) { /* A nonincremental scalar initializer--just return the element, after verifying there is just one. */ if (vec_safe_is_empty (constructor_elements)) { if (!constructor_erroneous && constructor_type != error_mark_node) error_init (loc, "empty scalar initializer"); ret.value = error_mark_node; } else if (vec_safe_length (constructor_elements) != 1) { error_init (loc, "extra elements in scalar initializer"); ret.value = (*constructor_elements)[0].value; } else ret.value = (*constructor_elements)[0].value; } else { if (constructor_erroneous) ret.value = error_mark_node; else { ret.value = build_constructor (constructor_type, constructor_elements); if (constructor_constant) TREE_CONSTANT (ret.value) = 1; if (constructor_constant && constructor_simple) TREE_STATIC (ret.value) = 1; if (constructor_nonconst) CONSTRUCTOR_NON_CONST (ret.value) = 1; } } if (ret.value && TREE_CODE (ret.value) != CONSTRUCTOR) { if (constructor_nonconst) ret.original_code = C_MAYBE_CONST_EXPR; else if (ret.original_code == C_MAYBE_CONST_EXPR) ret.original_code = ERROR_MARK; } constructor_type = p->type; constructor_fields = p->fields; constructor_index = p->index; constructor_max_index = p->max_index; constructor_unfilled_index = p->unfilled_index; constructor_unfilled_fields = p->unfilled_fields; constructor_bit_index = p->bit_index; constructor_elements = p->elements; constructor_constant = p->constant; constructor_simple = p->simple; constructor_nonconst = p->nonconst; constructor_erroneous = p->erroneous; constructor_incremental = p->incremental; constructor_designated = p->designated; designator_depth = p->designator_depth; constructor_pending_elts = p->pending_elts; constructor_depth = p->depth; if (!p->implicit) constructor_range_stack = p->range_stack; RESTORE_SPELLING_DEPTH (constructor_depth); constructor_stack = p->next; free (p); if (ret.value == NULL_TREE && constructor_stack == 0) ret.value = error_mark_node; return ret; } /* Common handling for both array range and field name designators. ARRAY argument is nonzero for array ranges. Returns false for success. */ static bool set_designator (location_t loc, bool array, struct obstack *braced_init_obstack) { tree subtype; enum tree_code subcode; /* Don't die if an entire brace-pair level is superfluous in the containing level, or for an erroneous type. */ if (constructor_type == NULL_TREE || constructor_type == error_mark_node) return true; /* If there were errors in this designator list already, bail out silently. */ if (designator_erroneous) return true; /* Likewise for an initializer for a variable-size type. Those are diagnosed in digest_init. */ if (COMPLETE_TYPE_P (constructor_type) && TREE_CODE (TYPE_SIZE (constructor_type)) != INTEGER_CST) return true; if (!designator_depth) { gcc_assert (!constructor_range_stack); /* Designator list starts at the level of closest explicit braces. */ while (constructor_stack->implicit) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack, last_init_list_comma), true, braced_init_obstack); constructor_designated = 1; return false; } switch (TREE_CODE (constructor_type)) { case RECORD_TYPE: case UNION_TYPE: subtype = TREE_TYPE (constructor_fields); if (subtype != error_mark_node) subtype = TYPE_MAIN_VARIANT (subtype); break; case ARRAY_TYPE: subtype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type)); break; default: gcc_unreachable (); } subcode = TREE_CODE (subtype); if (array && subcode != ARRAY_TYPE) { error_init (loc, "array index in non-array initializer"); return true; } else if (!array && subcode != RECORD_TYPE && subcode != UNION_TYPE) { error_init (loc, "field name not in record or union initializer"); return true; } constructor_designated = 1; finish_implicit_inits (loc, braced_init_obstack); push_init_level (loc, 2, braced_init_obstack); return false; } /* If there are range designators in designator list, push a new designator to constructor_range_stack. RANGE_END is end of such stack range or NULL_TREE if there is no range designator at this level. */ static void push_range_stack (tree range_end, struct obstack * braced_init_obstack) { struct constructor_range_stack *p; p = (struct constructor_range_stack *) obstack_alloc (braced_init_obstack, sizeof (struct constructor_range_stack)); p->prev = constructor_range_stack; p->next = 0; p->fields = constructor_fields; p->range_start = constructor_index; p->index = constructor_index; p->stack = constructor_stack; p->range_end = range_end; if (constructor_range_stack) constructor_range_stack->next = p; constructor_range_stack = p; } /* Within an array initializer, specify the next index to be initialized. FIRST is that index. If LAST is nonzero, then initialize a range of indices, running from FIRST through LAST. */ void set_init_index (location_t loc, tree first, tree last, struct obstack *braced_init_obstack) { if (set_designator (loc, true, braced_init_obstack)) return; designator_erroneous = 1; if (!INTEGRAL_TYPE_P (TREE_TYPE (first)) || (last && !INTEGRAL_TYPE_P (TREE_TYPE (last)))) { error_init (loc, "array index in initializer not of integer type"); return; } if (TREE_CODE (first) != INTEGER_CST) { first = c_fully_fold (first, false, NULL); if (TREE_CODE (first) == INTEGER_CST) pedwarn_init (loc, OPT_Wpedantic, "array index in initializer is not " "an integer constant expression"); } if (last && TREE_CODE (last) != INTEGER_CST) { last = c_fully_fold (last, false, NULL); if (TREE_CODE (last) == INTEGER_CST) pedwarn_init (loc, OPT_Wpedantic, "array index in initializer is not " "an integer constant expression"); } if (TREE_CODE (first) != INTEGER_CST) error_init (loc, "nonconstant array index in initializer"); else if (last != NULL_TREE && TREE_CODE (last) != INTEGER_CST) error_init (loc, "nonconstant array index in initializer"); else if (TREE_CODE (constructor_type) != ARRAY_TYPE) error_init (loc, "array index in non-array initializer"); else if (tree_int_cst_sgn (first) == -1) error_init (loc, "array index in initializer exceeds array bounds"); else if (constructor_max_index && tree_int_cst_lt (constructor_max_index, first)) error_init (loc, "array index in initializer exceeds array bounds"); else { constant_expression_warning (first); if (last) constant_expression_warning (last); constructor_index = convert (bitsizetype, first); if (tree_int_cst_lt (constructor_index, first)) { constructor_index = copy_node (constructor_index); TREE_OVERFLOW (constructor_index) = 1; } if (last) { if (tree_int_cst_equal (first, last)) last = NULL_TREE; else if (tree_int_cst_lt (last, first)) { error_init (loc, "empty index range in initializer"); last = NULL_TREE; } else { last = convert (bitsizetype, last); if (constructor_max_index != NULL_TREE && tree_int_cst_lt (constructor_max_index, last)) { error_init (loc, "array index range in initializer exceeds " "array bounds"); last = NULL_TREE; } } } designator_depth++; designator_erroneous = 0; if (constructor_range_stack || last) push_range_stack (last, braced_init_obstack); } } /* Within a struct initializer, specify the next field to be initialized. */ void set_init_label (location_t loc, tree fieldname, location_t fieldname_loc, struct obstack *braced_init_obstack) { tree field; if (set_designator (loc, false, braced_init_obstack)) return; designator_erroneous = 1; if (!RECORD_OR_UNION_TYPE_P (constructor_type)) { error_init (loc, "field name not in record or union initializer"); return; } field = lookup_field (constructor_type, fieldname); if (field == NULL_TREE) { tree guessed_id = lookup_field_fuzzy (constructor_type, fieldname); if (guessed_id) { gcc_rich_location rich_loc (fieldname_loc); rich_loc.add_fixit_misspelled_id (fieldname_loc, guessed_id); error_at (&rich_loc, "%qT has no member named %qE; did you mean %qE?", constructor_type, fieldname, guessed_id); } else error_at (fieldname_loc, "%qT has no member named %qE", constructor_type, fieldname); } else do { constructor_fields = TREE_VALUE (field); designator_depth++; designator_erroneous = 0; if (constructor_range_stack) push_range_stack (NULL_TREE, braced_init_obstack); field = TREE_CHAIN (field); if (field) { if (set_designator (loc, false, braced_init_obstack)) return; } } while (field != NULL_TREE); } /* Add a new initializer to the tree of pending initializers. PURPOSE identifies the initializer, either array index or field in a structure. VALUE is the value of that index or field. If ORIGTYPE is not NULL_TREE, it is the original type of VALUE. IMPLICIT is true if value comes from pop_init_level (1), the new initializer has been merged with the existing one and thus no warnings should be emitted about overriding an existing initializer. */ static void add_pending_init (location_t loc, tree purpose, tree value, tree origtype, bool implicit, struct obstack *braced_init_obstack) { struct init_node *p, **q, *r; q = &constructor_pending_elts; p = 0; if (TREE_CODE (constructor_type) == ARRAY_TYPE) { while (*q != 0) { p = *q; if (tree_int_cst_lt (purpose, p->purpose)) q = &p->left; else if (tree_int_cst_lt (p->purpose, purpose)) q = &p->right; else { if (!implicit) { if (TREE_SIDE_EFFECTS (p->value)) warning_init (loc, OPT_Woverride_init_side_effects, "initialized field with side-effects " "overwritten"); else if (warn_override_init) warning_init (loc, OPT_Woverride_init, "initialized field overwritten"); } p->value = value; p->origtype = origtype; return; } } } else { tree bitpos; bitpos = bit_position (purpose); while (*q != NULL) { p = *q; if (tree_int_cst_lt (bitpos, bit_position (p->purpose))) q = &p->left; else if (p->purpose != purpose) q = &p->right; else { if (!implicit) { if (TREE_SIDE_EFFECTS (p->value)) warning_init (loc, OPT_Woverride_init_side_effects, "initialized field with side-effects " "overwritten"); else if (warn_override_init) warning_init (loc, OPT_Woverride_init, "initialized field overwritten"); } p->value = value; p->origtype = origtype; return; } } } r = (struct init_node *) obstack_alloc (braced_init_obstack, sizeof (struct init_node)); r->purpose = purpose; r->value = value; r->origtype = origtype; *q = r; r->parent = p; r->left = 0; r->right = 0; r->balance = 0; while (p) { struct init_node *s; if (r == p->left) { if (p->balance == 0) p->balance = -1; else if (p->balance < 0) { if (r->balance < 0) { /* L rotation. */ p->left = r->right; if (p->left) p->left->parent = p; r->right = p; p->balance = 0; r->balance = 0; s = p->parent; p->parent = r; r->parent = s; if (s) { if (s->left == p) s->left = r; else s->right = r; } else constructor_pending_elts = r; } else { /* LR rotation. */ struct init_node *t = r->right; r->right = t->left; if (r->right) r->right->parent = r; t->left = r; p->left = t->right; if (p->left) p->left->parent = p; t->right = p; p->balance = t->balance < 0; r->balance = -(t->balance > 0); t->balance = 0; s = p->parent; p->parent = t; r->parent = t; t->parent = s; if (s) { if (s->left == p) s->left = t; else s->right = t; } else constructor_pending_elts = t; } break; } else { /* p->balance == +1; growth of left side balances the node. */ p->balance = 0; break; } } else /* r == p->right */ { if (p->balance == 0) /* Growth propagation from right side. */ p->balance++; else if (p->balance > 0) { if (r->balance > 0) { /* R rotation. */ p->right = r->left; if (p->right) p->right->parent = p; r->left = p; p->balance = 0; r->balance = 0; s = p->parent; p->parent = r; r->parent = s; if (s) { if (s->left == p) s->left = r; else s->right = r; } else constructor_pending_elts = r; } else /* r->balance == -1 */ { /* RL rotation */ struct init_node *t = r->left; r->left = t->right; if (r->left) r->left->parent = r; t->right = r; p->right = t->left; if (p->right) p->right->parent = p; t->left = p; r->balance = (t->balance < 0); p->balance = -(t->balance > 0); t->balance = 0; s = p->parent; p->parent = t; r->parent = t; t->parent = s; if (s) { if (s->left == p) s->left = t; else s->right = t; } else constructor_pending_elts = t; } break; } else { /* p->balance == -1; growth of right side balances the node. */ p->balance = 0; break; } } r = p; p = p->parent; } } /* Build AVL tree from a sorted chain. */ static void set_nonincremental_init (struct obstack * braced_init_obstack) { unsigned HOST_WIDE_INT ix; tree index, value; if (TREE_CODE (constructor_type) != RECORD_TYPE && TREE_CODE (constructor_type) != ARRAY_TYPE) return; FOR_EACH_CONSTRUCTOR_ELT (constructor_elements, ix, index, value) add_pending_init (input_location, index, value, NULL_TREE, true, braced_init_obstack); constructor_elements = NULL; if (TREE_CODE (constructor_type) == RECORD_TYPE) { constructor_unfilled_fields = TYPE_FIELDS (constructor_type); /* Skip any nameless bit fields at the beginning. */ while (constructor_unfilled_fields != NULL_TREE && DECL_UNNAMED_BIT_FIELD (constructor_unfilled_fields)) constructor_unfilled_fields = TREE_CHAIN (constructor_unfilled_fields); } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (TYPE_DOMAIN (constructor_type)) constructor_unfilled_index = convert (bitsizetype, TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type))); else constructor_unfilled_index = bitsize_zero_node; } constructor_incremental = 0; } /* Build AVL tree from a string constant. */ static void set_nonincremental_init_from_string (tree str, struct obstack * braced_init_obstack) { tree value, purpose, type; HOST_WIDE_INT val[2]; const char *p, *end; int byte, wchar_bytes, charwidth, bitpos; gcc_assert (TREE_CODE (constructor_type) == ARRAY_TYPE); wchar_bytes = TYPE_PRECISION (TREE_TYPE (TREE_TYPE (str))) / BITS_PER_UNIT; charwidth = TYPE_PRECISION (char_type_node); gcc_assert ((size_t) wchar_bytes * charwidth <= ARRAY_SIZE (val) * HOST_BITS_PER_WIDE_INT); type = TREE_TYPE (constructor_type); p = TREE_STRING_POINTER (str); end = p + TREE_STRING_LENGTH (str); for (purpose = bitsize_zero_node; p < end && !(constructor_max_index && tree_int_cst_lt (constructor_max_index, purpose)); purpose = size_binop (PLUS_EXPR, purpose, bitsize_one_node)) { if (wchar_bytes == 1) { val[0] = (unsigned char) *p++; val[1] = 0; } else { val[1] = 0; val[0] = 0; for (byte = 0; byte < wchar_bytes; byte++) { if (BYTES_BIG_ENDIAN) bitpos = (wchar_bytes - byte - 1) * charwidth; else bitpos = byte * charwidth; val[bitpos / HOST_BITS_PER_WIDE_INT] |= ((unsigned HOST_WIDE_INT) ((unsigned char) *p++)) << (bitpos % HOST_BITS_PER_WIDE_INT); } } if (!TYPE_UNSIGNED (type)) { bitpos = ((wchar_bytes - 1) * charwidth) + HOST_BITS_PER_CHAR; if (bitpos < HOST_BITS_PER_WIDE_INT) { if (val[0] & (HOST_WIDE_INT_1 << (bitpos - 1))) { val[0] |= HOST_WIDE_INT_M1U << bitpos; val[1] = -1; } } else if (bitpos == HOST_BITS_PER_WIDE_INT) { if (val[0] < 0) val[1] = -1; } else if (val[1] & (HOST_WIDE_INT_1 << (bitpos - 1 - HOST_BITS_PER_WIDE_INT))) val[1] |= HOST_WIDE_INT_M1U << (bitpos - HOST_BITS_PER_WIDE_INT); } value = wide_int_to_tree (type, wide_int::from_array (val, 2, HOST_BITS_PER_WIDE_INT * 2)); add_pending_init (input_location, purpose, value, NULL_TREE, true, braced_init_obstack); } constructor_incremental = 0; } /* Return value of FIELD in pending initializer or NULL_TREE if the field was not initialized yet. */ static tree find_init_member (tree field, struct obstack * braced_init_obstack) { struct init_node *p; if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (constructor_incremental && tree_int_cst_lt (field, constructor_unfilled_index)) set_nonincremental_init (braced_init_obstack); p = constructor_pending_elts; while (p) { if (tree_int_cst_lt (field, p->purpose)) p = p->left; else if (tree_int_cst_lt (p->purpose, field)) p = p->right; else return p->value; } } else if (TREE_CODE (constructor_type) == RECORD_TYPE) { tree bitpos = bit_position (field); if (constructor_incremental && (!constructor_unfilled_fields || tree_int_cst_lt (bitpos, bit_position (constructor_unfilled_fields)))) set_nonincremental_init (braced_init_obstack); p = constructor_pending_elts; while (p) { if (field == p->purpose) return p->value; else if (tree_int_cst_lt (bitpos, bit_position (p->purpose))) p = p->left; else p = p->right; } } else if (TREE_CODE (constructor_type) == UNION_TYPE) { if (!vec_safe_is_empty (constructor_elements) && (constructor_elements->last ().index == field)) return constructor_elements->last ().value; } return NULL_TREE; } /* "Output" the next constructor element. At top level, really output it to assembler code now. Otherwise, collect it in a list from which we will make a CONSTRUCTOR. If ORIGTYPE is not NULL_TREE, it is the original type of VALUE. TYPE is the data type that the containing data type wants here. FIELD is the field (a FIELD_DECL) or the index that this element fills. If VALUE is a string constant, STRICT_STRING is true if it is unparenthesized or we should not warn here for it being parenthesized. For other types of VALUE, STRICT_STRING is not used. PENDING if true means output pending elements that belong right after this element. (PENDING is normally true; it is false while outputting pending elements, to avoid recursion.) IMPLICIT is true if value comes from pop_init_level (1), the new initializer has been merged with the existing one and thus no warnings should be emitted about overriding an existing initializer. */ static void output_init_element (location_t loc, tree value, tree origtype, bool strict_string, tree type, tree field, bool pending, bool implicit, struct obstack * braced_init_obstack) { tree semantic_type = NULL_TREE; bool maybe_const = true; bool npc; if (type == error_mark_node || value == error_mark_node) { constructor_erroneous = 1; return; } if (TREE_CODE (TREE_TYPE (value)) == ARRAY_TYPE && (TREE_CODE (value) == STRING_CST || TREE_CODE (value) == COMPOUND_LITERAL_EXPR) && !(TREE_CODE (value) == STRING_CST && TREE_CODE (type) == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (type))) && !comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (value)), TYPE_MAIN_VARIANT (type))) value = array_to_pointer_conversion (input_location, value); if (TREE_CODE (value) == COMPOUND_LITERAL_EXPR && require_constant_value && pending) { /* As an extension, allow initializing objects with static storage duration with compound literals (which are then treated just as the brace enclosed list they contain). */ if (flag_isoc99) pedwarn_init (loc, OPT_Wpedantic, "initializer element is not " "constant"); tree decl = COMPOUND_LITERAL_EXPR_DECL (value); value = DECL_INITIAL (decl); } npc = null_pointer_constant_p (value); if (TREE_CODE (value) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (value); value = TREE_OPERAND (value, 0); } value = c_fully_fold (value, require_constant_value, &maybe_const); if (value == error_mark_node) constructor_erroneous = 1; else if (!TREE_CONSTANT (value)) constructor_constant = 0; else if (!initializer_constant_valid_p (value, TREE_TYPE (value), AGGREGATE_TYPE_P (constructor_type) && TYPE_REVERSE_STORAGE_ORDER (constructor_type)) || (RECORD_OR_UNION_TYPE_P (constructor_type) && DECL_C_BIT_FIELD (field) && TREE_CODE (value) != INTEGER_CST)) constructor_simple = 0; if (!maybe_const) constructor_nonconst = 1; /* Digest the initializer and issue any errors about incompatible types before issuing errors about non-constant initializers. */ tree new_value = value; if (semantic_type) new_value = build1 (EXCESS_PRECISION_EXPR, semantic_type, value); new_value = digest_init (loc, type, new_value, origtype, npc, strict_string, require_constant_value); if (new_value == error_mark_node) { constructor_erroneous = 1; return; } if (require_constant_value || require_constant_elements) constant_expression_warning (new_value); /* Proceed to check the constness of the original initializer. */ if (!initializer_constant_valid_p (value, TREE_TYPE (value))) { if (require_constant_value) { error_init (loc, "initializer element is not constant"); value = error_mark_node; } else if (require_constant_elements) pedwarn (loc, OPT_Wpedantic, "initializer element is not computable at load time"); } else if (!maybe_const && (require_constant_value || require_constant_elements)) pedwarn_init (loc, OPT_Wpedantic, "initializer element is not a constant expression"); /* Issue -Wc++-compat warnings about initializing a bitfield with enum type. */ if (warn_cxx_compat && field != NULL_TREE && TREE_CODE (field) == FIELD_DECL && DECL_BIT_FIELD_TYPE (field) != NULL_TREE && (TYPE_MAIN_VARIANT (DECL_BIT_FIELD_TYPE (field)) != TYPE_MAIN_VARIANT (type)) && TREE_CODE (DECL_BIT_FIELD_TYPE (field)) == ENUMERAL_TYPE) { tree checktype = origtype != NULL_TREE ? origtype : TREE_TYPE (value); if (checktype != error_mark_node && (TYPE_MAIN_VARIANT (checktype) != TYPE_MAIN_VARIANT (DECL_BIT_FIELD_TYPE (field)))) warning_init (loc, OPT_Wc___compat, "enum conversion in initialization is invalid in C++"); } /* If this field is empty and does not have side effects (and is not at the end of structure), don't do anything other than checking the initializer. */ if (field && (TREE_TYPE (field) == error_mark_node || (COMPLETE_TYPE_P (TREE_TYPE (field)) && integer_zerop (TYPE_SIZE (TREE_TYPE (field))) && !TREE_SIDE_EFFECTS (new_value) && (TREE_CODE (constructor_type) == ARRAY_TYPE || DECL_CHAIN (field))))) return; /* Finally, set VALUE to the initializer value digested above. */ value = new_value; /* If this element doesn't come next in sequence, put it on constructor_pending_elts. */ if (TREE_CODE (constructor_type) == ARRAY_TYPE && (!constructor_incremental || !tree_int_cst_equal (field, constructor_unfilled_index))) { if (constructor_incremental && tree_int_cst_lt (field, constructor_unfilled_index)) set_nonincremental_init (braced_init_obstack); add_pending_init (loc, field, value, origtype, implicit, braced_init_obstack); return; } else if (TREE_CODE (constructor_type) == RECORD_TYPE && (!constructor_incremental || field != constructor_unfilled_fields)) { /* We do this for records but not for unions. In a union, no matter which field is specified, it can be initialized right away since it starts at the beginning of the union. */ if (constructor_incremental) { if (!constructor_unfilled_fields) set_nonincremental_init (braced_init_obstack); else { tree bitpos, unfillpos; bitpos = bit_position (field); unfillpos = bit_position (constructor_unfilled_fields); if (tree_int_cst_lt (bitpos, unfillpos)) set_nonincremental_init (braced_init_obstack); } } add_pending_init (loc, field, value, origtype, implicit, braced_init_obstack); return; } else if (TREE_CODE (constructor_type) == UNION_TYPE && !vec_safe_is_empty (constructor_elements)) { if (!implicit) { if (TREE_SIDE_EFFECTS (constructor_elements->last ().value)) warning_init (loc, OPT_Woverride_init_side_effects, "initialized field with side-effects overwritten"); else if (warn_override_init) warning_init (loc, OPT_Woverride_init, "initialized field overwritten"); } /* We can have just one union field set. */ constructor_elements = NULL; } /* Otherwise, output this element either to constructor_elements or to the assembler file. */ constructor_elt celt = {field, value}; vec_safe_push (constructor_elements, celt); /* Advance the variable that indicates sequential elements output. */ if (TREE_CODE (constructor_type) == ARRAY_TYPE) constructor_unfilled_index = size_binop_loc (input_location, PLUS_EXPR, constructor_unfilled_index, bitsize_one_node); else if (TREE_CODE (constructor_type) == RECORD_TYPE) { constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); /* Skip any nameless bit fields. */ while (constructor_unfilled_fields != NULL_TREE && DECL_UNNAMED_BIT_FIELD (constructor_unfilled_fields)) constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); } else if (TREE_CODE (constructor_type) == UNION_TYPE) constructor_unfilled_fields = NULL_TREE; /* Now output any pending elements which have become next. */ if (pending) output_pending_init_elements (0, braced_init_obstack); } /* For two FIELD_DECLs in the same chain, return -1 if field1 comes before field2, 1 if field1 comes after field2 and 0 if field1 == field2. */ static int init_field_decl_cmp (tree field1, tree field2) { if (field1 == field2) return 0; tree bitpos1 = bit_position (field1); tree bitpos2 = bit_position (field2); if (tree_int_cst_equal (bitpos1, bitpos2)) { /* If one of the fields has non-zero bitsize, then that field must be the last one in a sequence of zero sized fields, fields after it will have bigger bit_position. */ if (TREE_TYPE (field1) != error_mark_node && COMPLETE_TYPE_P (TREE_TYPE (field1)) && integer_nonzerop (TREE_TYPE (field1))) return 1; if (TREE_TYPE (field2) != error_mark_node && COMPLETE_TYPE_P (TREE_TYPE (field2)) && integer_nonzerop (TREE_TYPE (field2))) return -1; /* Otherwise, fallback to DECL_CHAIN walk to find out which field comes earlier. Walk chains of both fields, so that if field1 and field2 are close to each other in either order, it is found soon even for large sequences of zero sized fields. */ tree f1 = field1, f2 = field2; while (1) { f1 = DECL_CHAIN (f1); f2 = DECL_CHAIN (f2); if (f1 == NULL_TREE) { gcc_assert (f2); return 1; } if (f2 == NULL_TREE) return -1; if (f1 == field2) return -1; if (f2 == field1) return 1; if (!tree_int_cst_equal (bit_position (f1), bitpos1)) return 1; if (!tree_int_cst_equal (bit_position (f2), bitpos1)) return -1; } } else if (tree_int_cst_lt (bitpos1, bitpos2)) return -1; else return 1; } /* Output any pending elements which have become next. As we output elements, constructor_unfilled_{fields,index} advances, which may cause other elements to become next; if so, they too are output. If ALL is 0, we return when there are no more pending elements to output now. If ALL is 1, we output space as necessary so that we can output all the pending elements. */ static void output_pending_init_elements (int all, struct obstack * braced_init_obstack) { struct init_node *elt = constructor_pending_elts; tree next; retry: /* Look through the whole pending tree. If we find an element that should be output now, output it. Otherwise, set NEXT to the element that comes first among those still pending. */ next = NULL_TREE; while (elt) { if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (tree_int_cst_equal (elt->purpose, constructor_unfilled_index)) output_init_element (input_location, elt->value, elt->origtype, true, TREE_TYPE (constructor_type), constructor_unfilled_index, false, false, braced_init_obstack); else if (tree_int_cst_lt (constructor_unfilled_index, elt->purpose)) { /* Advance to the next smaller node. */ if (elt->left) elt = elt->left; else { /* We have reached the smallest node bigger than the current unfilled index. Fill the space first. */ next = elt->purpose; break; } } else { /* Advance to the next bigger node. */ if (elt->right) elt = elt->right; else { /* We have reached the biggest node in a subtree. Find the parent of it, which is the next bigger node. */ while (elt->parent && elt->parent->right == elt) elt = elt->parent; elt = elt->parent; if (elt && tree_int_cst_lt (constructor_unfilled_index, elt->purpose)) { next = elt->purpose; break; } } } } else if (RECORD_OR_UNION_TYPE_P (constructor_type)) { /* If the current record is complete we are done. */ if (constructor_unfilled_fields == NULL_TREE) break; int cmp = init_field_decl_cmp (constructor_unfilled_fields, elt->purpose); if (cmp == 0) output_init_element (input_location, elt->value, elt->origtype, true, TREE_TYPE (elt->purpose), elt->purpose, false, false, braced_init_obstack); else if (cmp < 0) { /* Advance to the next smaller node. */ if (elt->left) elt = elt->left; else { /* We have reached the smallest node bigger than the current unfilled field. Fill the space first. */ next = elt->purpose; break; } } else { /* Advance to the next bigger node. */ if (elt->right) elt = elt->right; else { /* We have reached the biggest node in a subtree. Find the parent of it, which is the next bigger node. */ while (elt->parent && elt->parent->right == elt) elt = elt->parent; elt = elt->parent; if (elt && init_field_decl_cmp (constructor_unfilled_fields, elt->purpose) < 0) { next = elt->purpose; break; } } } } } /* Ordinarily return, but not if we want to output all and there are elements left. */ if (!(all && next != NULL_TREE)) return; /* If it's not incremental, just skip over the gap, so that after jumping to retry we will output the next successive element. */ if (RECORD_OR_UNION_TYPE_P (constructor_type)) constructor_unfilled_fields = next; else if (TREE_CODE (constructor_type) == ARRAY_TYPE) constructor_unfilled_index = next; /* ELT now points to the node in the pending tree with the next initializer to output. */ goto retry; } /* Expression VALUE coincides with the start of type TYPE in a braced initializer. Return true if we should treat VALUE as initializing the first element of TYPE, false if we should treat it as initializing TYPE as a whole. If the initializer is clearly invalid, the question becomes: which choice gives the best error message? */ static bool initialize_elementwise_p (tree type, tree value) { if (type == error_mark_node || value == error_mark_node) return false; gcc_checking_assert (TYPE_MAIN_VARIANT (type) == type); tree value_type = TREE_TYPE (value); if (value_type == error_mark_node) return false; /* GNU vectors can be initialized elementwise. However, treat any kind of vector value as initializing the vector type as a whole, regardless of whether the value is a GNU vector. Such initializers are valid if and only if they would have been valid in a non-braced initializer like: TYPE foo = VALUE; so recursing into the vector type would be at best confusing or at worst wrong. For example, when -flax-vector-conversions is in effect, it's possible to initialize a V8HI from a V4SI, even though the vectors have different element types and different numbers of elements. */ if (gnu_vector_type_p (type)) return !VECTOR_TYPE_P (value_type); if (AGGREGATE_TYPE_P (type)) return type != TYPE_MAIN_VARIANT (value_type); return false; } /* Add one non-braced element to the current constructor level. This adjusts the current position within the constructor's type. This may also start or terminate implicit levels to handle a partly-braced initializer. Once this has found the correct level for the new element, it calls output_init_element. IMPLICIT is true if value comes from pop_init_level (1), the new initializer has been merged with the existing one and thus no warnings should be emitted about overriding an existing initializer. */ void process_init_element (location_t loc, struct c_expr value, bool implicit, struct obstack * braced_init_obstack) { tree orig_value = value.value; int string_flag = (orig_value != NULL_TREE && TREE_CODE (orig_value) == STRING_CST); bool strict_string = value.original_code == STRING_CST; bool was_designated = designator_depth != 0; designator_depth = 0; designator_erroneous = 0; if (!implicit && value.value && !integer_zerop (value.value)) constructor_zeroinit = 0; /* Handle superfluous braces around string cst as in char x[] = {"foo"}; */ if (string_flag && constructor_type && !was_designated && TREE_CODE (constructor_type) == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (constructor_type)) && integer_zerop (constructor_unfilled_index)) { if (constructor_stack->replacement_value.value) error_init (loc, "excess elements in %<char%> array initializer"); constructor_stack->replacement_value = value; return; } if (constructor_stack->replacement_value.value != NULL_TREE) { error_init (loc, "excess elements in struct initializer"); return; } /* Ignore elements of a brace group if it is entirely superfluous and has already been diagnosed, or if the type is erroneous. */ if (constructor_type == NULL_TREE || constructor_type == error_mark_node) return; /* Ignore elements of an initializer for a variable-size type. Those are diagnosed in digest_init. */ if (COMPLETE_TYPE_P (constructor_type) && !poly_int_tree_p (TYPE_SIZE (constructor_type))) return; if (!implicit && warn_designated_init && !was_designated && TREE_CODE (constructor_type) == RECORD_TYPE && lookup_attribute ("designated_init", TYPE_ATTRIBUTES (constructor_type))) warning_init (loc, OPT_Wdesignated_init, "positional initialization of field " "in %<struct%> declared with %<designated_init%> attribute"); /* If we've exhausted any levels that didn't have braces, pop them now. */ while (constructor_stack->implicit) { if (RECORD_OR_UNION_TYPE_P (constructor_type) && constructor_fields == NULL_TREE) process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack, last_init_list_comma), true, braced_init_obstack); else if ((TREE_CODE (constructor_type) == ARRAY_TYPE || gnu_vector_type_p (constructor_type)) && constructor_max_index && tree_int_cst_lt (constructor_max_index, constructor_index)) process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack, last_init_list_comma), true, braced_init_obstack); else break; } /* In the case of [LO ... HI] = VALUE, only evaluate VALUE once. */ if (constructor_range_stack) { /* If value is a compound literal and we'll be just using its content, don't put it into a SAVE_EXPR. */ if (TREE_CODE (value.value) != COMPOUND_LITERAL_EXPR || !require_constant_value) { tree semantic_type = NULL_TREE; if (TREE_CODE (value.value) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (value.value); value.value = TREE_OPERAND (value.value, 0); } value.value = save_expr (value.value); if (semantic_type) value.value = build1 (EXCESS_PRECISION_EXPR, semantic_type, value.value); } } while (1) { if (TREE_CODE (constructor_type) == RECORD_TYPE) { tree fieldtype; enum tree_code fieldcode; if (constructor_fields == NULL_TREE) { pedwarn_init (loc, 0, "excess elements in struct initializer"); break; } fieldtype = TREE_TYPE (constructor_fields); if (fieldtype != error_mark_node) fieldtype = TYPE_MAIN_VARIANT (fieldtype); fieldcode = TREE_CODE (fieldtype); /* Error for non-static initialization of a flexible array member. */ if (fieldcode == ARRAY_TYPE && !require_constant_value && TYPE_SIZE (fieldtype) == NULL_TREE && DECL_CHAIN (constructor_fields) == NULL_TREE) { error_init (loc, "non-static initialization of a flexible " "array member"); break; } /* Error for initialization of a flexible array member with a string constant if the structure is in an array. E.g.: struct S { int x; char y[]; }; struct S s[] = { { 1, "foo" } }; is invalid. */ if (string_flag && fieldcode == ARRAY_TYPE && constructor_depth > 1 && TYPE_SIZE (fieldtype) == NULL_TREE && DECL_CHAIN (constructor_fields) == NULL_TREE) { bool in_array_p = false; for (struct constructor_stack *p = constructor_stack; p && p->type; p = p->next) if (TREE_CODE (p->type) == ARRAY_TYPE) { in_array_p = true; break; } if (in_array_p) { error_init (loc, "initialization of flexible array " "member in a nested context"); break; } } /* Accept a string constant to initialize a subarray. */ if (value.value != NULL_TREE && fieldcode == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (fieldtype)) && string_flag) value.value = orig_value; /* Otherwise, if we have come to a subaggregate, and we don't have an element of its type, push into it. */ else if (value.value != NULL_TREE && initialize_elementwise_p (fieldtype, value.value)) { push_init_level (loc, 1, braced_init_obstack); continue; } if (value.value) { push_member_name (constructor_fields); output_init_element (loc, value.value, value.original_type, strict_string, fieldtype, constructor_fields, true, implicit, braced_init_obstack); RESTORE_SPELLING_DEPTH (constructor_depth); } else /* Do the bookkeeping for an element that was directly output as a constructor. */ { /* For a record, keep track of end position of last field. */ if (DECL_SIZE (constructor_fields)) constructor_bit_index = size_binop_loc (input_location, PLUS_EXPR, bit_position (constructor_fields), DECL_SIZE (constructor_fields)); /* If the current field was the first one not yet written out, it isn't now, so update. */ if (constructor_unfilled_fields == constructor_fields) { constructor_unfilled_fields = DECL_CHAIN (constructor_fields); /* Skip any nameless bit fields. */ while (constructor_unfilled_fields != 0 && (DECL_UNNAMED_BIT_FIELD (constructor_unfilled_fields))) constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); } } constructor_fields = DECL_CHAIN (constructor_fields); /* Skip any nameless bit fields at the beginning. */ while (constructor_fields != NULL_TREE && DECL_UNNAMED_BIT_FIELD (constructor_fields)) constructor_fields = DECL_CHAIN (constructor_fields); } else if (TREE_CODE (constructor_type) == UNION_TYPE) { tree fieldtype; enum tree_code fieldcode; if (constructor_fields == NULL_TREE) { pedwarn_init (loc, 0, "excess elements in union initializer"); break; } fieldtype = TREE_TYPE (constructor_fields); if (fieldtype != error_mark_node) fieldtype = TYPE_MAIN_VARIANT (fieldtype); fieldcode = TREE_CODE (fieldtype); /* Warn that traditional C rejects initialization of unions. We skip the warning if the value is zero. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. __STDC__ to avoid "missing initializer" warnings and relies on default initialization to zero in the traditional C case. We also skip the warning if the initializer is designated, again on the assumption that this must be conditional on __STDC__ anyway (and we've already complained about the member-designator already). */ if (!in_system_header_at (input_location) && !constructor_designated && !(value.value && (integer_zerop (value.value) || real_zerop (value.value)))) warning (OPT_Wtraditional, "traditional C rejects initialization " "of unions"); /* Accept a string constant to initialize a subarray. */ if (value.value != NULL_TREE && fieldcode == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (fieldtype)) && string_flag) value.value = orig_value; /* Otherwise, if we have come to a subaggregate, and we don't have an element of its type, push into it. */ else if (value.value != NULL_TREE && initialize_elementwise_p (fieldtype, value.value)) { push_init_level (loc, 1, braced_init_obstack); continue; } if (value.value) { push_member_name (constructor_fields); output_init_element (loc, value.value, value.original_type, strict_string, fieldtype, constructor_fields, true, implicit, braced_init_obstack); RESTORE_SPELLING_DEPTH (constructor_depth); } else /* Do the bookkeeping for an element that was directly output as a constructor. */ { constructor_bit_index = DECL_SIZE (constructor_fields); constructor_unfilled_fields = DECL_CHAIN (constructor_fields); } constructor_fields = NULL_TREE; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { tree elttype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type)); enum tree_code eltcode = TREE_CODE (elttype); /* Accept a string constant to initialize a subarray. */ if (value.value != NULL_TREE && eltcode == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (elttype)) && string_flag) value.value = orig_value; /* Otherwise, if we have come to a subaggregate, and we don't have an element of its type, push into it. */ else if (value.value != NULL_TREE && initialize_elementwise_p (elttype, value.value)) { push_init_level (loc, 1, braced_init_obstack); continue; } if (constructor_max_index != NULL_TREE && (tree_int_cst_lt (constructor_max_index, constructor_index) || integer_all_onesp (constructor_max_index))) { pedwarn_init (loc, 0, "excess elements in array initializer"); break; } /* Now output the actual element. */ if (value.value) { push_array_bounds (tree_to_uhwi (constructor_index)); output_init_element (loc, value.value, value.original_type, strict_string, elttype, constructor_index, true, implicit, braced_init_obstack); RESTORE_SPELLING_DEPTH (constructor_depth); } constructor_index = size_binop_loc (input_location, PLUS_EXPR, constructor_index, bitsize_one_node); if (!value.value) /* If we are doing the bookkeeping for an element that was directly output as a constructor, we must update constructor_unfilled_index. */ constructor_unfilled_index = constructor_index; } else if (gnu_vector_type_p (constructor_type)) { tree elttype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type)); /* Do a basic check of initializer size. Note that vectors always have a fixed size derived from their type. */ if (tree_int_cst_lt (constructor_max_index, constructor_index)) { pedwarn_init (loc, 0, "excess elements in vector initializer"); break; } /* Now output the actual element. */ if (value.value) { if (TREE_CODE (value.value) == VECTOR_CST) elttype = TYPE_MAIN_VARIANT (constructor_type); output_init_element (loc, value.value, value.original_type, strict_string, elttype, constructor_index, true, implicit, braced_init_obstack); } constructor_index = size_binop_loc (input_location, PLUS_EXPR, constructor_index, bitsize_one_node); if (!value.value) /* If we are doing the bookkeeping for an element that was directly output as a constructor, we must update constructor_unfilled_index. */ constructor_unfilled_index = constructor_index; } /* Handle the sole element allowed in a braced initializer for a scalar variable. */ else if (constructor_type != error_mark_node && constructor_fields == NULL_TREE) { pedwarn_init (loc, 0, "excess elements in scalar initializer"); break; } else { if (value.value) output_init_element (loc, value.value, value.original_type, strict_string, constructor_type, NULL_TREE, true, implicit, braced_init_obstack); constructor_fields = NULL_TREE; } /* Handle range initializers either at this level or anywhere higher in the designator stack. */ if (constructor_range_stack) { struct constructor_range_stack *p, *range_stack; int finish = 0; range_stack = constructor_range_stack; constructor_range_stack = 0; while (constructor_stack != range_stack->stack) { gcc_assert (constructor_stack->implicit); process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack, last_init_list_comma), true, braced_init_obstack); } for (p = range_stack; !p->range_end || tree_int_cst_equal (p->index, p->range_end); p = p->prev) { gcc_assert (constructor_stack->implicit); process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack, last_init_list_comma), true, braced_init_obstack); } p->index = size_binop_loc (input_location, PLUS_EXPR, p->index, bitsize_one_node); if (tree_int_cst_equal (p->index, p->range_end) && !p->prev) finish = 1; while (1) { constructor_index = p->index; constructor_fields = p->fields; if (finish && p->range_end && p->index == p->range_start) { finish = 0; p->prev = 0; } p = p->next; if (!p) break; finish_implicit_inits (loc, braced_init_obstack); push_init_level (loc, 2, braced_init_obstack); p->stack = constructor_stack; if (p->range_end && tree_int_cst_equal (p->index, p->range_end)) p->index = p->range_start; } if (!finish) constructor_range_stack = range_stack; continue; } break; } constructor_range_stack = 0; } /* Build a complete asm-statement, whose components are a CV_QUALIFIER (guaranteed to be 'volatile' or null) and ARGS (represented using an ASM_EXPR node). */ tree build_asm_stmt (bool is_volatile, tree args) { if (is_volatile) ASM_VOLATILE_P (args) = 1; return add_stmt (args); } /* Build an asm-expr, whose components are a STRING, some OUTPUTS, some INPUTS, and some CLOBBERS. The latter three may be NULL. SIMPLE indicates whether there was anything at all after the string in the asm expression -- asm("blah") and asm("blah" : ) are subtly different. We use a ASM_EXPR node to represent this. LOC is the location of the asm, and IS_INLINE says whether this is asm inline. */ tree build_asm_expr (location_t loc, tree string, tree outputs, tree inputs, tree clobbers, tree labels, bool simple, bool is_inline) { tree tail; tree args; int i; const char *constraint; const char **oconstraints; bool allows_mem, allows_reg, is_inout; int ninputs, noutputs; ninputs = list_length (inputs); noutputs = list_length (outputs); oconstraints = (const char **) alloca (noutputs * sizeof (const char *)); string = resolve_asm_operand_names (string, outputs, inputs, labels); /* Remove output conversions that change the type but not the mode. */ for (i = 0, tail = outputs; tail; ++i, tail = TREE_CHAIN (tail)) { tree output = TREE_VALUE (tail); output = c_fully_fold (output, false, NULL, true); /* ??? Really, this should not be here. Users should be using a proper lvalue, dammit. But there's a long history of using casts in the output operands. In cases like longlong.h, this becomes a primitive form of typechecking -- if the cast can be removed, then the output operand had a type of the proper width; otherwise we'll get an error. Gross, but ... */ STRIP_NOPS (output); if (!lvalue_or_else (loc, output, lv_asm)) output = error_mark_node; if (output != error_mark_node && (TREE_READONLY (output) || TYPE_READONLY (TREE_TYPE (output)) || (RECORD_OR_UNION_TYPE_P (TREE_TYPE (output)) && C_TYPE_FIELDS_READONLY (TREE_TYPE (output))))) readonly_error (loc, output, lv_asm); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail))); oconstraints[i] = constraint; if (parse_output_constraint (&constraint, i, ninputs, noutputs, &allows_mem, &allows_reg, &is_inout)) { /* If the operand is going to end up in memory, mark it addressable. */ if (!allows_reg && !c_mark_addressable (output)) output = error_mark_node; if (!(!allows_reg && allows_mem) && output != error_mark_node && VOID_TYPE_P (TREE_TYPE (output))) { error_at (loc, "invalid use of void expression"); output = error_mark_node; } } else output = error_mark_node; TREE_VALUE (tail) = output; } for (i = 0, tail = inputs; tail; ++i, tail = TREE_CHAIN (tail)) { tree input; constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail))); input = TREE_VALUE (tail); if (parse_input_constraint (&constraint, i, ninputs, noutputs, 0, oconstraints, &allows_mem, &allows_reg)) { /* If the operand is going to end up in memory, mark it addressable. */ if (!allows_reg && allows_mem) { input = c_fully_fold (input, false, NULL, true); /* Strip the nops as we allow this case. FIXME, this really should be rejected or made deprecated. */ STRIP_NOPS (input); if (!c_mark_addressable (input)) input = error_mark_node; } else { struct c_expr expr; memset (&expr, 0, sizeof (expr)); expr.value = input; expr = convert_lvalue_to_rvalue (loc, expr, true, false); input = c_fully_fold (expr.value, false, NULL); if (input != error_mark_node && VOID_TYPE_P (TREE_TYPE (input))) { error_at (loc, "invalid use of void expression"); input = error_mark_node; } } } else input = error_mark_node; TREE_VALUE (tail) = input; } /* ASMs with labels cannot have outputs. This should have been enforced by the parser. */ gcc_assert (outputs == NULL || labels == NULL); args = build_stmt (loc, ASM_EXPR, string, outputs, inputs, clobbers, labels); /* asm statements without outputs, including simple ones, are treated as volatile. */ ASM_INPUT_P (args) = simple; ASM_VOLATILE_P (args) = (noutputs == 0); ASM_INLINE_P (args) = is_inline; return args; } /* Generate a goto statement to LABEL. LOC is the location of the GOTO. */ tree c_finish_goto_label (location_t loc, tree label) { tree decl = lookup_label_for_goto (loc, label); if (!decl) return NULL_TREE; TREE_USED (decl) = 1; { add_stmt (build_predict_expr (PRED_GOTO, NOT_TAKEN)); tree t = build1 (GOTO_EXPR, void_type_node, decl); SET_EXPR_LOCATION (t, loc); return add_stmt (t); } } /* Generate a computed goto statement to EXPR. LOC is the location of the GOTO. */ tree c_finish_goto_ptr (location_t loc, tree expr) { tree t; pedwarn (loc, OPT_Wpedantic, "ISO C forbids %<goto *expr;%>"); expr = c_fully_fold (expr, false, NULL); expr = convert (ptr_type_node, expr); t = build1 (GOTO_EXPR, void_type_node, expr); SET_EXPR_LOCATION (t, loc); return add_stmt (t); } /* Generate a C `return' statement. RETVAL is the expression for what to return, or a null pointer for `return;' with no value. LOC is the location of the return statement, or the location of the expression, if the statement has any. If ORIGTYPE is not NULL_TREE, it is the original type of RETVAL. */ tree c_finish_return (location_t loc, tree retval, tree origtype) { tree valtype = TREE_TYPE (TREE_TYPE (current_function_decl)), ret_stmt; bool no_warning = false; bool npc = false; /* Use the expansion point to handle cases such as returning NULL in a function returning void. */ location_t xloc = expansion_point_location_if_in_system_header (loc); if (TREE_THIS_VOLATILE (current_function_decl)) warning_at (xloc, 0, "function declared %<noreturn%> has a %<return%> statement"); if (retval) { tree semantic_type = NULL_TREE; npc = null_pointer_constant_p (retval); if (TREE_CODE (retval) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (retval); retval = TREE_OPERAND (retval, 0); } retval = c_fully_fold (retval, false, NULL); if (semantic_type) retval = build1 (EXCESS_PRECISION_EXPR, semantic_type, retval); } if (!retval) { current_function_returns_null = 1; if ((warn_return_type >= 0 || flag_isoc99) && valtype != NULL_TREE && TREE_CODE (valtype) != VOID_TYPE) { bool warned_here; if (flag_isoc99) warned_here = pedwarn (loc, warn_return_type >= 0 ? OPT_Wreturn_type : 0, "%<return%> with no value, in function returning non-void"); else warned_here = warning_at (loc, OPT_Wreturn_type, "%<return%> with no value, in function returning non-void"); no_warning = true; if (warned_here) inform (DECL_SOURCE_LOCATION (current_function_decl), "declared here"); } } else if (valtype == NULL_TREE || TREE_CODE (valtype) == VOID_TYPE) { current_function_returns_null = 1; bool warned_here; if (TREE_CODE (TREE_TYPE (retval)) != VOID_TYPE) warned_here = pedwarn (xloc, warn_return_type >= 0 ? OPT_Wreturn_type : 0, "%<return%> with a value, in function returning void"); else warned_here = pedwarn (xloc, OPT_Wpedantic, "ISO C forbids " "%<return%> with expression, in function returning void"); if (warned_here) inform (DECL_SOURCE_LOCATION (current_function_decl), "declared here"); } else { tree t = convert_for_assignment (loc, UNKNOWN_LOCATION, valtype, retval, origtype, ic_return, npc, NULL_TREE, NULL_TREE, 0); tree res = DECL_RESULT (current_function_decl); tree inner; bool save; current_function_returns_value = 1; if (t == error_mark_node) return NULL_TREE; save = in_late_binary_op; if (TREE_CODE (TREE_TYPE (res)) == BOOLEAN_TYPE || TREE_CODE (TREE_TYPE (res)) == COMPLEX_TYPE || (TREE_CODE (TREE_TYPE (t)) == REAL_TYPE && (TREE_CODE (TREE_TYPE (res)) == INTEGER_TYPE || TREE_CODE (TREE_TYPE (res)) == ENUMERAL_TYPE) && sanitize_flags_p (SANITIZE_FLOAT_CAST))) in_late_binary_op = true; inner = t = convert (TREE_TYPE (res), t); in_late_binary_op = save; /* Strip any conversions, additions, and subtractions, and see if we are returning the address of a local variable. Warn if so. */ while (1) { switch (TREE_CODE (inner)) { CASE_CONVERT: case NON_LVALUE_EXPR: case PLUS_EXPR: case POINTER_PLUS_EXPR: inner = TREE_OPERAND (inner, 0); continue; case MINUS_EXPR: /* If the second operand of the MINUS_EXPR has a pointer type (or is converted from it), this may be valid, so don't give a warning. */ { tree op1 = TREE_OPERAND (inner, 1); while (!POINTER_TYPE_P (TREE_TYPE (op1)) && (CONVERT_EXPR_P (op1) || TREE_CODE (op1) == NON_LVALUE_EXPR)) op1 = TREE_OPERAND (op1, 0); if (POINTER_TYPE_P (TREE_TYPE (op1))) break; inner = TREE_OPERAND (inner, 0); continue; } case ADDR_EXPR: inner = TREE_OPERAND (inner, 0); while (REFERENCE_CLASS_P (inner) && !INDIRECT_REF_P (inner)) inner = TREE_OPERAND (inner, 0); if (DECL_P (inner) && !DECL_EXTERNAL (inner) && !TREE_STATIC (inner) && DECL_CONTEXT (inner) == current_function_decl && POINTER_TYPE_P (TREE_TYPE (TREE_TYPE (current_function_decl)))) { if (TREE_CODE (inner) == LABEL_DECL) warning_at (loc, OPT_Wreturn_local_addr, "function returns address of label"); else { warning_at (loc, OPT_Wreturn_local_addr, "function returns address of local variable"); tree zero = build_zero_cst (TREE_TYPE (res)); t = build2 (COMPOUND_EXPR, TREE_TYPE (res), t, zero); } } break; default: break; } break; } retval = build2 (MODIFY_EXPR, TREE_TYPE (res), res, t); SET_EXPR_LOCATION (retval, loc); if (warn_sequence_point) verify_sequence_points (retval); } ret_stmt = build_stmt (loc, RETURN_EXPR, retval); TREE_NO_WARNING (ret_stmt) |= no_warning; return add_stmt (ret_stmt); } struct c_switch { /* The SWITCH_STMT being built. */ tree switch_stmt; /* The original type of the testing expression, i.e. before the default conversion is applied. */ tree orig_type; /* A splay-tree mapping the low element of a case range to the high element, or NULL_TREE if there is no high element. Used to determine whether or not a new case label duplicates an old case label. We need a tree, rather than simply a hash table, because of the GNU case range extension. */ splay_tree cases; /* The bindings at the point of the switch. This is used for warnings crossing decls when branching to a case label. */ struct c_spot_bindings *bindings; /* Whether the switch includes any break statements. */ bool break_stmt_seen_p; /* The next node on the stack. */ struct c_switch *next; /* Remember whether the controlling expression had boolean type before integer promotions for the sake of -Wswitch-bool. */ bool bool_cond_p; }; /* A stack of the currently active switch statements. The innermost switch statement is on the top of the stack. There is no need to mark the stack for garbage collection because it is only active during the processing of the body of a function, and we never collect at that point. */ struct c_switch *c_switch_stack; /* Start a C switch statement, testing expression EXP. Return the new SWITCH_STMT. SWITCH_LOC is the location of the `switch'. SWITCH_COND_LOC is the location of the switch's condition. EXPLICIT_CAST_P is true if the expression EXP has an explicit cast. */ tree c_start_switch (location_t switch_loc, location_t switch_cond_loc, tree exp, bool explicit_cast_p) { tree orig_type = error_mark_node; bool bool_cond_p = false; struct c_switch *cs; if (exp != error_mark_node) { orig_type = TREE_TYPE (exp); if (!INTEGRAL_TYPE_P (orig_type)) { if (orig_type != error_mark_node) { error_at (switch_cond_loc, "switch quantity not an integer"); orig_type = error_mark_node; } exp = integer_zero_node; } else { tree type = TYPE_MAIN_VARIANT (orig_type); tree e = exp; /* Warn if the condition has boolean value. */ while (TREE_CODE (e) == COMPOUND_EXPR) e = TREE_OPERAND (e, 1); if ((TREE_CODE (type) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (e))) /* Explicit cast to int suppresses this warning. */ && !(TREE_CODE (type) == INTEGER_TYPE && explicit_cast_p)) bool_cond_p = true; if (!in_system_header_at (input_location) && (type == long_integer_type_node || type == long_unsigned_type_node)) warning_at (switch_cond_loc, OPT_Wtraditional, "%<long%> switch expression not " "converted to %<int%> in ISO C"); exp = c_fully_fold (exp, false, NULL); exp = default_conversion (exp); if (warn_sequence_point) verify_sequence_points (exp); } } /* Add this new SWITCH_STMT to the stack. */ cs = XNEW (struct c_switch); cs->switch_stmt = build_stmt (switch_loc, SWITCH_STMT, exp, NULL_TREE, orig_type, NULL_TREE); cs->orig_type = orig_type; cs->cases = splay_tree_new (case_compare, NULL, NULL); cs->bindings = c_get_switch_bindings (); cs->break_stmt_seen_p = false; cs->bool_cond_p = bool_cond_p; cs->next = c_switch_stack; c_switch_stack = cs; return add_stmt (cs->switch_stmt); } /* Process a case label at location LOC. */ tree do_case (location_t loc, tree low_value, tree high_value) { tree label = NULL_TREE; if (low_value && TREE_CODE (low_value) != INTEGER_CST) { low_value = c_fully_fold (low_value, false, NULL); if (TREE_CODE (low_value) == INTEGER_CST) pedwarn (loc, OPT_Wpedantic, "case label is not an integer constant expression"); } if (high_value && TREE_CODE (high_value) != INTEGER_CST) { high_value = c_fully_fold (high_value, false, NULL); if (TREE_CODE (high_value) == INTEGER_CST) pedwarn (input_location, OPT_Wpedantic, "case label is not an integer constant expression"); } if (c_switch_stack == NULL) { if (low_value) error_at (loc, "case label not within a switch statement"); else error_at (loc, "%<default%> label not within a switch statement"); return NULL_TREE; } if (c_check_switch_jump_warnings (c_switch_stack->bindings, EXPR_LOCATION (c_switch_stack->switch_stmt), loc)) return NULL_TREE; label = c_add_case_label (loc, c_switch_stack->cases, SWITCH_STMT_COND (c_switch_stack->switch_stmt), low_value, high_value); if (label == error_mark_node) label = NULL_TREE; return label; } /* Finish the switch statement. TYPE is the original type of the controlling expression of the switch, or NULL_TREE. */ void c_finish_switch (tree body, tree type) { struct c_switch *cs = c_switch_stack; location_t switch_location; SWITCH_STMT_BODY (cs->switch_stmt) = body; /* Emit warnings as needed. */ switch_location = EXPR_LOCATION (cs->switch_stmt); c_do_switch_warnings (cs->cases, switch_location, type ? type : SWITCH_STMT_TYPE (cs->switch_stmt), SWITCH_STMT_COND (cs->switch_stmt), cs->bool_cond_p); if (c_switch_covers_all_cases_p (cs->cases, SWITCH_STMT_TYPE (cs->switch_stmt))) SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1; SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = !cs->break_stmt_seen_p; /* Pop the stack. */ c_switch_stack = cs->next; splay_tree_delete (cs->cases); c_release_switch_bindings (cs->bindings); XDELETE (cs); } /* Emit an if statement. IF_LOCUS is the location of the 'if'. COND, THEN_BLOCK and ELSE_BLOCK are expressions to be used; ELSE_BLOCK may be null. */ void c_finish_if_stmt (location_t if_locus, tree cond, tree then_block, tree else_block) { tree stmt; stmt = build3 (COND_EXPR, void_type_node, cond, then_block, else_block); SET_EXPR_LOCATION (stmt, if_locus); add_stmt (stmt); } tree c_finish_bc_stmt (location_t loc, tree label, bool is_break) { /* In switch statements break is sometimes stylistically used after a return statement. This can lead to spurious warnings about control reaching the end of a non-void function when it is inlined. Note that we are calling block_may_fallthru with language specific tree nodes; this works because block_may_fallthru returns true when given something it does not understand. */ bool skip = !block_may_fallthru (cur_stmt_list); if (is_break) switch (in_statement) { case 0: error_at (loc, "break statement not within loop or switch"); return NULL_TREE; case IN_OMP_BLOCK: error_at (loc, "invalid exit from OpenMP structured block"); return NULL_TREE; case IN_OMP_FOR: error_at (loc, "break statement used with OpenMP for loop"); return NULL_TREE; case IN_ITERATION_STMT: case IN_OBJC_FOREACH: break; default: gcc_assert (in_statement & IN_SWITCH_STMT); c_switch_stack->break_stmt_seen_p = true; break; } else switch (in_statement & ~IN_SWITCH_STMT) { case 0: error_at (loc, "continue statement not within a loop"); return NULL_TREE; case IN_OMP_BLOCK: error_at (loc, "invalid exit from OpenMP structured block"); return NULL_TREE; case IN_ITERATION_STMT: case IN_OMP_FOR: case IN_OBJC_FOREACH: break; default: gcc_unreachable (); } if (skip) return NULL_TREE; else if (in_statement & IN_OBJC_FOREACH) { /* The foreach expander produces low-level code using gotos instead of a structured loop construct. */ gcc_assert (label); return add_stmt (build_stmt (loc, GOTO_EXPR, label)); } return add_stmt (build_stmt (loc, (is_break ? BREAK_STMT : CONTINUE_STMT))); } /* A helper routine for c_process_expr_stmt and c_finish_stmt_expr. */ static void emit_side_effect_warnings (location_t loc, tree expr) { if (expr == error_mark_node) ; else if (!TREE_SIDE_EFFECTS (expr)) { if (!VOID_TYPE_P (TREE_TYPE (expr)) && !TREE_NO_WARNING (expr)) warning_at (loc, OPT_Wunused_value, "statement with no effect"); } else if (TREE_CODE (expr) == COMPOUND_EXPR) { tree r = expr; location_t cloc = loc; while (TREE_CODE (r) == COMPOUND_EXPR) { if (EXPR_HAS_LOCATION (r)) cloc = EXPR_LOCATION (r); r = TREE_OPERAND (r, 1); } if (!TREE_SIDE_EFFECTS (r) && !VOID_TYPE_P (TREE_TYPE (r)) && !CONVERT_EXPR_P (r) && !TREE_NO_WARNING (r) && !TREE_NO_WARNING (expr)) warning_at (cloc, OPT_Wunused_value, "right-hand operand of comma expression has no effect"); } else warn_if_unused_value (expr, loc); } /* Process an expression as if it were a complete statement. Emit diagnostics, but do not call ADD_STMT. LOC is the location of the statement. */ tree c_process_expr_stmt (location_t loc, tree expr) { tree exprv; if (!expr) return NULL_TREE; expr = c_fully_fold (expr, false, NULL); if (warn_sequence_point) verify_sequence_points (expr); if (TREE_TYPE (expr) != error_mark_node && !COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (expr)) && TREE_CODE (TREE_TYPE (expr)) != ARRAY_TYPE) error_at (loc, "expression statement has incomplete type"); /* If we're not processing a statement expression, warn about unused values. Warnings for statement expressions will be emitted later, once we figure out which is the result. */ if (!STATEMENT_LIST_STMT_EXPR (cur_stmt_list) && warn_unused_value) emit_side_effect_warnings (EXPR_LOC_OR_LOC (expr, loc), expr); exprv = expr; while (TREE_CODE (exprv) == COMPOUND_EXPR) exprv = TREE_OPERAND (exprv, 1); while (CONVERT_EXPR_P (exprv)) exprv = TREE_OPERAND (exprv, 0); if (DECL_P (exprv) || handled_component_p (exprv) || TREE_CODE (exprv) == ADDR_EXPR) mark_exp_read (exprv); /* If the expression is not of a type to which we cannot assign a line number, wrap the thing in a no-op NOP_EXPR. */ if (DECL_P (expr) || CONSTANT_CLASS_P (expr)) { expr = build1 (NOP_EXPR, TREE_TYPE (expr), expr); SET_EXPR_LOCATION (expr, loc); } return expr; } /* Emit an expression as a statement. LOC is the location of the expression. */ tree c_finish_expr_stmt (location_t loc, tree expr) { if (expr) return add_stmt (c_process_expr_stmt (loc, expr)); else return NULL; } /* Do the opposite and emit a statement as an expression. To begin, create a new binding level and return it. */ tree c_begin_stmt_expr (void) { tree ret; /* We must force a BLOCK for this level so that, if it is not expanded later, there is a way to turn off the entire subtree of blocks that are contained in it. */ keep_next_level (); ret = c_begin_compound_stmt (true); c_bindings_start_stmt_expr (c_switch_stack == NULL ? NULL : c_switch_stack->bindings); /* Mark the current statement list as belonging to a statement list. */ STATEMENT_LIST_STMT_EXPR (ret) = 1; return ret; } /* LOC is the location of the compound statement to which this body belongs. */ tree c_finish_stmt_expr (location_t loc, tree body) { tree last, type, tmp, val; tree *last_p; body = c_end_compound_stmt (loc, body, true); c_bindings_end_stmt_expr (c_switch_stack == NULL ? NULL : c_switch_stack->bindings); /* Locate the last statement in BODY. See c_end_compound_stmt about always returning a BIND_EXPR. */ last_p = &BIND_EXPR_BODY (body); last = BIND_EXPR_BODY (body); continue_searching: if (TREE_CODE (last) == STATEMENT_LIST) { tree_stmt_iterator l = tsi_last (last); while (!tsi_end_p (l) && TREE_CODE (tsi_stmt (l)) == DEBUG_BEGIN_STMT) tsi_prev (&l); /* This can happen with degenerate cases like ({ }). No value. */ if (tsi_end_p (l)) return body; /* If we're supposed to generate side effects warnings, process all of the statements except the last. */ if (warn_unused_value) { for (tree_stmt_iterator i = tsi_start (last); tsi_stmt (i) != tsi_stmt (l); tsi_next (&i)) { location_t tloc; tree t = tsi_stmt (i); tloc = EXPR_HAS_LOCATION (t) ? EXPR_LOCATION (t) : loc; emit_side_effect_warnings (tloc, t); } } last_p = tsi_stmt_ptr (l); last = *last_p; } /* If the end of the list is exception related, then the list was split by a call to push_cleanup. Continue searching. */ if (TREE_CODE (last) == TRY_FINALLY_EXPR || TREE_CODE (last) == TRY_CATCH_EXPR) { last_p = &TREE_OPERAND (last, 0); last = *last_p; goto continue_searching; } if (last == error_mark_node) return last; /* In the case that the BIND_EXPR is not necessary, return the expression out from inside it. */ if ((last == BIND_EXPR_BODY (body) /* Skip nested debug stmts. */ || last == expr_first (BIND_EXPR_BODY (body))) && BIND_EXPR_VARS (body) == NULL) { /* Even if this looks constant, do not allow it in a constant expression. */ last = c_wrap_maybe_const (last, true); /* Do not warn if the return value of a statement expression is unused. */ TREE_NO_WARNING (last) = 1; return last; } /* Extract the type of said expression. */ type = TREE_TYPE (last); /* If we're not returning a value at all, then the BIND_EXPR that we already have is a fine expression to return. */ if (!type || VOID_TYPE_P (type)) return body; /* Now that we've located the expression containing the value, it seems silly to make voidify_wrapper_expr repeat the process. Create a temporary of the appropriate type and stick it in a TARGET_EXPR. */ tmp = create_tmp_var_raw (type); /* Unwrap a no-op NOP_EXPR as added by c_finish_expr_stmt. This avoids tree_expr_nonnegative_p giving up immediately. */ val = last; if (TREE_CODE (val) == NOP_EXPR && TREE_TYPE (val) == TREE_TYPE (TREE_OPERAND (val, 0))) val = TREE_OPERAND (val, 0); *last_p = build2 (MODIFY_EXPR, void_type_node, tmp, val); SET_EXPR_LOCATION (*last_p, EXPR_LOCATION (last)); { tree t = build4 (TARGET_EXPR, type, tmp, body, NULL_TREE, NULL_TREE); SET_EXPR_LOCATION (t, loc); return t; } } /* Begin and end compound statements. This is as simple as pushing and popping new statement lists from the tree. */ tree c_begin_compound_stmt (bool do_scope) { tree stmt = push_stmt_list (); if (do_scope) push_scope (); return stmt; } /* End a compound statement. STMT is the statement. LOC is the location of the compound statement-- this is usually the location of the opening brace. */ tree c_end_compound_stmt (location_t loc, tree stmt, bool do_scope) { tree block = NULL; if (do_scope) { if (c_dialect_objc ()) objc_clear_super_receiver (); block = pop_scope (); } stmt = pop_stmt_list (stmt); stmt = c_build_bind_expr (loc, block, stmt); /* If this compound statement is nested immediately inside a statement expression, then force a BIND_EXPR to be created. Otherwise we'll do the wrong thing for ({ { 1; } }) or ({ 1; { } }). In particular, STATEMENT_LISTs merge, and thus we can lose track of what statement was really last. */ if (building_stmt_list_p () && STATEMENT_LIST_STMT_EXPR (cur_stmt_list) && TREE_CODE (stmt) != BIND_EXPR) { stmt = build3 (BIND_EXPR, void_type_node, NULL, stmt, NULL); TREE_SIDE_EFFECTS (stmt) = 1; SET_EXPR_LOCATION (stmt, loc); } return stmt; } /* Queue a cleanup. CLEANUP is an expression/statement to be executed when the current scope is exited. EH_ONLY is true when this is not meant to apply to normal control flow transfer. */ void push_cleanup (tree decl, tree cleanup, bool eh_only) { enum tree_code code; tree stmt, list; bool stmt_expr; code = eh_only ? TRY_CATCH_EXPR : TRY_FINALLY_EXPR; stmt = build_stmt (DECL_SOURCE_LOCATION (decl), code, NULL, cleanup); add_stmt (stmt); stmt_expr = STATEMENT_LIST_STMT_EXPR (cur_stmt_list); list = push_stmt_list (); TREE_OPERAND (stmt, 0) = list; STATEMENT_LIST_STMT_EXPR (list) = stmt_expr; } /* Build a vector comparison of ARG0 and ARG1 using CODE opcode into a value of TYPE type. Comparison is done via VEC_COND_EXPR. */ static tree build_vec_cmp (tree_code code, tree type, tree arg0, tree arg1) { tree zero_vec = build_zero_cst (type); tree minus_one_vec = build_minus_one_cst (type); tree cmp_type = truth_type_for (type); tree cmp = build2 (code, cmp_type, arg0, arg1); return build3 (VEC_COND_EXPR, type, cmp, minus_one_vec, zero_vec); } /* Build a binary-operation expression without default conversions. CODE is the kind of expression to build. LOCATION is the operator's location. This function differs from `build' in several ways: the data type of the result is computed and recorded in it, warnings are generated if arg data types are invalid, special handling for addition and subtraction of pointers is known, and some optimization is done (operations on narrow ints are done in the narrower type when that gives the same result). Constant folding is also done before the result is returned. Note that the operands will never have enumeral types, or function or array types, because either they will have the default conversions performed or they have both just been converted to some other type in which the arithmetic is to be done. */ tree build_binary_op (location_t location, enum tree_code code, tree orig_op0, tree orig_op1, bool convert_p) { tree type0, type1, orig_type0, orig_type1; tree eptype; enum tree_code code0, code1; tree op0, op1; tree ret = error_mark_node; const char *invalid_op_diag; bool op0_int_operands, op1_int_operands; bool int_const, int_const_or_overflow, int_operands; /* Expression code to give to the expression when it is built. Normally this is CODE, which is what the caller asked for, but in some special cases we change it. */ enum tree_code resultcode = code; /* Data type in which the computation is to be performed. In the simplest cases this is the common type of the arguments. */ tree result_type = NULL; /* When the computation is in excess precision, the type of the final EXCESS_PRECISION_EXPR. */ tree semantic_result_type = NULL; /* Nonzero means operands have already been type-converted in whatever way is necessary. Zero means they need to be converted to RESULT_TYPE. */ int converted = 0; /* Nonzero means create the expression with this type, rather than RESULT_TYPE. */ tree build_type = NULL_TREE; /* Nonzero means after finally constructing the expression convert it to this type. */ tree final_type = NULL_TREE; /* Nonzero if this is an operation like MIN or MAX which can safely be computed in short if both args are promoted shorts. Also implies COMMON. -1 indicates a bitwise operation; this makes a difference in the exact conditions for when it is safe to do the operation in a narrower mode. */ int shorten = 0; /* Nonzero if this is a comparison operation; if both args are promoted shorts, compare the original shorts. Also implies COMMON. */ int short_compare = 0; /* Nonzero if this is a right-shift operation, which can be computed on the original short and then promoted if the operand is a promoted short. */ int short_shift = 0; /* Nonzero means set RESULT_TYPE to the common type of the args. */ int common = 0; /* True means types are compatible as far as ObjC is concerned. */ bool objc_ok; /* True means this is an arithmetic operation that may need excess precision. */ bool may_need_excess_precision; /* True means this is a boolean operation that converts both its operands to truth-values. */ bool boolean_op = false; /* Remember whether we're doing / or %. */ bool doing_div_or_mod = false; /* Remember whether we're doing << or >>. */ bool doing_shift = false; /* Tree holding instrumentation expression. */ tree instrument_expr = NULL; if (location == UNKNOWN_LOCATION) location = input_location; op0 = orig_op0; op1 = orig_op1; op0_int_operands = EXPR_INT_CONST_OPERANDS (orig_op0); if (op0_int_operands) op0 = remove_c_maybe_const_expr (op0); op1_int_operands = EXPR_INT_CONST_OPERANDS (orig_op1); if (op1_int_operands) op1 = remove_c_maybe_const_expr (op1); int_operands = (op0_int_operands && op1_int_operands); if (int_operands) { int_const_or_overflow = (TREE_CODE (orig_op0) == INTEGER_CST && TREE_CODE (orig_op1) == INTEGER_CST); int_const = (int_const_or_overflow && !TREE_OVERFLOW (orig_op0) && !TREE_OVERFLOW (orig_op1)); } else int_const = int_const_or_overflow = false; /* Do not apply default conversion in mixed vector/scalar expression. */ if (convert_p && VECTOR_TYPE_P (TREE_TYPE (op0)) == VECTOR_TYPE_P (TREE_TYPE (op1))) { op0 = default_conversion (op0); op1 = default_conversion (op1); } orig_type0 = type0 = TREE_TYPE (op0); orig_type1 = type1 = TREE_TYPE (op1); /* The expression codes of the data types of the arguments tell us whether the arguments are integers, floating, pointers, etc. */ code0 = TREE_CODE (type0); code1 = TREE_CODE (type1); /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */ STRIP_TYPE_NOPS (op0); STRIP_TYPE_NOPS (op1); /* If an error was already reported for one of the arguments, avoid reporting another error. */ if (code0 == ERROR_MARK || code1 == ERROR_MARK) return error_mark_node; if (code0 == POINTER_TYPE && reject_gcc_builtin (op0, EXPR_LOCATION (orig_op0))) return error_mark_node; if (code1 == POINTER_TYPE && reject_gcc_builtin (op1, EXPR_LOCATION (orig_op1))) return error_mark_node; if ((invalid_op_diag = targetm.invalid_binary_op (code, type0, type1))) { error_at (location, invalid_op_diag); return error_mark_node; } switch (code) { case PLUS_EXPR: case MINUS_EXPR: case MULT_EXPR: case TRUNC_DIV_EXPR: case CEIL_DIV_EXPR: case FLOOR_DIV_EXPR: case ROUND_DIV_EXPR: case EXACT_DIV_EXPR: may_need_excess_precision = true; break; case EQ_EXPR: case NE_EXPR: case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR: /* Excess precision for implicit conversions of integers to floating point in C11 and later. */ may_need_excess_precision = (flag_isoc11 && (ANY_INTEGRAL_TYPE_P (type0) || ANY_INTEGRAL_TYPE_P (type1))); break; default: may_need_excess_precision = false; break; } if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR) { op0 = TREE_OPERAND (op0, 0); type0 = TREE_TYPE (op0); } else if (may_need_excess_precision && (eptype = excess_precision_type (type0)) != NULL_TREE) { type0 = eptype; op0 = convert (eptype, op0); } if (TREE_CODE (op1) == EXCESS_PRECISION_EXPR) { op1 = TREE_OPERAND (op1, 0); type1 = TREE_TYPE (op1); } else if (may_need_excess_precision && (eptype = excess_precision_type (type1)) != NULL_TREE) { type1 = eptype; op1 = convert (eptype, op1); } objc_ok = objc_compare_types (type0, type1, -3, NULL_TREE); /* In case when one of the operands of the binary operation is a vector and another is a scalar -- convert scalar to vector. */ if ((gnu_vector_type_p (type0) && code1 != VECTOR_TYPE) || (gnu_vector_type_p (type1) && code0 != VECTOR_TYPE)) { enum stv_conv convert_flag = scalar_to_vector (location, code, op0, op1, true); switch (convert_flag) { case stv_error: return error_mark_node; case stv_firstarg: { bool maybe_const = true; tree sc; sc = c_fully_fold (op0, false, &maybe_const); sc = save_expr (sc); sc = convert (TREE_TYPE (type1), sc); op0 = build_vector_from_val (type1, sc); if (!maybe_const) op0 = c_wrap_maybe_const (op0, true); orig_type0 = type0 = TREE_TYPE (op0); code0 = TREE_CODE (type0); converted = 1; break; } case stv_secondarg: { bool maybe_const = true; tree sc; sc = c_fully_fold (op1, false, &maybe_const); sc = save_expr (sc); sc = convert (TREE_TYPE (type0), sc); op1 = build_vector_from_val (type0, sc); if (!maybe_const) op1 = c_wrap_maybe_const (op1, true); orig_type1 = type1 = TREE_TYPE (op1); code1 = TREE_CODE (type1); converted = 1; break; } default: break; } } switch (code) { case PLUS_EXPR: /* Handle the pointer + int case. */ if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { ret = pointer_int_sum (location, PLUS_EXPR, op0, op1); goto return_build_binary_op; } else if (code1 == POINTER_TYPE && code0 == INTEGER_TYPE) { ret = pointer_int_sum (location, PLUS_EXPR, op1, op0); goto return_build_binary_op; } else common = 1; break; case MINUS_EXPR: /* Subtraction of two similar pointers. We must subtract them as integers, then divide by object size. */ if (code0 == POINTER_TYPE && code1 == POINTER_TYPE && comp_target_types (location, type0, type1)) { ret = pointer_diff (location, op0, op1, &instrument_expr); goto return_build_binary_op; } /* Handle pointer minus int. Just like pointer plus int. */ else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { ret = pointer_int_sum (location, MINUS_EXPR, op0, op1); goto return_build_binary_op; } else common = 1; break; case MULT_EXPR: common = 1; break; case TRUNC_DIV_EXPR: case CEIL_DIV_EXPR: case FLOOR_DIV_EXPR: case ROUND_DIV_EXPR: case EXACT_DIV_EXPR: doing_div_or_mod = true; warn_for_div_by_zero (location, op1); if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == FIXED_POINT_TYPE || code0 == COMPLEX_TYPE || gnu_vector_type_p (type0)) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == FIXED_POINT_TYPE || code1 == COMPLEX_TYPE || gnu_vector_type_p (type1))) { enum tree_code tcode0 = code0, tcode1 = code1; if (code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE) tcode0 = TREE_CODE (TREE_TYPE (TREE_TYPE (op0))); if (code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE) tcode1 = TREE_CODE (TREE_TYPE (TREE_TYPE (op1))); if (!((tcode0 == INTEGER_TYPE && tcode1 == INTEGER_TYPE) || (tcode0 == FIXED_POINT_TYPE && tcode1 == FIXED_POINT_TYPE))) resultcode = RDIV_EXPR; else /* Although it would be tempting to shorten always here, that loses on some targets, since the modulo instruction is undefined if the quotient can't be represented in the computation mode. We shorten only if unsigned or if dividing by something we know != -1. */ shorten = (TYPE_UNSIGNED (TREE_TYPE (orig_op0)) || (TREE_CODE (op1) == INTEGER_CST && !integer_all_onesp (op1))); common = 1; } break; case BIT_AND_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE) shorten = -1; /* Allow vector types which are not floating point types. */ else if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1) && !VECTOR_FLOAT_TYPE_P (type0) && !VECTOR_FLOAT_TYPE_P (type1)) common = 1; break; case TRUNC_MOD_EXPR: case FLOOR_MOD_EXPR: doing_div_or_mod = true; warn_for_div_by_zero (location, op1); if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1) && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE) common = 1; else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE) { /* Although it would be tempting to shorten always here, that loses on some targets, since the modulo instruction is undefined if the quotient can't be represented in the computation mode. We shorten only if unsigned or if dividing by something we know != -1. */ shorten = (TYPE_UNSIGNED (TREE_TYPE (orig_op0)) || (TREE_CODE (op1) == INTEGER_CST && !integer_all_onesp (op1))); common = 1; } break; case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: case TRUTH_AND_EXPR: case TRUTH_OR_EXPR: case TRUTH_XOR_EXPR: if ((code0 == INTEGER_TYPE || code0 == POINTER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE || code0 == FIXED_POINT_TYPE) && (code1 == INTEGER_TYPE || code1 == POINTER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE || code1 == FIXED_POINT_TYPE)) { /* Result of these operations is always an int, but that does not mean the operands should be converted to ints! */ result_type = integer_type_node; if (op0_int_operands) { op0 = c_objc_common_truthvalue_conversion (location, orig_op0); op0 = remove_c_maybe_const_expr (op0); } else op0 = c_objc_common_truthvalue_conversion (location, op0); if (op1_int_operands) { op1 = c_objc_common_truthvalue_conversion (location, orig_op1); op1 = remove_c_maybe_const_expr (op1); } else op1 = c_objc_common_truthvalue_conversion (location, op1); converted = 1; boolean_op = true; } if (code == TRUTH_ANDIF_EXPR) { int_const_or_overflow = (int_operands && TREE_CODE (orig_op0) == INTEGER_CST && (op0 == truthvalue_false_node || TREE_CODE (orig_op1) == INTEGER_CST)); int_const = (int_const_or_overflow && !TREE_OVERFLOW (orig_op0) && (op0 == truthvalue_false_node || !TREE_OVERFLOW (orig_op1))); } else if (code == TRUTH_ORIF_EXPR) { int_const_or_overflow = (int_operands && TREE_CODE (orig_op0) == INTEGER_CST && (op0 == truthvalue_true_node || TREE_CODE (orig_op1) == INTEGER_CST)); int_const = (int_const_or_overflow && !TREE_OVERFLOW (orig_op0) && (op0 == truthvalue_true_node || !TREE_OVERFLOW (orig_op1))); } break; /* Shift operations: result has same type as first operand; always convert second operand to int. Also set SHORT_SHIFT if shifting rightward. */ case RSHIFT_EXPR: if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1) && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE && known_eq (TYPE_VECTOR_SUBPARTS (type0), TYPE_VECTOR_SUBPARTS (type1))) { result_type = type0; converted = 1; } else if ((code0 == INTEGER_TYPE || code0 == FIXED_POINT_TYPE || (gnu_vector_type_p (type0) && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE)) && code1 == INTEGER_TYPE) { doing_shift = true; if (TREE_CODE (op1) == INTEGER_CST) { if (tree_int_cst_sgn (op1) < 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_negative, "right shift count is negative"); } else if (code0 == VECTOR_TYPE) { if (compare_tree_int (op1, TYPE_PRECISION (TREE_TYPE (type0))) >= 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_overflow, "right shift count >= width of vector element"); } } else { if (!integer_zerop (op1)) short_shift = 1; if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_overflow, "right shift count >= width of type"); } } } /* Use the type of the value to be shifted. */ result_type = type0; /* Avoid converting op1 to result_type later. */ converted = 1; } break; case LSHIFT_EXPR: if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1) && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE && known_eq (TYPE_VECTOR_SUBPARTS (type0), TYPE_VECTOR_SUBPARTS (type1))) { result_type = type0; converted = 1; } else if ((code0 == INTEGER_TYPE || code0 == FIXED_POINT_TYPE || (gnu_vector_type_p (type0) && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE)) && code1 == INTEGER_TYPE) { doing_shift = true; if (TREE_CODE (op0) == INTEGER_CST && tree_int_cst_sgn (op0) < 0) { /* Don't reject a left shift of a negative value in a context where a constant expression is needed in C90. */ if (flag_isoc99) int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_negative_value, "left shift of negative value"); } if (TREE_CODE (op1) == INTEGER_CST) { if (tree_int_cst_sgn (op1) < 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_negative, "left shift count is negative"); } else if (code0 == VECTOR_TYPE) { if (compare_tree_int (op1, TYPE_PRECISION (TREE_TYPE (type0))) >= 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_overflow, "left shift count >= width of vector element"); } } else if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_overflow, "left shift count >= width of type"); } else if (TREE_CODE (op0) == INTEGER_CST && maybe_warn_shift_overflow (location, op0, op1) && flag_isoc99) int_const = false; } /* Use the type of the value to be shifted. */ result_type = type0; /* Avoid converting op1 to result_type later. */ converted = 1; } break; case EQ_EXPR: case NE_EXPR: if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1)) { tree intt; if (!vector_types_compatible_elements_p (type0, type1)) { error_at (location, "comparing vectors with different " "element types"); return error_mark_node; } if (maybe_ne (TYPE_VECTOR_SUBPARTS (type0), TYPE_VECTOR_SUBPARTS (type1))) { error_at (location, "comparing vectors with different " "number of elements"); return error_mark_node; } /* It's not precisely specified how the usual arithmetic conversions apply to the vector types. Here, we use the unsigned type if one of the operands is signed and the other one is unsigned. */ if (TYPE_UNSIGNED (type0) != TYPE_UNSIGNED (type1)) { if (!TYPE_UNSIGNED (type0)) op0 = build1 (VIEW_CONVERT_EXPR, type1, op0); else op1 = build1 (VIEW_CONVERT_EXPR, type0, op1); warning_at (location, OPT_Wsign_compare, "comparison between " "types %qT and %qT", type0, type1); } /* Always construct signed integer vector type. */ intt = c_common_type_for_size (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (type0))), 0); if (!intt) { error_at (location, "could not find an integer type " "of the same size as %qT", TREE_TYPE (type0)); return error_mark_node; } result_type = build_opaque_vector_type (intt, TYPE_VECTOR_SUBPARTS (type0)); converted = 1; ret = build_vec_cmp (resultcode, result_type, op0, op1); goto return_build_binary_op; } if (FLOAT_TYPE_P (type0) || FLOAT_TYPE_P (type1)) warning_at (location, OPT_Wfloat_equal, "comparing floating-point with %<==%> or %<!=%> is unsafe"); /* Result of comparison is always int, but don't convert the args to int! */ build_type = integer_type_node; if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == FIXED_POINT_TYPE || code0 == COMPLEX_TYPE) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == FIXED_POINT_TYPE || code1 == COMPLEX_TYPE)) short_compare = 1; else if (code0 == POINTER_TYPE && null_pointer_constant_p (orig_op1)) { if (TREE_CODE (op0) == ADDR_EXPR && decl_with_nonnull_addr_p (TREE_OPERAND (op0, 0)) && !from_macro_expansion_at (location)) { if (code == EQ_EXPR) warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<false%> " "for the address of %qD will never be NULL", TREE_OPERAND (op0, 0)); else warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<true%> " "for the address of %qD will never be NULL", TREE_OPERAND (op0, 0)); } result_type = type0; } else if (code1 == POINTER_TYPE && null_pointer_constant_p (orig_op0)) { if (TREE_CODE (op1) == ADDR_EXPR && decl_with_nonnull_addr_p (TREE_OPERAND (op1, 0)) && !from_macro_expansion_at (location)) { if (code == EQ_EXPR) warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<false%> " "for the address of %qD will never be NULL", TREE_OPERAND (op1, 0)); else warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<true%> " "for the address of %qD will never be NULL", TREE_OPERAND (op1, 0)); } result_type = type1; } else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE) { tree tt0 = TREE_TYPE (type0); tree tt1 = TREE_TYPE (type1); addr_space_t as0 = TYPE_ADDR_SPACE (tt0); addr_space_t as1 = TYPE_ADDR_SPACE (tt1); addr_space_t as_common = ADDR_SPACE_GENERIC; /* Anything compares with void *. void * compares with anything. Otherwise, the targets must be compatible and both must be object or both incomplete. */ if (comp_target_types (location, type0, type1)) result_type = common_pointer_type (type0, type1); else if (!addr_space_superset (as0, as1, &as_common)) { error_at (location, "comparison of pointers to " "disjoint address spaces"); return error_mark_node; } else if (VOID_TYPE_P (tt0) && !TYPE_ATOMIC (tt0)) { if (pedantic && TREE_CODE (tt1) == FUNCTION_TYPE) pedwarn (location, OPT_Wpedantic, "ISO C forbids " "comparison of %<void *%> with function pointer"); } else if (VOID_TYPE_P (tt1) && !TYPE_ATOMIC (tt1)) { if (pedantic && TREE_CODE (tt0) == FUNCTION_TYPE) pedwarn (location, OPT_Wpedantic, "ISO C forbids " "comparison of %<void *%> with function pointer"); } else /* Avoid warning about the volatile ObjC EH puts on decls. */ if (!objc_ok) pedwarn (location, 0, "comparison of distinct pointer types lacks a cast"); if (result_type == NULL_TREE) { int qual = ENCODE_QUAL_ADDR_SPACE (as_common); result_type = build_pointer_type (build_qualified_type (void_type_node, qual)); } } else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { result_type = type0; pedwarn (location, 0, "comparison between pointer and integer"); } else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE) { result_type = type1; pedwarn (location, 0, "comparison between pointer and integer"); } if ((TREE_CODE (TREE_TYPE (orig_op0)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op0))) ^ (TREE_CODE (TREE_TYPE (orig_op1)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op1)))) maybe_warn_bool_compare (location, code, orig_op0, orig_op1); break; case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR: if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1)) { tree intt; if (!vector_types_compatible_elements_p (type0, type1)) { error_at (location, "comparing vectors with different " "element types"); return error_mark_node; } if (maybe_ne (TYPE_VECTOR_SUBPARTS (type0), TYPE_VECTOR_SUBPARTS (type1))) { error_at (location, "comparing vectors with different " "number of elements"); return error_mark_node; } /* It's not precisely specified how the usual arithmetic conversions apply to the vector types. Here, we use the unsigned type if one of the operands is signed and the other one is unsigned. */ if (TYPE_UNSIGNED (type0) != TYPE_UNSIGNED (type1)) { if (!TYPE_UNSIGNED (type0)) op0 = build1 (VIEW_CONVERT_EXPR, type1, op0); else op1 = build1 (VIEW_CONVERT_EXPR, type0, op1); warning_at (location, OPT_Wsign_compare, "comparison between " "types %qT and %qT", type0, type1); } /* Always construct signed integer vector type. */ intt = c_common_type_for_size (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (type0))), 0); if (!intt) { error_at (location, "could not find an integer type " "of the same size as %qT", TREE_TYPE (type0)); return error_mark_node; } result_type = build_opaque_vector_type (intt, TYPE_VECTOR_SUBPARTS (type0)); converted = 1; ret = build_vec_cmp (resultcode, result_type, op0, op1); goto return_build_binary_op; } build_type = integer_type_node; if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == FIXED_POINT_TYPE) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == FIXED_POINT_TYPE)) short_compare = 1; else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE) { addr_space_t as0 = TYPE_ADDR_SPACE (TREE_TYPE (type0)); addr_space_t as1 = TYPE_ADDR_SPACE (TREE_TYPE (type1)); addr_space_t as_common; if (comp_target_types (location, type0, type1)) { result_type = common_pointer_type (type0, type1); if (!COMPLETE_TYPE_P (TREE_TYPE (type0)) != !COMPLETE_TYPE_P (TREE_TYPE (type1))) pedwarn (location, 0, "comparison of complete and incomplete pointers"); else if (TREE_CODE (TREE_TYPE (type0)) == FUNCTION_TYPE) pedwarn (location, OPT_Wpedantic, "ISO C forbids " "ordered comparisons of pointers to functions"); else if (null_pointer_constant_p (orig_op0) || null_pointer_constant_p (orig_op1)) warning_at (location, OPT_Wextra, "ordered comparison of pointer with null pointer"); } else if (!addr_space_superset (as0, as1, &as_common)) { error_at (location, "comparison of pointers to " "disjoint address spaces"); return error_mark_node; } else { int qual = ENCODE_QUAL_ADDR_SPACE (as_common); result_type = build_pointer_type (build_qualified_type (void_type_node, qual)); pedwarn (location, 0, "comparison of distinct pointer types lacks a cast"); } } else if (code0 == POINTER_TYPE && null_pointer_constant_p (orig_op1)) { result_type = type0; if (pedantic) pedwarn (location, OPT_Wpedantic, "ordered comparison of pointer with integer zero"); else if (extra_warnings) warning_at (location, OPT_Wextra, "ordered comparison of pointer with integer zero"); } else if (code1 == POINTER_TYPE && null_pointer_constant_p (orig_op0)) { result_type = type1; if (pedantic) pedwarn (location, OPT_Wpedantic, "ordered comparison of pointer with integer zero"); else if (extra_warnings) warning_at (location, OPT_Wextra, "ordered comparison of pointer with integer zero"); } else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { result_type = type0; pedwarn (location, 0, "comparison between pointer and integer"); } else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE) { result_type = type1; pedwarn (location, 0, "comparison between pointer and integer"); } if ((code0 == POINTER_TYPE || code1 == POINTER_TYPE) && sanitize_flags_p (SANITIZE_POINTER_COMPARE)) { op0 = save_expr (op0); op1 = save_expr (op1); tree tt = builtin_decl_explicit (BUILT_IN_ASAN_POINTER_COMPARE); instrument_expr = build_call_expr_loc (location, tt, 2, op0, op1); } if ((TREE_CODE (TREE_TYPE (orig_op0)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op0))) ^ (TREE_CODE (TREE_TYPE (orig_op1)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op1)))) maybe_warn_bool_compare (location, code, orig_op0, orig_op1); break; default: gcc_unreachable (); } if (code0 == ERROR_MARK || code1 == ERROR_MARK) return error_mark_node; if (gnu_vector_type_p (type0) && gnu_vector_type_p (type1) && (!tree_int_cst_equal (TYPE_SIZE (type0), TYPE_SIZE (type1)) || !vector_types_compatible_elements_p (type0, type1))) { gcc_rich_location richloc (location); maybe_range_label_for_tree_type_mismatch label_for_op0 (orig_op0, orig_op1), label_for_op1 (orig_op1, orig_op0); richloc.maybe_add_expr (orig_op0, &label_for_op0); richloc.maybe_add_expr (orig_op1, &label_for_op1); binary_op_error (&richloc, code, type0, type1); return error_mark_node; } if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE || code0 == FIXED_POINT_TYPE || gnu_vector_type_p (type0)) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE || code1 == FIXED_POINT_TYPE || gnu_vector_type_p (type1))) { bool first_complex = (code0 == COMPLEX_TYPE); bool second_complex = (code1 == COMPLEX_TYPE); int none_complex = (!first_complex && !second_complex); if (shorten || common || short_compare) { result_type = c_common_type (type0, type1); do_warn_double_promotion (result_type, type0, type1, "implicit conversion from %qT to %qT " "to match other operand of binary " "expression", location); if (result_type == error_mark_node) return error_mark_node; } if (first_complex != second_complex && (code == PLUS_EXPR || code == MINUS_EXPR || code == MULT_EXPR || (code == TRUNC_DIV_EXPR && first_complex)) && TREE_CODE (TREE_TYPE (result_type)) == REAL_TYPE && flag_signed_zeros) { /* An operation on mixed real/complex operands must be handled specially, but the language-independent code can more easily optimize the plain complex arithmetic if -fno-signed-zeros. */ tree real_type = TREE_TYPE (result_type); tree real, imag; if (type0 != orig_type0 || type1 != orig_type1) { gcc_assert (may_need_excess_precision && common); semantic_result_type = c_common_type (orig_type0, orig_type1); } if (first_complex) { if (TREE_TYPE (op0) != result_type) op0 = convert_and_check (location, result_type, op0); if (TREE_TYPE (op1) != real_type) op1 = convert_and_check (location, real_type, op1); } else { if (TREE_TYPE (op0) != real_type) op0 = convert_and_check (location, real_type, op0); if (TREE_TYPE (op1) != result_type) op1 = convert_and_check (location, result_type, op1); } if (TREE_CODE (op0) == ERROR_MARK || TREE_CODE (op1) == ERROR_MARK) return error_mark_node; if (first_complex) { op0 = save_expr (op0); real = build_unary_op (EXPR_LOCATION (orig_op0), REALPART_EXPR, op0, true); imag = build_unary_op (EXPR_LOCATION (orig_op0), IMAGPART_EXPR, op0, true); switch (code) { case MULT_EXPR: case TRUNC_DIV_EXPR: op1 = save_expr (op1); imag = build2 (resultcode, real_type, imag, op1); /* Fall through. */ case PLUS_EXPR: case MINUS_EXPR: real = build2 (resultcode, real_type, real, op1); break; default: gcc_unreachable(); } } else { op1 = save_expr (op1); real = build_unary_op (EXPR_LOCATION (orig_op1), REALPART_EXPR, op1, true); imag = build_unary_op (EXPR_LOCATION (orig_op1), IMAGPART_EXPR, op1, true); switch (code) { case MULT_EXPR: op0 = save_expr (op0); imag = build2 (resultcode, real_type, op0, imag); /* Fall through. */ case PLUS_EXPR: real = build2 (resultcode, real_type, op0, real); break; case MINUS_EXPR: real = build2 (resultcode, real_type, op0, real); imag = build1 (NEGATE_EXPR, real_type, imag); break; default: gcc_unreachable(); } } ret = build2 (COMPLEX_EXPR, result_type, real, imag); goto return_build_binary_op; } /* For certain operations (which identify themselves by shorten != 0) if both args were extended from the same smaller type, do the arithmetic in that type and then extend. shorten !=0 and !=1 indicates a bitwise operation. For them, this optimization is safe only if both args are zero-extended or both are sign-extended. Otherwise, we might change the result. Eg, (short)-1 | (unsigned short)-1 is (int)-1 but calculated in (unsigned short) it would be (unsigned short)-1. */ if (shorten && none_complex) { final_type = result_type; result_type = shorten_binary_op (result_type, op0, op1, shorten == -1); } /* Shifts can be shortened if shifting right. */ if (short_shift) { int unsigned_arg; tree arg0 = get_narrower (op0, &unsigned_arg); final_type = result_type; if (arg0 == op0 && final_type == TREE_TYPE (op0)) unsigned_arg = TYPE_UNSIGNED (TREE_TYPE (op0)); if (TYPE_PRECISION (TREE_TYPE (arg0)) < TYPE_PRECISION (result_type) && tree_int_cst_sgn (op1) > 0 /* We can shorten only if the shift count is less than the number of bits in the smaller type size. */ && compare_tree_int (op1, TYPE_PRECISION (TREE_TYPE (arg0))) < 0 /* We cannot drop an unsigned shift after sign-extension. */ && (!TYPE_UNSIGNED (final_type) || unsigned_arg)) { /* Do an unsigned shift if the operand was zero-extended. */ result_type = c_common_signed_or_unsigned_type (unsigned_arg, TREE_TYPE (arg0)); /* Convert value-to-be-shifted to that type. */ if (TREE_TYPE (op0) != result_type) op0 = convert (result_type, op0); converted = 1; } } /* Comparison operations are shortened too but differently. They identify themselves by setting short_compare = 1. */ if (short_compare) { /* Don't write &op0, etc., because that would prevent op0 from being kept in a register. Instead, make copies of the our local variables and pass the copies by reference, then copy them back afterward. */ tree xop0 = op0, xop1 = op1, xresult_type = result_type; enum tree_code xresultcode = resultcode; tree val = shorten_compare (location, &xop0, &xop1, &xresult_type, &xresultcode); if (val != NULL_TREE) { ret = val; goto return_build_binary_op; } op0 = xop0, op1 = xop1; converted = 1; resultcode = xresultcode; if (c_inhibit_evaluation_warnings == 0 && !c_in_omp_for) { bool op0_maybe_const = true; bool op1_maybe_const = true; tree orig_op0_folded, orig_op1_folded; if (in_late_binary_op) { orig_op0_folded = orig_op0; orig_op1_folded = orig_op1; } else { /* Fold for the sake of possible warnings, as in build_conditional_expr. This requires the "original" values to be folded, not just op0 and op1. */ c_inhibit_evaluation_warnings++; op0 = c_fully_fold (op0, require_constant_value, &op0_maybe_const); op1 = c_fully_fold (op1, require_constant_value, &op1_maybe_const); c_inhibit_evaluation_warnings--; orig_op0_folded = c_fully_fold (orig_op0, require_constant_value, NULL); orig_op1_folded = c_fully_fold (orig_op1, require_constant_value, NULL); } if (warn_sign_compare) warn_for_sign_compare (location, orig_op0_folded, orig_op1_folded, op0, op1, result_type, resultcode); if (!in_late_binary_op && !int_operands) { if (!op0_maybe_const || TREE_CODE (op0) != INTEGER_CST) op0 = c_wrap_maybe_const (op0, !op0_maybe_const); if (!op1_maybe_const || TREE_CODE (op1) != INTEGER_CST) op1 = c_wrap_maybe_const (op1, !op1_maybe_const); } } } } /* At this point, RESULT_TYPE must be nonzero to avoid an error message. If CONVERTED is zero, both args will be converted to type RESULT_TYPE. Then the expression will be built. It will be given type FINAL_TYPE if that is nonzero; otherwise, it will be given type RESULT_TYPE. */ if (!result_type) { /* Favor showing any expression locations that are available. */ op_location_t oploc (location, UNKNOWN_LOCATION); binary_op_rich_location richloc (oploc, orig_op0, orig_op1, true); binary_op_error (&richloc, code, TREE_TYPE (op0), TREE_TYPE (op1)); return error_mark_node; } if (build_type == NULL_TREE) { build_type = result_type; if ((type0 != orig_type0 || type1 != orig_type1) && !boolean_op) { gcc_assert (may_need_excess_precision && common); semantic_result_type = c_common_type (orig_type0, orig_type1); } } if (!converted) { op0 = ep_convert_and_check (location, result_type, op0, semantic_result_type); op1 = ep_convert_and_check (location, result_type, op1, semantic_result_type); /* This can happen if one operand has a vector type, and the other has a different type. */ if (TREE_CODE (op0) == ERROR_MARK || TREE_CODE (op1) == ERROR_MARK) return error_mark_node; } if (sanitize_flags_p ((SANITIZE_SHIFT | SANITIZE_DIVIDE | SANITIZE_FLOAT_DIVIDE)) && current_function_decl != NULL_TREE && (doing_div_or_mod || doing_shift) && !require_constant_value) { /* OP0 and/or OP1 might have side-effects. */ op0 = save_expr (op0); op1 = save_expr (op1); op0 = c_fully_fold (op0, false, NULL); op1 = c_fully_fold (op1, false, NULL); if (doing_div_or_mod && (sanitize_flags_p ((SANITIZE_DIVIDE | SANITIZE_FLOAT_DIVIDE)))) instrument_expr = ubsan_instrument_division (location, op0, op1); else if (doing_shift && sanitize_flags_p (SANITIZE_SHIFT)) instrument_expr = ubsan_instrument_shift (location, code, op0, op1); } /* Treat expressions in initializers specially as they can't trap. */ if (int_const_or_overflow) ret = (require_constant_value ? fold_build2_initializer_loc (location, resultcode, build_type, op0, op1) : fold_build2_loc (location, resultcode, build_type, op0, op1)); else ret = build2 (resultcode, build_type, op0, op1); if (final_type != NULL_TREE) ret = convert (final_type, ret); return_build_binary_op: gcc_assert (ret != error_mark_node); if (TREE_CODE (ret) == INTEGER_CST && !TREE_OVERFLOW (ret) && !int_const) ret = (int_operands ? note_integer_operands (ret) : build1 (NOP_EXPR, TREE_TYPE (ret), ret)); else if (TREE_CODE (ret) != INTEGER_CST && int_operands && !in_late_binary_op) ret = note_integer_operands (ret); protected_set_expr_location (ret, location); if (instrument_expr != NULL) ret = fold_build2 (COMPOUND_EXPR, TREE_TYPE (ret), instrument_expr, ret); if (semantic_result_type) ret = build1_loc (location, EXCESS_PRECISION_EXPR, semantic_result_type, ret); return ret; } /* Convert EXPR to be a truth-value, validating its type for this purpose. LOCATION is the source location for the expression. */ tree c_objc_common_truthvalue_conversion (location_t location, tree expr) { bool int_const, int_operands; switch (TREE_CODE (TREE_TYPE (expr))) { case ARRAY_TYPE: error_at (location, "used array that cannot be converted to pointer where scalar is required"); return error_mark_node; case RECORD_TYPE: error_at (location, "used struct type value where scalar is required"); return error_mark_node; case UNION_TYPE: error_at (location, "used union type value where scalar is required"); return error_mark_node; case VOID_TYPE: error_at (location, "void value not ignored as it ought to be"); return error_mark_node; case POINTER_TYPE: if (reject_gcc_builtin (expr)) return error_mark_node; break; case FUNCTION_TYPE: gcc_unreachable (); case VECTOR_TYPE: error_at (location, "used vector type where scalar is required"); return error_mark_node; default: break; } int_const = (TREE_CODE (expr) == INTEGER_CST && !TREE_OVERFLOW (expr)); int_operands = EXPR_INT_CONST_OPERANDS (expr); if (int_operands && TREE_CODE (expr) != INTEGER_CST) { expr = remove_c_maybe_const_expr (expr); expr = build2 (NE_EXPR, integer_type_node, expr, convert (TREE_TYPE (expr), integer_zero_node)); expr = note_integer_operands (expr); } else /* ??? Should we also give an error for vectors rather than leaving those to give errors later? */ expr = c_common_truthvalue_conversion (location, expr); if (TREE_CODE (expr) == INTEGER_CST && int_operands && !int_const) { if (TREE_OVERFLOW (expr)) return expr; else return note_integer_operands (expr); } if (TREE_CODE (expr) == INTEGER_CST && !int_const) return build1 (NOP_EXPR, TREE_TYPE (expr), expr); return expr; } /* Convert EXPR to a contained DECL, updating *TC, *TI and *SE as required. */ tree c_expr_to_decl (tree expr, bool *tc ATTRIBUTE_UNUSED, bool *se) { if (TREE_CODE (expr) == COMPOUND_LITERAL_EXPR) { tree decl = COMPOUND_LITERAL_EXPR_DECL (expr); /* Executing a compound literal inside a function reinitializes it. */ if (!TREE_STATIC (decl)) *se = true; return decl; } else return expr; } /* Generate OMP construct CODE, with BODY and CLAUSES as its compound statement. LOC is the location of the construct. */ tree c_finish_omp_construct (location_t loc, enum tree_code code, tree body, tree clauses) { body = c_end_compound_stmt (loc, body, true); tree stmt = make_node (code); TREE_TYPE (stmt) = void_type_node; OMP_BODY (stmt) = body; OMP_CLAUSES (stmt) = clauses; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Generate OACC_DATA, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_DATA. */ tree c_finish_oacc_data (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OACC_DATA); TREE_TYPE (stmt) = void_type_node; OACC_DATA_CLAUSES (stmt) = clauses; OACC_DATA_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Generate OACC_HOST_DATA, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_HOST_DATA. */ tree c_finish_oacc_host_data (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OACC_HOST_DATA); TREE_TYPE (stmt) = void_type_node; OACC_HOST_DATA_CLAUSES (stmt) = clauses; OACC_HOST_DATA_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Like c_begin_compound_stmt, except force the retention of the BLOCK. */ tree c_begin_omp_parallel (void) { tree block; keep_next_level (); block = c_begin_compound_stmt (true); return block; } /* Generate OMP_PARALLEL, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OMP_PARALLEL. */ tree c_finish_omp_parallel (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OMP_PARALLEL); TREE_TYPE (stmt) = void_type_node; OMP_PARALLEL_CLAUSES (stmt) = clauses; OMP_PARALLEL_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Like c_begin_compound_stmt, except force the retention of the BLOCK. */ tree c_begin_omp_task (void) { tree block; keep_next_level (); block = c_begin_compound_stmt (true); return block; } /* Generate OMP_TASK, with CLAUSES and BLOCK as its compound statement. LOC is the location of the #pragma. */ tree c_finish_omp_task (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OMP_TASK); TREE_TYPE (stmt) = void_type_node; OMP_TASK_CLAUSES (stmt) = clauses; OMP_TASK_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Generate GOMP_cancel call for #pragma omp cancel. */ void c_finish_omp_cancel (location_t loc, tree clauses) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_CANCEL); int mask = 0; if (omp_find_clause (clauses, OMP_CLAUSE_PARALLEL)) mask = 1; else if (omp_find_clause (clauses, OMP_CLAUSE_FOR)) mask = 2; else if (omp_find_clause (clauses, OMP_CLAUSE_SECTIONS)) mask = 4; else if (omp_find_clause (clauses, OMP_CLAUSE_TASKGROUP)) mask = 8; else { error_at (loc, "%<#pragma omp cancel%> must specify one of " "%<parallel%>, %<for%>, %<sections%> or %<taskgroup%> " "clauses"); return; } tree ifc = omp_find_clause (clauses, OMP_CLAUSE_IF); if (ifc != NULL_TREE) { if (OMP_CLAUSE_IF_MODIFIER (ifc) != ERROR_MARK && OMP_CLAUSE_IF_MODIFIER (ifc) != VOID_CST) error_at (OMP_CLAUSE_LOCATION (ifc), "expected %<cancel%> %<if%> clause modifier"); else { tree ifc2 = omp_find_clause (OMP_CLAUSE_CHAIN (ifc), OMP_CLAUSE_IF); if (ifc2 != NULL_TREE) { gcc_assert (OMP_CLAUSE_IF_MODIFIER (ifc) == VOID_CST && OMP_CLAUSE_IF_MODIFIER (ifc2) != ERROR_MARK && OMP_CLAUSE_IF_MODIFIER (ifc2) != VOID_CST); error_at (OMP_CLAUSE_LOCATION (ifc2), "expected %<cancel%> %<if%> clause modifier"); } } tree type = TREE_TYPE (OMP_CLAUSE_IF_EXPR (ifc)); ifc = fold_build2_loc (OMP_CLAUSE_LOCATION (ifc), NE_EXPR, boolean_type_node, OMP_CLAUSE_IF_EXPR (ifc), build_zero_cst (type)); } else ifc = boolean_true_node; tree stmt = build_call_expr_loc (loc, fn, 2, build_int_cst (integer_type_node, mask), ifc); add_stmt (stmt); } /* Generate GOMP_cancellation_point call for #pragma omp cancellation point. */ void c_finish_omp_cancellation_point (location_t loc, tree clauses) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_CANCELLATION_POINT); int mask = 0; if (omp_find_clause (clauses, OMP_CLAUSE_PARALLEL)) mask = 1; else if (omp_find_clause (clauses, OMP_CLAUSE_FOR)) mask = 2; else if (omp_find_clause (clauses, OMP_CLAUSE_SECTIONS)) mask = 4; else if (omp_find_clause (clauses, OMP_CLAUSE_TASKGROUP)) mask = 8; else { error_at (loc, "%<#pragma omp cancellation point%> must specify one of " "%<parallel%>, %<for%>, %<sections%> or %<taskgroup%> " "clauses"); return; } tree stmt = build_call_expr_loc (loc, fn, 1, build_int_cst (integer_type_node, mask)); add_stmt (stmt); } /* Helper function for handle_omp_array_sections. Called recursively to handle multiple array-section-subscripts. C is the clause, T current expression (initially OMP_CLAUSE_DECL), which is either a TREE_LIST for array-section-subscript (TREE_PURPOSE is low-bound expression if specified, TREE_VALUE length expression if specified, TREE_CHAIN is what it has been specified after, or some decl. TYPES vector is populated with array section types, MAYBE_ZERO_LEN set to true if any of the array-section-subscript could have length of zero (explicit or implicit), FIRST_NON_ONE is the index of the first array-section-subscript which is known not to have length of one. Given say: map(a[:b][2:1][:c][:2][:d][e:f][2:5]) FIRST_NON_ONE will be 3, array-section-subscript [:b], [2:1] and [:c] all are or may have length of 1, array-section-subscript [:2] is the first one known not to have length 1. For array-section-subscript <= FIRST_NON_ONE we diagnose non-contiguous arrays if low bound isn't 0 or length isn't the array domain max + 1, for > FIRST_NON_ONE we can if MAYBE_ZERO_LEN is false. MAYBE_ZERO_LEN will be true in the above case though, as some lengths could be zero. */ static tree handle_omp_array_sections_1 (tree c, tree t, vec<tree> &types, bool &maybe_zero_len, unsigned int &first_non_one, enum c_omp_region_type ort) { tree ret, low_bound, length, type; if (TREE_CODE (t) != TREE_LIST) { if (error_operand_p (t)) return error_mark_node; ret = t; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && TYPE_ATOMIC (strip_array_types (TREE_TYPE (t)))) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (TREE_CODE (t) == COMPONENT_REF && (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TO || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FROM)) { if (DECL_BIT_FIELD (TREE_OPERAND (t, 1))) { error_at (OMP_CLAUSE_LOCATION (c), "bit-field %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } while (TREE_CODE (t) == COMPONENT_REF) { if (TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == UNION_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is a member of a union", t); return error_mark_node; } t = TREE_OPERAND (t, 0); if (ort == C_ORT_ACC && TREE_CODE (t) == MEM_REF) { if (maybe_ne (mem_ref_offset (t), 0)) error_at (OMP_CLAUSE_LOCATION (c), "cannot dereference %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else t = TREE_OPERAND (t, 0); } } } if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { if (DECL_P (t)) error_at (OMP_CLAUSE_LOCATION (c), "%qD is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } else if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && TYPE_ATOMIC (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qD in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } else if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && VAR_P (t) && DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qD is threadprivate variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND && TYPE_ATOMIC (TREE_TYPE (t)) && POINTER_TYPE_P (TREE_TYPE (t))) { /* If the array section is pointer based and the pointer itself is _Atomic qualified, we need to atomically load the pointer. */ c_expr expr; memset (&expr, 0, sizeof (expr)); expr.value = ret; expr = convert_lvalue_to_rvalue (OMP_CLAUSE_LOCATION (c), expr, false, false); ret = expr.value; } return ret; } ret = handle_omp_array_sections_1 (c, TREE_CHAIN (t), types, maybe_zero_len, first_non_one, ort); if (ret == error_mark_node || ret == NULL_TREE) return ret; type = TREE_TYPE (ret); low_bound = TREE_PURPOSE (t); length = TREE_VALUE (t); if (low_bound == error_mark_node || length == error_mark_node) return error_mark_node; if (low_bound && !INTEGRAL_TYPE_P (TREE_TYPE (low_bound))) { error_at (OMP_CLAUSE_LOCATION (c), "low bound %qE of array section does not have integral type", low_bound); return error_mark_node; } if (length && !INTEGRAL_TYPE_P (TREE_TYPE (length))) { error_at (OMP_CLAUSE_LOCATION (c), "length %qE of array section does not have integral type", length); return error_mark_node; } if (low_bound && TREE_CODE (low_bound) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (low_bound)) > TYPE_PRECISION (sizetype)) low_bound = fold_convert (sizetype, low_bound); if (length && TREE_CODE (length) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (length)) > TYPE_PRECISION (sizetype)) length = fold_convert (sizetype, length); if (low_bound == NULL_TREE) low_bound = integer_zero_node; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_ATTACH || OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_DETACH)) { if (length != integer_one_node) { error_at (OMP_CLAUSE_LOCATION (c), "expected single pointer in %qs clause", c_omp_map_clause_name (c, ort == C_ORT_ACC)); return error_mark_node; } } if (length != NULL_TREE) { if (!integer_nonzerop (length)) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IN_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TASK_REDUCTION) { if (integer_zerop (length)) { error_at (OMP_CLAUSE_LOCATION (c), "zero length array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } } else maybe_zero_len = true; } if (first_non_one == types.length () && (TREE_CODE (length) != INTEGER_CST || integer_onep (length))) first_non_one++; } if (TREE_CODE (type) == ARRAY_TYPE) { if (length == NULL_TREE && (TYPE_DOMAIN (type) == NULL_TREE || TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL_TREE)) { error_at (OMP_CLAUSE_LOCATION (c), "for unknown bound array type length expression must " "be specified"); return error_mark_node; } if (TREE_CODE (low_bound) == INTEGER_CST && tree_int_cst_sgn (low_bound) == -1) { error_at (OMP_CLAUSE_LOCATION (c), "negative low bound in array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (length != NULL_TREE && TREE_CODE (length) == INTEGER_CST && tree_int_cst_sgn (length) == -1) { error_at (OMP_CLAUSE_LOCATION (c), "negative length in array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)) && TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (type))) == INTEGER_CST) { tree size = fold_convert (sizetype, TYPE_MAX_VALUE (TYPE_DOMAIN (type))); size = size_binop (PLUS_EXPR, size, size_one_node); if (TREE_CODE (low_bound) == INTEGER_CST) { if (tree_int_cst_lt (size, low_bound)) { error_at (OMP_CLAUSE_LOCATION (c), "low bound %qE above array section size " "in %qs clause", low_bound, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (tree_int_cst_equal (size, low_bound)) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IN_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TASK_REDUCTION) { error_at (OMP_CLAUSE_LOCATION (c), "zero length array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } maybe_zero_len = true; } else if (length == NULL_TREE && first_non_one == types.length () && tree_int_cst_equal (TYPE_MAX_VALUE (TYPE_DOMAIN (type)), low_bound)) first_non_one++; } else if (length == NULL_TREE) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_REDUCTION && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_IN_REDUCTION && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_TASK_REDUCTION) maybe_zero_len = true; if (first_non_one == types.length ()) first_non_one++; } if (length && TREE_CODE (length) == INTEGER_CST) { if (tree_int_cst_lt (size, length)) { error_at (OMP_CLAUSE_LOCATION (c), "length %qE above array section size " "in %qs clause", length, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (TREE_CODE (low_bound) == INTEGER_CST) { tree lbpluslen = size_binop (PLUS_EXPR, fold_convert (sizetype, low_bound), fold_convert (sizetype, length)); if (TREE_CODE (lbpluslen) == INTEGER_CST && tree_int_cst_lt (size, lbpluslen)) { error_at (OMP_CLAUSE_LOCATION (c), "high bound %qE above array section size " "in %qs clause", lbpluslen, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } } } } else if (length == NULL_TREE) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_REDUCTION && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_IN_REDUCTION && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_TASK_REDUCTION) maybe_zero_len = true; if (first_non_one == types.length ()) first_non_one++; } /* For [lb:] we will need to evaluate lb more than once. */ if (length == NULL_TREE && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND) { tree lb = save_expr (low_bound); if (lb != low_bound) { TREE_PURPOSE (t) = lb; low_bound = lb; } } } else if (TREE_CODE (type) == POINTER_TYPE) { if (length == NULL_TREE) { if (TREE_CODE (ret) == PARM_DECL && C_ARRAY_PARAMETER (ret)) error_at (OMP_CLAUSE_LOCATION (c), "for array function parameter length expression " "must be specified"); else error_at (OMP_CLAUSE_LOCATION (c), "for pointer type length expression must be specified"); return error_mark_node; } if (length != NULL_TREE && TREE_CODE (length) == INTEGER_CST && tree_int_cst_sgn (length) == -1) { error_at (OMP_CLAUSE_LOCATION (c), "negative length in array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } /* If there is a pointer type anywhere but in the very first array-section-subscript, the array section can't be contiguous. */ if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && TREE_CODE (TREE_CHAIN (t)) == TREE_LIST) { error_at (OMP_CLAUSE_LOCATION (c), "array section is not contiguous in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } } else { error_at (OMP_CLAUSE_LOCATION (c), "%qE does not have pointer or array type", ret); return error_mark_node; } if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND) types.safe_push (TREE_TYPE (ret)); /* We will need to evaluate lb more than once. */ tree lb = save_expr (low_bound); if (lb != low_bound) { TREE_PURPOSE (t) = lb; low_bound = lb; } ret = build_array_ref (OMP_CLAUSE_LOCATION (c), ret, low_bound); return ret; } /* Handle array sections for clause C. */ static bool handle_omp_array_sections (tree c, enum c_omp_region_type ort) { bool maybe_zero_len = false; unsigned int first_non_one = 0; auto_vec<tree, 10> types; tree *tp = &OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND && TREE_CODE (*tp) == TREE_LIST && TREE_PURPOSE (*tp) && TREE_CODE (TREE_PURPOSE (*tp)) == TREE_VEC) tp = &TREE_VALUE (*tp); tree first = handle_omp_array_sections_1 (c, *tp, types, maybe_zero_len, first_non_one, ort); if (first == error_mark_node) return true; if (first == NULL_TREE) return false; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND) { tree t = *tp; tree tem = NULL_TREE; /* Need to evaluate side effects in the length expressions if any. */ while (TREE_CODE (t) == TREE_LIST) { if (TREE_VALUE (t) && TREE_SIDE_EFFECTS (TREE_VALUE (t))) { if (tem == NULL_TREE) tem = TREE_VALUE (t); else tem = build2 (COMPOUND_EXPR, TREE_TYPE (tem), TREE_VALUE (t), tem); } t = TREE_CHAIN (t); } if (tem) first = build2 (COMPOUND_EXPR, TREE_TYPE (first), tem, first); first = c_fully_fold (first, false, NULL, true); *tp = first; } else { unsigned int num = types.length (), i; tree t, side_effects = NULL_TREE, size = NULL_TREE; tree condition = NULL_TREE; if (int_size_in_bytes (TREE_TYPE (first)) <= 0) maybe_zero_len = true; for (i = num, t = OMP_CLAUSE_DECL (c); i > 0; t = TREE_CHAIN (t)) { tree low_bound = TREE_PURPOSE (t); tree length = TREE_VALUE (t); i--; if (low_bound && TREE_CODE (low_bound) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (low_bound)) > TYPE_PRECISION (sizetype)) low_bound = fold_convert (sizetype, low_bound); if (length && TREE_CODE (length) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (length)) > TYPE_PRECISION (sizetype)) length = fold_convert (sizetype, length); if (low_bound == NULL_TREE) low_bound = integer_zero_node; if (!maybe_zero_len && i > first_non_one) { if (integer_nonzerop (low_bound)) goto do_warn_noncontiguous; if (length != NULL_TREE && TREE_CODE (length) == INTEGER_CST && TYPE_DOMAIN (types[i]) && TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])) && TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (types[i]))) == INTEGER_CST) { tree size; size = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])), size_one_node); if (!tree_int_cst_equal (length, size)) { do_warn_noncontiguous: error_at (OMP_CLAUSE_LOCATION (c), "array section is not contiguous in %qs " "clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return true; } } if (length != NULL_TREE && TREE_SIDE_EFFECTS (length)) { if (side_effects == NULL_TREE) side_effects = length; else side_effects = build2 (COMPOUND_EXPR, TREE_TYPE (side_effects), length, side_effects); } } else { tree l; if (i > first_non_one && ((length && integer_nonzerop (length)) || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IN_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TASK_REDUCTION)) continue; if (length) l = fold_convert (sizetype, length); else { l = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])), size_one_node); l = size_binop (MINUS_EXPR, l, fold_convert (sizetype, low_bound)); } if (i > first_non_one) { l = fold_build2 (NE_EXPR, boolean_type_node, l, size_zero_node); if (condition == NULL_TREE) condition = l; else condition = fold_build2 (BIT_AND_EXPR, boolean_type_node, l, condition); } else if (size == NULL_TREE) { size = size_in_bytes (TREE_TYPE (types[i])); tree eltype = TREE_TYPE (types[num - 1]); while (TREE_CODE (eltype) == ARRAY_TYPE) eltype = TREE_TYPE (eltype); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IN_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TASK_REDUCTION) { if (integer_zerop (size) || integer_zerop (size_in_bytes (eltype))) { error_at (OMP_CLAUSE_LOCATION (c), "zero length array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } size = size_binop (EXACT_DIV_EXPR, size, size_in_bytes (eltype)); } size = size_binop (MULT_EXPR, size, l); if (condition) size = fold_build3 (COND_EXPR, sizetype, condition, size, size_zero_node); } else size = size_binop (MULT_EXPR, size, l); } } if (side_effects) size = build2 (COMPOUND_EXPR, sizetype, side_effects, size); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_IN_REDUCTION || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TASK_REDUCTION) { size = size_binop (MINUS_EXPR, size, size_one_node); size = c_fully_fold (size, false, NULL); size = save_expr (size); tree index_type = build_index_type (size); tree eltype = TREE_TYPE (first); while (TREE_CODE (eltype) == ARRAY_TYPE) eltype = TREE_TYPE (eltype); tree type = build_array_type (eltype, index_type); tree ptype = build_pointer_type (eltype); if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE) t = build_fold_addr_expr (t); tree t2 = build_fold_addr_expr (first); t2 = fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, t2); t2 = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, ptrdiff_type_node, t2, fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, t)); t2 = c_fully_fold (t2, false, NULL); if (tree_fits_shwi_p (t2)) t = build2 (MEM_REF, type, t, build_int_cst (ptype, tree_to_shwi (t2))); else { t2 = fold_convert_loc (OMP_CLAUSE_LOCATION (c), sizetype, t2); t = build2_loc (OMP_CLAUSE_LOCATION (c), POINTER_PLUS_EXPR, TREE_TYPE (t), t, t2); t = build2 (MEM_REF, type, t, build_int_cst (ptype, 0)); } OMP_CLAUSE_DECL (c) = t; return false; } first = c_fully_fold (first, false, NULL); OMP_CLAUSE_DECL (c) = first; if (size) size = c_fully_fold (size, false, NULL); OMP_CLAUSE_SIZE (c) = size; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP || (TREE_CODE (t) == COMPONENT_REF && TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)) return false; gcc_assert (OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FORCE_DEVICEPTR); if (ort == C_ORT_OMP || ort == C_ORT_ACC) switch (OMP_CLAUSE_MAP_KIND (c)) { case GOMP_MAP_ALLOC: case GOMP_MAP_IF_PRESENT: case GOMP_MAP_TO: case GOMP_MAP_FROM: case GOMP_MAP_TOFROM: case GOMP_MAP_ALWAYS_TO: case GOMP_MAP_ALWAYS_FROM: case GOMP_MAP_ALWAYS_TOFROM: case GOMP_MAP_RELEASE: case GOMP_MAP_DELETE: case GOMP_MAP_FORCE_TO: case GOMP_MAP_FORCE_FROM: case GOMP_MAP_FORCE_TOFROM: case GOMP_MAP_FORCE_PRESENT: OMP_CLAUSE_MAP_MAYBE_ZERO_LENGTH_ARRAY_SECTION (c) = 1; break; default: break; } tree c2 = build_omp_clause (OMP_CLAUSE_LOCATION (c), OMP_CLAUSE_MAP); if (ort != C_ORT_OMP && ort != C_ORT_ACC) OMP_CLAUSE_SET_MAP_KIND (c2, GOMP_MAP_POINTER); else if (TREE_CODE (t) == COMPONENT_REF) { gomp_map_kind k = (ort == C_ORT_ACC) ? GOMP_MAP_ATTACH_DETACH : GOMP_MAP_ALWAYS_POINTER; OMP_CLAUSE_SET_MAP_KIND (c2, k); } else OMP_CLAUSE_SET_MAP_KIND (c2, GOMP_MAP_FIRSTPRIVATE_POINTER); if (OMP_CLAUSE_MAP_KIND (c2) != GOMP_MAP_FIRSTPRIVATE_POINTER && !c_mark_addressable (t)) return false; OMP_CLAUSE_DECL (c2) = t; t = build_fold_addr_expr (first); t = fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, t); tree ptr = OMP_CLAUSE_DECL (c2); if (!POINTER_TYPE_P (TREE_TYPE (ptr))) ptr = build_fold_addr_expr (ptr); t = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, ptrdiff_type_node, t, fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, ptr)); t = c_fully_fold (t, false, NULL); OMP_CLAUSE_SIZE (c2) = t; OMP_CLAUSE_CHAIN (c2) = OMP_CLAUSE_CHAIN (c); OMP_CLAUSE_CHAIN (c) = c2; } return false; } /* Helper function of finish_omp_clauses. Clone STMT as if we were making an inline call. But, remap the OMP_DECL1 VAR_DECL (omp_out resp. omp_orig) to PLACEHOLDER and OMP_DECL2 VAR_DECL (omp_in resp. omp_priv) to DECL. */ static tree c_clone_omp_udr (tree stmt, tree omp_decl1, tree omp_decl2, tree decl, tree placeholder) { copy_body_data id; hash_map<tree, tree> decl_map; decl_map.put (omp_decl1, placeholder); decl_map.put (omp_decl2, decl); memset (&id, 0, sizeof (id)); id.src_fn = DECL_CONTEXT (omp_decl1); id.dst_fn = current_function_decl; id.src_cfun = DECL_STRUCT_FUNCTION (id.src_fn); id.decl_map = &decl_map; id.copy_decl = copy_decl_no_change; id.transform_call_graph_edges = CB_CGE_DUPLICATE; id.transform_new_cfg = true; id.transform_return_to_modify = false; id.transform_lang_insert_block = NULL; id.eh_lp_nr = 0; walk_tree (&stmt, copy_tree_body_r, &id, NULL); return stmt; } /* Helper function of c_finish_omp_clauses, called via walk_tree. Find OMP_CLAUSE_PLACEHOLDER (passed in DATA) in *TP. */ static tree c_find_omp_placeholder_r (tree *tp, int *, void *data) { if (*tp == (tree) data) return *tp; return NULL_TREE; } /* Similarly, but also walk aggregate fields. */ struct c_find_omp_var_s { tree var; hash_set<tree> *pset; }; static tree c_find_omp_var_r (tree *tp, int *, void *data) { if (*tp == ((struct c_find_omp_var_s *) data)->var) return *tp; if (RECORD_OR_UNION_TYPE_P (*tp)) { tree field; hash_set<tree> *pset = ((struct c_find_omp_var_s *) data)->pset; for (field = TYPE_FIELDS (*tp); field; field = DECL_CHAIN (field)) if (TREE_CODE (field) == FIELD_DECL) { tree ret = walk_tree (&DECL_FIELD_OFFSET (field), c_find_omp_var_r, data, pset); if (ret) return ret; ret = walk_tree (&DECL_SIZE (field), c_find_omp_var_r, data, pset); if (ret) return ret; ret = walk_tree (&DECL_SIZE_UNIT (field), c_find_omp_var_r, data, pset); if (ret) return ret; ret = walk_tree (&TREE_TYPE (field), c_find_omp_var_r, data, pset); if (ret) return ret; } } else if (INTEGRAL_TYPE_P (*tp)) return walk_tree (&TYPE_MAX_VALUE (*tp), c_find_omp_var_r, data, ((struct c_find_omp_var_s *) data)->pset); return NULL_TREE; } /* Finish OpenMP iterators ITER. Return true if they are errorneous and clauses containing them should be removed. */ static bool c_omp_finish_iterators (tree iter) { bool ret = false; for (tree it = iter; it; it = TREE_CHAIN (it)) { tree var = TREE_VEC_ELT (it, 0); tree begin = TREE_VEC_ELT (it, 1); tree end = TREE_VEC_ELT (it, 2); tree step = TREE_VEC_ELT (it, 3); tree orig_step; tree type = TREE_TYPE (var); location_t loc = DECL_SOURCE_LOCATION (var); if (type == error_mark_node) { ret = true; continue; } if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type)) { error_at (loc, "iterator %qD has neither integral nor pointer type", var); ret = true; continue; } else if (TYPE_ATOMIC (type)) { error_at (loc, "iterator %qD has %<_Atomic%> qualified type", var); ret = true; continue; } else if (TYPE_READONLY (type)) { error_at (loc, "iterator %qD has const qualified type", var); ret = true; continue; } else if (step == error_mark_node || TREE_TYPE (step) == error_mark_node) { ret = true; continue; } else if (!INTEGRAL_TYPE_P (TREE_TYPE (step))) { error_at (EXPR_LOC_OR_LOC (step, loc), "iterator step with non-integral type"); ret = true; continue; } begin = c_fully_fold (build_c_cast (loc, type, begin), false, NULL); end = c_fully_fold (build_c_cast (loc, type, end), false, NULL); orig_step = save_expr (c_fully_fold (step, false, NULL)); tree stype = POINTER_TYPE_P (type) ? sizetype : type; step = c_fully_fold (build_c_cast (loc, stype, orig_step), false, NULL); if (POINTER_TYPE_P (type)) { begin = save_expr (begin); step = pointer_int_sum (loc, PLUS_EXPR, begin, step); step = fold_build2_loc (loc, MINUS_EXPR, sizetype, fold_convert (sizetype, step), fold_convert (sizetype, begin)); step = fold_convert (ssizetype, step); } if (integer_zerop (step)) { error_at (loc, "iterator %qD has zero step", var); ret = true; continue; } if (begin == error_mark_node || end == error_mark_node || step == error_mark_node || orig_step == error_mark_node) { ret = true; continue; } hash_set<tree> pset; tree it2; for (it2 = TREE_CHAIN (it); it2; it2 = TREE_CHAIN (it2)) { tree var2 = TREE_VEC_ELT (it2, 0); tree begin2 = TREE_VEC_ELT (it2, 1); tree end2 = TREE_VEC_ELT (it2, 2); tree step2 = TREE_VEC_ELT (it2, 3); tree type2 = TREE_TYPE (var2); location_t loc2 = DECL_SOURCE_LOCATION (var2); struct c_find_omp_var_s data = { var, &pset }; if (walk_tree (&type2, c_find_omp_var_r, &data, &pset)) { error_at (loc2, "type of iterator %qD refers to outer iterator %qD", var2, var); break; } else if (walk_tree (&begin2, c_find_omp_var_r, &data, &pset)) { error_at (EXPR_LOC_OR_LOC (begin2, loc2), "begin expression refers to outer iterator %qD", var); break; } else if (walk_tree (&end2, c_find_omp_var_r, &data, &pset)) { error_at (EXPR_LOC_OR_LOC (end2, loc2), "end expression refers to outer iterator %qD", var); break; } else if (walk_tree (&step2, c_find_omp_var_r, &data, &pset)) { error_at (EXPR_LOC_OR_LOC (step2, loc2), "step expression refers to outer iterator %qD", var); break; } } if (it2) { ret = true; continue; } TREE_VEC_ELT (it, 1) = begin; TREE_VEC_ELT (it, 2) = end; TREE_VEC_ELT (it, 3) = step; TREE_VEC_ELT (it, 4) = orig_step; } return ret; } /* Ensure that pointers are used in OpenACC attach and detach clauses. Return true if an error has been detected. */ static bool c_oacc_check_attachments (tree c) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) return false; /* OpenACC attach / detach clauses must be pointers. */ if (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_ATTACH || OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_DETACH) { tree t = OMP_CLAUSE_DECL (c); while (TREE_CODE (t) == TREE_LIST) t = TREE_CHAIN (t); if (TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "expected pointer in %qs clause", c_omp_map_clause_name (c, true)); return true; } } return false; } /* For all elements of CLAUSES, validate them against their constraints. Remove any elements from the list that are invalid. */ tree c_finish_omp_clauses (tree clauses, enum c_omp_region_type ort) { bitmap_head generic_head, firstprivate_head, lastprivate_head; bitmap_head aligned_head, map_head, map_field_head, oacc_reduction_head; tree c, t, type, *pc; tree simdlen = NULL_TREE, safelen = NULL_TREE; bool branch_seen = false; bool copyprivate_seen = false; bool linear_variable_step_check = false; tree *nowait_clause = NULL; tree ordered_clause = NULL_TREE; tree schedule_clause = NULL_TREE; bool oacc_async = false; tree last_iterators = NULL_TREE; bool last_iterators_remove = false; tree *nogroup_seen = NULL; tree *order_clause = NULL; /* 1 if normal/task reduction has been seen, -1 if inscan reduction has been seen, -2 if mixed inscan/normal reduction diagnosed. */ int reduction_seen = 0; bitmap_obstack_initialize (NULL); bitmap_initialize (&generic_head, &bitmap_default_obstack); bitmap_initialize (&firstprivate_head, &bitmap_default_obstack); bitmap_initialize (&lastprivate_head, &bitmap_default_obstack); bitmap_initialize (&aligned_head, &bitmap_default_obstack); /* If ort == C_ORT_OMP_DECLARE_SIMD used as uniform_head instead. */ bitmap_initialize (&map_head, &bitmap_default_obstack); bitmap_initialize (&map_field_head, &bitmap_default_obstack); /* If ort == C_ORT_OMP used as nontemporal_head or use_device_xxx_head instead. */ bitmap_initialize (&oacc_reduction_head, &bitmap_default_obstack); if (ort & C_ORT_ACC) for (c = clauses; c; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_ASYNC) { oacc_async = true; break; } for (pc = &clauses, c = clauses; c ; c = *pc) { bool remove = false; bool need_complete = false; bool need_implicitly_determined = false; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: need_implicitly_determined = true; goto check_dup_generic; case OMP_CLAUSE_PRIVATE: need_complete = true; need_implicitly_determined = true; goto check_dup_generic; case OMP_CLAUSE_REDUCTION: if (reduction_seen == 0) reduction_seen = OMP_CLAUSE_REDUCTION_INSCAN (c) ? -1 : 1; else if (reduction_seen != -2 && reduction_seen != (OMP_CLAUSE_REDUCTION_INSCAN (c) ? -1 : 1)) { error_at (OMP_CLAUSE_LOCATION (c), "%<inscan%> and non-%<inscan%> %<reduction%> clauses " "on the same construct"); reduction_seen = -2; } /* FALLTHRU */ case OMP_CLAUSE_IN_REDUCTION: case OMP_CLAUSE_TASK_REDUCTION: need_implicitly_determined = true; t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) == TREE_LIST) { if (handle_omp_array_sections (c, ort)) { remove = true; break; } t = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION && OMP_CLAUSE_REDUCTION_INSCAN (c)) { error_at (OMP_CLAUSE_LOCATION (c), "%<inscan%> %<reduction%> clause with array " "section"); remove = true; break; } } t = require_complete_type (OMP_CLAUSE_LOCATION (c), t); if (t == error_mark_node) { remove = true; break; } if (oacc_async) c_mark_addressable (t); type = TREE_TYPE (t); if (TREE_CODE (t) == MEM_REF) type = TREE_TYPE (type); if (TREE_CODE (type) == ARRAY_TYPE) { tree oatype = type; gcc_assert (TREE_CODE (t) != MEM_REF); while (TREE_CODE (type) == ARRAY_TYPE) type = TREE_TYPE (type); if (integer_zerop (TYPE_SIZE_UNIT (type))) { error_at (OMP_CLAUSE_LOCATION (c), "%qD in %<reduction%> clause is a zero size array", t); remove = true; break; } tree size = size_binop (EXACT_DIV_EXPR, TYPE_SIZE_UNIT (oatype), TYPE_SIZE_UNIT (type)); if (integer_zerop (size)) { error_at (OMP_CLAUSE_LOCATION (c), "%qD in %<reduction%> clause is a zero size array", t); remove = true; break; } size = size_binop (MINUS_EXPR, size, size_one_node); size = save_expr (size); tree index_type = build_index_type (size); tree atype = build_array_type (type, index_type); tree ptype = build_pointer_type (type); if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE) t = build_fold_addr_expr (t); t = build2 (MEM_REF, atype, t, build_int_cst (ptype, 0)); OMP_CLAUSE_DECL (c) = t; } if (TYPE_ATOMIC (type)) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qE in %<reduction%> clause", t); remove = true; break; } if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_REDUCTION || OMP_CLAUSE_REDUCTION_TASK (c)) { /* Disallow zero sized or potentially zero sized task reductions. */ if (integer_zerop (TYPE_SIZE_UNIT (type))) { error_at (OMP_CLAUSE_LOCATION (c), "zero sized type %qT in %qs clause", type, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; break; } else if (TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST) { error_at (OMP_CLAUSE_LOCATION (c), "variable sized type %qT in %qs clause", type, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; break; } } if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) == NULL_TREE && (FLOAT_TYPE_P (type) || TREE_CODE (type) == COMPLEX_TYPE)) { enum tree_code r_code = OMP_CLAUSE_REDUCTION_CODE (c); const char *r_name = NULL; switch (r_code) { case PLUS_EXPR: case MULT_EXPR: case MINUS_EXPR: break; case MIN_EXPR: if (TREE_CODE (type) == COMPLEX_TYPE) r_name = "min"; break; case MAX_EXPR: if (TREE_CODE (type) == COMPLEX_TYPE) r_name = "max"; break; case BIT_AND_EXPR: r_name = "&"; break; case BIT_XOR_EXPR: r_name = "^"; break; case BIT_IOR_EXPR: r_name = "|"; break; case TRUTH_ANDIF_EXPR: if (FLOAT_TYPE_P (type)) r_name = "&&"; break; case TRUTH_ORIF_EXPR: if (FLOAT_TYPE_P (type)) r_name = "||"; break; default: gcc_unreachable (); } if (r_name) { error_at (OMP_CLAUSE_LOCATION (c), "%qE has invalid type for %<reduction(%s)%>", t, r_name); remove = true; break; } } else if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) == error_mark_node) { error_at (OMP_CLAUSE_LOCATION (c), "user defined reduction not found for %qE", t); remove = true; break; } else if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree list = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); type = TYPE_MAIN_VARIANT (type); tree placeholder = build_decl (OMP_CLAUSE_LOCATION (c), VAR_DECL, NULL_TREE, type); tree decl_placeholder = NULL_TREE; OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = placeholder; DECL_ARTIFICIAL (placeholder) = 1; DECL_IGNORED_P (placeholder) = 1; if (TREE_CODE (t) == MEM_REF) { decl_placeholder = build_decl (OMP_CLAUSE_LOCATION (c), VAR_DECL, NULL_TREE, type); OMP_CLAUSE_REDUCTION_DECL_PLACEHOLDER (c) = decl_placeholder; DECL_ARTIFICIAL (decl_placeholder) = 1; DECL_IGNORED_P (decl_placeholder) = 1; } if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 0))) c_mark_addressable (placeholder); if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 1))) c_mark_addressable (decl_placeholder ? decl_placeholder : OMP_CLAUSE_DECL (c)); OMP_CLAUSE_REDUCTION_MERGE (c) = c_clone_omp_udr (TREE_VEC_ELT (list, 2), TREE_VEC_ELT (list, 0), TREE_VEC_ELT (list, 1), decl_placeholder ? decl_placeholder : OMP_CLAUSE_DECL (c), placeholder); OMP_CLAUSE_REDUCTION_MERGE (c) = build3_loc (OMP_CLAUSE_LOCATION (c), BIND_EXPR, void_type_node, NULL_TREE, OMP_CLAUSE_REDUCTION_MERGE (c), NULL_TREE); TREE_SIDE_EFFECTS (OMP_CLAUSE_REDUCTION_MERGE (c)) = 1; if (TREE_VEC_LENGTH (list) == 6) { if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 3))) c_mark_addressable (decl_placeholder ? decl_placeholder : OMP_CLAUSE_DECL (c)); if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 4))) c_mark_addressable (placeholder); tree init = TREE_VEC_ELT (list, 5); if (init == error_mark_node) init = DECL_INITIAL (TREE_VEC_ELT (list, 3)); OMP_CLAUSE_REDUCTION_INIT (c) = c_clone_omp_udr (init, TREE_VEC_ELT (list, 4), TREE_VEC_ELT (list, 3), decl_placeholder ? decl_placeholder : OMP_CLAUSE_DECL (c), placeholder); if (TREE_VEC_ELT (list, 5) == error_mark_node) { tree v = decl_placeholder ? decl_placeholder : t; OMP_CLAUSE_REDUCTION_INIT (c) = build2 (INIT_EXPR, TREE_TYPE (v), v, OMP_CLAUSE_REDUCTION_INIT (c)); } if (walk_tree (&OMP_CLAUSE_REDUCTION_INIT (c), c_find_omp_placeholder_r, placeholder, NULL)) OMP_CLAUSE_REDUCTION_OMP_ORIG_REF (c) = 1; } else { tree init; tree v = decl_placeholder ? decl_placeholder : t; if (AGGREGATE_TYPE_P (TREE_TYPE (v))) init = build_constructor (TREE_TYPE (v), NULL); else init = fold_convert (TREE_TYPE (v), integer_zero_node); OMP_CLAUSE_REDUCTION_INIT (c) = build2 (INIT_EXPR, TREE_TYPE (v), v, init); } OMP_CLAUSE_REDUCTION_INIT (c) = build3_loc (OMP_CLAUSE_LOCATION (c), BIND_EXPR, void_type_node, NULL_TREE, OMP_CLAUSE_REDUCTION_INIT (c), NULL_TREE); TREE_SIDE_EFFECTS (OMP_CLAUSE_REDUCTION_INIT (c)) = 1; } if (TREE_CODE (t) == MEM_REF) { if (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))) == NULL_TREE || TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t)))) != INTEGER_CST) { sorry ("variable length element type in array " "%<reduction%> clause"); remove = true; break; } t = TREE_OPERAND (t, 0); if (TREE_CODE (t) == POINTER_PLUS_EXPR) t = TREE_OPERAND (t, 0); if (TREE_CODE (t) == ADDR_EXPR) t = TREE_OPERAND (t, 0); } goto check_dup_generic_t; case OMP_CLAUSE_COPYPRIVATE: copyprivate_seen = true; if (nowait_clause) { error_at (OMP_CLAUSE_LOCATION (*nowait_clause), "%<nowait%> clause must not be used together " "with %<copyprivate%>"); *nowait_clause = OMP_CLAUSE_CHAIN (*nowait_clause); nowait_clause = NULL; } goto check_dup_generic; case OMP_CLAUSE_COPYIN: t = OMP_CLAUSE_DECL (c); if (!VAR_P (t) || !DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qE must be %<threadprivate%> for %<copyin%>", t); remove = true; break; } goto check_dup_generic; case OMP_CLAUSE_LINEAR: if (ort != C_ORT_OMP_DECLARE_SIMD) need_implicitly_determined = true; t = OMP_CLAUSE_DECL (c); if (ort != C_ORT_OMP_DECLARE_SIMD && OMP_CLAUSE_LINEAR_KIND (c) != OMP_CLAUSE_LINEAR_DEFAULT) { error_at (OMP_CLAUSE_LOCATION (c), "modifier should not be specified in %<linear%> " "clause on %<simd%> or %<for%> constructs"); OMP_CLAUSE_LINEAR_KIND (c) = OMP_CLAUSE_LINEAR_DEFAULT; } if (!INTEGRAL_TYPE_P (TREE_TYPE (t)) && TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "linear clause applied to non-integral non-pointer " "variable with type %qT", TREE_TYPE (t)); remove = true; break; } if (TYPE_ATOMIC (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qD in %<linear%> clause", t); remove = true; break; } if (ort == C_ORT_OMP_DECLARE_SIMD) { tree s = OMP_CLAUSE_LINEAR_STEP (c); if (TREE_CODE (s) == PARM_DECL) { OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (c) = 1; /* map_head bitmap is used as uniform_head if declare_simd. */ if (!bitmap_bit_p (&map_head, DECL_UID (s))) linear_variable_step_check = true; goto check_dup_generic; } if (TREE_CODE (s) != INTEGER_CST) { error_at (OMP_CLAUSE_LOCATION (c), "%<linear%> clause step %qE is neither constant " "nor a parameter", s); remove = true; break; } } if (TREE_CODE (TREE_TYPE (OMP_CLAUSE_DECL (c))) == POINTER_TYPE) { tree s = OMP_CLAUSE_LINEAR_STEP (c); s = pointer_int_sum (OMP_CLAUSE_LOCATION (c), PLUS_EXPR, OMP_CLAUSE_DECL (c), s); s = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, sizetype, fold_convert (sizetype, s), fold_convert (sizetype, OMP_CLAUSE_DECL (c))); if (s == error_mark_node) s = size_one_node; OMP_CLAUSE_LINEAR_STEP (c) = s; } else OMP_CLAUSE_LINEAR_STEP (c) = fold_convert (TREE_TYPE (t), OMP_CLAUSE_LINEAR_STEP (c)); goto check_dup_generic; check_dup_generic: t = OMP_CLAUSE_DECL (c); check_dup_generic_t: if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if ((ort == C_ORT_ACC && OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION) || (ort == C_ORT_OMP && (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_USE_DEVICE_PTR || (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_USE_DEVICE_ADDR)))) { if (bitmap_bit_p (&oacc_reduction_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), ort == C_ORT_ACC ? "%qD appears more than once in reduction clauses" : "%qD appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&oacc_reduction_head, DECL_UID (t)); } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t)) || bitmap_bit_p (&lastprivate_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in data clauses", t); remove = true; } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE && bitmap_bit_p (&map_head, DECL_UID (t))) { if (ort == C_ORT_ACC) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in data clauses", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qD appears both in data and map clauses", t); remove = true; } else bitmap_set_bit (&generic_head, DECL_UID (t)); break; case OMP_CLAUSE_FIRSTPRIVATE: t = OMP_CLAUSE_DECL (c); need_complete = true; need_implicitly_determined = true; if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %<firstprivate%>", t); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in data clauses", t); remove = true; } else if (bitmap_bit_p (&map_head, DECL_UID (t))) { if (ort == C_ORT_ACC) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in data clauses", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qD appears both in data and map clauses", t); remove = true; } else bitmap_set_bit (&firstprivate_head, DECL_UID (t)); break; case OMP_CLAUSE_LASTPRIVATE: t = OMP_CLAUSE_DECL (c); need_complete = true; need_implicitly_determined = true; if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %<lastprivate%>", t); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&lastprivate_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&lastprivate_head, DECL_UID (t)); break; case OMP_CLAUSE_ALIGNED: t = OMP_CLAUSE_DECL (c); if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %<aligned%> clause", t); remove = true; } else if (!POINTER_TYPE_P (TREE_TYPE (t)) && TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "%qE in %<aligned%> clause is neither a pointer nor " "an array", t); remove = true; } else if (TYPE_ATOMIC (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qD in %<aligned%> clause", t); remove = true; break; } else if (bitmap_bit_p (&aligned_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in %<aligned%> clauses", t); remove = true; } else bitmap_set_bit (&aligned_head, DECL_UID (t)); break; case OMP_CLAUSE_NONTEMPORAL: t = OMP_CLAUSE_DECL (c); if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %<nontemporal%> clause", t); remove = true; } else if (bitmap_bit_p (&oacc_reduction_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in %<nontemporal%> " "clauses", t); remove = true; } else bitmap_set_bit (&oacc_reduction_head, DECL_UID (t)); break; case OMP_CLAUSE_DEPEND: t = OMP_CLAUSE_DECL (c); if (t == NULL_TREE) { gcc_assert (OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_SOURCE); break; } if (OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_SINK) { gcc_assert (TREE_CODE (t) == TREE_LIST); for (; t; t = TREE_CHAIN (t)) { tree decl = TREE_VALUE (t); if (TREE_CODE (TREE_TYPE (decl)) == POINTER_TYPE) { tree offset = TREE_PURPOSE (t); bool neg = wi::neg_p (wi::to_wide (offset)); offset = fold_unary (ABS_EXPR, TREE_TYPE (offset), offset); tree t2 = pointer_int_sum (OMP_CLAUSE_LOCATION (c), neg ? MINUS_EXPR : PLUS_EXPR, decl, offset); t2 = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, sizetype, fold_convert (sizetype, t2), fold_convert (sizetype, decl)); if (t2 == error_mark_node) { remove = true; break; } TREE_PURPOSE (t) = t2; } } break; } if (TREE_CODE (t) == TREE_LIST && TREE_PURPOSE (t) && TREE_CODE (TREE_PURPOSE (t)) == TREE_VEC) { if (TREE_PURPOSE (t) != last_iterators) last_iterators_remove = c_omp_finish_iterators (TREE_PURPOSE (t)); last_iterators = TREE_PURPOSE (t); t = TREE_VALUE (t); if (last_iterators_remove) t = error_mark_node; } else last_iterators = NULL_TREE; if (TREE_CODE (t) == TREE_LIST) { if (handle_omp_array_sections (c, ort)) remove = true; else if (OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_DEPOBJ) { error_at (OMP_CLAUSE_LOCATION (c), "%<depend%> clause with %<depobj%> dependence " "type on array section"); remove = true; } break; } if (t == error_mark_node) remove = true; else if (!lvalue_p (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not lvalue expression nor array section in " "%<depend%> clause", t); remove = true; } else if (TREE_CODE (t) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (t, 1))) { error_at (OMP_CLAUSE_LOCATION (c), "bit-field %qE in %qs clause", t, "depend"); remove = true; } else if (OMP_CLAUSE_DEPEND_KIND (c) == OMP_CLAUSE_DEPEND_DEPOBJ) { if (!c_omp_depend_t_p (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE does not have %<omp_depend_t%> type in " "%<depend%> clause with %<depobj%> dependence " "type", t); remove = true; } } else if (c_omp_depend_t_p (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE should not have %<omp_depend_t%> type in " "%<depend%> clause with dependence type other than " "%<depobj%>", t); remove = true; } if (!remove) { tree addr = build_unary_op (OMP_CLAUSE_LOCATION (c), ADDR_EXPR, t, false); if (addr == error_mark_node) remove = true; else { t = build_indirect_ref (OMP_CLAUSE_LOCATION (c), addr, RO_UNARY_STAR); if (t == error_mark_node) remove = true; else if (TREE_CODE (OMP_CLAUSE_DECL (c)) == TREE_LIST && TREE_PURPOSE (OMP_CLAUSE_DECL (c)) && (TREE_CODE (TREE_PURPOSE (OMP_CLAUSE_DECL (c))) == TREE_VEC)) TREE_VALUE (OMP_CLAUSE_DECL (c)) = t; else OMP_CLAUSE_DECL (c) = t; } } break; case OMP_CLAUSE_MAP: case OMP_CLAUSE_TO: case OMP_CLAUSE_FROM: case OMP_CLAUSE__CACHE_: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) == TREE_LIST) { if (handle_omp_array_sections (c, ort)) remove = true; else { t = OMP_CLAUSE_DECL (c); if (!lang_hooks.types.omp_mappable_type (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "array section does not have mappable type " "in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (TYPE_ATOMIC (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } while (TREE_CODE (t) == ARRAY_REF) t = TREE_OPERAND (t, 0); if (TREE_CODE (t) == COMPONENT_REF && TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE) { while (TREE_CODE (t) == COMPONENT_REF) t = TREE_OPERAND (t, 0); if (bitmap_bit_p (&map_field_head, DECL_UID (t))) break; if (bitmap_bit_p (&map_head, DECL_UID (t))) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in motion " "clauses", t); else if (ort == C_ORT_ACC) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in data " "clauses", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in map " "clauses", t); remove = true; } else { bitmap_set_bit (&map_head, DECL_UID (t)); bitmap_set_bit (&map_field_head, DECL_UID (t)); } } } if (c_oacc_check_attachments (c)) remove = true; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_ATTACH || OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_DETACH)) /* In this case, we have a single array element which is a pointer, and we already set OMP_CLAUSE_SIZE in handle_omp_array_sections above. For attach/detach clauses, reset the OMP_CLAUSE_SIZE (representing a bias) to zero here. */ OMP_CLAUSE_SIZE (c) = size_zero_node; break; } if (t == error_mark_node) { remove = true; break; } /* OpenACC attach / detach clauses must be pointers. */ if (c_oacc_check_attachments (c)) { remove = true; break; } if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_ATTACH || OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_DETACH)) /* For attach/detach clauses, set OMP_CLAUSE_SIZE (representing a bias) to zero here, so it is not set erroneously to the pointer size later on in gimplify.c. */ OMP_CLAUSE_SIZE (c) = size_zero_node; if (TREE_CODE (t) == COMPONENT_REF && OMP_CLAUSE_CODE (c) != OMP_CLAUSE__CACHE_) { if (DECL_BIT_FIELD (TREE_OPERAND (t, 1))) { error_at (OMP_CLAUSE_LOCATION (c), "bit-field %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (!lang_hooks.types.omp_mappable_type (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE does not have a mappable type in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (TYPE_ATOMIC (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } while (TREE_CODE (t) == COMPONENT_REF) { if (TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == UNION_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is a member of a union", t); remove = true; break; } t = TREE_OPERAND (t, 0); if (ort == C_ORT_ACC && TREE_CODE (t) == MEM_REF) { if (maybe_ne (mem_ref_offset (t), 0)) error_at (OMP_CLAUSE_LOCATION (c), "cannot dereference %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else t = TREE_OPERAND (t, 0); } } if (remove) break; if (VAR_P (t) || TREE_CODE (t) == PARM_DECL) { if (bitmap_bit_p (&map_field_head, DECL_UID (t))) break; } } if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (VAR_P (t) && DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qD is threadprivate variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if ((OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP || (OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FIRSTPRIVATE_POINTER)) && !c_mark_addressable (t)) remove = true; else if (!(OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER || (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_POINTER) || (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FORCE_DEVICEPTR))) && t == OMP_CLAUSE_DECL (c) && !lang_hooks.types.omp_mappable_type (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qD does not have a mappable type in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (TREE_TYPE (t) == error_mark_node) remove = true; else if (TYPE_ATOMIC (strip_array_types (TREE_TYPE (t)))) { error_at (OMP_CLAUSE_LOCATION (c), "%<_Atomic%> %qE in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FIRSTPRIVATE_POINTER) { if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in data clauses", t); remove = true; } else if (bitmap_bit_p (&map_head, DECL_UID (t))) { if (ort == C_ORT_ACC) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in data clauses", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qD appears both in data and map clauses", t); remove = true; } else bitmap_set_bit (&generic_head, DECL_UID (t)); } else if (bitmap_bit_p (&map_head, DECL_UID (t))) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in motion clauses", t); else if (ort == C_ORT_ACC) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in data clauses", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in map clauses", t); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t))) { if (ort == C_ORT_ACC) error_at (OMP_CLAUSE_LOCATION (c), "%qD appears more than once in data clauses", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qD appears both in data and map clauses", t); remove = true; } else { bitmap_set_bit (&map_head, DECL_UID (t)); if (t != OMP_CLAUSE_DECL (c) && TREE_CODE (OMP_CLAUSE_DECL (c)) == COMPONENT_REF) bitmap_set_bit (&map_field_head, DECL_UID (t)); } break; case OMP_CLAUSE_TO_DECLARE: case OMP_CLAUSE_LINK: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) == FUNCTION_DECL && OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TO_DECLARE) ; else if (!VAR_P (t)) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_TO_DECLARE) error_at (OMP_CLAUSE_LOCATION (c), "%qE is neither a variable nor a function name in " "clause %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qD is threadprivate variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (!lang_hooks.types.omp_mappable_type (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qD does not have a mappable type in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } if (remove) break; if (bitmap_bit_p (&generic_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once on the same " "%<declare target%> directive", t); remove = true; } else bitmap_set_bit (&generic_head, DECL_UID (t)); break; case OMP_CLAUSE_UNIFORM: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != PARM_DECL) { if (DECL_P (t)) error_at (OMP_CLAUSE_LOCATION (c), "%qD is not an argument in %<uniform%> clause", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qE is not an argument in %<uniform%> clause", t); remove = true; break; } /* map_head bitmap is used as uniform_head if declare_simd. */ bitmap_set_bit (&map_head, DECL_UID (t)); goto check_dup_generic; case OMP_CLAUSE_IS_DEVICE_PTR: case OMP_CLAUSE_USE_DEVICE_PTR: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE) { if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_USE_DEVICE_PTR && ort == C_ORT_OMP) { error_at (OMP_CLAUSE_LOCATION (c), "%qs variable is not a pointer", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "%qs variable is neither a pointer nor an array", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } } goto check_dup_generic; case OMP_CLAUSE_USE_DEVICE_ADDR: t = OMP_CLAUSE_DECL (c); if (VAR_P (t) || TREE_CODE (t) == PARM_DECL) c_mark_addressable (t); goto check_dup_generic; case OMP_CLAUSE_NOWAIT: if (copyprivate_seen) { error_at (OMP_CLAUSE_LOCATION (c), "%<nowait%> clause must not be used together " "with %<copyprivate%>"); remove = true; break; } nowait_clause = pc; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_ORDER: if (ordered_clause) { error_at (OMP_CLAUSE_LOCATION (c), "%<order%> clause must not be used together " "with %<ordered%>"); remove = true; break; } else if (order_clause) { /* Silently remove duplicates. */ remove = true; break; } order_clause = pc; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_NUM_TEAMS: case OMP_CLAUSE_THREAD_LIMIT: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_FINAL: case OMP_CLAUSE_MERGEABLE: case OMP_CLAUSE_DEVICE: case OMP_CLAUSE_DIST_SCHEDULE: case OMP_CLAUSE_PARALLEL: case OMP_CLAUSE_FOR: case OMP_CLAUSE_SECTIONS: case OMP_CLAUSE_TASKGROUP: case OMP_CLAUSE_PROC_BIND: case OMP_CLAUSE_DEVICE_TYPE: case OMP_CLAUSE_PRIORITY: case OMP_CLAUSE_GRAINSIZE: case OMP_CLAUSE_NUM_TASKS: case OMP_CLAUSE_THREADS: case OMP_CLAUSE_SIMD: case OMP_CLAUSE_HINT: case OMP_CLAUSE_DEFAULTMAP: case OMP_CLAUSE_BIND: case OMP_CLAUSE_NUM_GANGS: case OMP_CLAUSE_NUM_WORKERS: case OMP_CLAUSE_VECTOR_LENGTH: case OMP_CLAUSE_ASYNC: case OMP_CLAUSE_WAIT: case OMP_CLAUSE_AUTO: case OMP_CLAUSE_INDEPENDENT: case OMP_CLAUSE_SEQ: case OMP_CLAUSE_GANG: case OMP_CLAUSE_WORKER: case OMP_CLAUSE_VECTOR: case OMP_CLAUSE_TILE: case OMP_CLAUSE_IF_PRESENT: case OMP_CLAUSE_FINALIZE: pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_NOGROUP: nogroup_seen = pc; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_SCHEDULE: schedule_clause = c; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_ORDERED: ordered_clause = c; if (order_clause) { error_at (OMP_CLAUSE_LOCATION (*order_clause), "%<order%> clause must not be used together " "with %<ordered%>"); *order_clause = OMP_CLAUSE_CHAIN (*order_clause); order_clause = NULL; } pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_SAFELEN: safelen = c; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_SIMDLEN: simdlen = c; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_INBRANCH: case OMP_CLAUSE_NOTINBRANCH: if (branch_seen) { error_at (OMP_CLAUSE_LOCATION (c), "%<inbranch%> clause is incompatible with " "%<notinbranch%>"); remove = true; break; } branch_seen = true; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_INCLUSIVE: case OMP_CLAUSE_EXCLUSIVE: need_complete = true; need_implicitly_determined = true; t = OMP_CLAUSE_DECL (c); if (!VAR_P (t) && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } break; default: gcc_unreachable (); } if (!remove) { t = OMP_CLAUSE_DECL (c); if (need_complete) { t = require_complete_type (OMP_CLAUSE_LOCATION (c), t); if (t == error_mark_node) remove = true; } if (need_implicitly_determined) { const char *share_name = NULL; if (VAR_P (t) && DECL_THREAD_LOCAL_P (t)) share_name = "threadprivate"; else switch (c_omp_predetermined_sharing (t)) { case OMP_CLAUSE_DEFAULT_UNSPECIFIED: break; case OMP_CLAUSE_DEFAULT_SHARED: if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_SHARED || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE) && c_omp_predefined_variable (t)) /* The __func__ variable and similar function-local predefined variables may be listed in a shared or firstprivate clause. */ break; share_name = "shared"; break; case OMP_CLAUSE_DEFAULT_PRIVATE: share_name = "private"; break; default: gcc_unreachable (); } if (share_name) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is predetermined %qs for %qs", t, share_name, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (TREE_READONLY (t) && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_SHARED && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_FIRSTPRIVATE) { error_at (OMP_CLAUSE_LOCATION (c), "%<const%> qualified %qE may appear only in " "%<shared%> or %<firstprivate%> clauses", t); remove = true; } } } if (remove) *pc = OMP_CLAUSE_CHAIN (c); else pc = &OMP_CLAUSE_CHAIN (c); } if (simdlen && safelen && tree_int_cst_lt (OMP_CLAUSE_SAFELEN_EXPR (safelen), OMP_CLAUSE_SIMDLEN_EXPR (simdlen))) { error_at (OMP_CLAUSE_LOCATION (simdlen), "%<simdlen%> clause value is bigger than " "%<safelen%> clause value"); OMP_CLAUSE_SIMDLEN_EXPR (simdlen) = OMP_CLAUSE_SAFELEN_EXPR (safelen); } if (ordered_clause && schedule_clause && (OMP_CLAUSE_SCHEDULE_KIND (schedule_clause) & OMP_CLAUSE_SCHEDULE_NONMONOTONIC)) { error_at (OMP_CLAUSE_LOCATION (schedule_clause), "%<nonmonotonic%> schedule modifier specified together " "with %<ordered%> clause"); OMP_CLAUSE_SCHEDULE_KIND (schedule_clause) = (enum omp_clause_schedule_kind) (OMP_CLAUSE_SCHEDULE_KIND (schedule_clause) & ~OMP_CLAUSE_SCHEDULE_NONMONOTONIC); } if (reduction_seen < 0 && ordered_clause) { error_at (OMP_CLAUSE_LOCATION (ordered_clause), "%qs clause specified together with %<inscan%> " "%<reduction%> clause", "ordered"); reduction_seen = -2; } if (reduction_seen < 0 && schedule_clause) { error_at (OMP_CLAUSE_LOCATION (schedule_clause), "%qs clause specified together with %<inscan%> " "%<reduction%> clause", "schedule"); reduction_seen = -2; } if (linear_variable_step_check || reduction_seen == -2) for (pc = &clauses, c = clauses; c ; c = *pc) { bool remove = false; if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LINEAR && OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (c) && !bitmap_bit_p (&map_head, DECL_UID (OMP_CLAUSE_LINEAR_STEP (c)))) { error_at (OMP_CLAUSE_LOCATION (c), "%<linear%> clause step is a parameter %qD not " "specified in %<uniform%> clause", OMP_CLAUSE_LINEAR_STEP (c)); remove = true; } else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION) OMP_CLAUSE_REDUCTION_INSCAN (c) = 0; if (remove) *pc = OMP_CLAUSE_CHAIN (c); else pc = &OMP_CLAUSE_CHAIN (c); } if (nogroup_seen && reduction_seen) { error_at (OMP_CLAUSE_LOCATION (*nogroup_seen), "%<nogroup%> clause must not be used together with " "%<reduction%> clause"); *nogroup_seen = OMP_CLAUSE_CHAIN (*nogroup_seen); } bitmap_obstack_release (NULL); return clauses; } /* Return code to initialize DST with a copy constructor from SRC. C doesn't have copy constructors nor assignment operators, only for _Atomic vars we need to perform __atomic_load from src into a temporary followed by __atomic_store of the temporary to dst. */ tree c_omp_clause_copy_ctor (tree clause, tree dst, tree src) { if (!really_atomic_lvalue (dst) && !really_atomic_lvalue (src)) return build2 (MODIFY_EXPR, TREE_TYPE (dst), dst, src); location_t loc = OMP_CLAUSE_LOCATION (clause); tree type = TREE_TYPE (dst); tree nonatomic_type = build_qualified_type (type, TYPE_UNQUALIFIED); tree tmp = create_tmp_var (nonatomic_type); tree tmp_addr = build_fold_addr_expr (tmp); TREE_ADDRESSABLE (tmp) = 1; TREE_NO_WARNING (tmp) = 1; tree src_addr = build_fold_addr_expr (src); tree dst_addr = build_fold_addr_expr (dst); tree seq_cst = build_int_cst (integer_type_node, MEMMODEL_SEQ_CST); vec<tree, va_gc> *params; /* Expansion of a generic atomic load may require an addition element, so allocate enough to prevent a resize. */ vec_alloc (params, 4); /* Build __atomic_load (&src, &tmp, SEQ_CST); */ tree fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_LOAD); params->quick_push (src_addr); params->quick_push (tmp_addr); params->quick_push (seq_cst); tree load = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); vec_alloc (params, 4); /* Build __atomic_store (&dst, &tmp, SEQ_CST); */ fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_STORE); params->quick_push (dst_addr); params->quick_push (tmp_addr); params->quick_push (seq_cst); tree store = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); return build2 (COMPOUND_EXPR, void_type_node, load, store); } /* Create a transaction node. */ tree c_finish_transaction (location_t loc, tree block, int flags) { tree stmt = build_stmt (loc, TRANSACTION_EXPR, block); if (flags & TM_STMT_ATTR_OUTER) TRANSACTION_EXPR_OUTER (stmt) = 1; if (flags & TM_STMT_ATTR_RELAXED) TRANSACTION_EXPR_RELAXED (stmt) = 1; return add_stmt (stmt); } /* Make a variant type in the proper way for C/C++, propagating qualifiers down to the element type of an array. If ORIG_QUAL_TYPE is not NULL, then it should be used as the qualified type ORIG_QUAL_INDIRECT levels down in array type derivation (to preserve information about the typedef name from which an array type was derived). */ tree c_build_qualified_type (tree type, int type_quals, tree orig_qual_type, size_t orig_qual_indirect) { if (type == error_mark_node) return type; if (TREE_CODE (type) == ARRAY_TYPE) { tree t; tree element_type = c_build_qualified_type (TREE_TYPE (type), type_quals, orig_qual_type, orig_qual_indirect - 1); /* See if we already have an identically qualified type. */ if (orig_qual_type && orig_qual_indirect == 0) t = orig_qual_type; else for (t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t)) { if (TYPE_QUALS (strip_array_types (t)) == type_quals && TYPE_NAME (t) == TYPE_NAME (type) && TYPE_CONTEXT (t) == TYPE_CONTEXT (type) && attribute_list_equal (TYPE_ATTRIBUTES (t), TYPE_ATTRIBUTES (type))) break; } if (!t) { tree domain = TYPE_DOMAIN (type); t = build_variant_type_copy (type); TREE_TYPE (t) = element_type; if (TYPE_STRUCTURAL_EQUALITY_P (element_type) || (domain && TYPE_STRUCTURAL_EQUALITY_P (domain))) SET_TYPE_STRUCTURAL_EQUALITY (t); else if (TYPE_CANONICAL (element_type) != element_type || (domain && TYPE_CANONICAL (domain) != domain)) { tree unqualified_canon = build_array_type (TYPE_CANONICAL (element_type), domain? TYPE_CANONICAL (domain) : NULL_TREE); if (TYPE_REVERSE_STORAGE_ORDER (type)) { unqualified_canon = build_distinct_type_copy (unqualified_canon); TYPE_REVERSE_STORAGE_ORDER (unqualified_canon) = 1; } TYPE_CANONICAL (t) = c_build_qualified_type (unqualified_canon, type_quals); } else TYPE_CANONICAL (t) = t; } return t; } /* A restrict-qualified pointer type must be a pointer to object or incomplete type. Note that the use of POINTER_TYPE_P also allows REFERENCE_TYPEs, which is appropriate for C++. */ if ((type_quals & TYPE_QUAL_RESTRICT) && (!POINTER_TYPE_P (type) || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))) { error ("invalid use of %<restrict%>"); type_quals &= ~TYPE_QUAL_RESTRICT; } tree var_type = (orig_qual_type && orig_qual_indirect == 0 ? orig_qual_type : build_qualified_type (type, type_quals)); /* A variant type does not inherit the list of incomplete vars from the type main variant. */ if ((RECORD_OR_UNION_TYPE_P (var_type) || TREE_CODE (var_type) == ENUMERAL_TYPE) && TYPE_MAIN_VARIANT (var_type) != var_type) C_TYPE_INCOMPLETE_VARS (var_type) = 0; return var_type; } /* Build a VA_ARG_EXPR for the C parser. */ tree c_build_va_arg (location_t loc1, tree expr, location_t loc2, tree type) { if (error_operand_p (type)) return error_mark_node; /* VA_ARG_EXPR cannot be used for a scalar va_list with reverse storage order because it takes the address of the expression. */ else if (handled_component_p (expr) && reverse_storage_order_for_component_p (expr)) { error_at (loc1, "cannot use %<va_arg%> with reverse storage order"); return error_mark_node; } else if (!COMPLETE_TYPE_P (type)) { error_at (loc2, "second argument to %<va_arg%> is of incomplete " "type %qT", type); return error_mark_node; } else if (warn_cxx_compat && TREE_CODE (type) == ENUMERAL_TYPE) warning_at (loc2, OPT_Wc___compat, "C++ requires promoted type, not enum type, in %<va_arg%>"); return build_va_arg (loc2, expr, type); } /* Return truthvalue of whether T1 is the same tree structure as T2. Return 1 if they are the same. Return false if they are different. */ bool c_tree_equal (tree t1, tree t2) { enum tree_code code1, code2; if (t1 == t2) return true; if (!t1 || !t2) return false; for (code1 = TREE_CODE (t1); CONVERT_EXPR_CODE_P (code1) || code1 == NON_LVALUE_EXPR; code1 = TREE_CODE (t1)) t1 = TREE_OPERAND (t1, 0); for (code2 = TREE_CODE (t2); CONVERT_EXPR_CODE_P (code2) || code2 == NON_LVALUE_EXPR; code2 = TREE_CODE (t2)) t2 = TREE_OPERAND (t2, 0); /* They might have become equal now. */ if (t1 == t2) return true; if (code1 != code2) return false; switch (code1) { case INTEGER_CST: return wi::to_wide (t1) == wi::to_wide (t2); case REAL_CST: return real_equal (&TREE_REAL_CST (t1), &TREE_REAL_CST (t2)); case STRING_CST: return TREE_STRING_LENGTH (t1) == TREE_STRING_LENGTH (t2) && !memcmp (TREE_STRING_POINTER (t1), TREE_STRING_POINTER (t2), TREE_STRING_LENGTH (t1)); case FIXED_CST: return FIXED_VALUES_IDENTICAL (TREE_FIXED_CST (t1), TREE_FIXED_CST (t2)); case COMPLEX_CST: return c_tree_equal (TREE_REALPART (t1), TREE_REALPART (t2)) && c_tree_equal (TREE_IMAGPART (t1), TREE_IMAGPART (t2)); case VECTOR_CST: return operand_equal_p (t1, t2, OEP_ONLY_CONST); case CONSTRUCTOR: /* We need to do this when determining whether or not two non-type pointer to member function template arguments are the same. */ if (!comptypes (TREE_TYPE (t1), TREE_TYPE (t2)) || CONSTRUCTOR_NELTS (t1) != CONSTRUCTOR_NELTS (t2)) return false; { tree field, value; unsigned int i; FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t1), i, field, value) { constructor_elt *elt2 = CONSTRUCTOR_ELT (t2, i); if (!c_tree_equal (field, elt2->index) || !c_tree_equal (value, elt2->value)) return false; } } return true; case TREE_LIST: if (!c_tree_equal (TREE_PURPOSE (t1), TREE_PURPOSE (t2))) return false; if (!c_tree_equal (TREE_VALUE (t1), TREE_VALUE (t2))) return false; return c_tree_equal (TREE_CHAIN (t1), TREE_CHAIN (t2)); case SAVE_EXPR: return c_tree_equal (TREE_OPERAND (t1, 0), TREE_OPERAND (t2, 0)); case CALL_EXPR: { tree arg1, arg2; call_expr_arg_iterator iter1, iter2; if (!c_tree_equal (CALL_EXPR_FN (t1), CALL_EXPR_FN (t2))) return false; for (arg1 = first_call_expr_arg (t1, &iter1), arg2 = first_call_expr_arg (t2, &iter2); arg1 && arg2; arg1 = next_call_expr_arg (&iter1), arg2 = next_call_expr_arg (&iter2)) if (!c_tree_equal (arg1, arg2)) return false; if (arg1 || arg2) return false; return true; } case TARGET_EXPR: { tree o1 = TREE_OPERAND (t1, 0); tree o2 = TREE_OPERAND (t2, 0); /* Special case: if either target is an unallocated VAR_DECL, it means that it's going to be unified with whatever the TARGET_EXPR is really supposed to initialize, so treat it as being equivalent to anything. */ if (VAR_P (o1) && DECL_NAME (o1) == NULL_TREE && !DECL_RTL_SET_P (o1)) /*Nop*/; else if (VAR_P (o2) && DECL_NAME (o2) == NULL_TREE && !DECL_RTL_SET_P (o2)) /*Nop*/; else if (!c_tree_equal (o1, o2)) return false; return c_tree_equal (TREE_OPERAND (t1, 1), TREE_OPERAND (t2, 1)); } case COMPONENT_REF: if (TREE_OPERAND (t1, 1) != TREE_OPERAND (t2, 1)) return false; return c_tree_equal (TREE_OPERAND (t1, 0), TREE_OPERAND (t2, 0)); case PARM_DECL: case VAR_DECL: case CONST_DECL: case FIELD_DECL: case FUNCTION_DECL: case IDENTIFIER_NODE: case SSA_NAME: return false; case TREE_VEC: { unsigned ix; if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2)) return false; for (ix = TREE_VEC_LENGTH (t1); ix--;) if (!c_tree_equal (TREE_VEC_ELT (t1, ix), TREE_VEC_ELT (t2, ix))) return false; return true; } default: break; } switch (TREE_CODE_CLASS (code1)) { case tcc_unary: case tcc_binary: case tcc_comparison: case tcc_expression: case tcc_vl_exp: case tcc_reference: case tcc_statement: { int i, n = TREE_OPERAND_LENGTH (t1); switch (code1) { case PREINCREMENT_EXPR: case PREDECREMENT_EXPR: case POSTINCREMENT_EXPR: case POSTDECREMENT_EXPR: n = 1; break; case ARRAY_REF: n = 2; break; default: break; } if (TREE_CODE_CLASS (code1) == tcc_vl_exp && n != TREE_OPERAND_LENGTH (t2)) return false; for (i = 0; i < n; ++i) if (!c_tree_equal (TREE_OPERAND (t1, i), TREE_OPERAND (t2, i))) return false; return true; } case tcc_type: return comptypes (t1, t2); default: gcc_unreachable (); } /* We can get here with --disable-checking. */ return false; } /* Returns true when the function declaration FNDECL is implicit, introduced as a result of a call to an otherwise undeclared function, and false otherwise. */ bool c_decl_implicit (const_tree fndecl) { return C_DECL_IMPLICIT (fndecl); }
openmp_normal_numbers.c
#include <omp.h> #include <stdio.h> #include <sys/time.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #define NUMBER_OF_ELEMENTS 1 #define MEAN 0 #define STANDARD_DEVIATION 1 int main (int argc, char *argv[]) { int number_of_elements; if (argc == 1) { number_of_elements = NUMBER_OF_ELEMENTS; } else if (argc == 2) { number_of_elements = atoi(argv[1]); } else { fprintf(stderr, "%s\n", "Wrong number of arguments."); fprintf(stderr, "%s\n", "Use: ./normal_numbers number_of_elements"); exit(EXIT_FAILURE); } double *numbers = malloc (number_of_elements * sizeof(double)); double mean = MEAN; double standard_deviation = STANDARD_DEVIATION; // declare the necessary random number generator variables const gsl_rng_type *T; gsl_rng *r; // set the default values for the random number generator variables gsl_rng_env_setup(); // create a seed based on time struct timeval tv; gettimeofday(&tv,0); unsigned long seed = tv.tv_sec + tv.tv_usec; // setup the generator using the seed just created T = gsl_rng_default; r = gsl_rng_alloc (T); gsl_rng_set(r, seed); // generate number_of_elements normal random numbers #pragma omp parallel for for (int i = 0; i < number_of_elements; i++) { numbers[i] = mean + gsl_ran_gaussian (r, standard_deviation); } // print numbers if(number_of_elements < 10) { for (int i = 0; i < number_of_elements; i++) { printf (" %f", numbers[i]); } printf("\n"); } else { printf("(Array size = %d. Printing only its first and last elements)\n", number_of_elements); printf("%f %f ... %f %f\n", numbers[0], numbers[1], numbers[number_of_elements -2], numbers[number_of_elements -1]); } // free memory gsl_rng_free (r); free(numbers); return 0; }
omp3.c
// RUN: mlir-clang %s --function=* -fopenmp -S | FileCheck %s void square(double* x) { int i; #pragma omp parallel for private(i) for(i=3; i < 10; i+= 2) { x[i] = i; i++; x[i] = i; } } // CHECK: func @square(%arg0: memref<?xf64>) // CHECK-NEXT: %c1 = arith.constant 1 : index // CHECK-NEXT: %c2 = arith.constant 2 : index // CHECK-NEXT: %c11 = arith.constant 11 : index // CHECK-NEXT: %c1_i32 = arith.constant 1 : i32 // CHECK-NEXT: %c3 = arith.constant 3 : index // CHECK-NEXT: scf.parallel (%arg1) = (%c3) to (%c11) step (%c2) { // CHECK-NEXT: %0 = arith.index_cast %arg1 : index to i32 // CHECK-NEXT: %1 = arith.sitofp %0 : i32 to f64 // CHECK-NEXT: memref.store %1, %arg0[%arg1] : memref<?xf64> // CHECK-NEXT: %2 = arith.addi %0, %c1_i32 : i32 // CHECK-NEXT: %3 = arith.addi %arg1, %c1 : index // CHECK-NEXT: %4 = arith.sitofp %2 : i32 to f64 // CHECK-NEXT: memref.store %4, %arg0[%3] : memref<?xf64> // CHECK-NEXT: scf.yield // CHECK-NEXT: } // CHECK-NEXT: return // CHECK-NEXT: }
LJFunctor.h
/** * @file LJFunctor.h * * @date 17 Jan 2018 * @author tchipevn */ #pragma once #include <array> #include "ParticlePropertiesLibrary.h" #include "autopas/pairwiseFunctors/Functor.h" #include "autopas/particles/OwnershipState.h" #include "autopas/utils/AlignedAllocator.h" #include "autopas/utils/ArrayMath.h" #include "autopas/utils/ExceptionHandler.h" #include "autopas/utils/SoA.h" #include "autopas/utils/StaticBoolSelector.h" #include "autopas/utils/WrapOpenMP.h" #include "autopas/utils/inBox.h" namespace autopas { /** * A functor to handle lennard-jones interactions between two particles (molecules). * This functor assumes that duplicated calculations are always happening, which is characteristic for a Full-Shell * scheme. * @tparam Particle The type of particle. * @tparam applyShift Switch for the lj potential to be truncated shifted. * @tparam useMixing Switch for the functor to be used with multiple particle types. * If set to false, _epsilon and _sigma need to be set and the constructor with PPL can be omitted. * @tparam useNewton3 Switch for the functor to support newton3 on, off or both. See FunctorN3Modes for possible values. * @tparam calculateGlobals Defines whether the global values are to be calculated (energy, virial). * @tparam relevantForTuning Whether or not the auto-tuner should consider this functor. */ template <class Particle, bool applyShift = false, bool useMixing = false, FunctorN3Modes useNewton3 = FunctorN3Modes::Both, bool calculateGlobals = false, bool relevantForTuning = true> class LJFunctor : public Functor<Particle, LJFunctor<Particle, applyShift, useMixing, useNewton3, calculateGlobals, relevantForTuning>> { /** * Structure of the SoAs defined by the particle. */ using SoAArraysType = typename Particle::SoAArraysType; /** * Precision of SoA entries. */ using SoAFloatPrecision = typename Particle::ParticleSoAFloatPrecision; public: /** * Deleted default constructor */ LJFunctor() = delete; private: /** * Internal, actual constructor. * @param cutoff * @note param dummy is unused, only there to make the signature different from the public constructor. */ explicit LJFunctor(double cutoff, void * /*dummy*/) : Functor<Particle, LJFunctor<Particle, applyShift, useMixing, useNewton3, calculateGlobals, relevantForTuning>>( cutoff), _cutoffsquare{cutoff * cutoff}, _upotSum{0.}, _virialSum{0., 0., 0.}, _aosThreadData(), _postProcessed{false} { if constexpr (calculateGlobals) { _aosThreadData.resize(autopas_get_max_threads()); } } public: /** * Constructor for Functor with mixing disabled. When using this functor it is necessary to call * setParticleProperties() to set internal constants because it does not use a particle properties library. * * @note Only to be used with mixing == false. * * @param cutoff */ explicit LJFunctor(double cutoff) : LJFunctor(cutoff, nullptr) { static_assert(not useMixing, "Mixing without a ParticlePropertiesLibrary is not possible! Use a different constructor or set " "mixing to false."); } /** * Constructor for Functor with mixing active. This functor takes a ParticlePropertiesLibrary to look up (mixed) * properties like sigma, epsilon and shift. * @param cutoff * @param particlePropertiesLibrary */ explicit LJFunctor(double cutoff, ParticlePropertiesLibrary<double, size_t> &particlePropertiesLibrary) : LJFunctor(cutoff, nullptr) { static_assert(useMixing, "Not using Mixing but using a ParticlePropertiesLibrary is not allowed! Use a different constructor " "or set mixing to true."); _PPLibrary = &particlePropertiesLibrary; } bool isRelevantForTuning() final { return relevantForTuning; } bool allowsNewton3() final { return useNewton3 == FunctorN3Modes::Newton3Only or useNewton3 == FunctorN3Modes::Both; } bool allowsNonNewton3() final { return useNewton3 == FunctorN3Modes::Newton3Off or useNewton3 == FunctorN3Modes::Both; } void AoSFunctor(Particle &i, Particle &j, bool newton3) final { if (i.isDummy() or j.isDummy()) { return; } auto sigmasquare = _sigmasquare; auto epsilon24 = _epsilon24; auto shift6 = _shift6; if constexpr (useMixing) { sigmasquare = _PPLibrary->mixingSigmaSquare(i.getTypeId(), j.getTypeId()); epsilon24 = _PPLibrary->mixing24Epsilon(i.getTypeId(), j.getTypeId()); if constexpr (applyShift) { shift6 = _PPLibrary->mixingShift6(i.getTypeId(), j.getTypeId()); } } auto dr = utils::ArrayMath::sub(i.getR(), j.getR()); double dr2 = utils::ArrayMath::dot(dr, dr); if (dr2 > _cutoffsquare) { return; } double invdr2 = 1. / dr2; double lj6 = sigmasquare * invdr2; lj6 = lj6 * lj6 * lj6; double lj12 = lj6 * lj6; double lj12m6 = lj12 - lj6; double fac = epsilon24 * (lj12 + lj12m6) * invdr2; auto f = utils::ArrayMath::mulScalar(dr, fac); i.addF(f); if (newton3) { // only if we use newton 3 here, we want to j.subF(f); } if (calculateGlobals) { auto virial = utils::ArrayMath::mul(dr, f); double upot = epsilon24 * lj12m6 + shift6; const int threadnum = autopas_get_thread_num(); // for non-newton3 the division is in the post-processing step. if (newton3) { upot *= 0.5; virial = utils::ArrayMath::mulScalar(virial, (double)0.5); } if (i.isOwned()) { _aosThreadData[threadnum].upotSum += upot; _aosThreadData[threadnum].virialSum = utils::ArrayMath::add(_aosThreadData[threadnum].virialSum, virial); } // for non-newton3 the second particle will be considered in a separate calculation if (newton3 and j.isOwned()) { _aosThreadData[threadnum].upotSum += upot; _aosThreadData[threadnum].virialSum = utils::ArrayMath::add(_aosThreadData[threadnum].virialSum, virial); } } } /** * @copydoc Functor::SoAFunctorSingle(SoAView<SoAArraysType> soa, bool newton3) * This functor ignores will use a newton3 like traversing of the soa, however, it still needs to know about newton3 * to use it correctly for the global values. */ void SoAFunctorSingle(SoAView<SoAArraysType> soa, bool newton3) final { if (soa.getNumParticles() == 0) return; const auto *const __restrict xptr = soa.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict yptr = soa.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict zptr = soa.template begin<Particle::AttributeNames::posZ>(); const auto *const __restrict ownedStatePtr = soa.template begin<Particle::AttributeNames::ownershipState>(); SoAFloatPrecision *const __restrict fxptr = soa.template begin<Particle::AttributeNames::forceX>(); SoAFloatPrecision *const __restrict fyptr = soa.template begin<Particle::AttributeNames::forceY>(); SoAFloatPrecision *const __restrict fzptr = soa.template begin<Particle::AttributeNames::forceZ>(); [[maybe_unused]] auto *const __restrict typeptr = soa.template begin<Particle::AttributeNames::typeId>(); // the local redeclaration of the following values helps the SoAFloatPrecision-generation of various compilers. const SoAFloatPrecision cutoffsquare = _cutoffsquare; SoAFloatPrecision upotSum = 0.; SoAFloatPrecision virialSumX = 0.; SoAFloatPrecision virialSumY = 0.; SoAFloatPrecision virialSumZ = 0.; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> sigmaSquares; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> epsilon24s; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> shift6s; if constexpr (useMixing) { // Preload all sigma and epsilons for next vectorized region. // Not preloading and directly using the values, will produce worse results. sigmaSquares.resize(soa.getNumParticles()); epsilon24s.resize(soa.getNumParticles()); // if no mixing or mixing but no shift shift6 is constant therefore we do not need this vector. if constexpr (applyShift) { shift6s.resize(soa.getNumParticles()); } } const SoAFloatPrecision const_shift6 = _shift6; const SoAFloatPrecision const_sigmasquare = _sigmasquare; const SoAFloatPrecision const_epsilon24 = _epsilon24; for (unsigned int i = 0; i < soa.getNumParticles(); ++i) { const auto ownedStateI = ownedStatePtr[i]; if (ownedStateI == OwnershipState::dummy) { continue; } SoAFloatPrecision fxacc = 0.; SoAFloatPrecision fyacc = 0.; SoAFloatPrecision fzacc = 0.; if constexpr (useMixing) { for (unsigned int j = 0; j < soa.getNumParticles(); ++j) { auto mixingData = _PPLibrary->getMixingData(typeptr[i], typeptr[j]); sigmaSquares[j] = mixingData.sigmaSquare; epsilon24s[j] = mixingData.epsilon24; if constexpr (applyShift) { shift6s[j] = mixingData.shift6; } } } // icpc vectorizes this. // g++ only with -ffast-math or -funsafe-math-optimizations #pragma omp simd reduction(+ : fxacc, fyacc, fzacc, upotSum, virialSumX, virialSumY, virialSumZ) for (unsigned int j = i + 1; j < soa.getNumParticles(); ++j) { SoAFloatPrecision shift6 = const_shift6; SoAFloatPrecision sigmasquare = const_sigmasquare; SoAFloatPrecision epsilon24 = const_epsilon24; if constexpr (useMixing) { sigmasquare = sigmaSquares[j]; epsilon24 = epsilon24s[j]; if constexpr (applyShift) { shift6 = shift6s[j]; } } const auto ownedStateJ = ownedStatePtr[j]; const SoAFloatPrecision drx = xptr[i] - xptr[j]; const SoAFloatPrecision dry = yptr[i] - yptr[j]; const SoAFloatPrecision drz = zptr[i] - zptr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; // Mask away if distance is too large or any particle is a dummy. // Particle ownedStateI was already checked previously. const bool mask = dr2 <= cutoffsquare and ownedStateJ != OwnershipState::dummy; const SoAFloatPrecision invdr2 = 1. / dr2; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = mask ? epsilon24 * (lj12 + lj12m6) * invdr2 : 0.; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; // newton 3 fxptr[j] -= fx; fyptr[j] -= fy; fzptr[j] -= fz; if (calculateGlobals) { const SoAFloatPrecision virialx = drx * fx; const SoAFloatPrecision virialy = dry * fy; const SoAFloatPrecision virialz = drz * fz; const SoAFloatPrecision upot = mask ? (epsilon24 * lj12m6 + shift6) : 0.; // In this function, all pairs are only traversed once (newton3-scheme!). // In this case, the calculations are later divided by two! SoAFloatPrecision energyFactor = (ownedStateI == OwnershipState::owned ? 1. : 0.) + (ownedStateJ == OwnershipState::owned ? 1. : 0.); upotSum += upot * energyFactor; virialSumX += virialx * energyFactor; virialSumY += virialy * energyFactor; virialSumZ += virialz * energyFactor; } } fxptr[i] += fxacc; fyptr[i] += fyacc; fzptr[i] += fzacc; } if (calculateGlobals) { const int threadnum = autopas_get_thread_num(); double factor = 1.; // we assume newton3 to be enabled in this function call, thus we multiply by two if the value of newton3 is // false, since for newton3 disabled we divide by two later on. factor *= newton3 ? .5 : 1.; _aosThreadData[threadnum].upotSum += upotSum * factor; _aosThreadData[threadnum].virialSum[0] += virialSumX * factor; _aosThreadData[threadnum].virialSum[1] += virialSumY * factor; _aosThreadData[threadnum].virialSum[2] += virialSumZ * factor; } } /** * @copydoc Functor::SoAFunctorPair(SoAView<SoAArraysType> soa1, SoAView<SoAArraysType> soa2, bool newton3) */ void SoAFunctorPair(SoAView<SoAArraysType> soa1, SoAView<SoAArraysType> soa2, const bool newton3) final { if (newton3) { SoAFunctorPairImpl<true>(soa1, soa2); } else { SoAFunctorPairImpl<false>(soa1, soa2); } } private: /** * Implementation function of SoAFunctorPair(soa1, soa2, newton3) * * @tparam newton3 * @param soa1 * @param soa2 */ template <bool newton3> void SoAFunctorPairImpl(SoAView<SoAArraysType> soa1, SoAView<SoAArraysType> soa2) { if (soa1.getNumParticles() == 0 || soa2.getNumParticles() == 0) return; const auto *const __restrict x1ptr = soa1.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict y1ptr = soa1.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict z1ptr = soa1.template begin<Particle::AttributeNames::posZ>(); const auto *const __restrict x2ptr = soa2.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict y2ptr = soa2.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict z2ptr = soa2.template begin<Particle::AttributeNames::posZ>(); const auto *const __restrict ownedStatePtr1 = soa1.template begin<Particle::AttributeNames::ownershipState>(); const auto *const __restrict ownedStatePtr2 = soa2.template begin<Particle::AttributeNames::ownershipState>(); auto *const __restrict fx1ptr = soa1.template begin<Particle::AttributeNames::forceX>(); auto *const __restrict fy1ptr = soa1.template begin<Particle::AttributeNames::forceY>(); auto *const __restrict fz1ptr = soa1.template begin<Particle::AttributeNames::forceZ>(); auto *const __restrict fx2ptr = soa2.template begin<Particle::AttributeNames::forceX>(); auto *const __restrict fy2ptr = soa2.template begin<Particle::AttributeNames::forceY>(); auto *const __restrict fz2ptr = soa2.template begin<Particle::AttributeNames::forceZ>(); [[maybe_unused]] auto *const __restrict typeptr1 = soa1.template begin<Particle::AttributeNames::typeId>(); [[maybe_unused]] auto *const __restrict typeptr2 = soa2.template begin<Particle::AttributeNames::typeId>(); // Checks whether the cells are halo cells. SoAFloatPrecision upotSum = 0.; SoAFloatPrecision virialSumX = 0.; SoAFloatPrecision virialSumY = 0.; SoAFloatPrecision virialSumZ = 0.; const SoAFloatPrecision cutoffsquare = _cutoffsquare; SoAFloatPrecision shift6 = _shift6; SoAFloatPrecision sigmasquare = _sigmasquare; SoAFloatPrecision epsilon24 = _epsilon24; // preload all sigma and epsilons for next vectorized region std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> sigmaSquares; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> epsilon24s; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> shift6s; if constexpr (useMixing) { sigmaSquares.resize(soa2.getNumParticles()); epsilon24s.resize(soa2.getNumParticles()); // if no mixing or mixing but no shift shift6 is constant therefore we do not need this vector. if constexpr (applyShift) { shift6s.resize(soa2.getNumParticles()); } } for (unsigned int i = 0; i < soa1.getNumParticles(); ++i) { SoAFloatPrecision fxacc = 0; SoAFloatPrecision fyacc = 0; SoAFloatPrecision fzacc = 0; const auto ownedStateI = ownedStatePtr1[i]; if (ownedStateI == OwnershipState::dummy) { continue; } // preload all sigma and epsilons for next vectorized region if constexpr (useMixing) { for (unsigned int j = 0; j < soa2.getNumParticles(); ++j) { sigmaSquares[j] = _PPLibrary->mixingSigmaSquare(typeptr1[i], typeptr2[j]); epsilon24s[j] = _PPLibrary->mixing24Epsilon(typeptr1[i], typeptr2[j]); if constexpr (applyShift) { shift6s[j] = _PPLibrary->mixingShift6(typeptr1[i], typeptr2[j]); } } } // icpc vectorizes this. // g++ only with -ffast-math or -funsafe-math-optimizations #pragma omp simd reduction(+ : fxacc, fyacc, fzacc, upotSum, virialSumX, virialSumY, virialSumZ) for (unsigned int j = 0; j < soa2.getNumParticles(); ++j) { if constexpr (useMixing) { sigmasquare = sigmaSquares[j]; epsilon24 = epsilon24s[j]; if constexpr (applyShift) { shift6 = shift6s[j]; } } const auto ownedStateJ = ownedStatePtr2[j]; const SoAFloatPrecision drx = x1ptr[i] - x2ptr[j]; const SoAFloatPrecision dry = y1ptr[i] - y2ptr[j]; const SoAFloatPrecision drz = z1ptr[i] - z2ptr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; // Mask away if distance is too large or any particle is a dummy. // Particle ownedStateI was already checked previously. const bool mask = dr2 <= cutoffsquare and ownedStateJ != OwnershipState::dummy; const SoAFloatPrecision invdr2 = 1. / dr2; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = mask ? epsilon24 * (lj12 + lj12m6) * invdr2 * mask : 0.; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; if (newton3) { fx2ptr[j] -= fx; fy2ptr[j] -= fy; fz2ptr[j] -= fz; } if constexpr (calculateGlobals) { SoAFloatPrecision virialx = drx * fx; SoAFloatPrecision virialy = dry * fy; SoAFloatPrecision virialz = drz * fz; SoAFloatPrecision upot = (epsilon24 * lj12m6 + shift6) * mask; SoAFloatPrecision energyFactor = (ownedStateI == OwnershipState::owned ? 1. : 0.); if constexpr (newton3) { energyFactor += (ownedStateJ == OwnershipState::owned ? 1. : 0.); } // if newton3 is enabled, we multiply by 0.5 at the end of this function call when adding up the values to // the threadData. upotSum += upot * energyFactor; virialSumX += virialx * energyFactor; virialSumY += virialy * energyFactor; virialSumZ += virialz * energyFactor; } } fx1ptr[i] += fxacc; fy1ptr[i] += fyacc; fz1ptr[i] += fzacc; } if (calculateGlobals) { const int threadnum = autopas_get_thread_num(); SoAFloatPrecision newton3Factor = 1.; if constexpr (newton3) { newton3Factor *= 0.5; // we count the energies partly to one of the two cells! } _aosThreadData[threadnum].upotSum += upotSum * newton3Factor; _aosThreadData[threadnum].virialSum[0] += virialSumX * newton3Factor; _aosThreadData[threadnum].virialSum[1] += virialSumY * newton3Factor; _aosThreadData[threadnum].virialSum[2] += virialSumZ * newton3Factor; } } public: // clang-format off /** * @copydoc Functor::SoAFunctorVerlet(SoAView<SoAArraysType> soa, const size_t indexFirst, const std::vector<size_t, autopas::AlignedAllocator<size_t>> &neighborList, bool newton3) * @note If you want to parallelize this by openmp, please ensure that there * are no dependencies, i.e. introduce colors! */ // clang-format on void SoAFunctorVerlet(SoAView<SoAArraysType> soa, const size_t indexFirst, const std::vector<size_t, autopas::AlignedAllocator<size_t>> &neighborList, bool newton3) final { if (soa.getNumParticles() == 0 or neighborList.empty()) return; if (newton3) { SoAFunctorVerletImpl<true>(soa, indexFirst, neighborList); } else { SoAFunctorVerletImpl<false>(soa, indexFirst, neighborList); } } /** * Sets the particle properties constants for this functor. * * This is only necessary if no particlePropertiesLibrary is used. * * @param epsilon24 * @param sigmaSquare */ void setParticleProperties(SoAFloatPrecision epsilon24, SoAFloatPrecision sigmaSquare) { _epsilon24 = epsilon24; _sigmasquare = sigmaSquare; if (applyShift) { _shift6 = ParticlePropertiesLibrary<double, size_t>::calcShift6(_epsilon24, _sigmasquare, _cutoffsquare); } else { _shift6 = 0.; } } /** * @copydoc Functor::getNeededAttr() */ constexpr static auto getNeededAttr() { return std::array<typename Particle::AttributeNames, 9>{ Particle::AttributeNames::id, Particle::AttributeNames::posX, Particle::AttributeNames::posY, Particle::AttributeNames::posZ, Particle::AttributeNames::forceX, Particle::AttributeNames::forceY, Particle::AttributeNames::forceZ, Particle::AttributeNames::typeId, Particle::AttributeNames::ownershipState}; } /** * @copydoc Functor::getNeededAttr(std::false_type) */ constexpr static auto getNeededAttr(std::false_type) { return std::array<typename Particle::AttributeNames, 6>{ Particle::AttributeNames::id, Particle::AttributeNames::posX, Particle::AttributeNames::posY, Particle::AttributeNames::posZ, Particle::AttributeNames::typeId, Particle::AttributeNames::ownershipState}; } /** * @copydoc Functor::getComputedAttr() */ constexpr static auto getComputedAttr() { return std::array<typename Particle::AttributeNames, 3>{ Particle::AttributeNames::forceX, Particle::AttributeNames::forceY, Particle::AttributeNames::forceZ}; } /** * * @return useMixing */ constexpr static bool getMixing() { return useMixing; } /** * Get the number of flops used per kernel call. This should count the * floating point operations needed for two particles that lie within a cutoff * radius. * @return the number of floating point operations */ static unsigned long getNumFlopsPerKernelCall() { // Kernel: 12 = 1 (inverse R squared) + 8 (compute scale) + 3 (apply // scale) sum Forces: 6 (forces) kernel total = 12 + 6 = 18 return 18ul; } /** * Reset the global values. * Will set the global values to zero to prepare for the next iteration. */ void initTraversal() final { _upotSum = 0.; _virialSum = {0., 0., 0.}; _postProcessed = false; for (size_t i = 0; i < _aosThreadData.size(); ++i) { _aosThreadData[i].setZero(); } } /** * Postprocesses global values, e.g. upot and virial * @param newton3 */ void endTraversal(bool newton3) final { if (_postProcessed) { throw utils::ExceptionHandler::AutoPasException( "Already postprocessed, endTraversal(bool newton3) was called twice without calling initTraversal()."); } if (calculateGlobals) { for (size_t i = 0; i < _aosThreadData.size(); ++i) { _upotSum += _aosThreadData[i].upotSum; _virialSum = utils::ArrayMath::add(_virialSum, _aosThreadData[i].virialSum); } if (not newton3) { // if the newton3 optimization is disabled we have added every energy contribution twice, so we divide by 2 // here. _upotSum *= 0.5; _virialSum = utils::ArrayMath::mulScalar(_virialSum, 0.5); } // we have always calculated 6*upot, so we divide by 6 here! _upotSum /= 6.; _postProcessed = true; } } /** * Get the potential Energy. * @return the potential Energy */ double getUpot() { if (not calculateGlobals) { throw utils::ExceptionHandler::AutoPasException( "Trying to get upot even though calculateGlobals is false. If you want this functor to calculate global " "values, please specify calculateGlobals to be true."); } if (not _postProcessed) { throw utils::ExceptionHandler::AutoPasException("Cannot get upot, because endTraversal was not called."); } return _upotSum; } /** * Get the virial. * @return */ double getVirial() { if (not calculateGlobals) { throw utils::ExceptionHandler::AutoPasException( "Trying to get virial even though calculateGlobals is false. If you want this functor to calculate global " "values, please specify calculateGlobals to be true."); } if (not _postProcessed) { throw utils::ExceptionHandler::AutoPasException("Cannot get virial, because endTraversal was not called."); } return _virialSum[0] + _virialSum[1] + _virialSum[2]; } /** * Getter for 24*epsilon. * @return 24*epsilon */ SoAFloatPrecision getEpsilon24() const { return _epsilon24; } /** * Getter for the squared sigma. * @return squared sigma. */ SoAFloatPrecision getSigmaSquare() const { return _sigmasquare; } private: template <bool newton3> void SoAFunctorVerletImpl(SoAView<SoAArraysType> soa, const size_t indexFirst, const std::vector<size_t, autopas::AlignedAllocator<size_t>> &neighborList) { const auto *const __restrict xptr = soa.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict yptr = soa.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict zptr = soa.template begin<Particle::AttributeNames::posZ>(); auto *const __restrict fxptr = soa.template begin<Particle::AttributeNames::forceX>(); auto *const __restrict fyptr = soa.template begin<Particle::AttributeNames::forceY>(); auto *const __restrict fzptr = soa.template begin<Particle::AttributeNames::forceZ>(); [[maybe_unused]] auto *const __restrict typeptr1 = soa.template begin<Particle::AttributeNames::typeId>(); [[maybe_unused]] auto *const __restrict typeptr2 = soa.template begin<Particle::AttributeNames::typeId>(); const auto *const __restrict ownedStatePtr = soa.template begin<Particle::AttributeNames::ownershipState>(); const SoAFloatPrecision cutoffsquare = _cutoffsquare; SoAFloatPrecision shift6 = _shift6; SoAFloatPrecision sigmasquare = _sigmasquare; SoAFloatPrecision epsilon24 = _epsilon24; SoAFloatPrecision upotSum = 0.; SoAFloatPrecision virialSumX = 0.; SoAFloatPrecision virialSumY = 0.; SoAFloatPrecision virialSumZ = 0.; SoAFloatPrecision fxacc = 0; SoAFloatPrecision fyacc = 0; SoAFloatPrecision fzacc = 0; const size_t neighborListSize = neighborList.size(); const size_t *const __restrict neighborListPtr = neighborList.data(); // checks whether particle i is owned. const auto ownedStateI = ownedStatePtr[indexFirst]; if (ownedStateI == OwnershipState::dummy) { return; } // this is a magic number, that should correspond to at least // vectorization width*N have testet multiple sizes: // 4: does not give a speedup, slower than original AoSFunctor // 8: small speedup compared to AoS // 12: highest speedup compared to Aos // 16: smaller speedup // in theory this is a variable, we could auto-tune over... #ifdef __AVX512F__ // use a multiple of 8 for avx constexpr size_t vecsize = 16; #else // for everything else 12 is faster constexpr size_t vecsize = 12; #endif size_t joff = 0; // if the size of the verlet list is larger than the given size vecsize, // we will use a vectorized version. if (neighborListSize >= vecsize) { alignas(64) std::array<SoAFloatPrecision, vecsize> xtmp, ytmp, ztmp, xArr, yArr, zArr, fxArr, fyArr, fzArr; alignas(64) std::array<OwnershipState, vecsize> ownedStateArr{}; // broadcast of the position of particle i for (size_t tmpj = 0; tmpj < vecsize; tmpj++) { xtmp[tmpj] = xptr[indexFirst]; ytmp[tmpj] = yptr[indexFirst]; ztmp[tmpj] = zptr[indexFirst]; } // loop over the verlet list from 0 to x*vecsize for (; joff < neighborListSize - vecsize + 1; joff += vecsize) { // in each iteration we calculate the interactions of particle i with // vecsize particles in the neighborlist of particle i starting at // particle joff [[maybe_unused]] alignas(DEFAULT_CACHE_LINE_SIZE) std::array<SoAFloatPrecision, vecsize> sigmaSquares; [[maybe_unused]] alignas(DEFAULT_CACHE_LINE_SIZE) std::array<SoAFloatPrecision, vecsize> epsilon24s; [[maybe_unused]] alignas(DEFAULT_CACHE_LINE_SIZE) std::array<SoAFloatPrecision, vecsize> shift6s; if constexpr (useMixing) { for (size_t j = 0; j < vecsize; j++) { sigmaSquares[j] = _PPLibrary->mixingSigmaSquare(typeptr1[indexFirst], typeptr2[neighborListPtr[joff + j]]); epsilon24s[j] = _PPLibrary->mixing24Epsilon(typeptr1[indexFirst], typeptr2[neighborListPtr[joff + j]]); if constexpr (applyShift) { shift6s[j] = _PPLibrary->mixingShift6(typeptr1[indexFirst], typeptr2[neighborListPtr[joff + j]]); } } } // gather position of particle j #pragma omp simd safelen(vecsize) for (size_t tmpj = 0; tmpj < vecsize; tmpj++) { xArr[tmpj] = xptr[neighborListPtr[joff + tmpj]]; yArr[tmpj] = yptr[neighborListPtr[joff + tmpj]]; zArr[tmpj] = zptr[neighborListPtr[joff + tmpj]]; ownedStateArr[tmpj] = ownedStatePtr[neighborListPtr[joff + tmpj]]; } // do omp simd with reduction of the interaction #pragma omp simd reduction(+ : fxacc, fyacc, fzacc, upotSum, virialSumX, virialSumY, virialSumZ) safelen(vecsize) for (size_t j = 0; j < vecsize; j++) { if constexpr (useMixing) { sigmasquare = sigmaSquares[j]; epsilon24 = epsilon24s[j]; if constexpr (applyShift) { shift6 = shift6s[j]; } } // const size_t j = currentList[jNeighIndex]; const auto ownedStateJ = ownedStateArr[j]; const SoAFloatPrecision drx = xtmp[j] - xArr[j]; const SoAFloatPrecision dry = ytmp[j] - yArr[j]; const SoAFloatPrecision drz = ztmp[j] - zArr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; // Mask away if distance is too large or any particle is a dummy. // Particle ownedStateI was already checked previously. const bool mask = dr2 <= cutoffsquare and ownedStateJ != OwnershipState::dummy; const SoAFloatPrecision invdr2 = 1. / dr2; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = mask ? epsilon24 * (lj12 + lj12m6) * invdr2 : 0.; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; if (newton3) { fxArr[j] = fx; fyArr[j] = fy; fzArr[j] = fz; } if (calculateGlobals) { SoAFloatPrecision virialx = drx * fx; SoAFloatPrecision virialy = dry * fy; SoAFloatPrecision virialz = drz * fz; SoAFloatPrecision upot = mask ? (epsilon24 * lj12m6 + shift6) : 0.; SoAFloatPrecision energyFactor = (ownedStateI == OwnershipState::owned ? 1. : 0.); if constexpr (newton3) { energyFactor += (ownedStateJ == OwnershipState::owned ? 1. : 0.); } upotSum += upot * energyFactor; virialSumX += virialx * energyFactor; virialSumY += virialy * energyFactor; virialSumZ += virialz * energyFactor; } } // scatter the forces to where they belong, this is only needed for newton3 if (newton3) { #pragma omp simd safelen(vecsize) for (size_t tmpj = 0; tmpj < vecsize; tmpj++) { const size_t j = neighborListPtr[joff + tmpj]; fxptr[j] -= fxArr[tmpj]; fyptr[j] -= fyArr[tmpj]; fzptr[j] -= fzArr[tmpj]; } } } } // this loop goes over the remainder and uses no optimizations for (size_t jNeighIndex = joff; jNeighIndex < neighborListSize; ++jNeighIndex) { size_t j = neighborList[jNeighIndex]; if (indexFirst == j) continue; if constexpr (useMixing) { sigmasquare = _PPLibrary->mixingSigmaSquare(typeptr1[indexFirst], typeptr2[j]); epsilon24 = _PPLibrary->mixing24Epsilon(typeptr1[indexFirst], typeptr2[j]); if constexpr (applyShift) { shift6 = _PPLibrary->mixingShift6(typeptr1[indexFirst], typeptr2[j]); } } const auto ownedStateJ = ownedStatePtr[j]; if (ownedStateJ == OwnershipState::dummy) { continue; } const SoAFloatPrecision drx = xptr[indexFirst] - xptr[j]; const SoAFloatPrecision dry = yptr[indexFirst] - yptr[j]; const SoAFloatPrecision drz = zptr[indexFirst] - zptr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; if (dr2 > cutoffsquare) { continue; } const SoAFloatPrecision invdr2 = 1. / dr2; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = epsilon24 * (lj12 + lj12m6) * invdr2; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; if (newton3) { fxptr[j] -= fx; fyptr[j] -= fy; fzptr[j] -= fz; } if (calculateGlobals) { SoAFloatPrecision virialx = drx * fx; SoAFloatPrecision virialy = dry * fy; SoAFloatPrecision virialz = drz * fz; SoAFloatPrecision upot = (epsilon24 * lj12m6 + shift6); SoAFloatPrecision energyFactor = (ownedStateI == OwnershipState::owned ? 1. : 0.); if constexpr (newton3) { energyFactor += (ownedStateJ == OwnershipState::owned ? 1. : 0.); } upotSum += upot * energyFactor; virialSumX += virialx * energyFactor; virialSumY += virialy * energyFactor; virialSumZ += virialz * energyFactor; } } if (fxacc != 0 or fyacc != 0 or fzacc != 0) { fxptr[indexFirst] += fxacc; fyptr[indexFirst] += fyacc; fzptr[indexFirst] += fzacc; } if (calculateGlobals) { const int threadnum = autopas_get_thread_num(); SoAFloatPrecision energyMul = newton3 ? 0.5 : 1.; _aosThreadData[threadnum].upotSum += upotSum * energyMul; _aosThreadData[threadnum].virialSum[0] += virialSumX * energyMul; _aosThreadData[threadnum].virialSum[1] += virialSumY * energyMul; _aosThreadData[threadnum].virialSum[2] += virialSumZ * energyMul; } } /** * This class stores internal data of each thread, make sure that this data has proper size, i.e. k*64 Bytes! */ class AoSThreadData { public: AoSThreadData() : virialSum{0., 0., 0.}, upotSum{0.}, __remainingTo64{} {} void setZero() { virialSum = {0., 0., 0.}; upotSum = 0.; } // variables std::array<double, 3> virialSum; double upotSum; private: // dummy parameter to get the right size (64 bytes) double __remainingTo64[(64 - 4 * sizeof(double)) / sizeof(double)]; }; // make sure of the size of AoSThreadData static_assert(sizeof(AoSThreadData) % 64 == 0, "AoSThreadData has wrong size"); const double _cutoffsquare; // not const because they might be reset through PPL double _epsilon24, _sigmasquare, _shift6 = 0; ParticlePropertiesLibrary<SoAFloatPrecision, size_t> *_PPLibrary = nullptr; // sum of the potential energy, only calculated if calculateGlobals is true double _upotSum; // sum of the virial, only calculated if calculateGlobals is true std::array<double, 3> _virialSum; // thread buffer for aos std::vector<AoSThreadData> _aosThreadData; // defines whether or whether not the global values are already preprocessed bool _postProcessed; }; } // namespace autopas
conv_dw_kernel_x86.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: qtang@openailab.com */ #include "conv_dw_kernel_x86.h" #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "utility/sys_port.h" #include "utility/float.h" #include "utility/log.h" #include "device/cpu/cpu_node.h" #include "device/cpu/cpu_graph.h" #include "device/cpu/cpu_module.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #if __SSE2__ #include <emmintrin.h> #endif #if __AVX__ #include <immintrin.h> #endif #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) static void relu(float* data, int size, int activation) { for (int i = 0; i < size; i++) { data[i] = max(data[i], (float)0); if (activation > 0) { data[i] = min(data[i], (float)activation); } } } static void pad(float* input, float* output, int in_h, int in_w, int out_h, int out_w, int top, int left, float v) { float* ptr = input; float* outptr = output; int y = 0; // fill top for (; y < top; y++) { int x = 0; for (; x < out_w; x++) { outptr[x] = v; } outptr += out_w; } // fill center for (; y < (top + in_h); y++) { int x = 0; for (; x < left; x++) { outptr[x] = v; } if (in_w < 12) { for (; x < (left + in_w); x++) { outptr[x] = ptr[x - left]; } } else { memcpy(outptr + left, ptr, in_w * sizeof(float)); x += in_w; } for (; x < out_w; x++) { outptr[x] = v; } ptr += in_w; outptr += out_w; } // fill bottom for (; y < out_h; y++) { int x = 0; for (; x < out_w; x++) { outptr[x] = v; } outptr += out_w; } } #if __AVX__ static void convdw3x3s1(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw, int outh, int outw, int num_thread) { int inwh = inw * inh; int outwh = outw * outh; int channel_count = inc >> 3; int channel_remain = inc - (channel_count << 3); // generate the image tmp float* img_tmp = (float*)sys_malloc(8 * (unsigned long)inwh * (channel_count + 1) * sizeof(float)); float* kernel_tmp = (float*)sys_malloc(8 * 9 * (channel_count + 1) * sizeof(float)); float* bias_tmp = (float*)sys_malloc(8 * (channel_count + 1) * sizeof(float)); { for (int i = 0; i < channel_count; i++) { int ii = i * 8; const float* k0 = img_data + (ii + 0) * inwh; const float* k1 = img_data + (ii + 1) * inwh; const float* k2 = img_data + (ii + 2) * inwh; const float* k3 = img_data + (ii + 3) * inwh; const float* k4 = img_data + (ii + 4) * inwh; const float* k5 = img_data + (ii + 5) * inwh; const float* k6 = img_data + (ii + 6) * inwh; const float* k7 = img_data + (ii + 7) * inwh; const float* f0 = kernel_data + (ii + 0) * 9; const float* f1 = kernel_data + (ii + 1) * 9; const float* f2 = kernel_data + (ii + 2) * 9; const float* f3 = kernel_data + (ii + 3) * 9; const float* f4 = kernel_data + (ii + 4) * 9; const float* f5 = kernel_data + (ii + 5) * 9; const float* f6 = kernel_data + (ii + 6) * 9; const float* f7 = kernel_data + (ii + 7) * 9; const float* b0 = bias_data + (ii + 0); const float* b1 = bias_data + (ii + 1); const float* b2 = bias_data + (ii + 2); const float* b3 = bias_data + (ii + 3); const float* b4 = bias_data + (ii + 4); const float* b5 = bias_data + (ii + 5); const float* b6 = bias_data + (ii + 6); const float* b7 = bias_data + (ii + 7); float* tmp0 = img_tmp + ii * inwh; float* tmp1 = kernel_tmp + ii * 9; float* tmp2 = bias_tmp + ii; for (int j = 0; j < inwh; j++) { tmp0[0] = k0[0]; tmp0[1] = k1[0]; tmp0[2] = k2[0]; tmp0[3] = k3[0]; tmp0[4] = k4[0]; tmp0[5] = k5[0]; tmp0[6] = k6[0]; tmp0[7] = k7[0]; tmp0 += 8; k0++; k1++; k2++; k3++; k4++; k5++; k6++; k7++; } for (int j = 0; j < 9; j++) { tmp1[0] = f0[0]; tmp1[1] = f1[0]; tmp1[2] = f2[0]; tmp1[3] = f3[0]; tmp1[4] = f4[0]; tmp1[5] = f5[0]; tmp1[6] = f6[0]; tmp1[7] = f7[0]; tmp1 += 8; f0++; f1++; f2++; f3++; f4++; f5++; f6++; f7++; } if (bias_data) { tmp2[0] = b0[0]; tmp2[1] = b1[0]; tmp2[2] = b2[0]; tmp2[3] = b3[0]; tmp2[4] = b4[0]; tmp2[5] = b5[0]; tmp2[6] = b6[0]; tmp2[7] = b7[0]; } else { tmp2[0] = 0; tmp2[1] = 0; tmp2[2] = 0; tmp2[3] = 0; tmp2[4] = 0; tmp2[5] = 0; tmp2[6] = 0; tmp2[7] = 0; } } int i = 0; for (; i + 3 < channel_remain; i += 4) { int ii = channel_count * 8 + i; float* k0 = img_data + (ii + 0) * inwh; float* k1 = img_data + (ii + 1) * inwh; float* k2 = img_data + (ii + 2) * inwh; float* k3 = img_data + (ii + 3) * inwh; float* f0 = kernel_data + (ii + 0) * 9; float* f1 = kernel_data + (ii + 1) * 9; float* f2 = kernel_data + (ii + 2) * 9; float* f3 = kernel_data + (ii + 3) * 9; float* b0 = bias_data + (ii + 0); float* b1 = bias_data + (ii + 1); float* b2 = bias_data + (ii + 2); float* b3 = bias_data + (ii + 3); float* tmp0 = img_tmp + channel_count * 8 * inwh; float* tmp1 = kernel_tmp + channel_count * 8 * 9; float* tmp2 = bias_tmp + ii; for (int j = 0; j < inwh; j++) { tmp0[0] = k0[0]; tmp0[1] = k1[0]; tmp0[2] = k2[0]; tmp0[3] = k3[0]; tmp0 += 8; k0++; k1++; k2++; k3++; } for (int j = 0; j < 9; j++) { tmp1[0] = f0[0]; tmp1[1] = f1[0]; tmp1[2] = f2[0]; tmp1[3] = f3[0]; tmp1 += 8; f0++; f1++; f2++; f3++; } if (bias_data) { tmp2[0] = b0[0]; tmp2[1] = b1[0]; tmp2[2] = b2[0]; tmp2[3] = b3[0]; } else { tmp2[0] = 0; tmp2[1] = 0; tmp2[2] = 0; tmp2[3] = 0; } } for (; i < channel_remain; i++) { int ii = channel_count * 8 + i; float* k0 = img_data + ii * inwh; float* f0 = kernel_data + ii * 9; float* b0 = bias_data + ii; float* tmp0 = img_tmp + channel_count * 8 * inwh; float* tmp1 = kernel_tmp + channel_count * 8 * 9; float* tmp2 = bias_tmp + channel_count * 8; for (int j = 0; j < inwh; j++) { tmp0[i] = k0[0]; tmp0 += 8; k0++; } for (int j = 0; j < 9; j++) { tmp1[i] = f0[0]; tmp1 += 8; f0++; } if (bias_data) { tmp2[i] = b0[0]; } else { tmp2[i] = 0; } } } float* output_tmp = (float*)sys_malloc((unsigned long)outwh * (channel_count + 1) * 8 * sizeof(float)); for (int c = 0; c < channel_count + 1; c++) { float* ktmp = kernel_tmp + c * 8 * 9; float* btmp = bias_tmp + c * 8; for (int i = 0; i < outh; i++) { int j = 0; float* itmp0 = img_tmp + c * 8 * inwh + 8 * i * inw; float* itmp1 = img_tmp + c * 8 * inwh + 8 * (i + 1) * inw; float* itmp2 = img_tmp + c * 8 * inwh + 8 * (i + 2) * inw; float* otmp = output_tmp + c * 8 * outwh + 8 * i * outw; for (; j + 7 < outw; j += 8) { __m256 _sum0 = _mm256_loadu_ps(btmp); __m256 _sum1 = _mm256_loadu_ps(btmp); __m256 _sum2 = _mm256_loadu_ps(btmp); __m256 _sum3 = _mm256_loadu_ps(btmp); __m256 _sum4 = _mm256_loadu_ps(btmp); __m256 _sum5 = _mm256_loadu_ps(btmp); __m256 _sum6 = _mm256_loadu_ps(btmp); __m256 _sum7 = _mm256_loadu_ps(btmp); __m256 _va0 = _mm256_loadu_ps(itmp0); __m256 _va1 = _mm256_loadu_ps(itmp0 + 8); __m256 _va2 = _mm256_loadu_ps(itmp0 + 16); __m256 _va3 = _mm256_loadu_ps(itmp0 + 24); __m256 _va4 = _mm256_loadu_ps(itmp0 + 32); __m256 _va5 = _mm256_loadu_ps(itmp0 + 40); __m256 _va6 = _mm256_loadu_ps(itmp0 + 48); __m256 _va7 = _mm256_loadu_ps(itmp0 + 56); __m256 _va8 = _mm256_loadu_ps(itmp0 + 64); __m256 _va9 = _mm256_loadu_ps(itmp0 + 72); __m256 _vb0 = _mm256_loadu_ps(ktmp); __m256 _vb1 = _mm256_loadu_ps(ktmp + 8); __m256 _vb2 = _mm256_loadu_ps(ktmp + 16); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2); _sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2); _sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3); _sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4); _sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3); _sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5); _sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4); _sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5); _sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4); _sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6); _sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7); _sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5); _sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6); _sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7); _sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6); _sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7); _va0 = _mm256_loadu_ps(itmp1); _va1 = _mm256_loadu_ps(itmp1 + 8); _va2 = _mm256_loadu_ps(itmp1 + 16); _va3 = _mm256_loadu_ps(itmp1 + 24); _va4 = _mm256_loadu_ps(itmp1 + 32); _va5 = _mm256_loadu_ps(itmp1 + 40); _va6 = _mm256_loadu_ps(itmp1 + 48); _va7 = _mm256_loadu_ps(itmp1 + 56); _va8 = _mm256_loadu_ps(itmp1 + 64); _va9 = _mm256_loadu_ps(itmp1 + 72); _vb0 = _mm256_loadu_ps(ktmp + 24); _vb1 = _mm256_loadu_ps(ktmp + 32); _vb2 = _mm256_loadu_ps(ktmp + 40); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2); _sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2); _sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3); _sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4); _sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3); _sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5); _sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4); _sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5); _sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4); _sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6); _sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7); _sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5); _sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6); _sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7); _sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6); _sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7); _va0 = _mm256_loadu_ps(itmp2); _va1 = _mm256_loadu_ps(itmp2 + 8); _va2 = _mm256_loadu_ps(itmp2 + 16); _va3 = _mm256_loadu_ps(itmp2 + 24); _va4 = _mm256_loadu_ps(itmp2 + 32); _va5 = _mm256_loadu_ps(itmp2 + 40); _va6 = _mm256_loadu_ps(itmp2 + 48); _va7 = _mm256_loadu_ps(itmp2 + 56); _va8 = _mm256_loadu_ps(itmp2 + 64); _va9 = _mm256_loadu_ps(itmp2 + 72); _vb0 = _mm256_loadu_ps(ktmp + 48); _vb1 = _mm256_loadu_ps(ktmp + 56); _vb2 = _mm256_loadu_ps(ktmp + 64); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2); _sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2); _sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3); _sum4 = _mm256_fmadd_ps(_va4, _vb0, _sum4); _sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3); _sum5 = _mm256_fmadd_ps(_va5, _vb0, _sum5); _sum4 = _mm256_fmadd_ps(_va5, _vb1, _sum4); _sum5 = _mm256_fmadd_ps(_va6, _vb1, _sum5); _sum4 = _mm256_fmadd_ps(_va6, _vb2, _sum4); _sum6 = _mm256_fmadd_ps(_va6, _vb0, _sum6); _sum7 = _mm256_fmadd_ps(_va7, _vb0, _sum7); _sum5 = _mm256_fmadd_ps(_va7, _vb2, _sum5); _sum6 = _mm256_fmadd_ps(_va7, _vb1, _sum6); _sum7 = _mm256_fmadd_ps(_va8, _vb1, _sum7); _sum6 = _mm256_fmadd_ps(_va8, _vb2, _sum6); _sum7 = _mm256_fmadd_ps(_va9, _vb2, _sum7); _mm256_storeu_ps(otmp, _sum0); _mm256_storeu_ps(otmp + 8, _sum1); _mm256_storeu_ps(otmp + 16, _sum2); _mm256_storeu_ps(otmp + 24, _sum3); _mm256_storeu_ps(otmp + 32, _sum4); _mm256_storeu_ps(otmp + 40, _sum5); _mm256_storeu_ps(otmp + 48, _sum6); _mm256_storeu_ps(otmp + 56, _sum7); itmp0 += 64; itmp1 += 64; itmp2 += 64; otmp += 64; } for (; j + 3 < outw; j += 4) { __m256 _sum0 = _mm256_loadu_ps(btmp); __m256 _sum1 = _mm256_loadu_ps(btmp); __m256 _sum2 = _mm256_loadu_ps(btmp); __m256 _sum3 = _mm256_loadu_ps(btmp); __m256 _va0 = _mm256_loadu_ps(itmp0); __m256 _va1 = _mm256_loadu_ps(itmp0 + 8); __m256 _va2 = _mm256_loadu_ps(itmp0 + 16); __m256 _va3 = _mm256_loadu_ps(itmp0 + 24); __m256 _va4 = _mm256_loadu_ps(itmp0 + 32); __m256 _va5 = _mm256_loadu_ps(itmp0 + 40); __m256 _vb0 = _mm256_loadu_ps(ktmp); __m256 _vb1 = _mm256_loadu_ps(ktmp + 8); __m256 _vb2 = _mm256_loadu_ps(ktmp + 16); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2); _sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2); _sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3); _sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3); _va0 = _mm256_loadu_ps(itmp1); _va1 = _mm256_loadu_ps(itmp1 + 8); _va2 = _mm256_loadu_ps(itmp1 + 16); _va3 = _mm256_loadu_ps(itmp1 + 24); _va4 = _mm256_loadu_ps(itmp1 + 32); _va5 = _mm256_loadu_ps(itmp1 + 40); _vb0 = _mm256_loadu_ps(ktmp + 24); _vb1 = _mm256_loadu_ps(ktmp + 32); _vb2 = _mm256_loadu_ps(ktmp + 40); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2); _sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2); _sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3); _sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3); _va0 = _mm256_loadu_ps(itmp2); _va1 = _mm256_loadu_ps(itmp2 + 8); _va2 = _mm256_loadu_ps(itmp2 + 16); _va3 = _mm256_loadu_ps(itmp2 + 24); _va4 = _mm256_loadu_ps(itmp2 + 32); _va5 = _mm256_loadu_ps(itmp2 + 40); _vb0 = _mm256_loadu_ps(ktmp + 48); _vb1 = _mm256_loadu_ps(ktmp + 56); _vb2 = _mm256_loadu_ps(ktmp + 64); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum2 = _mm256_fmadd_ps(_va2, _vb0, _sum2); _sum3 = _mm256_fmadd_ps(_va3, _vb0, _sum3); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va3, _vb1, _sum2); _sum3 = _mm256_fmadd_ps(_va4, _vb1, _sum3); _sum2 = _mm256_fmadd_ps(_va4, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va5, _vb2, _sum3); _mm256_storeu_ps(otmp, _sum0); _mm256_storeu_ps(otmp + 8, _sum1); _mm256_storeu_ps(otmp + 16, _sum2); _mm256_storeu_ps(otmp + 24, _sum3); itmp0 += 32; itmp1 += 32; itmp2 += 32; otmp += 32; } for (; j + 1 < outw; j += 2) { __m256 _sum0 = _mm256_loadu_ps(btmp); __m256 _sum1 = _mm256_loadu_ps(btmp); __m256 _va0 = _mm256_loadu_ps(itmp0); __m256 _va1 = _mm256_loadu_ps(itmp0 + 8); __m256 _va2 = _mm256_loadu_ps(itmp0 + 16); __m256 _va3 = _mm256_loadu_ps(itmp0 + 24); __m256 _vb0 = _mm256_loadu_ps(ktmp); __m256 _vb1 = _mm256_loadu_ps(ktmp + 8); __m256 _vb2 = _mm256_loadu_ps(ktmp + 16); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _va0 = _mm256_loadu_ps(itmp1); _va1 = _mm256_loadu_ps(itmp1 + 8); _va2 = _mm256_loadu_ps(itmp1 + 16); _va3 = _mm256_loadu_ps(itmp1 + 24); _vb0 = _mm256_loadu_ps(ktmp + 24); _vb1 = _mm256_loadu_ps(ktmp + 32); _vb2 = _mm256_loadu_ps(ktmp + 40); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _va0 = _mm256_loadu_ps(itmp2); _va1 = _mm256_loadu_ps(itmp2 + 8); _va2 = _mm256_loadu_ps(itmp2 + 16); _va3 = _mm256_loadu_ps(itmp2 + 24); _vb0 = _mm256_loadu_ps(ktmp + 48); _vb1 = _mm256_loadu_ps(ktmp + 56); _vb2 = _mm256_loadu_ps(ktmp + 64); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum1 = _mm256_fmadd_ps(_va1, _vb0, _sum1); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb1, _sum1); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va3, _vb2, _sum1); _mm256_storeu_ps(otmp, _sum0); _mm256_storeu_ps(otmp + 8, _sum1); itmp0 += 16; itmp1 += 16; itmp2 += 16; otmp += 16; } for (; j < outw; j++) { __m256 _sum0 = _mm256_loadu_ps(btmp); __m256 _va0 = _mm256_loadu_ps(itmp0); __m256 _va1 = _mm256_loadu_ps(itmp0 + 8); __m256 _va2 = _mm256_loadu_ps(itmp0 + 16); __m256 _vb0 = _mm256_loadu_ps(ktmp); __m256 _vb1 = _mm256_loadu_ps(ktmp + 8); __m256 _vb2 = _mm256_loadu_ps(ktmp + 16); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _va0 = _mm256_loadu_ps(itmp1); _va1 = _mm256_loadu_ps(itmp1 + 8); _va2 = _mm256_loadu_ps(itmp1 + 16); _vb0 = _mm256_loadu_ps(ktmp + 24); _vb1 = _mm256_loadu_ps(ktmp + 32); _vb2 = _mm256_loadu_ps(ktmp + 40); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _va0 = _mm256_loadu_ps(itmp2); _va1 = _mm256_loadu_ps(itmp2 + 8); _va2 = _mm256_loadu_ps(itmp2 + 16); _vb0 = _mm256_loadu_ps(ktmp + 48); _vb1 = _mm256_loadu_ps(ktmp + 56); _vb2 = _mm256_loadu_ps(ktmp + 64); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _mm256_storeu_ps(otmp, _sum0); itmp0 += 8; itmp1 += 8; itmp2 += 8; otmp += 8; } } } // load_data { for (int i = 0; i < channel_count; i++) { float* otmp = output_tmp + i * 8 * outwh; float* tmp0 = output + i * 8 * outwh; float* tmp1 = output + i * 8 * outwh + 1 * outwh; float* tmp2 = output + i * 8 * outwh + 2 * outwh; float* tmp3 = output + i * 8 * outwh + 3 * outwh; float* tmp4 = output + i * 8 * outwh + 4 * outwh; float* tmp5 = output + i * 8 * outwh + 5 * outwh; float* tmp6 = output + i * 8 * outwh + 6 * outwh; float* tmp7 = output + i * 8 * outwh + 7 * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[0]; tmp1[0] = otmp[1]; tmp2[0] = otmp[2]; tmp3[0] = otmp[3]; tmp4[0] = otmp[4]; tmp5[0] = otmp[5]; tmp6[0] = otmp[6]; tmp7[0] = otmp[7]; otmp += 8; tmp0++; tmp1++; tmp2++; tmp3++; tmp4++; tmp5++; tmp6++; tmp7++; } } int i = 0; for (; i + 3 < channel_remain; i += 4) { int ii = channel_count * 8 + i; float* otmp = output_tmp + ii * outwh; float* tmp0 = output + ii * outwh; float* tmp1 = output + ii * outwh + 1 * outwh; float* tmp2 = output + ii * outwh + 2 * outwh; float* tmp3 = output + ii * outwh + 3 * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[0]; tmp1[0] = otmp[1]; tmp2[0] = otmp[2]; tmp3[0] = otmp[3]; otmp += 8; tmp0++; tmp1++; tmp2++; tmp3++; } } for (; i < channel_remain; i++) { int ii = channel_count * 8 + i; float* otmp = output_tmp + channel_count * 8 * outwh; float* tmp0 = output + ii * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[i]; otmp += 8; tmp0++; } } } sys_free(output_tmp); sys_free(img_tmp); sys_free(kernel_tmp); sys_free(bias_tmp); } static void convdw3x3s2(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw, int outh, int outw, int num_thread) { int inwh = inw * inh; int outwh = outw * outh; int channel_count = inc >> 3; int channel_remain = inc - (channel_count << 3); // generate the image tmp float* img_tmp = (float*)sys_malloc(8 * (unsigned long)inwh * (channel_count + 1) * sizeof(float)); float* kernel_tmp = (float*)sys_malloc(8 * 9 * (channel_count + 1) * sizeof(float)); float* bias_tmp = (float*)sys_malloc(8 * (channel_count + 1) * sizeof(float)); { for (int i = 0; i < channel_count; i++) { int ii = i * 8; const float* k0 = img_data + (ii + 0) * inwh; const float* k1 = img_data + (ii + 1) * inwh; const float* k2 = img_data + (ii + 2) * inwh; const float* k3 = img_data + (ii + 3) * inwh; const float* k4 = img_data + (ii + 4) * inwh; const float* k5 = img_data + (ii + 5) * inwh; const float* k6 = img_data + (ii + 6) * inwh; const float* k7 = img_data + (ii + 7) * inwh; const float* f0 = kernel_data + (ii + 0) * 9; const float* f1 = kernel_data + (ii + 1) * 9; const float* f2 = kernel_data + (ii + 2) * 9; const float* f3 = kernel_data + (ii + 3) * 9; const float* f4 = kernel_data + (ii + 4) * 9; const float* f5 = kernel_data + (ii + 5) * 9; const float* f6 = kernel_data + (ii + 6) * 9; const float* f7 = kernel_data + (ii + 7) * 9; const float* b0 = bias_data + (ii + 0); const float* b1 = bias_data + (ii + 1); const float* b2 = bias_data + (ii + 2); const float* b3 = bias_data + (ii + 3); const float* b4 = bias_data + (ii + 4); const float* b5 = bias_data + (ii + 5); const float* b6 = bias_data + (ii + 6); const float* b7 = bias_data + (ii + 7); float* tmp0 = img_tmp + ii * inwh; float* tmp1 = kernel_tmp + ii * 9; float* tmp2 = bias_tmp + ii; for (int j = 0; j < inwh; j++) { tmp0[0] = k0[0]; tmp0[1] = k1[0]; tmp0[2] = k2[0]; tmp0[3] = k3[0]; tmp0[4] = k4[0]; tmp0[5] = k5[0]; tmp0[6] = k6[0]; tmp0[7] = k7[0]; tmp0 += 8; k0++; k1++; k2++; k3++; k4++; k5++; k6++; k7++; } for (int j = 0; j < 9; j++) { tmp1[0] = f0[0]; tmp1[1] = f1[0]; tmp1[2] = f2[0]; tmp1[3] = f3[0]; tmp1[4] = f4[0]; tmp1[5] = f5[0]; tmp1[6] = f6[0]; tmp1[7] = f7[0]; tmp1 += 8; f0++; f1++; f2++; f3++; f4++; f5++; f6++; f7++; } if (bias_data) { tmp2[0] = b0[0]; tmp2[1] = b1[0]; tmp2[2] = b2[0]; tmp2[3] = b3[0]; tmp2[4] = b4[0]; tmp2[5] = b5[0]; tmp2[6] = b6[0]; tmp2[7] = b7[0]; } else { tmp2[0] = 0; tmp2[1] = 0; tmp2[2] = 0; tmp2[3] = 0; tmp2[4] = 0; tmp2[5] = 0; tmp2[6] = 0; tmp2[7] = 0; } } int i = 0; for (; i + 3 < channel_remain; i += 4) { int ii = channel_count * 8 + i; float* k0 = img_data + (ii + 0) * inwh; float* k1 = img_data + (ii + 1) * inwh; float* k2 = img_data + (ii + 2) * inwh; float* k3 = img_data + (ii + 3) * inwh; float* f0 = kernel_data + (ii + 0) * 9; float* f1 = kernel_data + (ii + 1) * 9; float* f2 = kernel_data + (ii + 2) * 9; float* f3 = kernel_data + (ii + 3) * 9; float* b0 = bias_data + (ii + 0); float* b1 = bias_data + (ii + 1); float* b2 = bias_data + (ii + 2); float* b3 = bias_data + (ii + 3); float* tmp0 = img_tmp + channel_count * 8 * inwh; float* tmp1 = kernel_tmp + channel_count * 8 * 9; float* tmp2 = bias_tmp + ii; for (int j = 0; j < inwh; j++) { tmp0[0] = k0[0]; tmp0[1] = k1[0]; tmp0[2] = k2[0]; tmp0[3] = k3[0]; tmp0 += 8; k0++; k1++; k2++; k3++; } for (int j = 0; j < 9; j++) { tmp1[0] = f0[0]; tmp1[1] = f1[0]; tmp1[2] = f2[0]; tmp1[3] = f3[0]; tmp1 += 8; f0++; f1++; f2++; f3++; } if (bias_data) { tmp2[0] = b0[0]; tmp2[1] = b1[0]; tmp2[2] = b2[0]; tmp2[3] = b3[0]; } else { tmp2[0] = 0; tmp2[1] = 0; tmp2[2] = 0; tmp2[3] = 0; } } for (; i < channel_remain; i++) { int ii = channel_count * 8 + i; float* k0 = img_data + ii * inwh; float* f0 = kernel_data + ii * 9; float* b0 = bias_data + ii; float* tmp0 = img_tmp + channel_count * 8 * inwh; float* tmp1 = kernel_tmp + channel_count * 8 * 9; float* tmp2 = bias_tmp + channel_count * 8; for (int j = 0; j < inwh; j++) { tmp0[i] = k0[0]; tmp0 += 8; k0++; } for (int j = 0; j < 9; j++) { tmp1[i] = f0[0]; tmp1 += 8; f0++; } if (bias_data) { tmp2[i] = b0[0]; } else { tmp2[i] = 0; } } } float* output_tmp = (float*)sys_malloc((unsigned long)outwh * (channel_count + 1) * 8 * sizeof(float)); for (int c = 0; c < channel_count + 1; c++) { float* ktmp = kernel_tmp + c * 8 * 9; float* btmp = bias_tmp + c * 8; for (int i = 0; i < outh; i++) { int j = 0; float* itmp0 = img_tmp + c * 8 * inwh + 8 * i * 2 * inw; float* itmp1 = img_tmp + c * 8 * inwh + 8 * (i * 2 + 1) * inw; float* itmp2 = img_tmp + c * 8 * inwh + 8 * (i * 2 + 2) * inw; float* otmp = output_tmp + c * 8 * outwh + 8 * i * outw; for (; j + 3 < outw; j += 4) { __m256 _sum0 = _mm256_loadu_ps(btmp); __m256 _sum1 = _mm256_loadu_ps(btmp); __m256 _sum2 = _mm256_loadu_ps(btmp); __m256 _sum3 = _mm256_loadu_ps(btmp); __m256 _va0 = _mm256_loadu_ps(itmp0); __m256 _va1 = _mm256_loadu_ps(itmp0 + 8); __m256 _va2 = _mm256_loadu_ps(itmp0 + 16); __m256 _va3 = _mm256_loadu_ps(itmp0 + 24); __m256 _va4 = _mm256_loadu_ps(itmp0 + 32); __m256 _va5 = _mm256_loadu_ps(itmp0 + 40); __m256 _va6 = _mm256_loadu_ps(itmp0 + 48); __m256 _va7 = _mm256_loadu_ps(itmp0 + 56); __m256 _va8 = _mm256_loadu_ps(itmp0 + 64); __m256 _vb0 = _mm256_loadu_ps(ktmp); __m256 _vb1 = _mm256_loadu_ps(ktmp + 8); __m256 _vb2 = _mm256_loadu_ps(ktmp + 16); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1); _sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1); _sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2); _sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2); _sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3); _sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3); _sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3); _va0 = _mm256_loadu_ps(itmp1); _va1 = _mm256_loadu_ps(itmp1 + 8); _va2 = _mm256_loadu_ps(itmp1 + 16); _va3 = _mm256_loadu_ps(itmp1 + 24); _va4 = _mm256_loadu_ps(itmp1 + 32); _va5 = _mm256_loadu_ps(itmp1 + 40); _va6 = _mm256_loadu_ps(itmp1 + 48); _va7 = _mm256_loadu_ps(itmp1 + 56); _va8 = _mm256_loadu_ps(itmp1 + 64); _vb0 = _mm256_loadu_ps(ktmp + 24); _vb1 = _mm256_loadu_ps(ktmp + 32); _vb2 = _mm256_loadu_ps(ktmp + 40); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1); _sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1); _sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2); _sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2); _sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3); _sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3); _sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3); _va0 = _mm256_loadu_ps(itmp2); _va1 = _mm256_loadu_ps(itmp2 + 8); _va2 = _mm256_loadu_ps(itmp2 + 16); _va3 = _mm256_loadu_ps(itmp2 + 24); _va4 = _mm256_loadu_ps(itmp2 + 32); _va5 = _mm256_loadu_ps(itmp2 + 40); _va6 = _mm256_loadu_ps(itmp2 + 48); _va7 = _mm256_loadu_ps(itmp2 + 56); _va8 = _mm256_loadu_ps(itmp2 + 64); _vb0 = _mm256_loadu_ps(ktmp + 48); _vb1 = _mm256_loadu_ps(ktmp + 56); _vb2 = _mm256_loadu_ps(ktmp + 64); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1); _sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1); _sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1); _sum2 = _mm256_fmadd_ps(_va4, _vb0, _sum2); _sum2 = _mm256_fmadd_ps(_va5, _vb1, _sum2); _sum2 = _mm256_fmadd_ps(_va6, _vb2, _sum2); _sum3 = _mm256_fmadd_ps(_va6, _vb0, _sum3); _sum3 = _mm256_fmadd_ps(_va7, _vb1, _sum3); _sum3 = _mm256_fmadd_ps(_va8, _vb2, _sum3); _mm256_storeu_ps(otmp, _sum0); _mm256_storeu_ps(otmp + 8, _sum1); _mm256_storeu_ps(otmp + 16, _sum2); _mm256_storeu_ps(otmp + 24, _sum3); itmp0 += 64; itmp1 += 64; itmp2 += 64; otmp += 32; } for (; j + 1 < outw; j += 2) { __m256 _sum0 = _mm256_loadu_ps(btmp); __m256 _sum1 = _mm256_loadu_ps(btmp); __m256 _va0 = _mm256_loadu_ps(itmp0); __m256 _va1 = _mm256_loadu_ps(itmp0 + 8); __m256 _va2 = _mm256_loadu_ps(itmp0 + 16); __m256 _va3 = _mm256_loadu_ps(itmp0 + 24); __m256 _va4 = _mm256_loadu_ps(itmp0 + 32); __m256 _vb0 = _mm256_loadu_ps(ktmp); __m256 _vb1 = _mm256_loadu_ps(ktmp + 8); __m256 _vb2 = _mm256_loadu_ps(ktmp + 16); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1); _sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1); _sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1); _va0 = _mm256_loadu_ps(itmp1); _va1 = _mm256_loadu_ps(itmp1 + 8); _va2 = _mm256_loadu_ps(itmp1 + 16); _va3 = _mm256_loadu_ps(itmp1 + 24); _va4 = _mm256_loadu_ps(itmp1 + 32); _vb0 = _mm256_loadu_ps(ktmp + 24); _vb1 = _mm256_loadu_ps(ktmp + 32); _vb2 = _mm256_loadu_ps(ktmp + 40); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1); _sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1); _sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1); _va0 = _mm256_loadu_ps(itmp2); _va1 = _mm256_loadu_ps(itmp2 + 8); _va2 = _mm256_loadu_ps(itmp2 + 16); _va3 = _mm256_loadu_ps(itmp2 + 24); _va4 = _mm256_loadu_ps(itmp2 + 32); _vb0 = _mm256_loadu_ps(ktmp + 48); _vb1 = _mm256_loadu_ps(ktmp + 56); _vb2 = _mm256_loadu_ps(ktmp + 64); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _sum1 = _mm256_fmadd_ps(_va2, _vb0, _sum1); _sum1 = _mm256_fmadd_ps(_va3, _vb1, _sum1); _sum1 = _mm256_fmadd_ps(_va4, _vb2, _sum1); _mm256_storeu_ps(otmp, _sum0); _mm256_storeu_ps(otmp + 8, _sum1); itmp0 += 32; itmp1 += 32; itmp2 += 32; otmp += 16; } for (; j < outw; j++) { __m256 _sum0 = _mm256_loadu_ps(btmp); __m256 _va0 = _mm256_loadu_ps(itmp0); __m256 _va1 = _mm256_loadu_ps(itmp0 + 8); __m256 _va2 = _mm256_loadu_ps(itmp0 + 16); __m256 _vb0 = _mm256_loadu_ps(ktmp); __m256 _vb1 = _mm256_loadu_ps(ktmp + 8); __m256 _vb2 = _mm256_loadu_ps(ktmp + 16); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _va0 = _mm256_loadu_ps(itmp1); _va1 = _mm256_loadu_ps(itmp1 + 8); _va2 = _mm256_loadu_ps(itmp1 + 16); _vb0 = _mm256_loadu_ps(ktmp + 24); _vb1 = _mm256_loadu_ps(ktmp + 32); _vb2 = _mm256_loadu_ps(ktmp + 40); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _va0 = _mm256_loadu_ps(itmp2); _va1 = _mm256_loadu_ps(itmp2 + 8); _va2 = _mm256_loadu_ps(itmp2 + 16); _vb0 = _mm256_loadu_ps(ktmp + 48); _vb1 = _mm256_loadu_ps(ktmp + 56); _vb2 = _mm256_loadu_ps(ktmp + 64); _sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0); _sum0 = _mm256_fmadd_ps(_va1, _vb1, _sum0); _sum0 = _mm256_fmadd_ps(_va2, _vb2, _sum0); _mm256_storeu_ps(otmp, _sum0); itmp0 += 16; itmp1 += 16; itmp2 += 16; otmp += 8; } } } // load_data { for (int i = 0; i < channel_count; i++) { float* otmp = output_tmp + i * 8 * outwh; float* tmp0 = output + i * 8 * outwh; float* tmp1 = output + i * 8 * outwh + 1 * outwh; float* tmp2 = output + i * 8 * outwh + 2 * outwh; float* tmp3 = output + i * 8 * outwh + 3 * outwh; float* tmp4 = output + i * 8 * outwh + 4 * outwh; float* tmp5 = output + i * 8 * outwh + 5 * outwh; float* tmp6 = output + i * 8 * outwh + 6 * outwh; float* tmp7 = output + i * 8 * outwh + 7 * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[0]; tmp1[0] = otmp[1]; tmp2[0] = otmp[2]; tmp3[0] = otmp[3]; tmp4[0] = otmp[4]; tmp5[0] = otmp[5]; tmp6[0] = otmp[6]; tmp7[0] = otmp[7]; otmp += 8; tmp0++; tmp1++; tmp2++; tmp3++; tmp4++; tmp5++; tmp6++; tmp7++; } } int i = 0; for (; i + 3 < channel_remain; i += 4) { int ii = channel_count * 8 + i; float* otmp = output_tmp + ii * outwh; float* tmp0 = output + ii * outwh; float* tmp1 = output + ii * outwh + 1 * outwh; float* tmp2 = output + ii * outwh + 2 * outwh; float* tmp3 = output + ii * outwh + 3 * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[0]; tmp1[0] = otmp[1]; tmp2[0] = otmp[2]; tmp3[0] = otmp[3]; otmp += 8; tmp0++; tmp1++; tmp2++; tmp3++; } } for (; i < channel_remain; i++) { int ii = channel_count * 8 + i; float* otmp = output_tmp + channel_count * 8 * outwh; float* tmp0 = output + ii * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[i]; otmp += 8; tmp0++; } } } sys_free(output_tmp); sys_free(img_tmp); sys_free(kernel_tmp); sys_free(bias_tmp); } #elif __SSE2__ static void convdw3x3s1(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw, int outh, int outw, int num_thread) { int inwh = inw * inh; int outwh = outw * outh; int channel_count = inc >> 2; int channel_remain = inc - (channel_count << 2); // generate the image tmp float* img_tmp = (float*)sys_malloc(4 * inwh * (channel_count + 1) * sizeof(float)); float* kernel_tmp = (float*)sys_malloc(4 * 9 * (channel_count + 1) * sizeof(float)); float* bias_tmp = (float*)sys_malloc(4 * (channel_count + 1) * sizeof(float)); { for (int i = 0; i < channel_count; i++) { int ii = i * 4; float* k0 = img_data + (ii + 0) * inwh; float* k1 = img_data + (ii + 1) * inwh; float* k2 = img_data + (ii + 2) * inwh; float* k3 = img_data + (ii + 3) * inwh; float* f0 = kernel_data + (ii + 0) * 9; float* f1 = kernel_data + (ii + 1) * 9; float* f2 = kernel_data + (ii + 2) * 9; float* f3 = kernel_data + (ii + 3) * 9; float* b0 = bias_data + (ii + 0); float* b1 = bias_data + (ii + 1); float* b2 = bias_data + (ii + 2); float* b3 = bias_data + (ii + 3); float* tmp0 = img_tmp + ii * inwh; float* tmp1 = kernel_tmp + ii * 9; float* tmp2 = bias_tmp + ii; for (int j = 0; j < inwh; j++) { tmp0[0] = k0[0]; tmp0[1] = k1[0]; tmp0[2] = k2[0]; tmp0[3] = k3[0]; tmp0 += 4; k0++; k1++; k2++; k3++; } for (int j = 0; j < 9; j++) { tmp1[0] = f0[0]; tmp1[1] = f1[0]; tmp1[2] = f2[0]; tmp1[3] = f3[0]; tmp1 += 4; f0++; f1++; f2++; f3++; } if (bias_data) { tmp2[0] = b0[0]; tmp2[1] = b1[0]; tmp2[2] = b2[0]; tmp2[3] = b3[0]; } else { tmp2[0] = 0; tmp2[1] = 0; tmp2[2] = 0; tmp2[3] = 0; } } for (int i = 0; i < channel_remain; i++) { int ii = channel_count * 4 + i; float* k0 = img_data + ii * inwh; float* f0 = kernel_data + ii * 9; float* b0 = bias_data + ii; float* tmp0 = img_tmp + channel_count * 4 * inwh; float* tmp1 = kernel_tmp + channel_count * 4 * 9; float* tmp2 = bias_tmp + channel_count * 4; for (int j = 0; j < inwh; j++) { tmp0[i] = k0[0]; tmp0 += 4; k0++; } for (int j = 0; j < 9; j++) { tmp1[i] = f0[0]; tmp1 += 4; f0++; } if (bias_data) { tmp2[i] = b0[0]; } else { tmp2[i] = 0; } } } float* output_tmp = (float*)sys_malloc(outwh * 4 * (channel_count + 1) * sizeof(float)); for (int c = 0; c < channel_count + 1; c++) { float* ktmp = kernel_tmp + c * 4 * 9; float* btmp = bias_tmp + c * 4; for (int i = 0; i < outh; i++) { int j = 0; float* itmp0 = img_tmp + c * 4 * inwh + 4 * i * inw; float* itmp1 = img_tmp + c * 4 * inwh + 4 * (i + 1) * inw; float* itmp2 = img_tmp + c * 4 * inwh + 4 * (i + 2) * inw; float* otmp = output_tmp + c * 4 * outwh + 4 * i * outw; for (; j + 7 < outw; j += 8) { #if __SSE__ __m128 _sum0 = _mm_loadu_ps(btmp); __m128 _sum1 = _mm_loadu_ps(btmp); __m128 _sum2 = _mm_loadu_ps(btmp); __m128 _sum3 = _mm_loadu_ps(btmp); __m128 _sum4 = _mm_loadu_ps(btmp); __m128 _sum5 = _mm_loadu_ps(btmp); __m128 _sum6 = _mm_loadu_ps(btmp); __m128 _sum7 = _mm_loadu_ps(btmp); __m128 _va0 = _mm_loadu_ps(itmp0); __m128 _va1 = _mm_loadu_ps(itmp0 + 4); __m128 _va2 = _mm_loadu_ps(itmp0 + 8); __m128 _va3 = _mm_loadu_ps(itmp0 + 12); __m128 _va4 = _mm_loadu_ps(itmp0 + 16); __m128 _va5 = _mm_loadu_ps(itmp0 + 20); __m128 _va6 = _mm_loadu_ps(itmp0 + 24); __m128 _va7 = _mm_loadu_ps(itmp0 + 28); __m128 _va8 = _mm_loadu_ps(itmp0 + 32); __m128 _va9 = _mm_loadu_ps(itmp0 + 36); __m128 _vb0 = _mm_loadu_ps(ktmp); __m128 _vb1 = _mm_loadu_ps(ktmp + 4); __m128 _vb2 = _mm_loadu_ps(ktmp + 8); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3); _sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1); _sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3); _sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4); _sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3); _sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5); _sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4); _sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5); _sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4); _sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7); _sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5); _sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7); _sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7); _va0 = _mm_loadu_ps(itmp1); _va1 = _mm_loadu_ps(itmp1 + 4); _va2 = _mm_loadu_ps(itmp1 + 8); _va3 = _mm_loadu_ps(itmp1 + 12); _va4 = _mm_loadu_ps(itmp1 + 16); _va5 = _mm_loadu_ps(itmp1 + 20); _va6 = _mm_loadu_ps(itmp1 + 24); _va7 = _mm_loadu_ps(itmp1 + 28); _va8 = _mm_loadu_ps(itmp1 + 32); _va9 = _mm_loadu_ps(itmp1 + 36); _vb0 = _mm_loadu_ps(ktmp + 12); _vb1 = _mm_loadu_ps(ktmp + 16); _vb2 = _mm_loadu_ps(ktmp + 20); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3); _sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1); _sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3); _sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4); _sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3); _sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5); _sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4); _sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5); _sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4); _sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7); _sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5); _sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7); _sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7); _va0 = _mm_loadu_ps(itmp2); _va1 = _mm_loadu_ps(itmp2 + 4); _va2 = _mm_loadu_ps(itmp2 + 8); _va3 = _mm_loadu_ps(itmp2 + 12); _va4 = _mm_loadu_ps(itmp2 + 16); _va5 = _mm_loadu_ps(itmp2 + 20); _va6 = _mm_loadu_ps(itmp2 + 24); _va7 = _mm_loadu_ps(itmp2 + 28); _va8 = _mm_loadu_ps(itmp2 + 32); _va9 = _mm_loadu_ps(itmp2 + 36); _vb0 = _mm_loadu_ps(ktmp + 24); _vb1 = _mm_loadu_ps(ktmp + 28); _vb2 = _mm_loadu_ps(ktmp + 32); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3); _sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1); _sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3); _sum4 = _mm_add_ps(_mm_mul_ps(_va4, _vb0), _sum4); _sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3); _sum5 = _mm_add_ps(_mm_mul_ps(_va5, _vb0), _sum5); _sum4 = _mm_add_ps(_mm_mul_ps(_va5, _vb1), _sum4); _sum5 = _mm_add_ps(_mm_mul_ps(_va6, _vb1), _sum5); _sum4 = _mm_add_ps(_mm_mul_ps(_va6, _vb2), _sum4); _sum6 = _mm_add_ps(_mm_mul_ps(_va6, _vb0), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va7, _vb0), _sum7); _sum5 = _mm_add_ps(_mm_mul_ps(_va7, _vb2), _sum5); _sum6 = _mm_add_ps(_mm_mul_ps(_va7, _vb1), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va8, _vb1), _sum7); _sum6 = _mm_add_ps(_mm_mul_ps(_va8, _vb2), _sum6); _sum7 = _mm_add_ps(_mm_mul_ps(_va9, _vb2), _sum7); _mm_storeu_ps(otmp, _sum0); _mm_storeu_ps(otmp + 4, _sum1); _mm_storeu_ps(otmp + 8, _sum2); _mm_storeu_ps(otmp + 12, _sum3); _mm_storeu_ps(otmp + 16, _sum4); _mm_storeu_ps(otmp + 20, _sum5); _mm_storeu_ps(otmp + 24, _sum6); _mm_storeu_ps(otmp + 28, _sum7); #else float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum4[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum5[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum6[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum7[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; for (int k = 0; k < 4; k++) { sum0[k] += itmp0[k] * ktmp[k]; sum0[k] += itmp1[k] * ktmp[k + 12]; sum0[k] += itmp2[k] * ktmp[k + 24]; sum0[k] += itmp0[k + 4] * ktmp[k + 4]; sum0[k] += itmp1[k + 4] * ktmp[k + 16]; sum0[k] += itmp2[k + 4] * ktmp[k + 28]; sum0[k] += itmp0[k + 8] * ktmp[k + 8]; sum0[k] += itmp1[k + 8] * ktmp[k + 20]; sum0[k] += itmp2[k + 8] * ktmp[k + 32]; sum1[k] += itmp0[k + 4] * ktmp[k]; sum1[k] += itmp1[k + 4] * ktmp[k + 12]; sum1[k] += itmp2[k + 4] * ktmp[k + 24]; sum1[k] += itmp0[k + 8] * ktmp[k + 4]; sum1[k] += itmp1[k + 8] * ktmp[k + 16]; sum1[k] += itmp2[k + 8] * ktmp[k + 28]; sum1[k] += itmp0[k + 12] * ktmp[k + 8]; sum1[k] += itmp1[k + 12] * ktmp[k + 20]; sum1[k] += itmp2[k + 12] * ktmp[k + 32]; sum2[k] += itmp0[k + 8] * ktmp[k]; sum2[k] += itmp1[k + 8] * ktmp[k + 12]; sum2[k] += itmp2[k + 8] * ktmp[k + 24]; sum2[k] += itmp0[k + 12] * ktmp[k + 4]; sum2[k] += itmp1[k + 12] * ktmp[k + 16]; sum2[k] += itmp2[k + 12] * ktmp[k + 28]; sum2[k] += itmp0[k + 16] * ktmp[k + 8]; sum2[k] += itmp1[k + 16] * ktmp[k + 20]; sum2[k] += itmp2[k + 16] * ktmp[k + 32]; sum3[k] += itmp0[k + 12] * ktmp[k]; sum3[k] += itmp1[k + 12] * ktmp[k + 12]; sum3[k] += itmp2[k + 12] * ktmp[k + 24]; sum3[k] += itmp0[k + 16] * ktmp[k + 4]; sum3[k] += itmp1[k + 16] * ktmp[k + 16]; sum3[k] += itmp2[k + 16] * ktmp[k + 28]; sum3[k] += itmp0[k + 20] * ktmp[k + 8]; sum3[k] += itmp1[k + 20] * ktmp[k + 20]; sum3[k] += itmp2[k + 20] * ktmp[k + 32]; sum4[k] += itmp0[k + 16] * ktmp[k]; sum4[k] += itmp1[k + 16] * ktmp[k + 12]; sum4[k] += itmp2[k + 16] * ktmp[k + 24]; sum4[k] += itmp0[k + 20] * ktmp[k + 4]; sum4[k] += itmp1[k + 20] * ktmp[k + 16]; sum4[k] += itmp2[k + 20] * ktmp[k + 28]; sum4[k] += itmp0[k + 24] * ktmp[k + 8]; sum4[k] += itmp1[k + 24] * ktmp[k + 20]; sum4[k] += itmp2[k + 24] * ktmp[k + 32]; sum5[k] += itmp0[k + 20] * ktmp[k]; sum5[k] += itmp1[k + 20] * ktmp[k + 12]; sum5[k] += itmp2[k + 20] * ktmp[k + 24]; sum5[k] += itmp0[k + 24] * ktmp[k + 4]; sum5[k] += itmp1[k + 24] * ktmp[k + 16]; sum5[k] += itmp2[k + 24] * ktmp[k + 28]; sum5[k] += itmp0[k + 28] * ktmp[k + 8]; sum5[k] += itmp1[k + 28] * ktmp[k + 20]; sum5[k] += itmp2[k + 28] * ktmp[k + 32]; sum6[k] += itmp0[k + 24] * ktmp[k]; sum6[k] += itmp1[k + 24] * ktmp[k + 12]; sum6[k] += itmp2[k + 24] * ktmp[k + 24]; sum6[k] += itmp0[k + 28] * ktmp[k + 4]; sum6[k] += itmp1[k + 28] * ktmp[k + 16]; sum6[k] += itmp2[k + 28] * ktmp[k + 28]; sum6[k] += itmp0[k + 32] * ktmp[k + 8]; sum6[k] += itmp1[k + 32] * ktmp[k + 20]; sum6[k] += itmp2[k + 32] * ktmp[k + 32]; sum7[k] += itmp0[k + 28] * ktmp[k]; sum7[k] += itmp1[k + 28] * ktmp[k + 12]; sum7[k] += itmp2[k + 28] * ktmp[k + 24]; sum7[k] += itmp0[k + 32] * ktmp[k + 4]; sum7[k] += itmp1[k + 32] * ktmp[k + 16]; sum7[k] += itmp2[k + 32] * ktmp[k + 28]; sum7[k] += itmp0[k + 36] * ktmp[k + 8]; sum7[k] += itmp1[k + 36] * ktmp[k + 20]; sum7[k] += itmp2[k + 36] * ktmp[k + 32]; } for (int k = 0; k < 4; k++) { otmp[k] = sum0[k]; otmp[k + 4] = sum1[k]; otmp[k + 8] = sum2[k]; otmp[k + 12] = sum3[k]; otmp[k + 16] = sum4[k]; otmp[k + 20] = sum5[k]; otmp[k + 24] = sum6[k]; otmp[k + 28] = sum7[k]; } #endif itmp0 += 32; itmp1 += 32; itmp2 += 32; otmp += 32; } for (; j + 3 < outw; j += 4) { #if __SSE__ __m128 _sum0 = _mm_loadu_ps(btmp); __m128 _sum1 = _mm_loadu_ps(btmp); __m128 _sum2 = _mm_loadu_ps(btmp); __m128 _sum3 = _mm_loadu_ps(btmp); __m128 _va0 = _mm_loadu_ps(itmp0); __m128 _va1 = _mm_loadu_ps(itmp0 + 4); __m128 _va2 = _mm_loadu_ps(itmp0 + 8); __m128 _va3 = _mm_loadu_ps(itmp0 + 12); __m128 _va4 = _mm_loadu_ps(itmp0 + 16); __m128 _va5 = _mm_loadu_ps(itmp0 + 20); __m128 _vb0 = _mm_loadu_ps(ktmp); __m128 _vb1 = _mm_loadu_ps(ktmp + 4); __m128 _vb2 = _mm_loadu_ps(ktmp + 8); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3); _sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1); _sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3); _sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3); _va0 = _mm_loadu_ps(itmp1); _va1 = _mm_loadu_ps(itmp1 + 4); _va2 = _mm_loadu_ps(itmp1 + 8); _va3 = _mm_loadu_ps(itmp1 + 12); _va4 = _mm_loadu_ps(itmp1 + 16); _va5 = _mm_loadu_ps(itmp1 + 20); _vb0 = _mm_loadu_ps(ktmp + 12); _vb1 = _mm_loadu_ps(ktmp + 16); _vb2 = _mm_loadu_ps(ktmp + 20); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3); _sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1); _sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3); _sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3); _va0 = _mm_loadu_ps(itmp2); _va1 = _mm_loadu_ps(itmp2 + 4); _va2 = _mm_loadu_ps(itmp2 + 8); _va3 = _mm_loadu_ps(itmp2 + 12); _va4 = _mm_loadu_ps(itmp2 + 16); _va5 = _mm_loadu_ps(itmp2 + 20); _vb0 = _mm_loadu_ps(ktmp + 24); _vb1 = _mm_loadu_ps(ktmp + 28); _vb2 = _mm_loadu_ps(ktmp + 32); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va1, _vb0), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum1 = _mm_add_ps(_mm_mul_ps(_va2, _vb1), _sum1); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _sum2 = _mm_add_ps(_mm_mul_ps(_va2, _vb0), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va3, _vb0), _sum3); _sum1 = _mm_add_ps(_mm_mul_ps(_va3, _vb2), _sum1); _sum2 = _mm_add_ps(_mm_mul_ps(_va3, _vb1), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va4, _vb1), _sum3); _sum2 = _mm_add_ps(_mm_mul_ps(_va4, _vb2), _sum2); _sum3 = _mm_add_ps(_mm_mul_ps(_va5, _vb2), _sum3); _mm_storeu_ps(otmp, _sum0); _mm_storeu_ps(otmp + 4, _sum1); _mm_storeu_ps(otmp + 8, _sum2); _mm_storeu_ps(otmp + 12, _sum3); #else float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; for (int k = 0; k < 4; k++) { sum0[k] += itmp0[k] * ktmp[k]; sum0[k] += itmp1[k] * ktmp[k + 12]; sum0[k] += itmp2[k] * ktmp[k + 24]; sum0[k] += itmp0[k + 4] * ktmp[k + 4]; sum0[k] += itmp1[k + 4] * ktmp[k + 16]; sum0[k] += itmp2[k + 4] * ktmp[k + 28]; sum0[k] += itmp0[k + 8] * ktmp[k + 8]; sum0[k] += itmp1[k + 8] * ktmp[k + 20]; sum0[k] += itmp2[k + 8] * ktmp[k + 32]; sum1[k] += itmp0[k + 4] * ktmp[k]; sum1[k] += itmp1[k + 4] * ktmp[k + 12]; sum1[k] += itmp2[k + 4] * ktmp[k + 24]; sum1[k] += itmp0[k + 8] * ktmp[k + 4]; sum1[k] += itmp1[k + 8] * ktmp[k + 16]; sum1[k] += itmp2[k + 8] * ktmp[k + 28]; sum1[k] += itmp0[k + 12] * ktmp[k + 8]; sum1[k] += itmp1[k + 12] * ktmp[k + 20]; sum1[k] += itmp2[k + 12] * ktmp[k + 32]; sum2[k] += itmp0[k + 8] * ktmp[k]; sum2[k] += itmp1[k + 8] * ktmp[k + 12]; sum2[k] += itmp2[k + 8] * ktmp[k + 24]; sum2[k] += itmp0[k + 12] * ktmp[k + 4]; sum2[k] += itmp1[k + 12] * ktmp[k + 16]; sum2[k] += itmp2[k + 12] * ktmp[k + 28]; sum2[k] += itmp0[k + 16] * ktmp[k + 8]; sum2[k] += itmp1[k + 16] * ktmp[k + 20]; sum2[k] += itmp2[k + 16] * ktmp[k + 32]; sum3[k] += itmp0[k + 12] * ktmp[k]; sum3[k] += itmp1[k + 12] * ktmp[k + 12]; sum3[k] += itmp2[k + 12] * ktmp[k + 24]; sum3[k] += itmp0[k + 16] * ktmp[k + 4]; sum3[k] += itmp1[k + 16] * ktmp[k + 16]; sum3[k] += itmp2[k + 16] * ktmp[k + 28]; sum3[k] += itmp0[k + 20] * ktmp[k + 8]; sum3[k] += itmp1[k + 20] * ktmp[k + 20]; sum3[k] += itmp2[k + 20] * ktmp[k + 32]; } for (int k = 0; k < 4; k++) { otmp[k] = sum0[k]; otmp[k + 4] = sum1[k]; otmp[k + 8] = sum2[k]; otmp[k + 12] = sum3[k]; } #endif itmp0 += 16; itmp1 += 16; itmp2 += 16; otmp += 16; } for (; j < outw; j++) { #if __SSE__ __m128 _sum0 = _mm_loadu_ps(btmp); __m128 _va0 = _mm_loadu_ps(itmp0); __m128 _va1 = _mm_loadu_ps(itmp0 + 4); __m128 _va2 = _mm_loadu_ps(itmp0 + 8); __m128 _vb0 = _mm_loadu_ps(ktmp); __m128 _vb1 = _mm_loadu_ps(ktmp + 4); __m128 _vb2 = _mm_loadu_ps(ktmp + 8); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _va0 = _mm_loadu_ps(itmp1); _va1 = _mm_loadu_ps(itmp1 + 4); _va2 = _mm_loadu_ps(itmp1 + 8); _vb0 = _mm_loadu_ps(ktmp + 12); _vb1 = _mm_loadu_ps(ktmp + 16); _vb2 = _mm_loadu_ps(ktmp + 20); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _va0 = _mm_loadu_ps(itmp2); _va1 = _mm_loadu_ps(itmp2 + 4); _va2 = _mm_loadu_ps(itmp2 + 8); _vb0 = _mm_loadu_ps(ktmp + 24); _vb1 = _mm_loadu_ps(ktmp + 28); _vb2 = _mm_loadu_ps(ktmp + 32); _sum0 = _mm_add_ps(_mm_mul_ps(_va0, _vb0), _sum0); _sum0 = _mm_add_ps(_mm_mul_ps(_va1, _vb1), _sum0); _sum0 = _mm_add_ps(_mm_mul_ps(_va2, _vb2), _sum0); _mm_storeu_ps(otmp, _sum0); #else float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; for (int k = 0; k < 4; k++) { sum0[k] += itmp0[k] * ktmp[k]; sum0[k] += itmp1[k] * ktmp[k + 12]; sum0[k] += itmp2[k] * ktmp[k + 24]; sum0[k] += itmp0[k + 4] * ktmp[k + 4]; sum0[k] += itmp1[k + 4] * ktmp[k + 16]; sum0[k] += itmp2[k + 4] * ktmp[k + 28]; sum0[k] += itmp0[k + 8] * ktmp[k + 8]; sum0[k] += itmp1[k + 8] * ktmp[k + 20]; sum0[k] += itmp2[k + 8] * ktmp[k + 32]; } for (int k = 0; k < 4; k++) { otmp[k] = sum0[k]; } #endif itmp0 += 4; itmp1 += 4; itmp2 += 4; otmp += 4; } } } { for (int i = 0; i < channel_count; i++) { float* otmp = output_tmp + i * 4 * outwh; float* tmp0 = output + i * 4 * outwh; float* tmp1 = output + i * 4 * outwh + 1 * outwh; float* tmp2 = output + i * 4 * outwh + 2 * outwh; float* tmp3 = output + i * 4 * outwh + 3 * outwh; for (int i = 0; i < outwh; i++) { tmp0[0] = otmp[0]; tmp1[0] = otmp[1]; tmp2[0] = otmp[2]; tmp3[0] = otmp[3]; otmp += 4; tmp0++; tmp1++; tmp2++; tmp3++; } } for (int i = 0; i < channel_remain; i++) { int ii = channel_count * 4 + i; float* otmp = output_tmp + channel_count * 4 * outwh; float* tmp0 = output + ii * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[i]; otmp += 4; tmp0++; } } } sys_free(output_tmp); sys_free(img_tmp); sys_free(kernel_tmp); sys_free(bias_tmp); } static void convdw3x3s2(float* output, float* img_data, float* kernel_data, float* bias_data, int inc, int inh, int inw, int outh, int outw, int num_thread) { int inwh = inw * inh; int outwh = outw * outh; int channel_count = inc >> 2; int channel_remain = inc - (channel_count << 2); // generate the image tmp float* img_tmp = (float*)sys_malloc(4 * inwh * (channel_count + 1) * sizeof(float)); float* kernel_tmp = (float*)sys_malloc(4 * 9 * (channel_count + 1) * sizeof(float)); float* bias_tmp = (float*)sys_malloc(4 * (channel_count + 1) * sizeof(float)); { for (int i = 0; i < channel_count; i++) { int ii = i * 4; float* k0 = img_data + (ii + 0) * inwh; float* k1 = img_data + (ii + 1) * inwh; float* k2 = img_data + (ii + 2) * inwh; float* k3 = img_data + (ii + 3) * inwh; float* f0 = kernel_data + (ii + 0) * 9; float* f1 = kernel_data + (ii + 1) * 9; float* f2 = kernel_data + (ii + 2) * 9; float* f3 = kernel_data + (ii + 3) * 9; float* b0 = bias_data + (ii + 0); float* b1 = bias_data + (ii + 1); float* b2 = bias_data + (ii + 2); float* b3 = bias_data + (ii + 3); float* tmp0 = img_tmp + ii * inwh; float* tmp1 = kernel_tmp + ii * 9; float* tmp2 = bias_tmp + ii; for (int j = 0; j < inwh; j++) { tmp0[0] = k0[0]; tmp0[1] = k1[0]; tmp0[2] = k2[0]; tmp0[3] = k3[0]; tmp0 += 4; k0++; k1++; k2++; k3++; } for (int j = 0; j < 9; j++) { tmp1[0] = f0[0]; tmp1[1] = f1[0]; tmp1[2] = f2[0]; tmp1[3] = f3[0]; tmp1 += 4; f0++; f1++; f2++; f3++; } if (bias_data) { tmp2[0] = b0[0]; tmp2[1] = b1[0]; tmp2[2] = b2[0]; tmp2[3] = b3[0]; } else { tmp2[0] = 0; tmp2[1] = 0; tmp2[2] = 0; tmp2[3] = 0; } } for (int i = 0; i < channel_remain; i++) { int ii = channel_count * 4 + i; float* k0 = img_data + ii * inwh; float* f0 = kernel_data + ii * 9; float* b0 = bias_data + ii; float* tmp0 = img_tmp + channel_count * 4 * inwh; float* tmp1 = kernel_tmp + channel_count * 4 * 9; float* tmp2 = bias_tmp + channel_count * 4; for (int j = 0; j < inwh; j++) { tmp0[i] = k0[0]; tmp0 += 4; k0++; } for (int j = 0; j < 9; j++) { tmp1[i] = f0[0]; tmp1 += 4; f0++; } if (bias_data) { tmp2[i] = b0[0]; } else { tmp2[i] = 0; } } } float* output_tmp = (float*)sys_malloc(outwh * 4 * (channel_count + 1) * sizeof(float)); for (int c = 0; c < channel_count + 1; c++) { float* ktmp = kernel_tmp + c * 4 * 9; float* btmp = bias_tmp + c * 4; for (int i = 0; i < outh; i++) { int j = 0; float* itmp0 = img_tmp + c * 4 * inwh + 4 * i * 2 * inw; float* itmp1 = img_tmp + c * 4 * inwh + 4 * (i * 2 + 1) * inw; float* itmp2 = img_tmp + c * 4 * inwh + 4 * (i * 2 + 2) * inw; float* otmp = output_tmp + c * 4 * outwh + 4 * i * outw; for (; j + 3 < outw; j += 4) { #if __SSE__ __m128 _sum0 = _mm_loadu_ps(btmp); __m128 _sum1 = _mm_loadu_ps(btmp); __m128 _sum2 = _mm_loadu_ps(btmp); __m128 _sum3 = _mm_loadu_ps(btmp); __m128 _va0 = _mm_loadu_ps(itmp0); __m128 _va1 = _mm_loadu_ps(itmp0 + 4); __m128 _va2 = _mm_loadu_ps(itmp0 + 8); __m128 _va3 = _mm_loadu_ps(itmp0 + 12); __m128 _va4 = _mm_loadu_ps(itmp0 + 16); __m128 _va5 = _mm_loadu_ps(itmp0 + 20); __m128 _va6 = _mm_loadu_ps(itmp0 + 24); __m128 _va7 = _mm_loadu_ps(itmp0 + 28); __m128 _va8 = _mm_loadu_ps(itmp0 + 32); __m128 _vb0 = _mm_loadu_ps(ktmp); __m128 _vb1 = _mm_loadu_ps(ktmp + 4); __m128 _vb2 = _mm_loadu_ps(ktmp + 8); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2)); _va0 = _mm_loadu_ps(itmp1); _va1 = _mm_loadu_ps(itmp1 + 4); _va2 = _mm_loadu_ps(itmp1 + 8); _va3 = _mm_loadu_ps(itmp1 + 12); _va4 = _mm_loadu_ps(itmp1 + 16); _va5 = _mm_loadu_ps(itmp1 + 20); _va6 = _mm_loadu_ps(itmp1 + 24); _va7 = _mm_loadu_ps(itmp1 + 28); _va8 = _mm_loadu_ps(itmp1 + 32); _vb0 = _mm_loadu_ps(ktmp + 12); _vb1 = _mm_loadu_ps(ktmp + 16); _vb2 = _mm_loadu_ps(ktmp + 20); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2)); _va0 = _mm_loadu_ps(itmp2); _va1 = _mm_loadu_ps(itmp2 + 4); _va2 = _mm_loadu_ps(itmp2 + 8); _va3 = _mm_loadu_ps(itmp2 + 12); _va4 = _mm_loadu_ps(itmp2 + 16); _va5 = _mm_loadu_ps(itmp2 + 20); _va6 = _mm_loadu_ps(itmp2 + 24); _va7 = _mm_loadu_ps(itmp2 + 28); _va8 = _mm_loadu_ps(itmp2 + 32); _vb0 = _mm_loadu_ps(ktmp + 24); _vb1 = _mm_loadu_ps(ktmp + 28); _vb2 = _mm_loadu_ps(ktmp + 32); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va2, _vb0)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va3, _vb1)); _sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va4, _vb2)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va4, _vb0)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va5, _vb1)); _sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va6, _vb2)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va6, _vb0)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va7, _vb1)); _sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va8, _vb2)); _mm_storeu_ps(otmp, _sum0); _mm_storeu_ps(otmp + 4, _sum1); _mm_storeu_ps(otmp + 8, _sum2); _mm_storeu_ps(otmp + 12, _sum3); #else float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum1[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum2[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; float sum3[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; for (int k = 0; k < 4; k++) { sum0[k] += itmp0[k] * ktmp[k]; sum0[k] += itmp1[k] * ktmp[k + 12]; sum0[k] += itmp2[k] * ktmp[k + 24]; sum0[k] += itmp0[k + 4] * ktmp[k + 4]; sum0[k] += itmp1[k + 4] * ktmp[k + 16]; sum0[k] += itmp2[k + 4] * ktmp[k + 28]; sum0[k] += itmp0[k + 8] * ktmp[k + 8]; sum0[k] += itmp1[k + 8] * ktmp[k + 20]; sum0[k] += itmp2[k + 8] * ktmp[k + 32]; sum1[k] += itmp0[k + 8] * ktmp[k]; sum1[k] += itmp1[k + 8] * ktmp[k + 12]; sum1[k] += itmp2[k + 8] * ktmp[k + 24]; sum1[k] += itmp0[k + 12] * ktmp[k + 4]; sum1[k] += itmp1[k + 12] * ktmp[k + 16]; sum1[k] += itmp2[k + 12] * ktmp[k + 28]; sum1[k] += itmp0[k + 16] * ktmp[k + 8]; sum1[k] += itmp1[k + 16] * ktmp[k + 20]; sum1[k] += itmp2[k + 16] * ktmp[k + 32]; sum2[k] += itmp0[k + 16] * ktmp[k]; sum2[k] += itmp1[k + 16] * ktmp[k + 12]; sum2[k] += itmp2[k + 16] * ktmp[k + 24]; sum2[k] += itmp0[k + 20] * ktmp[k + 4]; sum2[k] += itmp1[k + 20] * ktmp[k + 16]; sum2[k] += itmp2[k + 20] * ktmp[k + 28]; sum2[k] += itmp0[k + 24] * ktmp[k + 8]; sum2[k] += itmp1[k + 24] * ktmp[k + 20]; sum2[k] += itmp2[k + 24] * ktmp[k + 32]; sum3[k] += itmp0[k + 24] * ktmp[k]; sum3[k] += itmp1[k + 24] * ktmp[k + 12]; sum3[k] += itmp2[k + 24] * ktmp[k + 24]; sum3[k] += itmp0[k + 28] * ktmp[k + 4]; sum3[k] += itmp1[k + 28] * ktmp[k + 16]; sum3[k] += itmp2[k + 28] * ktmp[k + 28]; sum3[k] += itmp0[k + 32] * ktmp[k + 8]; sum3[k] += itmp1[k + 32] * ktmp[k + 20]; sum3[k] += itmp2[k + 32] * ktmp[k + 32]; } for (int k = 0; k < 4; k++) { otmp[k] = sum0[k]; otmp[k + 4] = sum1[k]; otmp[k + 8] = sum2[k]; otmp[k + 12] = sum3[k]; } #endif itmp0 += 32; itmp1 += 32; itmp2 += 32; otmp += 16; } for (; j < outw; j++) { #if __SSE__ __m128 _sum0 = _mm_loadu_ps(btmp); __m128 _va0 = _mm_loadu_ps(itmp0); __m128 _va1 = _mm_loadu_ps(itmp0 + 4); __m128 _va2 = _mm_loadu_ps(itmp0 + 8); __m128 _vb0 = _mm_loadu_ps(ktmp); __m128 _vb1 = _mm_loadu_ps(ktmp + 4); __m128 _vb2 = _mm_loadu_ps(ktmp + 8); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2)); _va0 = _mm_loadu_ps(itmp1); _va1 = _mm_loadu_ps(itmp1 + 4); _va2 = _mm_loadu_ps(itmp1 + 8); _vb0 = _mm_loadu_ps(ktmp + 12); _vb1 = _mm_loadu_ps(ktmp + 16); _vb2 = _mm_loadu_ps(ktmp + 20); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2)); _va0 = _mm_loadu_ps(itmp2); _va1 = _mm_loadu_ps(itmp2 + 4); _va2 = _mm_loadu_ps(itmp2 + 8); _vb0 = _mm_loadu_ps(ktmp + 24); _vb1 = _mm_loadu_ps(ktmp + 28); _vb2 = _mm_loadu_ps(ktmp + 32); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va1, _vb1)); _sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va2, _vb2)); _mm_storeu_ps(otmp, _sum0); #else float sum0[4] = {btmp[0], btmp[1], btmp[2], btmp[3]}; for (int k = 0; k < 4; k++) { sum0[k] += itmp0[k] * ktmp[k]; sum0[k] += itmp1[k] * ktmp[k + 12]; sum0[k] += itmp2[k] * ktmp[k + 24]; sum0[k] += itmp0[k + 4] * ktmp[k + 4]; sum0[k] += itmp1[k + 4] * ktmp[k + 16]; sum0[k] += itmp2[k + 4] * ktmp[k + 28]; sum0[k] += itmp0[k + 8] * ktmp[k + 8]; sum0[k] += itmp1[k + 8] * ktmp[k + 20]; sum0[k] += itmp2[k + 8] * ktmp[k + 32]; } for (int k = 0; k < 4; k++) { otmp[k] = sum0[k]; } #endif itmp0 += 8; itmp1 += 8; itmp2 += 8; otmp += 4; } } } { for (int i = 0; i < channel_count; i++) { float* otmp = output_tmp + i * 4 * outwh; float* tmp0 = output + i * 4 * outwh; float* tmp1 = output + i * 4 * outwh + 1 * outwh; float* tmp2 = output + i * 4 * outwh + 2 * outwh; float* tmp3 = output + i * 4 * outwh + 3 * outwh; for (int i = 0; i < outwh; i++) { tmp0[0] = otmp[0]; tmp1[0] = otmp[1]; tmp2[0] = otmp[2]; tmp3[0] = otmp[3]; otmp += 4; tmp0++; tmp1++; tmp2++; tmp3++; } } for (int i = 0; i < channel_remain; i++) { int ii = channel_count * 4 + i; float* otmp = output_tmp + channel_count * 4 * outwh; float* tmp0 = output + ii * outwh; for (int j = 0; j < outwh; j++) { tmp0[0] = otmp[i]; otmp += 4; tmp0++; } } } sys_free(output_tmp); sys_free(img_tmp); sys_free(kernel_tmp); sys_free(bias_tmp); } #else static void convdw3x3s1(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w, int out_h, int out_w, int num_thread) { int w = in_w; int h = in_h; int c_step_in = w * h; int outw = out_w; int outh = out_h; int c_step_out = outw * outh; const int group = channel; const float* kernel = _kernel; #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* out = output + g * c_step_out; float* outptr = out; float* outptr2 = outptr + outw; const float bias0 = _bias ? _bias[g] : 0.f; const float* kernel0 = kernel + g * 9; const float* img0 = input + g * c_step_in; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* r3 = img0 + w * 3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i + 1 < outh; i += 2) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; float sum2 = bias0; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr = sum; *outptr2 = sum2; r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w, int out_h, int out_w, int num_thread) { int w = in_w; int h = in_h; int c_step_in = w * h; int outw = out_w; int outh = out_h; int c_step_out = outw * outh; const int group = channel; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* out = output + g * c_step_out; float* outptr = out; const float* kernel0 = kernel + g * 9; const float bias0 = _bias ? _bias[g] : 0.f; const float* img0 = input + g * c_step_in; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } #endif int conv_dw_run(struct tensor* input_tensor, struct tensor* weight_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_priv_info* conv_info, struct conv_param* param, int num_thread, int cpu_affinity) { float* input = (float*)input_tensor->data; float* output = (float*)output_tensor->data; float* kernel = (float*)weight_tensor->data; float* biases = NULL; if (bias_tensor) biases = (float*)bias_tensor->data; int batch_number = input_tensor->dims[0]; int inc = input_tensor->dims[1]; int inh = input_tensor->dims[2]; int inw = input_tensor->dims[3]; int in_chw = inc * inh * inw; int outc = output_tensor->dims[1]; int outh = output_tensor->dims[2]; int outw = output_tensor->dims[3]; int out_hw = outh * outw; int out_chw = out_hw * outc; int ksize_h = param->kernel_h; int ksize_w = param->kernel_w; int pad_w = param->pad_w0; int pad_h = param->pad_h0; int stride_w = param->stride_w; int stride_h = param->stride_h; int dilation_w = param->dilation_w; int dilation_h = param->dilation_h; int group = param->group; int activation = param->activation; /* pading */ int inh_tmp = inh + pad_h + pad_h; int inw_tmp = inw + pad_w + pad_w; float* input_tmp = NULL; if (inh_tmp == inh && inw_tmp == inw) input_tmp = input; else { input_tmp = (float*)sys_malloc((size_t)inh_tmp * inw_tmp * group * sizeof(float)); #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* pad_in = input + g * inh * inw; float* pad_out = input_tmp + g * inh_tmp * inw_tmp; pad(pad_in, pad_out, inh, inw, inh_tmp, inw_tmp, pad_h, pad_w, 0.f); } } /* process */ for (int i = 0; i < batch_number; i++) { if (stride_h == 1) convdw3x3s1(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread); else convdw3x3s2(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread); } /* relu */ if (activation >= 0) relu(output, batch_number * out_chw, activation); if (!(inh_tmp == inh && inw_tmp == inw)) sys_free(input_tmp); return 0; }
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite-private.h" #include "magick/distribute-cache-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/policy.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/registry.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/utility.h" #include "magick/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const IndexPacket *GetVirtualIndexesFromCache(const Image *); static const PixelPacket *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t, PixelPacket *,ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,PixelPacket *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), ReadPixelCacheIndexes(CacheInfo *,NexusInfo *,ExceptionInfo *), ReadPixelCachePixels(CacheInfo *,NexusInfo *,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCacheIndexes(CacheInfo *,NexusInfo *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *,NexusInfo *,ExceptionInfo *); static PixelPacket *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *,const MapMode, const RectangleInfo *,const MagickBooleanType,NexusInfo *,ExceptionInfo *) magick_hot_spot; #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static volatile MagickBooleanType instantiate_cache = MagickFalse; static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickExport Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *restrict cache_info; char *synchronize; cache_info=(CacheInfo *) AcquireQuantumMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->channels=4; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { cache_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } cache_info->semaphore=AllocateSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AllocateSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickExport NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory( number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads, sizeof(**nexus_info)); if (nexus_info[0] == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(nexus_info[0],0,number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) number_threads; i++) { nexus_info[i]=(&nexus_info[0][i]); nexus_info[i]->signature=MagickSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % const void *AcquirePixelCachePixels(const Image *image, % MagickSizeType *length,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport const void *AcquirePixelCachePixels(const Image *image, MagickSizeType *length,ExceptionInfo *exception) { CacheInfo *restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); (void) exception; *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((const void *) NULL); *length=cache_info->length; return((const void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickExport MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AllocateSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickExport void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); LockSemaphoreInfo(cache_semaphore); instantiate_cache=MagickFalse; UnlockSemaphoreInfo(cache_semaphore); DestroySemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *restrict cache_info; MagickSizeType number_pixels; NexusInfo **restrict clip_nexus, **restrict image_nexus; register const PixelPacket *restrict r; register IndexPacket *restrict nexus_indexes, *restrict indexes; register PixelPacket *restrict p, *restrict q; register ssize_t i; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->clip_mask == (Image *) NULL) || (image->storage_class == PseudoClass)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); clip_nexus=AcquirePixelCacheNexus(1); if ((image_nexus == (NexusInfo **) NULL) || (clip_nexus == (NexusInfo **) NULL)) ThrowBinaryException(CacheError,"UnableToGetCacheNexus",image->filename); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,image_nexus[0], exception); indexes=image_nexus[0]->indexes; q=nexus_info->pixels; nexus_indexes=nexus_info->indexes; r=GetVirtualPixelsFromNexus(image->clip_mask,MaskVirtualPixelMethod, nexus_info->region.x,nexus_info->region.y,nexus_info->region.width, nexus_info->region.height,clip_nexus[0],exception); number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (i=0; i < (ssize_t) number_pixels; i++) { if ((p == (PixelPacket *) NULL) || (r == (const PixelPacket *) NULL)) break; if (GetPixelIntensity(image,r) > (QuantumRange/2)) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,GetPixelOpacity(p)); if (cache_info->active_index_channel != MagickFalse) SetPixelIndex(nexus_indexes+i,GetPixelIndex(indexes+i)); } p++; q++; r++; } clip_nexus=DestroyPixelCacheNexus(clip_nexus,1); image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (i < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickExport Cache ClonePixelCache(const Cache cache) { CacheInfo *restrict clone_info; const CacheInfo *restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); if (clone_info == (Cache) NULL) return((Cache) NULL); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickExport void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *restrict cache_info, *restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static inline void CopyPixels(PixelPacket *destination, const PixelPacket *source,const MagickSizeType number_pixels) { #if !defined(MAGICKCORE_OPENMP_SUPPORT) || (MAGICKCORE_QUANTUM_DEPTH <= 8) (void) memcpy(destination,source,(size_t) number_pixels*sizeof(*source)); #else { register MagickOffsetType i; if ((number_pixels*sizeof(*source)) < MagickMaxBufferExtent) { (void) memcpy(destination,source,(size_t) number_pixels* sizeof(*source)); return; } #pragma omp parallel for for (i=0; i < (MagickOffsetType) number_pixels; i++) destination[i]=source[i]; } #endif } static inline MagickSizeType MagickMin(const MagickSizeType x, const MagickSizeType y) { if (x < y) return(x); return(y); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *restrict clone_info,CacheInfo *restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads 2 #define cache_threads(source,destination,chunk) \ num_threads((chunk) < (16*GetMagickResourceLimit(ThreadResource)) ? 1 : \ GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \ GetMagickResourceLimit(ThreadResource) : MaxCacheThreads) MagickBooleanType status; NexusInfo **restrict cache_nexus, **restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache)) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->active_index_channel == clone_info->active_index_channel)) { /* Identical pixel cache morphology. */ CopyPixels(clone_info->pixels,cache_info->pixels,cache_info->columns* cache_info->rows); if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) (void) memcpy(clone_info->indexes,cache_info->indexes, cache_info->columns*cache_info->rows*sizeof(*cache_info->indexes)); return(MagickTrue); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); if ((cache_nexus == (NexusInfo **) NULL) || (clone_nexus == (NexusInfo **) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->pixels); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info,cache_info->rows) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length); status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) { /* Clone indexes. */ length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->indexes); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info,cache_info->rows) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length); status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache == (void *) NULL) return; image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { if (cache_info->mapped == MagickFalse) cache_info->pixels=(PixelPacket *) RelinquishAlignedMemory( cache_info->pixels); else { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(PixelPacket *) NULL; } RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(PixelPacket *) NULL; if (cache_info->mode != ReadMode) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if (cache_info->mode != ReadMode) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->indexes=(IndexPacket *) NULL; } MagickExport Cache DestroyPixelCache(Cache cache) { CacheInfo *restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickSignature); cache_info=(CacheInfo *) RelinquishMagickMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(PixelPacket *) NULL; nexus_info->pixels=(PixelPacket *) NULL; nexus_info->indexes=(IndexPacket *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickExport NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) number_threads; i++) { if (nexus_info[i]->cache != (PixelPacket *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickSignature); } nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c I n d e x e s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticIndexesFromCache() returns the indexes associated with the last % call to QueueAuthenticPixelsCache() or GetAuthenticPixelsCache(). % % The format of the GetAuthenticIndexesFromCache() method is: % % IndexPacket *GetAuthenticIndexesFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static IndexPacket *GetAuthenticIndexesFromCache(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c I n d e x Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticIndexQueue() returns the authentic black channel or the colormap % indexes associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % The format of the GetAuthenticIndexQueue() method is: % % IndexPacket *GetAuthenticIndexQueue(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport IndexPacket *GetAuthenticIndexQueue(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_authentic_indexes_from_handler != (GetAuthenticIndexesFromHandler) NULL) return(cache_info->methods.get_authentic_indexes_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % PixelPacket *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *GetAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *restrict cache_info; PixelPacket *restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (PixelPacket *) NULL) return((PixelPacket *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((PixelPacket *) NULL); if (cache_info->active_index_channel != MagickFalse) if (ReadPixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse) return((PixelPacket *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % PixelPacket *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static PixelPacket *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated with the % last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % PixelPacket *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport PixelPacket *GetAuthenticPixelQueue(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a PixelPacket array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or if the storage class is % PseduoClass, call GetAuthenticIndexQueue() after invoking % GetAuthenticPixels() to obtain the black color component or colormap indexes % (of type IndexPacket) corresponding to the region. Once the PixelPacket % (and/or IndexPacket) array has been updated, the changes must be saved back % to the underlying image using SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) return(cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception)); assert(id < (int) cache_info->number_threads); return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((PixelPacket *) NULL); assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated with the % last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *restrict image) { CacheInfo *restrict cache_info; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cpu_throttle = 0, cycles = 0, time_limit = 0; static time_t cache_timestamp = 0; status=MagickTrue; LockSemaphoreInfo(image->semaphore); if (cpu_throttle == 0) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != MagickResourceInfinity) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (time_limit == 0) { /* Set the expire time in seconds. */ time_limit=GetMagickResourceLimit(TimeResource); cache_timestamp=time((time_t *) NULL); } if ((time_limit != MagickResourceInfinity) && ((MagickSizeType) (time((time_t *) NULL)-cache_timestamp) >= time_limit)) { #if defined(ECANCELED) errno=ECANCELED; #endif ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AllocateSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status != MagickFalse) { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status != MagickFalse) { if (cache_info->reference_count == 1) cache_info->nexus_info=(NexusInfo **) NULL; destroy=MagickTrue; image->cache=clone_image.cache; } } DestroySemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ image->taint=MagickTrue; image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->type == DiskCache) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MapCache, MemoryCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetPixelCacheType(const Image *image) { return(GetImagePixelCacheType(image)); } MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *restrict cache_info; PixelPacket *restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y, pixel,exception)); pixels=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); if (pixels == (PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,PixelPacket *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); PixelPacket *restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l M a g i c k P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualMagickPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualMagickPixel() method is: % % MagickBooleanType GetOneVirtualMagickPixel(const Image image, % const ssize_t x,const ssize_t y,MagickPixelPacket *pixel, % ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualMagickPixel(const Image *image, const ssize_t x,const ssize_t y,MagickPixelPacket *pixel, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); register const IndexPacket *restrict indexes; register const PixelPacket *restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); GetMagickPixelPacket(image,pixel); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); indexes=GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id]); SetMagickPixelPacket(image,pixels,indexes,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l M e t h o d P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualMethodPixel() returns a single pixel at the specified (x,y) % location as defined by specified pixel method. The image background color % is returned if an error occurs. If you plan to modify the pixel, use % GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualMethodPixel() method is: % % MagickBooleanType GetOneVirtualMethodPixel(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,Pixelpacket *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualMethodPixel(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, virtual_pixel_method,x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelPacket method,const ssize_t x,const ssize_t y, % PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); *pixel=image->background_color; pixels=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheChannels() returns the number of pixel channels associated % with this instance of the pixel cache. % % The format of the GetPixelCacheChannels() method is: % % size_t GetPixelCacheChannels(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheChannels returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickExport size_t GetPixelCacheChannels(const Cache cache) { CacheInfo *restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->channels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the class type of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickExport ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickExport void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) ResetMagickMemory(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_indexes_from_handler=GetVirtualIndexesFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_indexes_from_handler= GetAuthenticIndexesFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated with % the last call to SetPixelCacheNexusPixels() or GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickExport MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *nexus_info) { CacheInfo *restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); (void) exception; *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=cache_info->length; return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickExport ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimize cache tile width in pixels. % % o height: the optimize cache tile height in pixels. % */ MagickExport void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *width=2048UL/sizeof(PixelPacket); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/sizeof(PixelPacket); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l I n d e x e s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexesFromCache() returns the indexes associated with the last % call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualIndexesFromCache() method is: % % IndexPacket *GetVirtualIndexesFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const IndexPacket *GetVirtualIndexesFromCache(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l I n d e x e s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexesFromNexus() returns the indexes associated with the % specified cache nexus. % % The format of the GetVirtualIndexesFromNexus() method is: % % const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap indexes. % */ MagickExport const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache, NexusInfo *nexus_info) { CacheInfo *restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->storage_class == UndefinedClass) return((IndexPacket *) NULL); return(nexus_info->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l I n d e x Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexQueue() returns the virtual black channel or the % colormap indexes associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % The format of the GetVirtualIndexQueue() method is: % % const IndexPacket *GetVirtualIndexQueue(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const IndexPacket *GetVirtualIndexQueue(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_virtual_indexes_from_handler != (GetVirtualIndexesFromHandler) NULL) return(cache_info->methods.get_virtual_indexes_from_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsFromNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelsFromNexus() method is: % % PixelPacket *GetVirtualPixelsFromNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } /* VirtualPixelModulo() computes the remainder of dividing offset by extent. It returns not only the quotient (tile the offset falls in) but also the positive remainer within that tile such that 0 <= remainder < extent. This method is essentially a ldiv() using a floored modulo division rather than the normal default truncated modulo division. */ static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; modulo.quotient=offset/(ssize_t) extent; if (offset < 0L) modulo.quotient--; modulo.remainder=offset-modulo.quotient*(ssize_t) extent; return(modulo); } MagickExport const PixelPacket *GetVirtualPixelsFromNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *restrict cache_info; IndexPacket virtual_index; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo **restrict virtual_nexus; PixelPacket *restrict pixels, virtual_pixel; RectangleInfo region; register const IndexPacket *restrict virtual_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t u, v; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->type == UndefinedCache) return((const PixelPacket *) NULL); region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, (image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ? MagickTrue : MagickFalse,nexus_info,exception); if (pixels == (PixelPacket *) NULL) return((const PixelPacket *) NULL); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const PixelPacket *) NULL); if ((cache_info->storage_class == PseudoClass) || (cache_info->colorspace == CMYKColorspace)) { status=ReadPixelCacheIndexes(cache_info,nexus_info,exception); if (status == MagickFalse) return((const PixelPacket *) NULL); } return(pixels); } /* Pixel request is outside cache extents. */ q=pixels; indexes=nexus_info->indexes; virtual_nexus=AcquirePixelCacheNexus(1); if (virtual_nexus == (NexusInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "UnableToGetCacheNexus","`%s'",image->filename); return((const PixelPacket *) NULL); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { SetPixelRed(&virtual_pixel,0); SetPixelGreen(&virtual_pixel,0); SetPixelBlue(&virtual_pixel,0); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } case GrayVirtualPixelMethod: { SetPixelRed(&virtual_pixel,QuantumRange/2); SetPixelGreen(&virtual_pixel,QuantumRange/2); SetPixelBlue(&virtual_pixel,QuantumRange/2); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } case TransparentVirtualPixelMethod: { SetPixelRed(&virtual_pixel,0); SetPixelGreen(&virtual_pixel,0); SetPixelBlue(&virtual_pixel,0); SetPixelOpacity(&virtual_pixel,TransparentOpacity); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { SetPixelRed(&virtual_pixel,QuantumRange); SetPixelGreen(&virtual_pixel,QuantumRange); SetPixelBlue(&virtual_pixel,QuantumRange); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } default: { virtual_pixel=image->background_color; break; } } virtual_index=0; for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case ConstantVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } } if (p == (const PixelPacket *) NULL) break; *q++=(*p); if ((indexes != (IndexPacket *) NULL) && (virtual_indexes != (const IndexPacket *) NULL)) *indexes++=(*virtual_indexes); continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,*virtual_nexus,exception); if (p == (const PixelPacket *) NULL) break; virtual_indexes=GetVirtualIndexesFromNexus(cache_info,*virtual_nexus); (void) memcpy(q,p,(size_t) length*sizeof(*p)); q+=length; if ((indexes != (IndexPacket *) NULL) && (virtual_indexes != (const IndexPacket *) NULL)) { (void) memcpy(indexes,virtual_indexes,(size_t) length* sizeof(*virtual_indexes)); indexes+=length; } } } virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const PixelPacket *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const PixelPacket *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated with the % last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const PixelPacket *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const PixelPacket *GetVirtualPixelQueue(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to access % the black color component or to obtain the colormap indexes (of type % IndexPacket) corresponding to the region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const PixelPacket *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const PixelPacket *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated with the last call % to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % PixelPacket *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const PixelPacket *GetVirtualPixelsCache(const Image *image) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const IndexPacket *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickExport const PixelPacket *GetVirtualPixelsNexus(const Cache cache, NexusInfo *nexus_info) { CacheInfo *restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->storage_class == UndefinedClass) return((PixelPacket *) NULL); return((const PixelPacket *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the image mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline void MagickPixelCompositeMask(const MagickPixelPacket *p, const MagickRealType alpha,const MagickPixelPacket *q, const MagickRealType beta,MagickPixelPacket *composite) { double gamma; if (alpha == TransparentOpacity) { *composite=(*q); return; } gamma=1.0-QuantumScale*QuantumScale*alpha*beta; gamma=PerceptibleReciprocal(gamma); composite->red=gamma*MagickOver_(p->red,alpha,q->red,beta); composite->green=gamma*MagickOver_(p->green,alpha,q->green,beta); composite->blue=gamma*MagickOver_(p->blue,alpha,q->blue,beta); if ((p->colorspace == CMYKColorspace) && (q->colorspace == CMYKColorspace)) composite->index=gamma*MagickOver_(p->index,alpha,q->index,beta); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *restrict cache_info; MagickPixelPacket alpha, beta; MagickSizeType number_pixels; NexusInfo **restrict clip_nexus, **restrict image_nexus; register const PixelPacket *restrict r; register IndexPacket *restrict nexus_indexes, *restrict indexes; register PixelPacket *restrict p, *restrict q; register ssize_t i; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->mask == (Image *) NULL) || (image->storage_class == PseudoClass)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); clip_nexus=AcquirePixelCacheNexus(1); if ((image_nexus == (NexusInfo **) NULL) || (clip_nexus == (NexusInfo **) NULL)) ThrowBinaryException(CacheError,"UnableToGetCacheNexus",image->filename); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x, nexus_info->region.y,nexus_info->region.width,nexus_info->region.height, image_nexus[0],exception); indexes=image_nexus[0]->indexes; q=nexus_info->pixels; nexus_indexes=nexus_info->indexes; r=GetVirtualPixelsFromNexus(image->mask,MaskVirtualPixelMethod, nexus_info->region.x,nexus_info->region.y,nexus_info->region.width, nexus_info->region.height,clip_nexus[0],&image->exception); GetMagickPixelPacket(image,&alpha); GetMagickPixelPacket(image,&beta); number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (i=0; i < (ssize_t) number_pixels; i++) { if ((p == (PixelPacket *) NULL) || (r == (const PixelPacket *) NULL)) break; SetMagickPixelPacket(image,p,indexes+i,&alpha); SetMagickPixelPacket(image,q,nexus_indexes+i,&beta); MagickPixelCompositeMask(&beta,GetPixelIntensity(image,r),&alpha, alpha.opacity,&beta); SetPixelRed(q,ClampToQuantum(beta.red)); SetPixelGreen(q,ClampToQuantum(beta.green)); SetPixelBlue(q,ClampToQuantum(beta.blue)); SetPixelOpacity(q,ClampToQuantum(beta.opacity)); if (cache_info->active_index_channel != MagickFalse) SetPixelIndex(nexus_indexes+i,GetPixelIndex(indexes+i)); p++; q++; r++; } clip_nexus=DestroyPixelCacheNexus(clip_nexus,1); image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (i < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % colormap indexes, and memory mapping the cache if it is disk based. The % cache nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static inline void AllocatePixelCachePixels(CacheInfo *cache_info) { cache_info->mapped=MagickFalse; cache_info->pixels=(PixelPacket *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->mapped=MagickTrue; cache_info->pixels=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if defined(SIGBUS) static void CacheSignalHandler(int status) { ThrowFatalException(CacheFatalError,"UnableToExtendPixelCache"); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if (cache_info->file != -1) return(MagickTrue); /* cache already open */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); cache_info->file=file; cache_info->mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MaxTextExtent], message[MaxTextExtent]; (void) FormatMagickSize(length,MagickFalse,format); (void) FormatLocaleString(message,MaxTextExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) return(MagickTrue); extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) { int status; status=posix_fallocate(cache_info->file,offset+1,extent-offset); if (status != 0) return(MagickFalse); } #endif #if defined(SIGBUS) (void) signal(SIGBUS,CacheSignalHandler); #endif return(count != (MagickOffsetType) 1 ? MagickFalse : MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *restrict cache_info, source_info; char format[MaxTextExtent], message[MaxTextExtent]; const char *type; MagickSizeType length, number_pixels; MagickStatusType status; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MaxTextExtent,"%s[%.20g]", image->filename,(double) GetImageIndexInList(image)); cache_info->mode=mode; cache_info->rows=image->rows; cache_info->columns=image->columns; cache_info->channels=image->channels; cache_info->active_index_channel=((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; cache_info->pixels=(PixelPacket *) NULL; cache_info->indexes=(IndexPacket *) NULL; cache_info->length=0; return(MagickTrue); } number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) packet_size+=sizeof(IndexPacket); length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if (cache_info->columns != columns) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { AllocatePixelCachePixels(cache_info); if (cache_info->pixels == (PixelPacket *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ cache_info->colorspace=image->colorspace; cache_info->type=MemoryCache; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status&=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s %s, %.20gx%.20g %s)",cache_info->filename, cache_info->mapped != MagickFalse ? "Anonymous" : "Heap", type,(double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } cache_info->storage_class=image->storage_class; return(MagickTrue); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MaxTextExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse, format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,GetDistributeCacheFile( (DistributeCacheInfo *) cache_info->server_info),type, (double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->pixels=source_info.pixels; cache_info->type=DiskCache; } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(MapResource,cache_info->length); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *restrict cache_info, *restrict clone_info; Image clone_image; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MaxTextExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(MagickTrue); } if ((cache_info->mode != ReadMode) && (cache_info->type != MemoryCache) && (cache_info->reference_count == 1)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->mode != ReadMode) && (cache_info->type != MemoryCache) && (cache_info->reference_count == 1)) { int status; /* Usurp existing persistent pixel cache. */ status=rename_utf8(cache_info->cache_filename,filename); if (status == 0) { (void) CopyMagickString(cache_info->cache_filename,filename, MaxTextExtent); *offset+=cache_info->length+page_size-(cache_info->length % page_size); UnlockSemaphoreInfo(cache_info->semaphore); cache_info=(CacheInfo *) ReferencePixelCache(cache_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "Usurp resident persistent cache"); return(MagickTrue); } } UnlockSemaphoreInfo(cache_info->semaphore); } /* Clone persistent pixel cache. */ clone_image=(*image); clone_info=(CacheInfo *) clone_image.cache; image->cache=ClonePixelCache(cache_info); cache_info=(CacheInfo *) ReferencePixelCache(image->cache); (void) CopyMagickString(cache_info->cache_filename,filename,MaxTextExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); cache_info=(CacheInfo *) image->cache; status=OpenPixelCache(image,IOMode,exception); if (status != MagickFalse) status=ClonePixelCacheRepository(cache_info,clone_info,&image->exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % PixelPacket *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *QueueAuthenticPixel(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info, ExceptionInfo *exception) { return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,clone,nexus_info, exception)); } MagickExport PixelPacket *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; PixelPacket *restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((PixelPacket *) NULL); assert(cache_info->signature == MagickSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((PixelPacket *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((PixelPacket *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((PixelPacket *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region, (image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ? MagickTrue : MagickFalse,nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a PixelPacket array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to obtain % the black color component or the colormap indexes (of type IndexPacket) % corresponding to the region. Once the PixelPacket (and/or IndexPacket) % array has been updated, the changes must be saved back to the underlying % image using SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) return(cache_info->methods.queue_authentic_pixels_handler(image,x,y,columns, rows,exception)); assert(id < (int) cache_info->number_threads); return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheIndexes() reads colormap indexes from the specified region of % the pixel cache. % % The format of the ReadPixelCacheIndexes() method is: % % MagickBooleanType ReadPixelCacheIndexes(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the colormap indexes. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i, (MagickSizeType) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheIndexes(CacheInfo *restrict cache_info, NexusInfo *restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register IndexPacket *restrict q; register ssize_t y; size_t rows; if (cache_info->active_index_channel == MagickFalse) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket); rows=nexus_info->region.height; extent=length*rows; q=nexus_info->indexes; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register IndexPacket *restrict p; /* Read indexes from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->indexes+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->columns; q+=nexus_info->region.width; } break; } case DiskCache: { /* Read indexes from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* sizeof(PixelPacket)+offset*sizeof(*q),length,(unsigned char *) q); if ((MagickSizeType) count < length) break; offset+=cache_info->columns; q+=nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read indexes from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheIndexes((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels(CacheInfo *restrict cache_info, NexusInfo *restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register PixelPacket *restrict q; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket); rows=nexus_info->region.height; extent=length*rows; q=nexus_info->pixels; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register PixelPacket *restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->columns; q+=nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* sizeof(*q),length,(unsigned char *) q); if ((MagickSizeType) count < length) break; offset+=cache_info->columns; q+=nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickExport Cache ReferencePixelCache(Cache cache) { CacheInfo *restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickExport void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_indexes_from_handler != (GetVirtualIndexesFromHandler) NULL) cache_info->methods.get_virtual_indexes_from_handler= cache_methods->get_virtual_indexes_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_indexes_from_handler != (GetAuthenticIndexesFromHandler) NULL) cache_info->methods.get_authentic_indexes_from_handler= cache_methods->get_authentic_indexes_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % PixelPacket SetPixelCacheNexusPixels(const CacheInfo *cache_info, % const MapMode mode,const RectangleInfo *region, % const MagickBooleanType buffered,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o region: A pointer to the RectangleInfo structure that defines the % region of this particular cache nexus. % % o buffered: pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *restrict cache_info,NexusInfo *nexus_info, ExceptionInfo *exception) { if (nexus_info->length != (MagickSizeType) ((size_t) nexus_info->length)) return(MagickFalse); nexus_info->mapped=MagickFalse; nexus_info->cache=(PixelPacket *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) nexus_info->length)); if (nexus_info->cache == (PixelPacket *) NULL) { nexus_info->mapped=MagickTrue; nexus_info->cache=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) nexus_info->length); } if (nexus_info->cache == (PixelPacket *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } return(MagickTrue); } static inline MagickBooleanType IsAuthenticPixelCache( const CacheInfo *restrict cache_info,const NexusInfo *restrict nexus_info) { MagickBooleanType status; MagickOffsetType offset; /* Does nexus pixels point directly to in-core cache pixels or is it buffered? */ if (cache_info->type == PingCache) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; status=nexus_info->pixels == (cache_info->pixels+offset) ? MagickTrue : MagickFalse; return(status); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { magick_unreferenced(nexus_info); magick_unreferenced(mode); if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels,0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels,1,1); } static PixelPacket *SetPixelCacheNexusPixels(const CacheInfo *cache_info, const MapMode mode,const RectangleInfo *region, const MagickBooleanType buffered,NexusInfo *nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickSignature); if (cache_info->type == UndefinedCache) return((PixelPacket *) NULL); nexus_info->region=(*region); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { ssize_t x, y; x=nexus_info->region.x+(ssize_t) nexus_info->region.width-1; y=nexus_info->region.y+(ssize_t) nexus_info->region.height-1; if (((nexus_info->region.x >= 0) && (x < (ssize_t) cache_info->columns) && (nexus_info->region.y >= 0) && (y < (ssize_t) cache_info->rows)) && ((nexus_info->region.height == 1UL) || ((nexus_info->region.x == 0) && ((nexus_info->region.width == cache_info->columns) || ((nexus_info->region.width % cache_info->columns) == 0))))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; nexus_info->pixels=cache_info->pixels+offset; nexus_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) nexus_info->indexes=cache_info->indexes+offset; PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsAuthenticPixelCache(cache_info, nexus_info); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; length=number_pixels*sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) length+=number_pixels*sizeof(IndexPacket); if (nexus_info->cache == (PixelPacket *) NULL) { nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((PixelPacket *) NULL); } } else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((PixelPacket *) NULL); } } nexus_info->pixels=nexus_info->cache; nexus_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) nexus_info->indexes=(IndexPacket *) (nexus_info->pixels+number_pixels); PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsAuthenticPixelCache(cache_info, nexus_info); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image, % const VirtualPixelMethod virtual_pixel_method) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image, const Quantum opacity) { CacheInfo *restrict cache_info; CacheView *restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); image->matte=MagickTrue; status=MagickTrue; image_view=AcquireVirtualCacheView(image,&image->exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, &image->exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { q->opacity=opacity; q++; } status=SyncCacheViewAuthenticPixels(image_view,&image->exception); } image_view=DestroyCacheView(image_view); return(status); } MagickExport VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image, const VirtualPixelMethod virtual_pixel_method) { CacheInfo *restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.opacity != OpaqueOpacity) && (image->matte == MagickFalse)) (void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity); if ((IsPixelGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace((Image *) image,sRGBColorspace); break; } case TransparentVirtualPixelMethod: { if (image->matte == MagickFalse) (void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity); break; } default: break; } return(method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *restrict nexus_info,ExceptionInfo *exception) { CacheInfo *restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if ((image->storage_class == DirectClass) && (image->clip_mask != (Image *) NULL) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if ((image->storage_class == DirectClass) && (image->mask != (Image *) NULL) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); assert(cache_info->signature == MagickSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->active_index_channel != MagickFalse) && (WritePixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) return(cache_info->methods.sync_authentic_pixels_handler(image,exception)); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheIndexes() writes the colormap indexes to the specified % region of the pixel cache. % % The format of the WritePixelCacheIndexes() method is: % % MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the colormap indexes. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info, NexusInfo *restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const IndexPacket *restrict p; register ssize_t y; size_t rows; if (cache_info->active_index_channel == MagickFalse) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket); rows=nexus_info->region.height; extent=(MagickSizeType) length*rows; p=nexus_info->indexes; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register IndexPacket *restrict q; /* Write indexes to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->indexes+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width; q+=cache_info->columns; } break; } case DiskCache: { /* Write indexes to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* sizeof(PixelPacket)+offset*sizeof(*p),length,(const unsigned char *) p); if ((MagickSizeType) count < length) break; p+=nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write indexes to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheIndexes((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, NexusInfo *restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const PixelPacket *restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket); rows=nexus_info->region.height; extent=length*rows; p=nexus_info->pixels; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register PixelPacket *restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width; q+=cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* sizeof(*p),length,(const unsigned char *) p); if ((MagickSizeType) count < length) break; p+=nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
mpush2.c
/* C Library for Skeleton 2D Electrostatic OpenMP PIC Code */ /* written by Viktor K. Decyk, UCLA */ #include <stdlib.h> #include <stdio.h> #include <complex.h> #include <math.h> #include "mpush2.h" /*--------------------------------------------------------------------*/ double ranorm() { /* this program calculates a random number y from a gaussian distribution with zero mean and unit variance, according to the method of mueller and box: y(k) = (-2*ln(x(k)))**1/2*sin(2*pi*x(k+1)) y(k+1) = (-2*ln(x(k)))**1/2*cos(2*pi*x(k+1)), where x is a random number uniformly distributed on (0,1). written for the ibm by viktor k. decyk, ucla local data */ static int r1 = 885098780, r2 = 1824280461; static int r4 = 1396483093, r5 = 55318673; static int iflg = 0; static double h1l = 65531.0, h1u = 32767.0, h2l = 65525.0; static double r0 = 0.0; int isc, i1; double ranorm, r3, asc, bsc, temp; if (iflg==1) { ranorm = r0; r0 = 0.0; iflg = 0; return ranorm; } isc = 65536; asc = (double) isc; bsc = asc*asc; i1 = r1 - (r1/isc)*isc; r3 = h1l*(double) r1 + asc*h1u*(double) i1; i1 = r3/bsc; r3 -= ((double) i1)*bsc; bsc = 0.5*bsc; i1 = r2/isc; isc = r2 - i1*isc; r0 = h1l*(double) r2 + asc*h1u*(double) isc; asc = 1.0/bsc; isc = r0*asc; r2 = r0 - ((double) isc)*bsc; r3 += (double) isc + 2.0*h1u*(double) i1; isc = r3*asc; r1 = r3 - ((double) isc)*bsc; temp = sqrt(-2.0*log((((double) r1) + ((double) r2)*asc)*asc)); isc = 65536; asc = (double) isc; bsc = asc*asc; i1 = r4 - (r4/isc)*isc; r3 = h2l*(double) r4 + asc*h1u*(double) i1; i1 = r3/bsc; r3 -= ((double) i1)*bsc; bsc = 0.5*bsc; i1 = r5/isc; isc = r5 - i1*isc; r0 = h2l*(double) r5 + asc*h1u*(double) isc; asc = 1.0/bsc; isc = r0*asc; r5 = r0 - ((double) isc)*bsc; r3 += (double) isc + 2.0*h1u*(double) i1; isc = r3*asc; r4 = r3 - ((double) isc)*bsc; r0 = 6.28318530717959*((((double) r4) + ((double) r5)*asc)*asc); ranorm = temp*sin(r0); r0 = temp*cos(r0); iflg = 1; return ranorm; } /*--------------------------------------------------------------------*/ void cdistr2(float part[], float vtx, float vty, float vdx, float vdy, int npx, int npy, int idimp, int nop, int nx, int ny, int ipbc) { /* for 2d code, this subroutine calculates initial particle co-ordinates and velocities with uniform density and maxwellian velocity with drift part[n][0] = position x of particle n part[n][1] = position y of particle n part[n][2] = velocity vx of particle n part[n][3] = velocity vy of particle n vtx/vty = thermal velocity of electrons in x/y direction vdx/vdy = drift velocity of beam electrons in x/y direction npx/npy = initial number of particles distributed in x/y direction idimp = size of phase space = 4 nop = number of particles nx/ny = system length in x/y direction ipbc = particle boundary condition = (0,1,2,3) = (none,2d periodic,2d reflecting,mixed reflecting/periodic) ranorm = gaussian random number with zero mean and unit variance local data */ int j, k, k1, npxy; float edgelx, edgely, at1, at2, at3, sum1, sum2; double dsum1, dsum2; npxy = npx*npy; /* set boundary values */ edgelx = 0.0; edgely = 0.0; at1 = (float) nx/(float) npx; at2 = (float) ny/(float) npy; if (ipbc==2) { edgelx = 1.0; edgely = 1.0; at1 = (float) (nx-2)/(float) npx; at2 = (float) (ny-2)/(float) npy; } else if (ipbc==3) { edgelx = 1.0; at1 = (float) (nx-2)/(float) npx; } /* uniform density profile */ for (k = 0; k < npy; k++) { k1 = idimp*npx*k; at3 = edgely + at2*(((float) k) + 0.5); for (j = 0; j < npx; j++) { part[idimp*j+k1] = edgelx + at1*(((float) j) + 0.5); part[1+idimp*j+k1] = at3; } } /* maxwellian velocity distribution */ for (j = 0; j < npxy; j++) { part[2+idimp*j] = vtx*ranorm(); part[3+idimp*j] = vty*ranorm(); } /* add correct drift */ dsum1 = 0.0; dsum2 = 0.0; for (j = 0; j < npxy; j++) { dsum1 += part[2+idimp*j]; dsum2 += part[3+idimp*j]; } sum1 = dsum1; sum2 = dsum2; at1 = 1.0/(float) npxy; sum1 = at1*sum1 - vdx; sum2 = at1*sum2 - vdy; for (j = 0; j < npxy; j++) { part[2+idimp*j] -= sum1; part[3+idimp*j] -= sum2; } return; } /*--------------------------------------------------------------------*/ void cdblkp2l(float part[], int kpic[], int *nppmx, int idimp, int nop, int mx, int my, int mx1, int mxy1, int *irc) { /* this subroutine finds the maximum number of particles in each tile of mx, my to calculate size of segmented particle array ppart linear interpolation part = input particle array part[n][0] = position x of particle n part[n][1] = position y of particle n kpic = output number of particles per tile nppmx = return maximum number of particles in tile idimp = size of phase space = 4 nop = number of particles mx/my = number of grids in sorting cell in x and y mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int j, k, n, m, isum, ist, npx, ierr; ierr = 0; /* clear counter array */ for (k = 0; k < mxy1; k++) { kpic[k] = 0; } /* find how many particles in each tile */ for (j = 0; j < nop; j++) { n = part[idimp*j]; m = part[1+idimp*j]; n = n/mx; m = m/my; m = n + mx1*m; if (m < mxy1) { kpic[m] += 1; } else { ierr = ierr > (m - mxy1 + 1) ? ierr : (m - mxy1 + 1); } } /* find maximum */ isum = 0; npx = 0; for (k = 0; k < mxy1; k++) { ist = kpic[k]; npx = npx > ist ? npx : ist; isum += ist; } *nppmx = npx; /* check for errors */ if (ierr > 0) { *irc = ierr; } else if (isum != nop) { *irc = -1; } return; } /*--------------------------------------------------------------------*/ void cppmovin2l(float part[], float ppart[], int kpic[], int nppmx, int idimp, int nop, int mx, int my, int mx1, int mxy1, int *irc) { /* this subroutine sorts particles by x,y grid in tiles of mx, my and copies to segmented array ppart linear interpolation input: all except ppart, kpic, output: ppart, kpic part/ppart = input/output particle arrays part[n][0] = position x of particle n in partition part[n][1] = position y of particle n in partition ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = velocity vx of particle n in tile m ppart[m][n][3] = velocity vy of particle n in tile m kpic = output number of particles per tile nppmx = maximum number of particles in tile idimp = size of phase space = 4 nop = number of particles mx/my = number of grids in sorting cell in x and y mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int i, j, k, n, m, ip, ierr; ierr = 0; /* clear counter array */ for (k = 0; k < mxy1; k++) { kpic[k] = 0; } /* find addresses of particles at each tile and reorder particles */ for (j = 0; j < nop; j++) { n = part[idimp*j]; m = part[1+idimp*j]; n = n/mx; m = m/my; m = n + mx1*m; ip = kpic[m]; if (ip < nppmx) { for (i = 0; i < idimp; i++) { ppart[i+idimp*(ip+nppmx*m)] = part[i+idimp*j]; } } else { ierr = ierr > ip-nppmx+1 ? ierr : ip-nppmx+1; } kpic[m] = ip + 1; } if (ierr > 0) *irc = ierr; return; } /*--------------------------------------------------------------------*/ void cppcheck2l(float ppart[], int kpic[], int idimp, int nppmx, int nx, int ny, int mx, int my, int mx1, int my1, int *irc) { /* this subroutine performs a sanity check to make sure particles sorted by x,y grid in tiles of mx, my, are all within bounds. tiles are assumed to be arranged in 2D linear memory input: all except irc output: irc ppart[k][n][0] = position x of particle n in tile k ppart[k][n][1] = position y of particle n in tile k kpic[k] = number of reordered output particles in tile k idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 irc = particle error, returned only if error occurs, when irc > 0 local data */ int mxy1, noff, moff, npp, j, k, ist, nn, mm; float edgelx, edgely, edgerx, edgery, dx, dy; mxy1 = mx1*my1; /* loop over tiles */ #pragma omp parallel for \ private(j,k,noff,moff,npp,nn,mm,ist,edgelx,edgely,edgerx,edgery,dx,dy) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[k]; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; /* loop over particles in tile */ for (j = 0; j < npp; j++) { dx = ppart[idimp*(j+nppmx*k)]; dy = ppart[1+idimp*(j+nppmx*k)]; /* find particles going out of bounds */ ist = 0; if (dx < edgelx) ist = 1; if (dx >= edgerx) ist = 2; if (dy < edgely) ist += 3; if (dy >= edgery) ist += 6; if (ist > 0) *irc = k + 1; } } return; } /*--------------------------------------------------------------------*/ void cgppush2l(float ppart[], float fxy[], int kpic[], float qbm, float dt, float *ek, int idimp, int nppmx, int nx, int ny, int mx, int my, int nxv, int nyv, int mx1, int mxy1, int ipbc) { /* for 2d code, this subroutine updates particle co-ordinates and velocities using leap-frog scheme in time and first-order linear interpolation in space, with various boundary conditions. OpenMP version using guard cells data read in tiles particles stored segmented array 44 flops/particle, 12 loads, 4 stores input: all, output: ppart, ek equations used are: vx(t+dt/2) = vx(t-dt/2) + (q/m)*fx(x(t),y(t))*dt, vy(t+dt/2) = vy(t-dt/2) + (q/m)*fy(x(t),y(t))*dt, where q/m is charge/mass, and x(t+dt) = x(t) + vx(t+dt/2)*dt, y(t+dt) = y(t) + vy(t+dt/2)*dt fx(x(t),y(t)) and fy(x(t),y(t)) are approximated by interpolation from the nearest grid points: fx(x,y) = (1-dy)*((1-dx)*fx(n,m)+dx*fx(n+1,m)) + dy*((1-dx)*fx(n,m+1) + dx*fx(n+1,m+1)) fy(x,y) = (1-dy)*((1-dx)*fy(n,m)+dx*fy(n+1,m)) + dy*((1-dx)*fy(n,m+1) + dx*fy(n+1,m+1)) where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = velocity vx of particle n in tile m ppart[m][n][3] = velocity vy of particle n in tile m fxy[k][j][0] = x component of force/charge at grid (j,k) fxy[k][j][1] = y component of force/charge at grid (j,k) that is, convolution of electric field over particle shape kpic = number of particles per tile qbm = particle charge/mass dt = time interval between successive calculations kinetic energy/mass at time t is also calculated, using ek = .125*sum((vx(t+dt/2)+vx(t-dt/2))**2+(vy(t+dt/2)+vy(t-dt/2))**2) idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y nxv = first dimension of field arrays, must be >= nx+1 nyv = second dimension of field arrays, must be >= ny+1 mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 ipbc = particle boundary condition = (0,1,2,3) = (none,2d periodic,2d reflecting,mixed reflecting/periodic) local data */ #define MXV 33 #define MYV 33 int noff, moff, npoff, npp; int i, j, k, nn, mm, mxv; float qtm, edgelx, edgely, edgerx, edgery, dxp, dyp, amx, amy; float x, y, dx, dy, vx, vy; float sfxy[2*MXV*MYV]; /* float sfxy[2*(mx+1)*(my+1)]; */ double sum1, sum2; /* mxv = MXV; */ mxv = mx+1; qtm = qbm*dt; sum2 = 0.0; /* set boundary values */ edgelx = 0.0f; edgely = 0.0f; edgerx = (float) nx; edgery = (float) ny; if (ipbc==2) { edgelx = 1.0f; edgely = 1.0f; edgerx = (float) (nx-1); edgery = (float) (ny-1); } else if (ipbc==3) { edgelx = 1.0f; edgerx = (float) (nx-1); } /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,noff,moff,npp,npoff,nn,mm,x,y,dxp,dyp,amx,amy,dx,dy, \ vx,vy,sum1,sfxy) \ reduction(+:sum2) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[k]; npoff = nppmx*k; /* load local fields from global array */ nn = (mx < nx-noff ? mx : nx-noff) + 1; mm = (my < ny-moff ? my : ny-moff) + 1; for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sfxy[2*(i+mxv*j)] = fxy[2*(i+noff+nxv*(j+moff))]; sfxy[1+2*(i+mxv*j)] = fxy[1+2*(i+noff+nxv*(j+moff))]; } } sum1 = 0.0; /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; nn = x; mm = y; dxp = x - (float) nn; dyp = y - (float) mm; nn = 2*(nn - noff) + 2*mxv*(mm - moff); amx = 1.0f - dxp; amy = 1.0f - dyp; /* find acceleration */ dx = amx*sfxy[nn]; dy = amx*sfxy[nn+1]; dx = amy*(dxp*sfxy[nn+2] + dx); dy = amy*(dxp*sfxy[nn+3] + dy); nn += 2*mxv; vx = amx*sfxy[nn]; vy = amx*sfxy[nn+1]; dx += dyp*(dxp*sfxy[nn+2] + vx); dy += dyp*(dxp*sfxy[nn+3] + vy); /* new velocity */ vx = ppart[2+idimp*(j+npoff)]; vy = ppart[3+idimp*(j+npoff)]; dx = vx + qtm*dx; dy = vy + qtm*dy; /* average kinetic energy */ vx += dx; vy += dy; sum1 += vx*vx + vy*vy; ppart[2+idimp*(j+npoff)] = dx; ppart[3+idimp*(j+npoff)] = dy; /* new position */ dx = x + dx*dt; dy = y + dy*dt; /* reflecting boundary conditions */ if (ipbc==2) { if ((dx < edgelx) || (dx >= edgerx)) { dx = ppart[idimp*(j+npoff)]; ppart[2+idimp*(j+npoff)] = -ppart[2+idimp*(j+npoff)]; } if ((dy < edgely) || (dy >= edgery)) { dy = ppart[1+idimp*(j+npoff)]; ppart[3+idimp*(j+npoff)] = -ppart[3+idimp*(j+npoff)]; } } /* mixed reflecting/periodic boundary conditions */ else if (ipbc==3) { if ((dx < edgelx) || (dx >= edgerx)) { dx = ppart[idimp*(j+npoff)]; ppart[2+idimp*(j+npoff)] = -ppart[2+idimp*(j+npoff)]; } } /* set new position */ ppart[idimp*(j+npoff)] = dx; ppart[1+idimp*(j+npoff)] = dy; } sum2 += sum1; } /* normalize kinetic energy */ *ek += 0.125f*sum2; return; #undef MXV #undef MYV } /*--------------------------------------------------------------------*/ void cgppushf2l(float ppart[], float fxy[], int kpic[], int ncl[], int ihole[], float qbm, float dt, float *ek, int idimp, int nppmx, int nx, int ny, int mx, int my, int nxv, int nyv, int mx1, int mxy1, int ntmax, int *irc) { /* for 2d code, this subroutine updates particle co-ordinates and velocities using leap-frog scheme in time and first-order linear interpolation in space, with periodic boundary conditions. also determines list of particles which are leaving this tile OpenMP version using guard cells data read in tiles particles stored segmented array 44 flops/particle, 12 loads, 4 stores input: all except ncl, ihole, irc, output: ppart, ncl, ihole, ek, irc equations used are: vx(t+dt/2) = vx(t-dt/2) + (q/m)*fx(x(t),y(t))*dt, vy(t+dt/2) = vy(t-dt/2) + (q/m)*fy(x(t),y(t))*dt, where q/m is charge/mass, and x(t+dt) = x(t) + vx(t+dt/2)*dt, y(t+dt) = y(t) + vy(t+dt/2)*dt fx(x(t),y(t)) and fy(x(t),y(t)) are approximated by interpolation from the nearest grid points: fx(x,y) = (1-dy)*((1-dx)*fx(n,m)+dx*fx(n+1,m)) + dy*((1-dx)*fx(n,m+1) + dx*fx(n+1,m+1)) fy(x,y) = (1-dy)*((1-dx)*fy(n,m)+dx*fy(n+1,m)) + dy*((1-dx)*fy(n,m+1) + dx*fy(n+1,m+1)) where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = velocity vx of particle n in tile m ppart[m][n][3] = velocity vy of particle n in tile m fxy[k][j][0] = x component of force/charge at grid (j,k) fxy[k][j][1] = y component of force/charge at grid (j,k) that is, convolution of electric field over particle shape kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = destination of particle leaving hole ihole[k][0][0] = ih, number of holes left (error, if negative) qbm = particle charge/mass dt = time interval between successive calculations kinetic energy/mass at time t is also calculated, using ek = .125*sum((vx(t+dt/2)+vx(t-dt/2))**2+(vy(t+dt/2)+vy(t-dt/2))**2) idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y nxv = first dimension of field arrays, must be >= nx+1 nyv = second dimension of field arrays, must be >= ny+1 mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 optimized version local data */ #define MXV 33 #define MYV 33 int noff, moff, npoff, npp; int i, j, k, ih, nh, nn, mm, mxv; float qtm, dxp, dyp, amx, amy; float x, y, dx, dy, vx, vy; float anx, any, edgelx, edgely, edgerx, edgery; float sfxy[2*MXV*MYV]; /* float sfxy[2*(mx+1)*(my+1)]; */ double sum1, sum2; mxv = mx + 1; qtm = qbm*dt; anx = (float) nx; any = (float) ny; sum2 = 0.0; /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,noff,moff,npp,npoff,nn,mm,ih,nh,x,y,dxp,dyp,amx,amy, \ dx,dy,vx,vy,edgelx,edgely,edgerx,edgery,sum1,sfxy) \ reduction(+:sum2) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[k]; npoff = nppmx*k; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; ih = 0; nh = 0; nn += 1; mm += 1; /* load local fields from global array */ for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sfxy[2*(i+mxv*j)] = fxy[2*(i+noff+nxv*(j+moff))]; sfxy[1+2*(i+mxv*j)] = fxy[1+2*(i+noff+nxv*(j+moff))]; } } /* clear counters */ for (j = 0; j < 8; j++) { ncl[j+8*k] = 0; } sum1 = 0.0; /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; nn = x; mm = y; dxp = x - (float) nn; dyp = y - (float) mm; nn = 2*(nn - noff) + 2*mxv*(mm - moff); amx = 1.0f - dxp; amy = 1.0f - dyp; /* find acceleration */ dx = amx*sfxy[nn]; dy = amx*sfxy[nn+1]; dx = amy*(dxp*sfxy[nn+2] + dx); dy = amy*(dxp*sfxy[nn+3] + dy); nn += 2*mxv; vx = amx*sfxy[nn]; vy = amx*sfxy[nn+1]; dx += dyp*(dxp*sfxy[nn+2] + vx); dy += dyp*(dxp*sfxy[nn+3] + vy); /* new velocity */ vx = ppart[2+idimp*(j+npoff)]; vy = ppart[3+idimp*(j+npoff)]; dx = vx + qtm*dx; dy = vy + qtm*dy; /* average kinetic energy */ vx += dx; vy += dy; sum1 += (vx*vx + vy*vy); ppart[2+idimp*(j+npoff)] = dx; ppart[3+idimp*(j+npoff)] = dy; /* new position */ dx = x + dx*dt; dy = y + dy*dt; /* find particles going out of bounds */ mm = 0; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* mm = direction particle is going */ if (dx >= edgerx) { if (dx >= anx) dx -= anx; mm = 2; } else if (dx < edgelx) { if (dx < 0.0f) { dx += anx; if (dx < anx) mm = 1; else dx = 0.0; } else { mm = 1; } } if (dy >= edgery) { if (dy >= any) dy -= any; mm += 6; } else if (dy < edgely) { if (dy < 0.0) { dy += any; if (dy < any) mm += 3; else dy = 0.0; } else { mm += 3; } } /* set new position */ ppart[idimp*(j+npoff)] = dx; ppart[1+idimp*(j+npoff)] = dy; /* increment counters */ if (mm > 0) { ncl[mm+8*k-1] += 1; ih += 1; if (ih <= ntmax) { ihole[2*(ih+(ntmax+1)*k)] = j + 1; ihole[1+2*(ih+(ntmax+1)*k)] = mm; } else { nh = 1; } } } sum2 += sum1; /* set error and end of file flag */ /* ihole overflow */ if (nh > 0) { *irc = ih; ih = -ih; } ihole[2*(ntmax+1)*k] = ih; } /* normalize kinetic energy */ *ek += 0.125f*sum2; return; #undef MXV #undef MYV } /*--------------------------------------------------------------------*/ void cgppost2l(float ppart[], float q[], int kpic[], float qm, int nppmx, int idimp, int mx, int my, int nxv, int nyv, int mx1, int mxy1) { /* for 2d code, this subroutine calculates particle charge density using first-order linear interpolation, periodic boundaries OpenMP version using guard cells data deposited in tiles particles stored segmented array 17 flops/particle, 6 loads, 4 stores input: all, output: q charge density is approximated by values at the nearest grid points q(n,m)=qm*(1.-dx)*(1.-dy) q(n+1,m)=qm*dx*(1.-dy) q(n,m+1)=qm*(1.-dx)*dy q(n+1,m+1)=qm*dx*dy where n,m = leftmost grid points and dx = x-n, dy = y-m ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m q[k][j] = charge density at grid point j,k kpic = number of particles per tile qm = charge on particle, in units of e nppmx = maximum number of particles in tile idimp = size of phase space = 4 mx/my = number of grids in sorting cell in x/y nxv = first dimension of charge array, must be >= nx+1 nyv = second dimension of charge array, must be >= ny+1 mx1 = (system length in x direction - 1)/mx + 1 mxy1 = mx1*my1, where my1 = (system length in y direction - 1)/my + 1 local data */ #define MXV 33 #define MYV 33 int noff, moff, npoff, npp, mxv; int i, j, k, nn, mm; float x, y, dxp, dyp, amx, amy; float sq[MXV*MYV]; /* float sq[(mx+1)*(my+1)]; */ mxv = mx + 1; /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,noff,moff,npp,npoff,nn,mm,x,y,dxp,dyp,amx,amy,sq) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[k]; npoff = nppmx*k; /* zero out local accumulator */ for (j = 0; j < mxv*(my+1); j++) { sq[j] = 0.0f; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; nn = x; mm = y; dxp = qm*(x - (float) nn); dyp = y - (float) mm; nn = nn - noff + mxv*(mm - moff); amx = qm - dxp; amy = 1.0f - dyp; /* deposit charge within tile to local accumulator */ x = sq[nn] + amx*amy; y = sq[nn+1] + dxp*amy; sq[nn] = x; sq[nn+1] = y; nn += mxv; x = sq[nn] + amx*dyp; y = sq[nn+1] + dxp*dyp; sq[nn] = x; sq[nn+1] = y; } /* deposit charge to interior points in global array */ nn = nxv - noff; mm = nyv - moff; nn = mx < nn ? mx : nn; mm = my < mm ? my : mm; for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { q[i+noff+nxv*(j+moff)] += sq[i+mxv*j]; } } /* deposit charge to edge points in global array */ mm = nyv - moff; mm = my+1 < mm ? my+1 : mm; for (i = 1; i < nn; i++) { #pragma omp atomic q[i+noff+nxv*moff] += sq[i]; if (mm > my) { #pragma omp atomic q[i+noff+nxv*(mm+moff-1)] += sq[i+mxv*(mm-1)]; } } nn = nxv - noff; nn = mx+1 < nn ? mx+1 : nn; for (j = 0; j < mm; j++) { #pragma omp atomic q[noff+nxv*(j+moff)] += sq[mxv*j]; if (nn > mx) { #pragma omp atomic q[nn+noff-1+nxv*(j+moff)] += sq[nn-1+mxv*j]; } } } return; #undef MXV #undef MYV } /*--------------------------------------------------------------------*/ void cpporder2l(float ppart[], float ppbuff[], int kpic[], int ncl[], int ihole[], int idimp, int nppmx, int nx, int ny, int mx, int my, int mx1, int my1, int npbmx, int ntmax, int *irc) { /* this subroutine sorts particles by x,y grid in tiles of mx, my linear interpolation, with periodic boundary conditions tiles are assumed to be arranged in 2D linear memory algorithm has 3 steps. first, one finds particles leaving tile and stores their number in each directon, location, and destination in ncl and ihole. second, a prefix scan of ncl is performed and departing particles are buffered in ppbuff in direction order. finally, we copy the incoming particles from other tiles into ppart. input: all except ppbuff, ncl, ihole, irc output: ppart, ppbuff, kpic, ncl, ihole, irc ppart[k][n][0] = position x of particle n in tile k ppart[k][n][1] = position y of particle n in tile k ppbuff[k][n][i] = i co-ordinate of particle n in tile k kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = direction destination of particle leaving hole all for tile k ihole[k][0][0] = ih, number of holes left (error, if negative) idimp = size of phase space = 4 nppmx = maximum number of particles in tile nx/ny = system length in x/y direction mx/my = number of grids in sorting cell in x/y mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxy1, noff, moff, npp, ncoff; int i, j, k, ii, kx, ky, ih, nh, ist, nn, mm, isum; int ip, j1, j2, kxl, kxr, kk, kl, kr; float anx, any, edgelx, edgely, edgerx, edgery, dx, dy; int ks[8]; mxy1 = mx1*my1; anx = (float) nx; any = (float) ny; /* find and count particles leaving tiles and determine destination */ /* update ppart, ihole, ncl */ /* loop over tiles */ #pragma omp parallel for \ private(j,k,noff,moff,npp,nn,mm,ih,nh,ist,dx,dy,edgelx,edgely,edgerx, \ edgery) for (k = 0; k < mxy1; k++) { noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[k]; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; ih = 0; nh = 0; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; /* clear counters */ for (j = 0; j < 8; j++) { ncl[j+8*k] = 0; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { dx = ppart[idimp*(j+nppmx*k)]; dy = ppart[1+idimp*(j+nppmx*k)]; /* find particles going out of bounds */ ist = 0; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* ist = direction particle is going */ if (dx >= edgerx) { if (dx >= anx) ppart[idimp*(j+nppmx*k)] = dx - anx; ist = 2; } else if (dx < edgelx) { if (dx < 0.0) { dx += anx; if (dx < anx) ist = 1; else dx = 0.0; ppart[idimp*(j+nppmx*k)] = dx; } else { ist = 1; } } if (dy >= edgery) { if (dy >= any) ppart[1+idimp*(j+nppmx*k)] = dy - any; ist += 6; } else if (dy < edgely) { if (dy < 0.0) { dy += any; if (dy < any) ist += 3; else dy = 0.0; ppart[1+idimp*(j+nppmx*k)] = dy; } else { ist += 3; } } if (ist > 0) { ncl[ist+8*k-1] += 1; ih += 1; if (ih <= ntmax) { ihole[2*(ih+(ntmax+1)*k)] = j + 1; ihole[1+2*(ih+(ntmax+1)*k)] = ist; } else { nh = 1; } } } /* set error and end of file flag */ if (nh > 0) { *irc = ih; ih = -ih; } ihole[2*(ntmax+1)*k] = ih; } /* ihole overflow */ if (*irc > 0) return; /* buffer particles that are leaving tile: update ppbuff, ncl */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,isum,ist,nh,ip,j1,ii) for (k = 0; k < mxy1; k++) { /* find address offset for ordered ppbuff array */ isum = 0; for (j = 0; j < 8; j++) { ist = ncl[j+8*k]; ncl[j+8*k] = isum; isum += ist; } nh = ihole[2*(ntmax+1)*k]; ip = 0; /* loop over particles leaving tile */ for (j = 0; j < nh; j++) { /* buffer particles that are leaving tile, in direction order */ j1 = ihole[2*(j+1+(ntmax+1)*k)] - 1; ist = ihole[1+2*(j+1+(ntmax+1)*k)]; ii = ncl[ist+8*k-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[i+idimp*(ii+npbmx*k)] = ppart[i+idimp*(j1+nppmx*k)]; } } else { ip = 1; } ncl[ist+8*k-1] = ii + 1; } /* set error */ if (ip > 0) *irc = ncl[7+8*k]; } /* ppbuff overflow */ if (*irc > 0) return; /* copy incoming particles from buffer into ppart: update ppart, kpic */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,ii,kk,npp,kx,ky,kl,kr,kxl,kxr,ih,nh,ncoff,ist,j1,j2,ip,ks) for (k = 0; k < mxy1; k++) { npp = kpic[k]; ky = k/mx1; /* loop over tiles in y, assume periodic boundary conditions */ kk = ky*mx1; /* find tile above */ kl = ky - 1; if (kl < 0) kl += my1; kl = kl*mx1; /* find tile below */ kr = ky + 1; if (kr >= my1) kr -= my1; kr = kr*mx1; /* loop over tiles in x, assume periodic boundary conditions */ kx = k - ky*mx1; kxl = kx - 1; if (kxl < 0) kxl += mx1; kxr = kx + 1; if (kxr >= mx1) kxr -= mx1; /* find tile number for different directions */ ks[0] = kxr + kk; ks[1] = kxl + kk; ks[2] = kx + kr; ks[3] = kxr + kr; ks[4] = kxl + kr; ks[5] = kx + kl; ks[6] = kxr + kl; ks[7] = kxl + kl; /* loop over directions */ nh = ihole[2*(ntmax+1)*k]; ncoff = 0; ih = 0; ist = 0; j1 = 0; for (ii = 0; ii < 8; ii++) { if (ii > 0) ncoff = ncl[ii-1+8*ks[ii]]; /* ip = number of particles coming from direction ii */ ip = ncl[ii+8*ks[ii]] - ncoff; for (j = 0; j < ip; j++) { ih += 1; /* insert incoming particles into holes */ if (ih <= nh) { j1 = ihole[2*(ih+(ntmax+1)*k)] - 1; } /* place overflow at end of array */ else { j1 = npp; npp += 1; } if (j1 < nppmx) { for (i = 0; i < idimp; i++) { ppart[i+idimp*(j1+nppmx*k)] = ppbuff[i+idimp*(j+ncoff+npbmx*ks[ii])]; } } else { ist = 1; } } } /* set error */ if (ist > 0) *irc = j1+1; /* fill up remaining holes in particle array with particles from bottom */ if (ih < nh) { ip = nh - ih; for (j = 0; j < ip; j++) { j1 = npp - j - 1; j2 = ihole[2*(nh-j+(ntmax+1)*k)] - 1; if (j1 > j2) { /* move particle only if it is below current hole */ for (i = 0; i < idimp; i++) { ppart[i+idimp*(j2+nppmx*k)] = ppart[i+idimp*(j1+nppmx*k)]; } } } npp -= ip; } kpic[k] = npp; } return; } /*--------------------------------------------------------------------*/ void cpporderf2l(float ppart[], float ppbuff[], int kpic[], int ncl[], int ihole[], int idimp, int nppmx, int mx1, int my1, int npbmx, int ntmax, int *irc) { /* this subroutine sorts particles by x,y grid in tiles of mx, my linear interpolation, with periodic boundary conditions tiles are assumed to be arranged in 2D linear memory the algorithm has 2 steps. first, a prefix scan of ncl is performed and departing particles are buffered in ppbuff in direction order. then we copy the incoming particles from other tiles into ppart. it assumes that the number, location, and destination of particles leaving a tile have been previously stored in ncl and ihole by the cgppushf2l procedure. input: all except ppbuff, irc output: ppart, ppbuff, kpic, ncl, irc ppart[k][n][0] = position x of particle n in tile k ppart[k][n][1] = position y of particle n in tile k ppbuff[k][n][i] = i co-ordinate of particle n in tile k kpic[k] = number of particles in tile k ncl[k][i] = number of particles going to destination i, tile k ihole[k][:][0] = location of hole in array left by departing particle ihole[k][:][1] = direction destination of particle leaving hole all for tile k ihole[k][0][0] = ih, number of holes left (error, if negative) idimp = size of phase space = 4 nppmx = maximum number of particles in tile mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxy1, npp, ncoff; int i, j, k, ii, kx, ky, ih, nh, ist, isum; int ip, j1, j2, kxl, kxr, kk, kl, kr; int ks[8]; mxy1 = mx1*my1; /* buffer particles that are leaving tile: update ppbuff, ncl */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,isum,ist,nh,ip,j1,ii) for (k = 0; k < mxy1; k++) { /* find address offset for ordered ppbuff array */ isum = 0; for (j = 0; j < 8; j++) { ist = ncl[j+8*k]; ncl[j+8*k] = isum; isum += ist; } nh = ihole[2*(ntmax+1)*k]; ip = 0; /* loop over particles leaving tile */ for (j = 0; j < nh; j++) { /* buffer particles that are leaving tile, in direction order */ j1 = ihole[2*(j+1+(ntmax+1)*k)] - 1; ist = ihole[1+2*(j+1+(ntmax+1)*k)]; ii = ncl[ist+8*k-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[i+idimp*(ii+npbmx*k)] = ppart[i+idimp*(j1+nppmx*k)]; } } else { ip = 1; } ncl[ist+8*k-1] = ii + 1; } /* set error */ if (ip > 0) *irc = ncl[7+8*k]; } /* ppbuff overflow */ if (*irc > 0) return; /* copy incoming particles from buffer into ppart: update ppart, kpic */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,ii,kk,npp,kx,ky,kl,kr,kxl,kxr,ih,nh,ncoff,ist,j1,j2,ip,ks) for (k = 0; k < mxy1; k++) { npp = kpic[k]; ky = k/mx1; /* loop over tiles in y, assume periodic boundary conditions */ kk = ky*mx1; /* find tile above */ kl = ky - 1; if (kl < 0) kl += my1; kl = kl*mx1; /* find tile below */ kr = ky + 1; if (kr >= my1) kr -= my1; kr = kr*mx1; /* loop over tiles in x, assume periodic boundary conditions */ kx = k - ky*mx1; kxl = kx - 1; if (kxl < 0) kxl += mx1; kxr = kx + 1; if (kxr >= mx1) kxr -= mx1; /* find tile number for different directions */ ks[0] = kxr + kk; ks[1] = kxl + kk; ks[2] = kx + kr; ks[3] = kxr + kr; ks[4] = kxl + kr; ks[5] = kx + kl; ks[6] = kxr + kl; ks[7] = kxl + kl; /* loop over directions */ nh = ihole[2*(ntmax+1)*k]; ncoff = 0; ih = 0; ist = 0; j1 = 0; for (ii = 0; ii < 8; ii++) { if (ii > 0) ncoff = ncl[ii-1+8*ks[ii]]; /* ip = number of particles coming from direction ii */ ip = ncl[ii+8*ks[ii]] - ncoff; for (j = 0; j < ip; j++) { ih += 1; /* insert incoming particles into holes */ if (ih <= nh) { j1 = ihole[2*(ih+(ntmax+1)*k)] - 1; } /* place overflow at end of array */ else { j1 = npp; npp += 1; } if (j1 < nppmx) { for (i = 0; i < idimp; i++) { ppart[i+idimp*(j1+nppmx*k)] = ppbuff[i+idimp*(j+ncoff+npbmx*ks[ii])]; } } else { ist = 1; } } } /* set error */ if (ist > 0) *irc = j1+1; /* fill up remaining holes in particle array with particles from bottom */ if (ih < nh) { ip = nh - ih; for (j = 0; j < ip; j++) { j1 = npp - j - 1; j2 = ihole[2*(nh-j+(ntmax+1)*k)] - 1; if (j1 > j2) { /* move particle only if it is below current hole */ for (i = 0; i < idimp; i++) { ppart[i+idimp*(j2+nppmx*k)] = ppart[i+idimp*(j1+nppmx*k)]; } } } npp -= ip; } kpic[k] = npp; } return; } /*--------------------------------------------------------------------*/ void ccguard2l(float fxy[], int nx, int ny, int nxe, int nye) { /* replicate extended periodic vector field fxy linear interpolation nx/ny = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nxe = second dimension of field arrays, must be >= ny+1 local data */ int j, k; /* copy edges of extended field */ for (k = 0; k < ny; k++) { fxy[2*nx+2*nxe*k] = fxy[2*nxe*k]; fxy[1+2*nx+2*nxe*k] = fxy[1+2*nxe*k]; } for (j = 0; j < nx; j++) { fxy[2*j+2*nxe*ny] = fxy[2*j]; fxy[1+2*j+2*nxe*ny] = fxy[1+2*j]; } fxy[2*nx+2*nxe*ny] = fxy[0]; fxy[1+2*nx+2*nxe*ny] = fxy[1]; return; } /*--------------------------------------------------------------------*/ void caguard2l(float q[], int nx, int ny, int nxe, int nye) { /* accumulate extended periodic scalar field q linear interpolation nx/ny = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nxe = second dimension of field arrays, must be >= ny+1 local data */ int j, k; /* accumulate edges of extended field */ for (k = 0; k < ny; k++) { q[nxe*k] += q[nx+nxe*k]; q[nx+nxe*k] = 0.0; } for (j = 0; j < nx; j++) { q[j] += q[j+nxe*ny]; q[j+nxe*ny] = 0.0; } q[0] += q[nx+nxe*ny]; q[nx+nxe*ny] = 0.0; return; } /*--------------------------------------------------------------------*/ void cmpois22(float complex q[], float complex fxy[], int isign, float complex ffc[], float ax, float ay, float affp, float *we, int nx, int ny, int nxvh, int nyv, int nxhd, int nyhd) { /* this subroutine solves 2d poisson's equation in fourier space for force/charge (or convolution of electric field over particle shape) with periodic boundary conditions. for isign = 0, input: isign,ax,ay,affp,nx,ny,nxvh,nyhd, output: ffc for isign /= 0, input: q,ffc,isign,nx,ny,nxvh,nyhd, output: fxy,we approximate flop count is: 26*nxc*nyc + 12*(nxc + nyc) where nxc = nx/2 - 1, nyc = ny/2 - 1 equation used is: fx[ky][kx] = -sqrt(-1)*kx*g[ky][kx]*s[ky][kx]*q[ky][kx], fy[ky][kx] = -sqrt(-1)*ky*g[ky][kx]*s[ky][kx]*q[ky][kx], where kx = 2pi*j/nx, ky = 2pi*k/ny, and j,k = fourier mode numbers, g[ky][kx] = (affp/(kx**2+ky**2))*s(kx,ky), s[ky][kx] = exp(-((kx*ax)**2+(ky*ay)**2)/2), except for fx(kx=pi) = fy(kx=pi) = fx(ky=pi) = fy(ky=pi) = 0, and fx(kx=0,ky=0) = fy(kx=0,ky=0) = 0. q[k][j] = complex charge density for fourier mode (j,k) fxy[k][j][0] = x component of complex force/charge, fxy[k][j][1] = y component of complex force/charge, all for fourier mode (j,k) if isign = 0, form factor array is prepared if isign is not equal to 0, force/charge is calculated cimag(ffc[k][j]) = finite-size particle shape factor s for fourier mode (j,k) creal(ffc[k][j]) = potential green's function g for fourier mode (j,k) ax/ay = half-width of particle in x/y direction affp = normalization constant = nx*ny/np, where np=number of particles electric field energy is also calculated, using we = nx*ny*sum((affp/(kx**2+ky**2))*|q[ky][kx]*s[ky][kx]|**2) nx/ny = system length in x/y direction nxvh = first dimension of field arrays, must be >= nxh nyv = second dimension of field arrays, must be >= ny nxhd = first dimension of form factor array, must be >= nxh nyhd = second dimension of form factor array, must be >= nyh local data */ int nxh, nyh, j, k, k1, kk, kj; float dnx, dny, dkx, dky, at1, at2, at3, at4; float complex zero, zt1, zt2; double wp, sum1; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; zero = 0.0 + 0.0*_Complex_I; if (isign != 0) goto L30; /* prepare form factor array */ for (k = 0; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; at1 = dky*dky; at2 = pow((dky*ay),2); for (j = 0; j < nxh; j++) { dkx = dnx*(float) j; at3 = dkx*dkx + at1; at4 = exp(-0.5*(pow((dkx*ax),2) + at2)); if (at3==0.0) { ffc[j+kk] = affp + 1.0*_Complex_I; } else { ffc[j+kk] = (affp*at4/at3) + at4*_Complex_I; } } } return; /* calculate force/charge and sum field energy */ L30: sum1 = 0.0; #pragma omp parallel for \ private(j,k,k1,kk,kj,dky,at1,at2,at3,zt1,zt2,wp) \ reduction(+:sum1) /* mode numbers 0 < kx < nx/2 and 0 < ky < ny/2 */ for (k = 1; k < nyh; k++) { k1 = ny - k; dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; wp = 0.0; for (j = 1; j < nxh; j++) { at1 = crealf(ffc[j+kk])*cimagf(ffc[j+kk]); at2 = at1*dnx*(float) j; at3 = dky*at1; zt1 = cimagf(q[j+kj]) - crealf(q[j+kj])*_Complex_I; zt2 = cimagf(q[j+k1]) - crealf(q[j+k1])*_Complex_I; fxy[2*j+2*kj] = at2*zt1; fxy[1+2*j+2*kj] = at3*zt1; fxy[2*j+2*k1] = at2*zt2; fxy[1+2*j+2*k1] = -at3*zt2; wp += at1*(q[j+kj]*conjf(q[j+kj]) + q[j+k1]*conjf(q[j+k1])); } at1 = crealf(ffc[kk])*cimagf(ffc[kk]); at3 = at1*dny*(float) k; zt1 = cimagf(q[kj]) - crealf(q[kj])*_Complex_I; fxy[2*kj] = zero; fxy[1+2*kj] = at3*zt1; fxy[2*k1] = zero; fxy[1+2*k1] = zero; wp += at1*(q[kj]*conjf(q[kj])); sum1 += wp; } wp = 0.0; /* mode numbers ky = 0, ny/2 */ k1 = 2*nxvh*nyh; for (j = 1; j < nxh; j++) { at1 = crealf(ffc[j])*cimagf(ffc[j]); at2 = at1*dnx*(float) j; zt1 = cimagf(q[j]) - crealf(q[j])*_Complex_I; fxy[2*j] = at2*zt1; fxy[1+2*j] = zero; fxy[2*j+k1] = zero; fxy[1+2*j+k1] = zero; wp += at1*(q[j]*conjf(q[j])); } fxy[0] = zero; fxy[1] = zero; fxy[k1] = zero; fxy[1+k1] = zero; sum1 += wp; *we = sum1*(float) (nx*ny); return; } /*--------------------------------------------------------------------*/ void cwfft2rinit(int mixup[], float complex sct[], int indx, int indy, int nxhyd, int nxyhd) { /* this subroutine calculates tables needed by a two dimensional real to complex fast fourier transform and its inverse. input: indx, indy, nxhyd, nxyhd output: mixup, sct mixup = array of bit reversed addresses sct = sine/cosine table indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy nxhyd = maximum of (nx/2,ny) nxyhd = one half of maximum of (nx,ny) written by viktor k. decyk, ucla local data */ int indx1, indx1y, nx, ny, nxy, nxhy, nxyh; int j, k, lb, ll, jb, it; float dnxy, arg; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; ny = 1L<<indy; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; /* bit-reverse index table: mixup[j] = 1 + reversed bits of j */ for (j = 0; j < nxhy; j++) { lb = j; ll = 0; for (k = 0; k < indx1y; k++) { jb = lb/2; it = lb - 2*jb; lb = jb; ll = 2*ll + it; } mixup[j] = ll + 1; } /* sine/cosine table for the angles 2*n*pi/nxy */ nxyh = nxy/2; dnxy = 6.28318530717959/(float) nxy; for (j = 0; j < nxyh; j++) { arg = dnxy*(float) j; sct[j] = cosf(arg) - sinf(arg)*_Complex_I; } return; } /*--------------------------------------------------------------------*/ void cfft2rmxx(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nyi, int nyp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the x part of a two dimensional real to complex fast fourier transform and its inverse, for a subset of y, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, an inverse fourier transform in x is performed f[m][n] = (1/nx*ny)*sum(f[k][j]*exp(-sqrt(-1)*2pi*n*j/nx)) if isign = 1, a forward fourier transform in x is performed f[k][j] = sum(f[m][n]*exp(sqrt(-1)*2pi*n*j/nx)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = first dimension of f >= nx/2 nyd = second dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0]) = real part of mode nx/2,0 and imag(f[0][ny/2]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla local data */ int indx1, indx1y, nx, nxh, nxhh, ny, nxy, nxhy, nyt; int nrx, i, j, k, l, j1, j2, k1, k2, ns, ns2, km, kmr, nrxb, joff; float ani; float complex t1, t2, t3; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nyt = nyi + nyp - 1; if (isign > 0) goto L70; /* inverse fourier transform */ nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,j1,j2,joff,ani,t1,t2,t3) for (i = nyi-1; i < nyt; i++) { joff = nxhd*i; /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { t1 = f[j1+joff]; f[j1+joff] = f[j+joff]; f[j+joff] = t1; } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t2 = t1*f[j2+joff]; f[j2+joff] = f[j1+joff] - t2; f[j1+joff] += t2; } } ns = ns2; } /* unscramble coefficients and normalize */ kmr = nxy/nx; ani = 0.5/(((float) nx)*((float) ny)); for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; t2 = conjf(f[nxh-j+joff]); t1 = f[j+joff] + t2; t2 = (f[j+joff] - t2)*t3; f[j+joff] = ani*(t1 + t2); f[nxh-j+joff] = ani*conjf(t1 - t2); } ani = 2.0*ani; f[nxhh+joff] = ani*conjf(f[nxhh+joff]); f[joff] = ani*((crealf(f[joff]) + cimagf(f[joff])) + (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I); } return; /* forward fourier transform */ L70: nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,j1,j2,joff,t1,t2,t3) for (i = nyi-1; i < nyt; i++) { joff = nxhd*i; /* scramble coefficients */ kmr = nxy/nx; for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; t2 = conjf(f[nxh-j+joff]); t1 = f[j+joff] + t2; t2 = (f[j+joff] - t2)*t3; f[j+joff] = t1 + t2; f[nxh-j+joff] = conjf(t1 - t2); } f[nxhh+joff] = 2.0*conjf(f[nxhh+joff]); f[joff] = (crealf(f[joff]) + cimagf(f[joff])) + (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I; /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { t1 = f[j1+joff]; f[j1+joff] = f[j+joff]; f[j+joff] = t1; } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = conjf(sct[kmr*j]); t2 = t1*f[j2+joff]; f[j2+joff] = f[j1+joff] - t2; f[j1+joff] += t2; } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void cfft2rmxy(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxi, int nxp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the y part of a two dimensional real to complex fast fourier transform and its inverse, for a subset of x, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, an inverse fourier transform in y is performed f[m][n] = sum(f[k][j]*exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, a forward fourier transform in y is performed f[k][j] = sum(f[m][n]*exp(sqrt(-1)*2pi*m*k/ny)) mixup = array of bit reversed addresses sct = sine/cosine table nxi = initial x index used nxp = number of x indices used nxhd = first dimension of f >= nx/2 nyd = second dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0]) = real part of mode nx/2,0 and imag(f[0][ny/2]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla local data */ int indx1, indx1y, nx, ny, nyh, nxy, nxhy, nxt; int nry, i, j, k, l, j1, j2, k1, k2, ns, ns2, km, kmr, nryb, koff; float complex t1, t2; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; ny = 1L<<indy; nyh = ny/2; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nxt = nxi + nxp - 1; if (isign > 0) goto L70; /* inverse fourier transform */ nryb = nxhy/ny; nry = nxy/ny; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,j1,j2,koff,t1,t2) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd*k1; t1 = f[i+k1]; f[i+k1] = f[i+koff]; f[i+koff] = t1; } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhd*(j + k1); j2 = nxhd*(j + k2); t1 = sct[kmr*j]; t2 = t1*f[i+j2]; f[i+j2] = f[i+j1] - t2; f[i+j1] += t2; } } ns = ns2; } } /* unscramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = nxhd*k; k1 = nxhd*ny - koff; t1 = f[k1]; f[k1] = 0.5*(cimagf(f[koff] + t1) + crealf(f[koff] - t1)*_Complex_I); f[koff] = 0.5*(crealf(f[koff] + t1) + cimagf(f[koff] - t1)*_Complex_I); } } return; /* forward fourier transform */ L70: nryb = nxhy/ny; nry = nxy/ny; /* scramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = nxhd*k; k1 = nxhd*ny - koff; t1 = cimagf(f[k1]) + crealf(f[k1])*_Complex_I; f[k1] = conjf(f[koff] - t1); f[koff] += t1; } } #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,j1,j2,koff,t1,t2) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd*k1; t1 = f[i+k1]; f[i+k1] = f[i+koff]; f[i+koff] = t1; } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhd*(j + k1); j2 = nxhd*(j + k2); t1 = conjf(sct[kmr*j]); t2 = t1*f[i+j2]; f[i+j2] = f[i+j1] - t2; f[i+j1] += t2; } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void cfft2rm2x(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nyi, int nyp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the x part of 2 two dimensional real to complex fast fourier transforms, and their inverses, for a subset of y, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, two inverse fourier transforms in x are performed f[m][n][0:1] = (1/nx*ny)*sum(f[k][j][0:1]*exp(-sqrt(-1)*2pi*n*j/nx)) if isign = 1, two forward fourier transforms in x are performed f[k][j][0:1] = sum(f[m][n][0:1]*exp(sqrt(-1)*2pi*n*j/nx)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = second dimension of f >= nx/2 nyd = third dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j][0:1] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1][0:1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0][0:1]) = real part of mode nx/2,0 and imag(f[0][ny/2][0:1]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla local data */ int indx1, indx1y, nx, nxh, nxhh, ny, nxy, nxhy, nyt; int nrx, i, j, k, l, jj, j1, j2, k1, k2, ns, ns2, km, kmr, joff; int nrxb; float at1, ani; float complex t1, t2, t3; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nyt = nyi + nyp - 1; if (isign > 0) goto L100; /* inverse fourier transform */ nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,j2,joff,at1,ani,t1,t2,t3) for (i = nyi-1; i < nyt; i++) { joff = 2*nxhd*i; /* swap complex components */ for (j = 0; j < nxh; j++) { at1 = cimagf(f[2*j+joff]); f[2*j+joff] = crealf(f[2*j+joff]) + crealf(f[1+2*j+joff])*_Complex_I; f[1+2*j+joff] = at1 + cimagf(f[1+2*j+joff])*_Complex_I; } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { t1 = f[2*j1+joff]; t2 = f[1+2*j1+joff]; f[2*j1+joff] = f[2*j+joff]; f[1+2*j1+joff] = f[1+2*j+joff]; f[2*j+joff] = t1; f[1+2*j+joff] = t2; } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; t2 = t1*f[2*j2+joff]; t3 = t1*f[1+2*j2+joff]; f[2*j2+joff] = f[2*j1+joff] - t2; f[1+2*j2+joff] = f[1+2*j1+joff] - t3; f[2*j1+joff] += t2; f[1+2*j1+joff] += t3; } } ns = ns2; } /* unscramble coefficients and normalize */ kmr = nxy/nx; ani = 0.5/(((float) nx)*((float) ny)); for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; for (jj = 0; jj < 2; jj++) { t2 = conjf(f[jj+2*(nxh-j)+joff]); t1 = f[jj+2*j+joff] + t2; t2 = (f[jj+2*j+joff] - t2)*t3; f[jj+2*j+joff] = ani*(t1 + t2); f[jj+2*(nxh-j)+joff] = ani*conjf(t1 - t2); } } ani = 2.0*ani; for (jj = 0; jj < 2; jj++) { f[jj+2*nxhh+joff] = ani*conjf(f[jj+2*nxhh+joff]); f[jj+joff] = ani*((crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I); } } return; /* forward fourier transform */ L100: nrxb = nxhy/nxh; nrx = nxy/nxh; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,j2,joff,at1,t1,t2,t3) for (i = nyi-1; i < nyt; i++) { joff = 2*nxhd*i; /* scramble coefficients */ kmr = nxy/nx; for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; for (jj = 0; jj < 2; jj++) { t2 = conjf(f[jj+2*(nxh-j)+joff]); t1 = f[jj+2*j+joff] + t2; t2 = (f[jj+2*j+joff] - t2)*t3; f[jj+2*j+joff] = t1 + t2; f[jj+2*(nxh-j)+joff] = conjf(t1 - t2); } } for (jj = 0; jj < 2; jj++) { f[jj+2*nxhh+joff] = 2.0*conjf(f[jj+2*nxhh+joff]); f[jj+joff] = (crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I; } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { t1 = f[2*j1+joff]; t2 = f[1+2*j1+joff]; f[2*j1+joff] = f[2*j+joff]; f[1+2*j1+joff] = f[1+2*j+joff]; f[2*j+joff] = t1; f[1+2*j+joff] = t2; } } /* then transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = conjf(sct[kmr*j]); t2 = t1*f[2*j2+joff]; t3 = t1*f[1+2*j2+joff]; f[2*j2+joff] = f[2*j1+joff] - t2; f[1+2*j2+joff] = f[1+2*j1+joff] - t3; f[2*j1+joff] += t2; f[1+2*j1+joff] += t3; } } ns = ns2; } /* swap complex components */ for (j = 0; j < nxh; j++) { at1 = cimagf(f[2*j+joff]); f[2*j+joff] = crealf(f[2*j+joff]) + crealf(f[1+2*j+joff])*_Complex_I; f[1+2*j+joff] = at1 + cimagf(f[1+2*j+joff])*_Complex_I; } } return; } /*--------------------------------------------------------------------*/ void cfft2rm2y(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxi, int nxp, int nxhd, int nyd, int nxhyd, int nxyhd) { /* this subroutine performs the y part of 2 two dimensional real to complex fast fourier transforms, and their inverses, for a subset of x, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny indx/indy = exponent which determines length in x/y direction, where nx=2**indx, ny=2**indy if isign = -1, two inverse fourier transforms in y are performed f[m][n][0:1] = *sum(f[k][j][0:1]*exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, two forward fourier transforms in y are performed f[k][j][0:1] = sum(f[m][n][0:1]*exp(sqrt(-1)*2pi*n*j/nx)) mixup = array of bit reversed addresses sct = sine/cosine table nxi = initial x index used nxp = number of x indices used nxhd = second dimension of f >= nx/2 nyd = third dimension of f >= ny nxhyd = maximum of (nx/2,ny) nxyhd = maximum of (nx,ny)/2 fourier coefficients are stored as follows: f[k][j][0:1] = real, imaginary part of mode j,k, where 0 <= j < nx/2 and 0 <= k < ny, except for f[k][1][0:1] = real, imaginary part of mode nx/2,k, where ny/2+1 <= k < ny, and imag(f[0][0][0:1]) = real part of mode nx/2,0 and imag(f[0][ny/2][0:1]) = real part of mode nx/2,ny/2 written by viktor k. decyk, ucla local data */ int indx1, indx1y, nx, ny, nyh, nxy, nxhy, nxt; int nry, i, j, k, l, jj, j1, j2, k1, k2, ns, ns2, km, kmr, koff; int nryb; float complex t1, t2, t3; if (isign==0) return; indx1 = indx - 1; indx1y = indx1 > indy ? indx1 : indy; nx = 1L<<indx; ny = 1L<<indy; nyh = ny/2; nxy = nx > ny ? nx : ny; nxhy = 1L<<indx1y; nxt = nxi + nxp - 1; if (isign > 0) goto L80; /* inverse fourier transform */ nryb = nxhy/ny; nry = nxy/ny; #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,j2,koff,t1,t2,t3) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = 2*nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = 2*nxhd*k1; t1 = f[2*i+k1]; t2 = f[1+2*i+k1]; f[2*i+k1] = f[2*i+koff]; f[1+2*i+k1] = f[1+2*i+koff]; f[2*i+koff] = t1; f[1+2*i+koff] = t2; } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = 2*nxhd*(j + k1); j2 = 2*nxhd*(j + k2); t1 = sct[kmr*j]; t2 = t1*f[2*i+j2]; t3 = t1*f[1+2*i+j2]; f[2*i+j2] = f[2*i+j1] - t2; f[1+2*i+j2] = f[1+2*i+j1] - t3; f[2*i+j1] += t2; f[1+2*i+j1] += t3; } } ns = ns2; } } /* unscramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = 2*nxhd*k; k1 = 2*nxhd*ny - koff; for (jj = 0; jj < 2; jj++) { t1 = f[jj+k1]; f[jj+k1] = 0.5*(cimagf(f[jj+koff] + t1) + crealf(f[jj+koff] - t1)*_Complex_I); f[jj+koff] = 0.5*(crealf(f[jj+koff] + t1) + cimagf(f[jj+koff] - t1)*_Complex_I); } } } return; /* forward fourier transform */ L80: nryb = nxhy/ny; nry = nxy/ny; /* scramble modes kx = 0, nx/2 */ if (nxi==1) { for (k = 1; k < nyh; k++) { koff = 2*nxhd*k; k1 = 2*nxhd*ny - koff; for (jj = 0; jj < 2; jj++) { t1 = cimagf(f[jj+k1]) + crealf(f[jj+k1])*_Complex_I; f[jj+k1] = conjf(f[jj+koff] - t1); f[jj+koff] += t1; } } } #pragma omp parallel for \ private(i,j,k,l,ns,ns2,km,kmr,k1,k2,jj,j1,j2,koff,t1,t2,t3) for (i = nxi-1; i < nxt; i++) { /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { koff = 2*nxhd*k; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = 2*nxhd*k1; t1 = f[2*i+k1]; t2 = f[1+2*i+k1]; f[2*i+k1] = f[2*i+koff]; f[1+2*i+k1] = f[1+2*i+koff]; f[2*i+koff] = t1; f[1+2*i+koff] = t2; } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = 2*nxhd*(j + k1); j2 = 2*nxhd*(j + k2); t1 = conjf(sct[kmr*j]); t2 = t1*f[2*i+j2]; t3 = t1*f[1+2*i+j2]; f[2*i+j2] = f[2*i+j1] - t2; f[1+2*i+j2] = f[1+2*i+j1] - t3; f[2*i+j1] += t2; f[1+2*i+j1] += t3; } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void cwfft2rmx(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxhd, int nyd, int nxhyd, int nxyhd) { /* wrapper function for real to complex fft, with packed data */ /* parallelized with OpenMP */ /* local data */ int nxh, ny; static int nxi = 1, nyi = 1; /* calculate range of indices */ nxh = 1L<<(indx - 1); ny = 1L<<indy; /* inverse fourier transform */ if (isign < 0) { /* perform x fft */ cfft2rmxx(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); /* perform y fft */ cfft2rmxy(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); } /* forward fourier transform */ else if (isign > 0) { /* perform y fft */ cfft2rmxy(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); /* perform x fft */ cfft2rmxx(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); } return; } /*--------------------------------------------------------------------*/ void cwfft2rm2(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int nxhd, int nyd, int nxhyd, int nxyhd) { /* wrapper function for 2 2d real to complex ffts, with packed data */ /* parallelized with OpenMP */ /* local data */ int nxh, ny; static int nxi = 1, nyi = 1; /* calculate range of indices */ nxh = 1L<<(indx - 1); ny = 1L<<indy; /* inverse fourier transform */ if (isign < 0) { /* perform x fft */ cfft2rm2x(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); /* perform y fft */ cfft2rm2y(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); } /* forward fourier transform */ else if (isign > 0) { /* perform y fft */ cfft2rm2y(f,isign,mixup,sct,indx,indy,nxi,nxh,nxhd,nyd,nxhyd, nxyhd); /* perform x fft */ cfft2rm2x(f,isign,mixup,sct,indx,indy,nyi,ny,nxhd,nyd,nxhyd, nxyhd); } return; } /* Interfaces to Fortran */ /*--------------------------------------------------------------------*/ void cdistr2_(float *part, float *vtx, float *vty, float *vdx, float *vdy, int *npx, int *npy, int *idimp, int *nop, int *nx, int *ny, int *ipbc) { cdistr2(part,*vtx,*vty,*vdx,*vdy,*npx,*npy,*idimp,*nop,*nx,*ny,*ipbc); return; } /*--------------------------------------------------------------------*/ void cdblkp2l_(float *part, int *kpic, int *nppmx, int *idimp, int *nop, int *mx, int *my, int *mx1, int *mxy1, int *irc) { cdblkp2l(part,kpic,nppmx,*idimp,*nop,*mx,*my,*mx1,*mxy1,irc); return; } /*--------------------------------------------------------------------*/ void cppmovin2l_(float *part, float *ppart, int *kpic, int *nppmx, int *idimp, int *nop, int *mx, int *my, int *mx1, int *mxy1, int *irc) { cppmovin2l(part,ppart,kpic,*nppmx,*idimp,*nop,*mx,*my,*mx1,*mxy1, irc); return; } /*--------------------------------------------------------------------*/ void cppcheck2l_(float *ppart, int *kpic, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *mx1, int *my1, int *irc) { cppcheck2l(ppart,kpic,*idimp,*nppmx,*nx,*ny,*mx,*my,*mx1,*my1,irc); return; } /*--------------------------------------------------------------------*/ void cgppush2l_(float *ppart, float *fxy, int *kpic, float *qbm, float *dt, float *ek, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *nxv, int *nyv, int *mx1, int *mxy1, int *ipbc) { cgppush2l(ppart,fxy,kpic,*qbm,*dt,ek,*idimp,*nppmx,*nx,*ny,*mx,*my, *nxv,*nyv,*mx1,*mxy1,*ipbc); return; } /*--------------------------------------------------------------------*/ void cgppushf2l_(float *ppart, float *fxy, int *kpic, int *ncl, int *ihole, float *qbm, float *dt, float *ek, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *nxv, int *nyv, int *mx1, int *mxy1, int *ntmax, int *irc) { cgppushf2l(ppart,fxy,kpic,ncl,ihole,*qbm,*dt,ek,*idimp,*nppmx,*nx, *ny,*mx,*my,*nxv,*nyv,*mx1,*mxy1,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void cgppost2l_(float *ppart, float *q, int *kpic, float *qm, int *nppmx, int *idimp, int *mx, int *my, int *nxv, int *nyv, int *mx1, int *mxy1) { cgppost2l(ppart,q,kpic,*qm,*nppmx,*idimp,*mx,*my,*nxv,*nyv,*mx1, *mxy1); return; } /*--------------------------------------------------------------------*/ void cpporder2l_(float *ppart, float *ppbuff, int *kpic, int *ncl, int *ihole, int *idimp, int *nppmx, int *nx, int *ny, int *mx, int *my, int *mx1, int *my1, int *npbmx, int *ntmax, int *irc) { cpporder2l(ppart,ppbuff,kpic,ncl,ihole,*idimp,*nppmx,*nx,*ny,*mx,*my, *mx1,*my1,*npbmx,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void cpporderf2l_(float *ppart, float *ppbuff, int *kpic, int *ncl, int *ihole, int *idimp, int *nppmx, int *mx1, int *my1, int *npbmx, int *ntmax, int *irc) { cpporderf2l(ppart,ppbuff,kpic,ncl,ihole,*idimp,*nppmx,*mx1,*my1, *npbmx,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void ccguard2l_(float *fxy, int *nx, int *ny, int *nxe, int *nye) { ccguard2l(fxy,*nx,*ny,*nxe,*nye); return; } /*--------------------------------------------------------------------*/ void caguard2l_(float *q, int *nx, int *ny, int *nxe, int *nye) { caguard2l(q,*nx,*ny,*nxe,*nye); return; } /*--------------------------------------------------------------------*/ void cmpois22_(float complex *q, float complex *fxy, int *isign, float complex *ffc, float *ax, float *ay, float *affp, float *we, int *nx, int *ny, int *nxvh, int *nyv, int *nxhd, int *nyhd) { cmpois22(q,fxy,*isign,ffc,*ax,*ay,*affp,we,*nx,*ny,*nxvh,*nyv,*nxhd, *nyhd); return; } /*--------------------------------------------------------------------*/ void cwfft2rinit_(int *mixup, float complex *sct, int *indx, int *indy, int *nxhyd, int *nxyhd) { cwfft2rinit(mixup,sct,*indx,*indy,*nxhyd,*nxyhd); return; } /*--------------------------------------------------------------------*/ void cfft2rmxx_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nyi, int *nyp, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { cfft2rmxx(f,*isign,mixup,sct,*indx,*indy,*nyi,*nyp,*nxhd,*nyd,*nxhyd, *nxyhd); return; } /*--------------------------------------------------------------------*/ void cfft2rmxy_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nxi, int *nxp, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { cfft2rmxy(f,*isign,mixup,sct,*indx,*indy,*nxi,*nxp,*nxhd,*nyd,*nxhyd, *nxyhd); return; } /*--------------------------------------------------------------------*/ void cfft2rm2x_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nyi, int *nyp, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { cfft2rm2x(f,*isign,mixup,sct,*indx,*indy,*nyi,*nyp,*nxhd,*nyd,*nxhyd, *nxyhd); return; } /*--------------------------------------------------------------------*/ void cfft2rm2y_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nxi, int *nxp, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { cfft2rm2y(f,*isign,mixup,sct,*indx,*indy,*nxi,*nxp,*nxhd,*nyd,*nxhyd, *nxyhd); return; } /*--------------------------------------------------------------------*/ void cwfft2rmx_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { cwfft2rmx(f,*isign,mixup,sct,*indx,*indy,*nxhd,*nyd,*nxhyd,*nxyhd); return; } /*--------------------------------------------------------------------*/ void cwfft2rm2_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *nxhd, int *nyd, int *nxhyd, int *nxyhd) { cwfft2rm2(f,*isign,mixup,sct,*indx,*indy,*nxhd,*nyd,*nxhyd,*nxyhd); return; }
regionTest1.c
void foo(int a) { bar(a-1); #pragma omp parallel { int b; bar(a-1); b = 20; } } void bar(int a) { if (a > 10) { foo(a-1); } } int main () { int x; #pragma omp parallel { int x; x = 10 + 20; foo(x); } if (x < 10) { #pragma omp parallel { int y; y = 10; // foo(y); } } else { #pragma omp parallel { int z; z = 10; // foo(z); } } }
6a0cba_so4.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include <stdio.h> #include "omp.h" #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; }; int Kernel(struct dataobj *restrict block_sizes_vec, const float h_x, const float h_y, const float h_z, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict save_src_fxx_vec, struct dataobj *restrict save_src_fyy_vec, struct dataobj *restrict save_src_fzz_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict tau_sol_xx_vec, struct dataobj *restrict tau_sol_xy_vec, struct dataobj *restrict tau_sol_xz_vec, struct dataobj *restrict tau_sol_yy_vec, struct dataobj *restrict tau_sol_yz_vec, struct dataobj *restrict tau_sol_zz_vec, struct dataobj *restrict v_sol_x_vec, struct dataobj *restrict v_sol_y_vec, struct dataobj *restrict v_sol_z_vec, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine) { int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_fxx)[save_src_fxx_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fxx_vec->size[1]])save_src_fxx_vec->data; float(*restrict save_src_fyy)[save_src_fyy_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fyy_vec->size[1]])save_src_fyy_vec->data; float(*restrict save_src_fzz)[save_src_fzz_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fzz_vec->size[1]])save_src_fzz_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict tau_sol_xx)[tau_sol_xx_vec->size[1]][tau_sol_xx_vec->size[2]][tau_sol_xx_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xx_vec->size[1]][tau_sol_xx_vec->size[2]][tau_sol_xx_vec->size[3]])tau_sol_xx_vec->data; float(*restrict tau_sol_xy)[tau_sol_xy_vec->size[1]][tau_sol_xy_vec->size[2]][tau_sol_xy_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xy_vec->size[1]][tau_sol_xy_vec->size[2]][tau_sol_xy_vec->size[3]])tau_sol_xy_vec->data; float(*restrict tau_sol_xz)[tau_sol_xz_vec->size[1]][tau_sol_xz_vec->size[2]][tau_sol_xz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xz_vec->size[1]][tau_sol_xz_vec->size[2]][tau_sol_xz_vec->size[3]])tau_sol_xz_vec->data; float(*restrict tau_sol_yy)[tau_sol_yy_vec->size[1]][tau_sol_yy_vec->size[2]][tau_sol_yy_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_yy_vec->size[1]][tau_sol_yy_vec->size[2]][tau_sol_yy_vec->size[3]])tau_sol_yy_vec->data; float(*restrict tau_sol_yz)[tau_sol_yz_vec->size[1]][tau_sol_yz_vec->size[2]][tau_sol_yz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_yz_vec->size[1]][tau_sol_yz_vec->size[2]][tau_sol_yz_vec->size[3]])tau_sol_yz_vec->data; float(*restrict tau_sol_zz)[tau_sol_zz_vec->size[1]][tau_sol_zz_vec->size[2]][tau_sol_zz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_zz_vec->size[1]][tau_sol_zz_vec->size[2]][tau_sol_zz_vec->size[3]])tau_sol_zz_vec->data; float(*restrict v_sol_x)[v_sol_x_vec->size[1]][v_sol_x_vec->size[2]][v_sol_x_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_x_vec->size[1]][v_sol_x_vec->size[2]][v_sol_x_vec->size[3]])v_sol_x_vec->data; float(*restrict v_sol_y)[v_sol_y_vec->size[1]][v_sol_y_vec->size[2]][v_sol_y_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_y_vec->size[1]][v_sol_y_vec->size[2]][v_sol_y_vec->size[3]])v_sol_y_vec->data; float(*restrict v_sol_z)[v_sol_z_vec->size[1]][v_sol_z_vec->size[2]][v_sol_z_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_z_vec->size[1]][v_sol_z_vec->size[2]][v_sol_z_vec->size[3]])v_sol_z_vec->data; /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); int xb_size = block_sizes[0]; int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; int sf = 4; int t_blk_size = 2 * sf * (time_M - time_m); /* int xb_size = 64; int yb_size = 64; x0_blk0_size = 8; y0_blk0_size = 8; */ printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size , yb_size , x0_blk0_size, y0_blk0_size); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size) { //printf(" Change of outer xblock %d \n", xb); for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size) { for (int time = t_blk, t0 = (time) % (2), t1 = (time + 1) % (2); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1)) + 1) % (2), t1 = (((time / sf) % (time_M - time_m + 1))) % (2)) { int tw = ((time / sf) % (time_M - time_m + 1)); #pragma omp parallel num_threads(nthreads) { //printf(" Change of time block : %d \n", tw); #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { //printf(" Change of inner xblock %d \n", x0_blk0); for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { //printf(" Updating velocity x %d \n", x - time + 4); //printf(" \n PDE update : \n"); #pragma omp simd aligned(tau_sol_xx, tau_sol_xz, tau_sol_zz, v_sol_x, v_sol_z : 64) for (int z = z_m; z <= z_M; z += 1) { //printf(" Updating velocity x %d z: %d \n", x - time + 4, z + 4); float r26 = 1.0 / h_z; float r25 = 1.0 / h_y; float r24 = 1.0 / h_x; v_sol_x[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xx[t0][x - time + 3][y - time + 4][z + 4] - tau_sol_xx[t0][x - time + 6][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xx[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_xx[t0][x - time + 5][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_xy[t0][x - time + 4][y - time + 2][z + 4] - tau_sol_xy[t0][x - time + 4][y - time + 5][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xy[t0][x - time + 4][y - time + 3][z + 4] + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_xz[t0][x - time + 4][y - time + 4][z + 2] - tau_sol_xz[t0][x - time + 4][y - time + 4][z + 5]) + 7.36569563735987e-1F * (-tau_sol_xz[t0][x - time + 4][y - time + 4][z + 3] + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4])) + v_sol_x[t0][x - time + 4][y - time + 4][z + 4]; v_sol_y[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xy[t0][x - time + 2][y - time + 4][z + 4] - tau_sol_xy[t0][x - time + 5][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xy[t0][x - time + 3][y - time + 4][z + 4] + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_yy[t0][x - time + 4][y - time + 3][z + 4] - tau_sol_yy[t0][x - time + 4][y - time + 6][z + 4]) + 7.36569563735987e-1F * (-tau_sol_yy[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_yy[t0][x - time + 4][y - time + 5][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_yz[t0][x - time + 4][y - time + 4][z + 2] - tau_sol_yz[t0][x - time + 4][y - time + 4][z + 5]) + 7.36569563735987e-1F * (-tau_sol_yz[t0][x - time + 4][y - time + 4][z + 3] + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4])) + v_sol_y[t0][x - time + 4][y - time + 4][z + 4]; v_sol_z[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xz[t0][x - time + 2][y - time + 4][z + 4] - tau_sol_xz[t0][x - time + 5][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xz[t0][x - time + 3][y - time + 4][z + 4] + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_yz[t0][x - time + 4][y - time + 2][z + 4] - tau_sol_yz[t0][x - time + 4][y - time + 5][z + 4]) + 7.36569563735987e-1F * (-tau_sol_yz[t0][x - time + 4][y - time + 3][z + 4] + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_zz[t0][x - time + 4][y - time + 4][z + 3] - tau_sol_zz[t0][x - time + 4][y - time + 4][z + 6]) + 7.36569563735987e-1F * (-tau_sol_zz[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_zz[t0][x - time + 4][y - time + 4][z + 5])) + v_sol_z[t0][x - time + 4][y - time + 4][z + 4]; } } } } } } #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb - 2); x0_blk0 <= +min((x_M + time), (xb - 2 + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb - 2); y0_blk0 <= +min((y_M + time), (yb - 2 + yb_size)); y0_blk0 += y0_blk0_size) { for (int x = x0_blk0; x <= min(min((x_M + time), (xb - 2 + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb - 2 + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { //printf(" Updating stress x %d \n", x - time + 4); #pragma omp simd aligned(tau_sol_xx, tau_sol_xz, tau_sol_zz, v_sol_x, v_sol_z : 64) for (int z = z_m; z <= z_M; z += 1) { //printf(" Updating x %d z: %d \n", x - time + 4, z + 4); float r41 = -v_sol_z[t1][x - time + 4][y - time + 4][z + 4]; float r40 = -v_sol_y[t1][x - time + 4][y - time + 4][z + 4]; float r39 = -v_sol_x[t1][x - time + 4][y - time + 4][z + 4]; float r38 = v_sol_y[t1][x - time + 4][y - time + 2][z + 4] - v_sol_y[t1][x - time + 4][y - time + 5][z + 4]; float r37 = -v_sol_y[t1][x - time + 4][y - time + 3][z + 4] + v_sol_y[t1][x - time + 4][y - time + 4][z + 4]; float r36 = v_sol_z[t1][x - time + 4][y - time + 4][z + 2] - v_sol_z[t1][x - time + 4][y - time + 4][z + 5]; float r35 = -v_sol_z[t1][x - time + 4][y - time + 4][z + 3] + v_sol_z[t1][x - time + 4][y - time + 4][z + 4]; float r34 = v_sol_x[t1][x - time + 2][y - time + 4][z + 4] - v_sol_x[t1][x - time + 5][y - time + 4][z + 4]; float r33 = -v_sol_x[t1][x - time + 3][y - time + 4][z + 4] + v_sol_x[t1][x - time + 4][y - time + 4][z + 4]; float r32 = 1.0 / h_y; float r31 = 1.0 / h_z; float r30 = 1.0 / h_x; float r29 = r30 * (4.7729707730092F * r33 + 1.76776695286347e-1F * r34); float r28 = r31 * (4.7729707730092F * r35 + 1.76776695286347e-1F * r36); float r27 = r32 * (4.7729707730092F * r37 + 1.76776695286347e-1F * r38); tau_sol_xx[t1][x - time + 4][y - time + 4][z + 4] = r27 + r28 + r30 * (9.54594154601839F * r33 + 3.53553390572694e-1F * r34) + tau_sol_xx[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_xy[t1][x - time + 4][y - time + 4][z + 4] = r30 * (2.3864853865046F * (r40 + v_sol_y[t1][x - time + 5][y - time + 4][z + 4]) + 8.83883476431735e-2F * (v_sol_y[t1][x - time + 3][y - time + 4][z + 4] - v_sol_y[t1][x - time + 6][y - time + 4][z + 4])) + r32 * (2.3864853865046F * (r39 + v_sol_x[t1][x - time + 4][y - time + 5][z + 4]) + 8.83883476431735e-2F * (v_sol_x[t1][x - time + 4][y - time + 3][z + 4] - v_sol_x[t1][x - time + 4][y - time + 6][z + 4])) + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_xz[t1][x - time + 4][y - time + 4][z + 4] = r30 * (2.3864853865046F * (r41 + v_sol_z[t1][x - time + 5][y - time + 4][z + 4]) + 8.83883476431735e-2F * (v_sol_z[t1][x - time + 3][y - time + 4][z + 4] - v_sol_z[t1][x - time + 6][y - time + 4][z + 4])) + r31 * (2.3864853865046F * (r39 + v_sol_x[t1][x - time + 4][y - time + 4][z + 5]) + 8.83883476431735e-2F * (v_sol_x[t1][x - time + 4][y - time + 4][z + 3] - v_sol_x[t1][x - time + 4][y - time + 4][z + 6])) + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_yy[t1][x - time + 4][y - time + 4][z + 4] = r28 + r29 + r32 * (9.54594154601839F * r37 + 3.53553390572694e-1F * r38) + tau_sol_yy[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_yz[t1][x - time + 4][y - time + 4][z + 4] = r31 * (2.3864853865046F * (r40 + v_sol_y[t1][x - time + 4][y - time + 4][z + 5]) + 8.83883476431735e-2F * (v_sol_y[t1][x - time + 4][y - time + 4][z + 3] - v_sol_y[t1][x - time + 4][y - time + 4][z + 6])) + r32 * (2.3864853865046F * (r41 + v_sol_z[t1][x - time + 4][y - time + 5][z + 4]) + 8.83883476431735e-2F * (v_sol_z[t1][x - time + 4][y - time + 3][z + 4] - v_sol_z[t1][x - time + 4][y - time + 6][z + 4])) + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_zz[t1][x - time + 4][y - time + 4][z + 4] = r27 + r29 + r31 * (9.54594154601839F * r35 + 3.53553390572694e-1F * r36) + tau_sol_zz[t0][x - time + 4][y - time + 4][z + 4]; } for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1) { //printf("\n Source_injection at : "); int zind = sp_source_mask[x - time][y - time][sp_zi]; float r0 = save_src_fxx[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; float r1 = save_src_fyy[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; float r2 = save_src_fzz[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; tau_sol_xx[t1][x - time + 4][y - time + 4][zind + 4] += r0; tau_sol_yy[t1][x - time + 4][y - time + 4][zind + 4] += r1; tau_sol_zz[t1][x - time + 4][y - time + 4][zind + 4] += r2; //printf(" Time %d , at : %d, %d \n", tw, x - time + 4, zind + 4); } } } } } } } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; return 0; }
GB_binop__lxor_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__lxor_int64 // A.*B function (eWiseMult): GB_AemultB__lxor_int64 // A*D function (colscale): GB_AxD__lxor_int64 // D*A function (rowscale): GB_DxB__lxor_int64 // C+=B function (dense accum): GB_Cdense_accumB__lxor_int64 // C+=b function (dense accum): GB_Cdense_accumb__lxor_int64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lxor_int64 // C=scalar+B GB_bind1st__lxor_int64 // C=scalar+B' GB_bind1st_tran__lxor_int64 // C=A+scalar GB_bind2nd__lxor_int64 // C=A'+scalar GB_bind2nd_tran__lxor_int64 // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = ((aij != 0) != (bij != 0)) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = ((x != 0) != (y != 0)) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LXOR || GxB_NO_INT64 || GxB_NO_LXOR_INT64) //------------------------------------------------------------------------------ // 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__lxor_int64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__lxor_int64 ( 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__lxor_int64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__lxor_int64 ( 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 int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__lxor_int64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__lxor_int64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__lxor_int64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__lxor_int64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t bij = Bx [p] ; Cx [p] = ((x != 0) != (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__lxor_int64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t aij = Ax [p] ; Cx [p] = ((aij != 0) != (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__lxor_int64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__lxor_int64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
lab4_optimized.c
#include <stdio.h> #include "matrix.h" #include "data.h" #include "time.h" #define NUM_THREADS 8 int main(int argc, char **argv) { N = (int) strtol(argv[1], NULL, 10); init(); // Second matrix is transposed double **mat2_trans = matTrans(mat2); // Number of threads were defined according to available number of physical (2) and logical (4) cores // OpenMP scheduling was set to static because all threads have same workload markStartTime(); #pragma omp parallel for num_threads(NUM_THREADS) // Loop nest optimization. Calculate two rows and two columns in one iteration for (int i = 0; i < N; i += 2) { // Preload mat1 rows double *mat1_row0 = mat1[i]; double *mat1_row1 = mat1[i + 1]; double sum00, sum01, sum10, sum11; // Iterate for (int j = 0; j < N; j += 2) { // Preload mat2_trans rows double *mat2_col0 = mat2_trans[j]; double *mat2_col1 = mat2_trans[j + 1]; // Initialize sums to zero sum00 = 0, sum01 = 0, sum10 = 0, sum11 = 0; for (int k = 0; k < N; k += 2) { // Since pointer anyways increments by 1, change to ++. Group multiple commands together to reduce // for loop iterations sum00 += mat1_row0[k] * mat2_col0[k] + mat1_row0[k + 1] * mat2_col0[k + 1]; sum01 += mat1_row0[k] * mat2_col1[k] + mat1_row0[k + 1] * mat2_col1[k + 1]; sum10 += mat1_row1[k] * mat2_col0[k] + mat1_row1[k + 1] * mat2_col0[k + 1]; sum11 += mat1_row1[k] * mat2_col1[k] + mat1_row1[k + 1] * mat2_col1[k + 1]; } mat3[i][j] = sum00; mat3[i][j + 1] = sum01; mat3[i + 1][j] = sum10; mat3[i + 1][j + 1] = sum11; } } markStopTime(); cleanup(); printf("%d\n", getMillis()); return 0; }
test1.c
/* program main implicit none integer :: a = 10 !$omp target data map(tofrom: a) !$omp target map(tofrom: a) a = a + 1 !$omp end target !$omp target update from(a) !$omp end target data a = -15 !$omp target update from(a) print *, a !<-- expect -15; actual 11 end program main 2) segfault $>cat t.f program main implicit none integer :: a = 10 !$omp target map(tofrom: a) a = a + 1 !$omp end target !$omp target update from(a) a = -15 !$omp target update from(a) print *, a !<-- expect -15; actual segfault end program main */ #include <stdio.h> #define TEST1 1 #define TEST2 1 int main() { int a; // test 1 #if TEST1 a = 10; #pragma omp target data map(tofrom: a) { #pragma omp target map(tofrom: a) { a = a + 1; } //printf("test 1: a is %d (after target)\n", a); #pragma omp target update from(a) } //printf("test 1: a is %d (after target data)\n", a); a = -15; #pragma omp target update from(a) printf("test 1: a is %d\n", a); #endif #if TEST2 // test 2 a = 10; #pragma omp target map(tofrom: a) { a = a + 1; } #pragma omp target update from(a) a = -15; #pragma omp target update from(a) #endif printf("test 2: a is %d\n", a); return 1; }
GB_unaryop__ainv_int16_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_int16_fp64 // op(A') function: GB_tran__ainv_int16_fp64 // C type: int16_t // A type: double // cast: int16_t cij ; GB_CAST_SIGNED(cij,aij,16) // unaryop: cij = -aij #define GB_ATYPE \ double #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, aij) \ int16_t z ; GB_CAST_SIGNED(z,aij,16) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_INT16 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int16_fp64 ( int16_t *Cx, // Cx and Ax may be aliased double *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_int16_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
block-5.c
// { dg-do compile } void foo() { #pragma omp master { goto bad1; // { dg-error "invalid branch to/from OpenMP structured block" } } #pragma omp master { bad1: return; // { dg-error "invalid branch to/from OpenMP structured block" } } }
ZQ_CNN_BBoxUtils.h
#ifndef _ZQ_CNN_BBOX_UTILS_H_ #define _ZQ_CNN_BBOX_UTILS_H_ #pragma once #include "ZQ_CNN_BBox.h" #include <string> #include <math.h> #include <algorithm> namespace ZQ { class ZQ_CNN_BBoxUtils { public: enum PriorBoxCodeType { PriorBoxCodeType_CORNER = 0, PriorBoxCodeType_CORNER_SIZE, PriorBoxCodeType_CENTER_SIZE }; static bool _cmp_score(const ZQ_CNN_OrderScore& lsh, const ZQ_CNN_OrderScore& rsh) { return lsh.score < rsh.score; } static void _nms(std::vector<ZQ_CNN_BBox> &boundingBox, std::vector<ZQ_CNN_OrderScore> &bboxScore, const float overlap_threshold, const std::string& modelname = "Union", int overlap_count_thresh = 0, int thread_num = 1) { if (boundingBox.empty() || overlap_threshold >= 1.0) { return; } std::vector<int> heros; std::vector<int> overlap_num; //sort the score sort(bboxScore.begin(), bboxScore.end(), _cmp_score); int order = 0; float IOU = 0; float maxX = 0; float maxY = 0; float minX = 0; float minY = 0; while (bboxScore.size() > 0) { order = bboxScore.back().oriOrder; bboxScore.pop_back(); if (order < 0)continue; heros.push_back(order); int cur_overlap = 0; boundingBox[order].exist = false;//delete it int box_num = boundingBox.size(); if (thread_num == 1) { for (int num = 0; num < box_num; num++) { if (boundingBox[num].exist) { //the iou maxY = __max(boundingBox[num].row1, boundingBox[order].row1); maxX = __max(boundingBox[num].col1, boundingBox[order].col1); minY = __min(boundingBox[num].row2, boundingBox[order].row2); minX = __min(boundingBox[num].col2, boundingBox[order].col2); //maxX1 and maxY1 reuse maxX = __max(minX - maxX + 1, 0); maxY = __max(minY - maxY + 1, 0); //IOU reuse for the area of two bbox IOU = maxX * maxY; float area1 = boundingBox[num].area; float area2 = boundingBox[order].area; if (!modelname.compare("Union")) IOU = IOU / (area1 + area2 - IOU); else if (!modelname.compare("Min")) { IOU = IOU / __min(area1, area2); } if (IOU > overlap_threshold) { cur_overlap++; boundingBox[num].exist = false; for (std::vector<ZQ_CNN_OrderScore>::iterator it = bboxScore.begin(); it != bboxScore.end(); it++) { if ((*it).oriOrder == num) { (*it).oriOrder = -1; break; } } } } } } else { int chunk_size = ceil(box_num / thread_num); #pragma omp parallel for schedule(static, chunk_size) num_threads(thread_num) for (int num = 0; num < box_num; num++) { if (boundingBox.at(num).exist) { //the iou maxY = __max(boundingBox[num].row1, boundingBox[order].row1); maxX = __max(boundingBox[num].col1, boundingBox[order].col1); minY = __min(boundingBox[num].row2, boundingBox[order].row2); minX = __min(boundingBox[num].col2, boundingBox[order].col2); //maxX1 and maxY1 reuse maxX = __max(minX - maxX + 1, 0); maxY = __max(minY - maxY + 1, 0); //IOU reuse for the area of two bbox IOU = maxX * maxY; float area1 = boundingBox[num].area; float area2 = boundingBox[order].area; if (!modelname.compare("Union")) IOU = IOU / (area1 + area2 - IOU); else if (!modelname.compare("Min")) { IOU = IOU / __min(area1, area2); } if (IOU > overlap_threshold) { cur_overlap++; boundingBox.at(num).exist = false; for (std::vector<ZQ_CNN_OrderScore>::iterator it = bboxScore.begin(); it != bboxScore.end(); it++) { if ((*it).oriOrder == num) { (*it).oriOrder = -1; break; } } } } } } overlap_num.push_back(cur_overlap); } for (int i = 0; i < heros.size(); i++) { if(!boundingBox[heros[i]].need_check_overlap_count || overlap_num[i] >= overlap_count_thresh) boundingBox[heros[i]].exist = true; } //clear exist= false; for (int i = boundingBox.size() - 1; i >= 0; i--) { if (!boundingBox[i].exist) { boundingBox.erase(boundingBox.begin() + i); } } } static void _refine_and_square_bbox(std::vector<ZQ_CNN_BBox> &vecBbox, const int width, const int height, bool square = true) { float bbw = 0, bbh = 0, bboxSize = 0; float h = 0, w = 0; float x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (std::vector<ZQ_CNN_BBox>::iterator it = vecBbox.begin(); it != vecBbox.end(); it++) { if ((*it).exist) { bbh = (*it).row2 - (*it).row1 + 1; bbw = (*it).col2 - (*it).col1 + 1; y1 = (*it).row1 + (*it).regreCoord[1] * bbh; x1 = (*it).col1 + (*it).regreCoord[0] * bbw; y2 = (*it).row2 + (*it).regreCoord[3] * bbh; x2 = (*it).col2 + (*it).regreCoord[2] * bbw; w = x2 - x1 + 1; h = y2 - y1 + 1; if (square) { bboxSize = (h > w) ? h : w; y1 = y1 + h*0.5 - bboxSize*0.5; x1 = x1 + w*0.5 - bboxSize*0.5; (*it).row2 = round(y1 + bboxSize - 1); (*it).col2 = round(x1 + bboxSize - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); } else { (*it).row2 = round(y1 + h - 1); (*it).col2 = round(x1 + w - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); } //boundary check /*if ((*it).row1 < 0)(*it).row1 = 0; if ((*it).col1 < 0)(*it).col1 = 0; if ((*it).row2 > height)(*it).row2 = height - 1; if ((*it).col2 > width)(*it).col2 = width - 1;*/ it->area = (it->row2 - it->row1)*(it->col2 - it->col1); } } } static void _square_bbox(std::vector<ZQ_CNN_BBox> &vecBbox, const int width, const int height) { float bbw = 0, bbh = 0, bboxSize = 0; float h = 0, w = 0; float x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (std::vector<ZQ_CNN_BBox>::iterator it = vecBbox.begin(); it != vecBbox.end(); it++) { if ((*it).exist) { y1 = (*it).row1; x1 = (*it).col1; h = (*it).row2 - (*it).row1 + 1; w = (*it).col2 - (*it).col1 + 1; bboxSize = (h > w) ? h : w; y1 = y1 + h*0.5 - bboxSize*0.5; x1 = x1 + w*0.5 - bboxSize*0.5; (*it).row2 = round(y1 + bboxSize - 1); (*it).col2 = round(x1 + bboxSize - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); //boundary check /*if ((*it).row1 < 0)(*it).row1 = 0; if ((*it).col1 < 0)(*it).col1 = 0; if ((*it).row2 > height)(*it).row2 = height - 1; if ((*it).col2 > width)(*it).col2 = width - 1;*/ it->area = (it->row2 - it->row1)*(it->col2 - it->col1); } } } static bool DecodeBBoxesAll(const std::vector<ZQ_CNN_LabelBBox>& all_loc_preds, const std::vector<ZQ_CNN_NormalizedBBox>& prior_bboxes, const std::vector<std::vector<float> >& prior_variances, const int num, const bool share_location, const int num_loc_classes, const int background_label_id, const PriorBoxCodeType code_type, const bool variance_encoded_in_target, const bool clip, std::vector<ZQ_CNN_LabelBBox>* all_decode_bboxes) { if (all_loc_preds.size() != num) return false; all_decode_bboxes->clear(); all_decode_bboxes->resize(num); for (int i = 0; i < num; ++i) { // Decode predictions into bboxes. ZQ_CNN_LabelBBox& decode_bboxes = (*all_decode_bboxes)[i]; for (int c = 0; c < num_loc_classes; ++c) { int label = share_location ? -1 : c; if (label == background_label_id) { // Ignore background class. continue; } if (all_loc_preds[i].find(label) == all_loc_preds[i].end()) { // Something bad happened if there are no predictions for current label. //LOG(FATAL) << "Could not find location predictions for label " << label; } const std::vector<ZQ_CNN_NormalizedBBox>& label_loc_preds = all_loc_preds[i].find(label)->second; if (!DecodeBBoxes(prior_bboxes, prior_variances, code_type, variance_encoded_in_target, clip, label_loc_preds, &(decode_bboxes[label]))) return false; } } return true; } static bool DecodeBBoxes( const std::vector<ZQ_CNN_NormalizedBBox>& prior_bboxes, const std::vector<std::vector<float> >& prior_variances, const PriorBoxCodeType code_type, const bool variance_encoded_in_target, const bool clip_bbox, const std::vector<ZQ_CNN_NormalizedBBox>& bboxes, std::vector<ZQ_CNN_NormalizedBBox>* decode_bboxes) { if (prior_bboxes.size() != prior_variances.size()) return false; if (prior_bboxes.size() != bboxes.size()) return false; int num_bboxes = prior_bboxes.size(); if (num_bboxes >= 1) { if (prior_variances[0].size() != 4) return false; } decode_bboxes->clear(); for (int i = 0; i < num_bboxes; ++i) { ZQ_CNN_NormalizedBBox decode_bbox; if (!DecodeBBox(prior_bboxes[i], prior_variances[i], code_type, variance_encoded_in_target, clip_bbox, bboxes[i], &decode_bbox)) return false; decode_bboxes->push_back(decode_bbox); } return true; } static bool DecodeBBox( const ZQ_CNN_NormalizedBBox& prior_bbox, const std::vector<float>& prior_variance, const PriorBoxCodeType code_type, const bool variance_encoded_in_target, const bool clip_bbox, const ZQ_CNN_NormalizedBBox& bbox, ZQ_CNN_NormalizedBBox* decode_bbox) { if (code_type == PriorBoxCodeType_CORNER) { if (variance_encoded_in_target) { // variance is encoded in target, we simply need to add the offset // predictions. decode_bbox->col1 = prior_bbox.col1 + bbox.col1; decode_bbox->col2 = prior_bbox.col2 + bbox.col2; decode_bbox->row1 = prior_bbox.row1 + bbox.row1; decode_bbox->row2 = prior_bbox.row2 + bbox.row2; } else { // variance is encoded in bbox, we need to scale the offset accordingly. decode_bbox->col1 = prior_bbox.col1 + prior_variance[0] * bbox.col1; decode_bbox->row1 = prior_bbox.row1 + prior_variance[1] * bbox.row1; decode_bbox->col2 = prior_bbox.col2 + prior_variance[2] * bbox.col2; decode_bbox->row2 = prior_bbox.row2 + prior_variance[3] * bbox.row2; } } else if (code_type == PriorBoxCodeType_CENTER_SIZE) { float prior_width = prior_bbox.col2 - prior_bbox.col1; if (prior_width < 0) { // return false; printf("x = [%f , %f]\n", prior_bbox.col1, prior_bbox.col2); } float prior_height = prior_bbox.row2 - prior_bbox.row1; if (prior_height < 0) { //return false; printf("y = [%f , %f]\n", prior_bbox.row1, prior_bbox.row2); } float prior_center_x = (prior_bbox.col1 + prior_bbox.col2) / 2.; float prior_center_y = (prior_bbox.row1 + prior_bbox.row2) / 2.; float decode_bbox_center_x, decode_bbox_center_y; float decode_bbox_width, decode_bbox_height; if (variance_encoded_in_target) { // variance is encoded in target, we simply need to retore the offset // predictions. decode_bbox_center_x = bbox.col1 * prior_width + prior_center_x; decode_bbox_center_y = bbox.row1 * prior_height + prior_center_y; decode_bbox_width = exp(bbox.col2) * prior_width; decode_bbox_height = exp(bbox.row2) * prior_height; } else { // variance is encoded in bbox, we need to scale the offset accordingly. decode_bbox_center_x = prior_variance[0] * bbox.col1 * prior_width + prior_center_x; decode_bbox_center_y = prior_variance[1] * bbox.row1 * prior_height + prior_center_y; decode_bbox_width = exp(prior_variance[2] * bbox.col2) * prior_width; decode_bbox_height = exp(prior_variance[3] * bbox.row2) * prior_height; } decode_bbox->col1 = decode_bbox_center_x - decode_bbox_width / 2.; decode_bbox->row1 = decode_bbox_center_y - decode_bbox_height / 2.; decode_bbox->col2 = decode_bbox_center_x + decode_bbox_width / 2.; decode_bbox->row2 = decode_bbox_center_y + decode_bbox_height / 2.; } else if (code_type == PriorBoxCodeType_CORNER_SIZE) { float prior_width = prior_bbox.col2 - prior_bbox.col1; if (prior_width < 0) { //return false; printf("x = [%f , %f]\n", prior_bbox.col1, prior_bbox.col2); } float prior_height = prior_bbox.row2 - prior_bbox.row1; if (prior_height < 0) { // return false; printf("y = [%f , %f]\n", prior_bbox.row1, prior_bbox.row2); } if (variance_encoded_in_target) { // variance is encoded in target, we simply need to add the offset // predictions. decode_bbox->col1 = prior_bbox.col1 + bbox.col1 * prior_width; decode_bbox->row1 = prior_bbox.row1 + bbox.row1 * prior_height; decode_bbox->col2 = prior_bbox.col2 + bbox.col2 * prior_width; decode_bbox->row2 = prior_bbox.row2 + bbox.row2 * prior_height; } else { // variance is encoded in bbox, we need to scale the offset accordingly. decode_bbox->col1 = prior_bbox.col1 + prior_variance[0] * bbox.col1 * prior_width; decode_bbox->row1 = prior_bbox.row1 + prior_variance[1] * bbox.row1 * prior_height; decode_bbox->col2 = prior_bbox.col2 + prior_variance[2] * bbox.col2 * prior_width; decode_bbox->row2 = prior_bbox.row2 + prior_variance[3] * bbox.row2 * prior_height; } } else { printf("unknown code type\n"); return false; } float bbox_size = BBoxSize(*decode_bbox, true); decode_bbox->size = bbox_size; if (clip_bbox) { ClipBBox(*decode_bbox, decode_bbox); } return true; } static float BBoxSize(const ZQ_CNN_NormalizedBBox& bbox, const bool normalized) { if (bbox.col2 < bbox.col1 || bbox.row2 < bbox.row1) { // If bbox is invalid (e.g. xmax < xmin or ymax < ymin), return 0. return 0; } else { float width = bbox.col2 - bbox.col1; float height = bbox.row2 - bbox.row1; if (normalized) { return width * height; } else { // If bbox is not within range [0, 1]. return (width + 1) * (height + 1); } } } static void ClipBBox(const ZQ_CNN_NormalizedBBox& bbox, ZQ_CNN_NormalizedBBox* clip_bbox) { clip_bbox->col1 = std::max(std::min(bbox.col1, 1.f), 0.f); clip_bbox->row1 = std::max(std::min(bbox.row1, 1.f), 0.f); clip_bbox->col2 = std::max(std::min(bbox.col2, 1.f), 0.f); clip_bbox->row2 = std::max(std::min(bbox.row2, 1.f), 0.f); clip_bbox->size = BBoxSize(*clip_bbox, true); clip_bbox->difficult = bbox.difficult; } static bool GetLocPredictions(const float* loc_data, const int num, const int num_preds_per_class, const int num_loc_classes, const bool share_location, std::vector<ZQ_CNN_LabelBBox>* loc_preds) { loc_preds->clear(); if (share_location) { if (num_loc_classes != 1) return false; } loc_preds->resize(num); for (int i = 0; i < num; i++) { ZQ_CNN_LabelBBox& label_bbox = (*loc_preds)[i]; for (int p = 0; p < num_preds_per_class; p++) { int start_idx = p * num_loc_classes * 4; for (int c = 0; c < num_loc_classes; c++) { int label = share_location ? -1 : c; if (label_bbox.find(label) == label_bbox.end()) { label_bbox[label].resize(num_preds_per_class); } label_bbox[label][p].col1 = loc_data[start_idx + c * 4]; label_bbox[label][p].row1 = loc_data[start_idx + c * 4 + 1]; label_bbox[label][p].col2 = loc_data[start_idx + c * 4 + 2]; label_bbox[label][p].row2 = loc_data[start_idx + c * 4 + 3]; } } loc_data += num_preds_per_class * num_loc_classes * 4; } return true; } static void TransformLocations_MXNET(float *out, const float *anchors, const float *loc_pred, const bool clip, const float vx, const float vy, const float vw, const float vh) { // transform predictions to detection results float al = anchors[0]; float at = anchors[1]; float ar = anchors[2]; float ab = anchors[3]; float aw = ar - al; float ah = ab - at; float ax = (al + ar) / 2.f; float ay = (at + ab) / 2.f; float px = loc_pred[0]; float py = loc_pred[1]; float pw = loc_pred[2]; float ph = loc_pred[3]; float ox = px * vx * aw + ax; float oy = py * vy * ah + ay; float ow = exp(pw * vw) * aw / 2; float oh = exp(ph * vh) * ah / 2; out[0] = clip ? __max(0, __min(1, ox - ow)) : (ox - ow); out[1] = clip ? __max(0, __min(1, oy - oh)) : (oy - oh); out[2] = clip ? __max(0, __min(1, ox + ow)) : (ox + ow); out[3] = clip ? __max(0, __min(1, oy + oh)) : (oy + oh); } static void GetConfidenceScores(const float* conf_data, const int num, const int num_preds_per_class, const int num_classes, std::vector<std::map<int, std::vector<float> > >* conf_preds) { conf_preds->clear(); conf_preds->resize(num); for (int i = 0; i < num; ++i) { std::map<int, std::vector<float> >& label_scores = (*conf_preds)[i]; for (int p = 0; p < num_preds_per_class; ++p) { int start_idx = p * num_classes; for (int c = 0; c < num_classes; ++c) { label_scores[c].push_back(conf_data[start_idx + c]); } } conf_data += num_preds_per_class * num_classes; } } static void GetConfidenceScores(const float* conf_data, const int num, const int num_preds_per_class, const int num_classes, const bool class_major, std::vector<std::map<int, std::vector<float> > >* conf_preds) { conf_preds->clear(); conf_preds->resize(num); for (int i = 0; i < num; ++i) { std::map<int, std::vector<float> >& label_scores = (*conf_preds)[i]; if (class_major) { for (int c = 0; c < num_classes; ++c) { label_scores[c].assign(conf_data, conf_data + num_preds_per_class); conf_data += num_preds_per_class; } } else { for (int p = 0; p < num_preds_per_class; ++p) { int start_idx = p * num_classes; for (int c = 0; c < num_classes; ++c) { label_scores[c].push_back(conf_data[start_idx + c]); } } conf_data += num_preds_per_class * num_classes; } } } static void GetPriorBBoxes(const float* prior_data, const int num_priors, std::vector<ZQ_CNN_NormalizedBBox>* prior_bboxes, std::vector<std::vector<float> >* prior_variances) { prior_bboxes->clear(); prior_variances->clear(); for (int i = 0; i < num_priors; ++i) { int start_idx = i * 4; ZQ_CNN_NormalizedBBox bbox; bbox.col1 = prior_data[start_idx]; bbox.row1 = prior_data[start_idx + 1]; bbox.col2 = prior_data[start_idx + 2]; bbox.row2 = prior_data[start_idx + 3]; float bbox_size = BBoxSize(bbox, true); bbox.size = bbox_size; prior_bboxes->push_back(bbox); } for (int i = 0; i < num_priors;i++) { int start_idx = (num_priors + i) * 4; std::vector<float> var; for (int j = 0; j < 4; ++j) { var.push_back(prior_data[start_idx + j]); } prior_variances->push_back(var); } } static bool ApplyNMSFast(const std::vector<ZQ_CNN_NormalizedBBox>& bboxes, const std::vector<float>& scores, const float score_threshold, const float nms_threshold, const float eta, const int top_k, std::vector<int>* indices) { // Sanity check. if (bboxes.size() != scores.size()) { printf("bboxes and scores have different size.\n"); return false; } // Get top_k scores (with corresponding indices). std::vector<std::pair<float, int> > score_index_vec; GetMaxScoreIndex(scores, score_threshold, top_k, &score_index_vec); // Do nms. float adaptive_threshold = nms_threshold; indices->clear(); while (score_index_vec.size() != 0) { const int idx = score_index_vec.front().second; bool keep = true; for (int k = 0; k < indices->size(); ++k) { if (keep) { const int kept_idx = (*indices)[k]; float overlap = JaccardOverlap(bboxes[idx], bboxes[kept_idx], true); keep = overlap <= adaptive_threshold; } else { break; } } if (keep) { indices->push_back(idx); } score_index_vec.erase(score_index_vec.begin()); if (keep && eta < 1 && adaptive_threshold > 0.5) { adaptive_threshold *= eta; } } return true; } static void GetMaxScoreIndex(const std::vector<float>& scores, const float threshold, const int top_k, std::vector<std::pair<float, int> >* score_index_vec) { // Generate index score pairs. for (int i = 0; i < scores.size(); ++i) { if (scores[i] > threshold) { score_index_vec->push_back(std::make_pair(scores[i], i)); } } // Sort the score pair according to the scores in descending order std::stable_sort(score_index_vec->begin(), score_index_vec->end(), SortScorePairDescend<int>); // Keep top_k scores if needed. if (top_k > -1 && top_k < score_index_vec->size()) { score_index_vec->resize(top_k); } } template <typename T> static bool SortScorePairDescend(const std::pair<float, T>& pair1, const std::pair<float, T>& pair2) { return pair1.first > pair2.first; } static float JaccardOverlap(const ZQ_CNN_NormalizedBBox& bbox1, const ZQ_CNN_NormalizedBBox& bbox2, const bool normalized) { ZQ_CNN_NormalizedBBox intersect_bbox; IntersectBBox(bbox1, bbox2, &intersect_bbox); float intersect_width, intersect_height; if (normalized) { intersect_width = intersect_bbox.col2 - intersect_bbox.col1; intersect_height = intersect_bbox.row2 - intersect_bbox.row1; } else { intersect_width = intersect_bbox.col2 - intersect_bbox.col1 + 1; intersect_height = intersect_bbox.row2 - intersect_bbox.row1 + 1; } if (intersect_width > 0 && intersect_height > 0) { float intersect_size = intersect_width * intersect_height; float bbox1_size = BBoxSize(bbox1, true); float bbox2_size = BBoxSize(bbox2, true); return intersect_size / (bbox1_size + bbox2_size - intersect_size); } else { return 0.; } } static void IntersectBBox(const ZQ_CNN_NormalizedBBox& bbox1, const ZQ_CNN_NormalizedBBox& bbox2, ZQ_CNN_NormalizedBBox* intersect_bbox) { if (bbox2.col1 > bbox1.col2 || bbox2.col2 < bbox1.col1 || bbox2.row1 > bbox1.row2 || bbox2.row2 < bbox1.row1) { // Return [0, 0, 0, 0] if there is no intersection. intersect_bbox->col1 = 0; intersect_bbox->row1 = 0; intersect_bbox->col2 = 0; intersect_bbox->row2 = 0; } else { intersect_bbox->col1 = std::max(bbox1.col1, bbox2.col1); intersect_bbox->row1 = std::max(bbox1.row1, bbox2.row1); intersect_bbox->col2 = std::min(bbox1.col2, bbox2.col2); intersect_bbox->row2 = std::min(bbox1.row2, bbox2.row2); } } }; } #endif
omp_loop_static.h
// -*- C++ -*- // Copyright (C) 2007-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file parallel/omp_loop_static.h * @brief Parallelization of embarrassingly parallel execution by * means of an OpenMP for loop with static scheduling. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Felix Putze. #ifndef _GLIBCXX_PARALLEL_OMP_LOOP_STATIC_H #define _GLIBCXX_PARALLEL_OMP_LOOP_STATIC_H 1 #include <omp.h> #include <parallel/settings.h> #include <parallel/basic_iterator.h> namespace __gnu_parallel { /** @brief Embarrassingly parallel algorithm for random access * iterators, using an OpenMP for loop with static scheduling. * * @param __begin Begin iterator of element sequence. * @param __end End iterator of element sequence. * @param __o User-supplied functor (comparator, predicate, adding * functor, ...). * @param __f Functor to @a process an element with __op (depends on * desired functionality, e. g. for std::for_each(), ...). * @param __r Functor to @a add a single __result to the already processed * __elements (depends on functionality). * @param __base Base value for reduction. * @param __output Pointer to position where final result is written to * @param __bound Maximum number of elements processed (e. g. for * std::count_n()). * @return User-supplied functor (that may contain a part of the result). */ template<typename _RAIter, typename _Op, typename _Fu, typename _Red, typename _Result> _Op __for_each_template_random_access_omp_loop_static(_RAIter __begin, _RAIter __end, _Op __o, _Fu& __f, _Red __r, _Result __base, _Result& __output, typename std::iterator_traits<_RAIter>::difference_type __bound) { typedef typename std::iterator_traits<_RAIter>::difference_type _DifferenceType; _DifferenceType __length = __end - __begin; _ThreadIndex __num_threads = std::min<_DifferenceType> (__get_max_threads(), __length); _Result *__thread_results; # pragma omp parallel num_threads(__num_threads) { # pragma omp single { __num_threads = omp_get_num_threads(); __thread_results = new _Result[__num_threads]; for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __thread_results[__i] = _Result(); } _ThreadIndex __iam = omp_get_thread_num(); #pragma omp for schedule(static, _Settings::get().workstealing_chunk_size) for (_DifferenceType __pos = 0; __pos < __length; ++__pos) __thread_results[__iam] = __r(__thread_results[__iam], __f(__o, __begin+__pos)); } //parallel for (_ThreadIndex __i = 0; __i < __num_threads; ++__i) __output = __r(__output, __thread_results[__i]); delete [] __thread_results; // Points to last element processed (needed as return value for // some algorithms like transform). __f.finish_iterator = __begin + __length; return __o; } } // end namespace #endif /* _GLIBCXX_PARALLEL_OMP_LOOP_STATIC_H */
fused_rowwise_nbit_conversion_ops.h
#pragma once #include <algorithm> #include <vector> #ifdef _OPENMP #include <omp.h> #endif #include "caffe2/core/context.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" // for param_search_greedy #include "caffe2/operators/fused_rowwise_nbitfake_conversion_ops.h" #include "caffe2/perfkernels/fused_nbit_rowwise_conversion.h" namespace caffe2 { template < int BIT_RATE, typename T, void (*convert)(float* dst, const T* src, size_t N), bool GREEDY = false> class FloatToFusedNBitRowwiseQuantizedOp final : public Operator<CPUContext> { public: FloatToFusedNBitRowwiseQuantizedOp(const OperatorDef& def, Workspace* ws) : Operator<CPUContext>(def, ws) {} ~FloatToFusedNBitRowwiseQuantizedOp() override {} bool RunOnDevice() override { CAFFE_ENFORCE(internal::is_little_endian(), "Unsupported endianness"); const auto& input = Input(DATA_FLOAT); CAFFE_ENFORCE_GT(input.dim(), 0, "Input's dimension must be at least 1"); const auto input_rows = input.size_to_dim(input.dim() - 1); const auto input_columns = input.size(input.dim() - 1); static_assert(8 % BIT_RATE == 0, "BIT_RATE must divide 8"); constexpr int NUM_ELEM_PER_BYTE = 8 / BIT_RATE; CAFFE_ENFORCE_EQ( input.dim(input.dim() - 1) % NUM_ELEM_PER_BYTE, 0, "FloatToFused" + caffe2::to_string(BIT_RATE) + "BitRowwiseQuantizedOp only works for the number of " "columns a multiple of " + caffe2::to_string(NUM_ELEM_PER_BYTE)); // The "fused" representation stores the scale and bias with the // row-wise quantized data in one tensor. // Since we represent the scale and bias in 16-bit float, we'll use the // last 4 bytes of each row for scale (2 bytes) and bias (2 bytes). // | ... quantized data ... | scale | bias | // | number_of_columns | 2B | 2B | auto output_dimensions = input.sizes().vec(); output_dimensions[input.dim() - 1] = static_cast<std::int64_t>( (input_columns + NUM_ELEM_PER_BYTE - 1) / NUM_ELEM_PER_BYTE + 2 * sizeof(at::Half)); auto* output = Output( DATA_FUSED_SCALE_BIAS, output_dimensions, at::dtype<std::uint8_t>()); const auto* input_data = input.template data<T>(); auto* output_data = output->template mutable_data<std::uint8_t>(); if (!GREEDY && std::is_same<T, float>::value) { // fast path CAFFE_ENFORCE( reinterpret_cast<void (*)(float*, const float*, std::size_t)>( convert) == internal::convertfp32fp32, "When T == float, convert must be convertfp32fp32"); FloatToFusedNBitRowwiseQuantizedSBHalf( BIT_RATE, reinterpret_cast<const float*>(input_data), input_rows, input_columns, output_data); } else { const auto output_columns = output->size(output->dim() - 1); #ifdef _OPENMP vector<float> tmp_vec( input_columns * (GREEDY ? omp_get_max_threads() : 1)); #else vector<float> tmp_vec(input_columns); #endif #pragma omp parallel for if (GREEDY) for (int row = 0; row < input_rows; ++row) { float* tmp = tmp_vec.data(); #ifdef _OPENMP if (GREEDY) { tmp = &tmp_vec[omp_get_thread_num() * input_columns]; } #endif convert(tmp, input_data + row * input_columns, input_columns); std::uint8_t* output_row = output_data + row * output_columns; at::Half* output_row_scale = reinterpret_cast<at::Half*>( output_row + (input_columns + NUM_ELEM_PER_BYTE - 1) / NUM_ELEM_PER_BYTE); at::Half* output_row_bias = reinterpret_cast<at::Half*>( output_row + (input_columns + NUM_ELEM_PER_BYTE - 1) / NUM_ELEM_PER_BYTE + sizeof(at::Half)); float Xmin = *std::min_element(tmp, tmp + input_columns); float Xmax = *std::max_element(tmp, tmp + input_columns); if (GREEDY) { internal::param_search_greedy( tmp, input_columns, 200, 0.16, Xmin, Xmax, BIT_RATE); } // Round Xmin to fp16 to match with dequantization that will use fp16 // for Xmin. Xmin = static_cast<at::Half>(Xmin); const float range = Xmax - Xmin; // Round scale to fp16 to match with dequantization that will use fp16 // for scale. // Set scale to 1.0f for the corner case of Xmax == Xmin . // Any non-zero scale would work because during quantization // (X - Xmin) / scale will be 0 for all X unless scale is 0. at::Half scale = range == 0 ? 1.0f : range / ((1 << BIT_RATE) - 1); float inverse_scale = scale == 0 ? 1.0f : 1.0f / scale; if (scale == 0 || std::isinf(inverse_scale)) { // Corner case handling when Xmax == Xmin // Any scale would work because X - Xmin will be 0 for all X scale = 1.0f; inverse_scale = 1.0f; } *output_row_scale = scale; *output_row_bias = Xmin; for (int col = 0; col < input_columns; ++col) { float X = tmp[col]; std::uint8_t quantized = std::max( 0, std::min<int>( std::lrintf((X - Xmin) * inverse_scale), (1 << BIT_RATE) - 1)); if (col % NUM_ELEM_PER_BYTE == 0) { output_row[col / NUM_ELEM_PER_BYTE] = quantized; } else { output_row[col / NUM_ELEM_PER_BYTE] |= (quantized << ((col % NUM_ELEM_PER_BYTE) * BIT_RATE)); } } } } // GREEDY || !std::is_same<T, float>::value return true; } private: INPUT_TAGS(DATA_FLOAT); OUTPUT_TAGS(DATA_FUSED_SCALE_BIAS); }; template < int BIT_RATE, typename T, void (*convert)(T* dst, const float* src, size_t N)> class FusedNBitRowwiseQuantizedToFloatOp final : public Operator<CPUContext> { public: FusedNBitRowwiseQuantizedToFloatOp(const OperatorDef& def, Workspace* ws) : Operator<CPUContext>(def, ws) {} ~FusedNBitRowwiseQuantizedToFloatOp() override {} bool RunOnDevice() override { CAFFE_ENFORCE(internal::is_little_endian(), "Unsupported endianness"); const auto& input = Input(DATA_FUSED_SCALE_BIAS); CAFFE_ENFORCE_GT(input.dim(), 0, "Input's dimension must be at least 1"); const auto input_rows = input.size_to_dim(input.dim() - 1); const auto input_columns = input.size(input.dim() - 1); static_assert(8 % BIT_RATE == 0, "BIT_RATE must divide 8"); constexpr int NUM_ELEM_PER_BYTE = 8 / BIT_RATE; // The last 4 bytes per row are two fp16 scale and bias. // The rest of input_columns is the number of values in the original row. auto output_dimensions = input.sizes().vec(); output_dimensions[input.dim() - 1] = static_cast<std::int64_t>(input_columns - 2 * sizeof(at::Half)) * NUM_ELEM_PER_BYTE; auto* output = Output(DATA_FLOAT, output_dimensions, at::dtype<T>()); const auto output_columns = output->size(output->dim() - 1); const auto* input_data = input.template data<std::uint8_t>(); T* output_data = output->template mutable_data<T>(); if (std::is_same<T, float>::value) { // fast path CAFFE_ENFORCE( reinterpret_cast<void (*)(float*, const float*, std::size_t)>( convert) == internal::convertfp32fp32, "When T == float, convert must be convertfp32fp32"); FusedNBitRowwiseQuantizedSBHalfToFloat( BIT_RATE, input_data, input_rows, input_columns, reinterpret_cast<float*>(output_data)); } else { std::vector<float> tmp(output_columns); // NOLINTNEXTLINE(clang-diagnostic-sign-compare) for (size_t row = 0; row < input_rows; ++row) { const std::uint8_t* input_row = input_data + row * input_columns; float scale = *reinterpret_cast<const at::Half*>( input_row + (output_columns + NUM_ELEM_PER_BYTE - 1) / NUM_ELEM_PER_BYTE); float bias = *reinterpret_cast<const at::Half*>( input_row + (output_columns + NUM_ELEM_PER_BYTE - 1) / NUM_ELEM_PER_BYTE + sizeof(at::Half)); for (int col = 0; col < output_columns; ++col) { std::uint8_t quantized = input_row[col / NUM_ELEM_PER_BYTE]; quantized >>= (col % NUM_ELEM_PER_BYTE) * BIT_RATE; quantized &= (1 << BIT_RATE) - 1; tmp[col] = scale * quantized + bias; } convert(output_data + row * output_columns, tmp.data(), output_columns); } } return true; } private: INPUT_TAGS(DATA_FUSED_SCALE_BIAS); OUTPUT_TAGS(DATA_FLOAT); }; } // namespace caffe2
GB_binop__iseq_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__iseq_int8 // A.*B function (eWiseMult): GB_AemultB__iseq_int8 // A*D function (colscale): GB_AxD__iseq_int8 // D*A function (rowscale): GB_DxB__iseq_int8 // C+=B function (dense accum): GB_Cdense_accumB__iseq_int8 // C+=b function (dense accum): GB_Cdense_accumb__iseq_int8 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__iseq_int8 // C=scalar+B GB_bind1st__iseq_int8 // C=scalar+B' GB_bind1st_tran__iseq_int8 // C=A+scalar GB_bind2nd__iseq_int8 // C=A'+scalar GB_bind2nd_tran__iseq_int8 // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = (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) \ int8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x == y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISEQ || GxB_NO_INT8 || GxB_NO_ISEQ_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__iseq_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__iseq_int8 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__iseq_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__iseq_int8 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *GB_RESTRICT Cx = (int8_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__iseq_int8 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *GB_RESTRICT Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__iseq_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__iseq_int8 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__iseq_int8 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_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__iseq_int8 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_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 typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB_bind1st_tran__iseq_int8 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = Ax [pA] ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB_bind2nd_tran__iseq_int8 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
betweennessCentrality.c
#include "defs.h" extern LONG_T *volatile tmp_start; extern LONG_T *volatile tmp_end; extern VERT_T *volatile tmp_S; extern DOUBLE_T *volatile tmp_sig; extern LONG_T *volatile tmp_d; extern DOUBLE_T *volatile tmp_del; extern plist *volatile tmp_P; extern graph *volatile tmp_G; extern int volatile push_flag; extern int volatile g_hot2_j; extern int volatile g_phase_num; extern int volatile g_vertex; extern DOUBLE_T *volatile tmp_BC; double betweennessCentrality(graph* G, DOUBLE_T* BC) { VERT_T *S; /* stack of vertices in the order of non-decreasing distance from s. Also used to implicitly represent the BFS queue */ plist* P; /* predecessors of a vertex v on shortest paths from s */ DOUBLE_T* sig; /* No. of shortest paths */ LONG_T* d; /* Length of the shortest path between every pair */ DOUBLE_T* del; /* dependency of vertices */ LONG_T *in_degree, *numEdges, *pSums; LONG_T *pListMem; LONG_T* Srcs; LONG_T *start, *end; LONG_T MAX_NUM_PHASES; LONG_T *psCount; #ifdef _OPENMP omp_lock_t* vLock; LONG_T chunkSize; #endif int seed = 2387; double elapsed_time; #ifdef _OPENMP #pragma omp parallel { #endif VERT_T *myS, *myS_t; LONG_T myS_size; LONG_T i, j, k, p, count, myCount; LONG_T v, w, vert; LONG_T numV, num_traversals, n, m, phase_num; LONG_T tid, nthreads; int* stream; #ifdef DIAGNOSTIC double elapsed_time_part; #endif #ifdef _OPENMP int myLock; tid = omp_get_thread_num(); nthreads = omp_get_num_threads(); #else tid = 0; nthreads = 1; #endif #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds(); } #endif /* numV: no. of vertices to run BFS from = 2^K4approx */ numV = 1<<K4approx; n = G->n; m = G->m; /* Permute vertices */ if (tid == 0) { Srcs = (LONG_T *) malloc(n*sizeof(LONG_T)); #ifdef _OPENMP vLock = (omp_lock_t *) malloc(n*sizeof(omp_lock_t)); #endif } #ifdef _OPENMP #pragma omp barrier #pragma omp for for (i=0; i<n; i++) { omp_init_lock(&vLock[i]); } #endif /* Initialize RNG stream */ stream = init_sprng(0, tid, nthreads, seed, SPRNG_DEFAULT); #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) { Srcs[i] = i; } #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) { j = n*sprng(stream); if (i != j) { #ifdef _OPENMP int l1 = omp_test_lock(&vLock[i]); if (l1) { int l2 = omp_test_lock(&vLock[j]); if (l2) { #endif k = Srcs[i]; Srcs[i] = Srcs[j]; Srcs[j] = k; #ifdef _OPENMP omp_unset_lock(&vLock[j]); } omp_unset_lock(&vLock[i]); } #endif } } #ifdef _OPENMP #pragma omp barrier #endif #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() -elapsed_time_part; fprintf(stderr, "Vertex ID permutation time: %lf seconds\n", elapsed_time_part); elapsed_time_part = get_seconds(); } #endif /* Start timing code from here */ if (tid == 0) { elapsed_time = get_seconds(); #ifdef VERIFYK4 MAX_NUM_PHASES = 2*sqrt(n); #else MAX_NUM_PHASES = 50; #endif } #ifdef _OPENMP #pragma omp barrier #endif /* Initialize predecessor lists */ /* The size of the predecessor list of each vertex is bounded by its in-degree. So we first compute the in-degree of every vertex */ if (tid == 0) { P = (plist *) calloc(n, sizeof(plist)); in_degree = (LONG_T *) calloc(n+1, sizeof(LONG_T)); numEdges = (LONG_T *) malloc((n+1)*sizeof(LONG_T)); pSums = (LONG_T *) malloc(nthreads*sizeof(LONG_T)); } #ifdef _OPENMP #pragma omp barrier #pragma omp for #endif for (i=0; i<m; i++) { v = G->endV[i]; #ifdef _OPENMP omp_set_lock(&vLock[v]); #endif in_degree[v]++; #ifdef _OPENMP omp_unset_lock(&vLock[v]); #endif } prefix_sums(in_degree, numEdges, pSums, n); if (tid == 0) { pListMem = (LONG_T *) malloc(m*sizeof(LONG_T)); } #ifdef _OPENMP #pragma omp barrier #pragma omp for #endif for (i=0; i<n; i++) { P[i].list = pListMem + numEdges[i]; P[i].degree = in_degree[i]; P[i].count = 0; } #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() - elapsed_time_part; fprintf(stderr, "In-degree computation time: %lf seconds\n", elapsed_time_part); elapsed_time_part = get_seconds(); } #endif /* Allocate shared memory */ if (tid == 0) { free(in_degree); free(numEdges); free(pSums); S = (VERT_T *) malloc(n*sizeof(VERT_T)); sig = (DOUBLE_T *) malloc(n*sizeof(DOUBLE_T)); d = (LONG_T *) malloc(n*sizeof(LONG_T)); del = (DOUBLE_T *) calloc(n, sizeof(DOUBLE_T)); start = (LONG_T *) malloc(MAX_NUM_PHASES*sizeof(LONG_T)); end = (LONG_T *) malloc(MAX_NUM_PHASES*sizeof(LONG_T)); psCount = (LONG_T *) malloc((nthreads+1)*sizeof(LONG_T)); } /* local memory for each thread */ myS_size = (2*n)/nthreads; myS = (LONG_T *) malloc(myS_size*sizeof(LONG_T)); num_traversals = 0; myCount = 0; #ifdef _OPENMP #pragma omp barrier #endif #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) { d[i] = -1; } #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() -elapsed_time_part; fprintf(stderr, "BC initialization time: %lf seconds\n", elapsed_time_part); elapsed_time_part = get_seconds(); } #endif tmp_start=start; tmp_end=end; tmp_S=S; tmp_d=d; tmp_sig=sig; tmp_del=del; tmp_P=P; tmp_G=G; tmp_BC=BC; for (p=0; p<n; p++) { i = Srcs[p]; if (G->numEdges[i+1] - G->numEdges[i] == 0) { continue; } else { num_traversals++; } if (num_traversals == numV + 1) { break; } if (tid == 0) { sig[i] = 1; d[i] = 0; S[0] = i; start[0] = 0; end[0] = 1; } count = 1; phase_num = 0; #ifdef _OPENMP #pragma omp barrier #endif while (end[phase_num] - start[phase_num] > 0) { myCount = 0; #ifdef _OPENMP #pragma omp barrier #pragma omp for schedule(dynamic) #endif push_flag=1; for (vert = start[phase_num]; vert < end[phase_num]; vert++) { g_vertex=vert; v = S[vert]; for (j=G->numEdges[v]; j<G->numEdges[v+1]; j++) { #ifndef VERIFYK4 /* Filter edges with weights divisible by 8 */ if ((G->weight[j] & 7) != 0) { #endif w = G->endV[j]; if (v != w) { #ifdef _OPENMP myLock = omp_test_lock(&vLock[w]); if (myLock) { #endif /* w found for the first time? */ if (d[w] == -1) { if (myS_size == myCount) { /* Resize myS */ myS_t = (LONG_T *) malloc(2*myS_size*sizeof(VERT_T)); memcpy(myS_t, myS, myS_size*sizeof(VERT_T)); free(myS); myS = myS_t; myS_size = 2*myS_size; } myS[myCount++] = w; d[w] = d[v] + 1; sig[w] = sig[v]; P[w].list[P[w].count++] = v; } else if (d[w] == d[v] + 1) { sig[w] += sig[v]; P[w].list[P[w].count++] = v; } #ifdef _OPENMP omp_unset_lock(&vLock[w]); } else { if ((d[w] == -1) || (d[w] == d[v]+ 1)) { omp_set_lock(&vLock[w]); sig[w] += sig[v]; P[w].list[P[w].count++] = v; omp_unset_lock(&vLock[w]); } } #endif } #ifndef VERIFYK4 } #endif } } /* Merge all local stacks for next iteration */ push_flag=0; phase_num++; g_phase_num=phase_num; psCount[tid+1] = myCount; #ifdef _OPENMP #pragma omp barrier #endif if (tid == 0) { start[phase_num] = end[phase_num-1]; psCount[0] = start[phase_num]; for(k=1; k<=nthreads; k++) { psCount[k] = psCount[k-1] + psCount[k]; } end[phase_num] = psCount[nthreads]; } #ifdef _OPENMP #pragma omp barrier #endif for (k = psCount[tid]; k < psCount[tid+1]; k++) { S[k] = myS[k-psCount[tid]]; } #ifdef _OPENMP #pragma omp barrier #endif count = end[phase_num]; } phase_num--; #ifdef _OPENMP #pragma omp barrier #endif g_phase_num=phase_num; while (phase_num > 0) { #ifdef _OPENMP #pragma omp for #endif push_flag=2; for (j=start[phase_num]; j<end[phase_num]; j++) { g_hot2_j=j; w = S[j]; for (k = 0; k<P[w].count; k++) { v = P[w].list[k]; #ifdef _OPENMP omp_set_lock(&vLock[v]); #endif del[v] = del[v] + sig[v]*(1+del[w])/sig[w]; #ifdef _OPENMP omp_unset_lock(&vLock[v]); #endif } BC[w] += del[w]; } push_flag=0; phase_num--; g_phase_num=phase_num; #ifdef _OPENMP #pragma omp barrier #endif } #ifdef _OPENMP chunkSize = n/nthreads; #pragma omp for schedule(static, chunkSize) #endif for (j=0; j<count; j++) { w = S[j]; d[w] = -1; del[w] = 0; P[w].count = 0; } #ifdef _OPENMP #pragma omp barrier #endif } #ifdef DIAGNOSTIC if (tid == 0) { elapsed_time_part = get_seconds() -elapsed_time_part; fprintf(stderr, "BC computation time: %lf seconds\n", elapsed_time_part); } #endif #ifdef _OPENMP #pragma omp for for (i=0; i<n; i++) { omp_destroy_lock(&vLock[i]); } #endif free(myS); if (tid == 0) { free(S); free(pListMem); free(P); free(sig); free(d); free(del); #ifdef _OPENMP free(vLock); #endif free(start); free(end); free(psCount); elapsed_time = get_seconds() - elapsed_time; free(Srcs); } free_sprng(stream); #ifdef _OPENMP } #endif /* Verification */ #ifdef VERIFYK4 double BCval; if (SCALE % 2 == 0) { BCval = 0.5*pow(2, 3*SCALE/2)-pow(2, SCALE)+1.0; } else { BCval = 0.75*pow(2, (3*SCALE-1)/2)-pow(2, SCALE)+1.0; } int failed = 0; for (int i=0; i<G->n; i++) { if (round(BC[i] - BCval) != 0) { failed = 1; break; } } if (failed) { fprintf(stderr, "Kernel 4 failed validation!\n"); } else { fprintf(stderr, "Kernel 4 validation successful!\n"); } #endif return elapsed_time; }
pzlangb.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" #include "plasma_workspace.h" #include <plasma_core_blas.h> #include "core_lapack.h" #define A(m, n) (plasma_complex64_t*)plasma_tile_addr(A, m, n) /***************************************************************************//** * Parallel tile calculation of max, one, infinity or Frobenius matrix norm * for a general band matrix. ******************************************************************************/ void plasma_pzlangb(plasma_enum_t norm, plasma_desc_t A, double *work, double *value, plasma_sequence_t *sequence, plasma_request_t *request) { // Return if failed sequence. if (sequence->status != PlasmaSuccess) return; double stub; int wcnt = 0; int ldwork, klt, kut; double *workspace, *scale, *sumsq; switch (norm) { //================ // PlasmaMaxNorm //================ case PlasmaMaxNorm: wcnt = 0; for (int n = 0; n < A.nt; n++ ) { int nvan = plasma_tile_nview(A, n); int m_start = (imax(0, n*A.nb-A.ku)) / A.nb; int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb; for (int m = m_start; m <= m_end; m++ ) { int ldam = plasma_tile_mmain_band(A, m, n); int mvam = plasma_tile_mview(A, m); plasma_core_omp_zlange(PlasmaMaxNorm, mvam, nvan, A(m, n), ldam, &stub, &work[wcnt], sequence, request); wcnt++; } } #pragma omp taskwait plasma_core_omp_dlange(PlasmaMaxNorm, 1, wcnt, work, 1, &stub, value, sequence, request); break; //================ // PlasmaOneNorm //================ case PlasmaOneNorm: // # of tiles in upper band (not including diagonal) kut = (A.ku+A.nb-1)/A.nb; // # of tiles in lower band (not including diagonal) klt = (A.kl+A.nb-1)/A.nb; ldwork = kut+klt+1; for (int n = 0; n < A.nt; n++ ) { int nvan = plasma_tile_nview(A, n); int m_start = (imax(0, n*A.nb-A.ku)) / A.nb; int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb; for (int m = m_start; m <= m_end; m++ ) { int ldam = plasma_tile_mmain_band(A, m, n); int mvam = plasma_tile_mview(A, m); plasma_core_omp_zlange_aux(PlasmaOneNorm, mvam, nvan, A(m,n), ldam, &work[(m-m_start)*A.n+n*A.nb], sequence, request); } } #pragma omp taskwait workspace = &work[A.n*ldwork]; plasma_core_omp_dlange(PlasmaInfNorm, A.n, ldwork, work, A.n, workspace, value, sequence, request); break; //================ // PlasmaInfNorm //================ case PlasmaInfNorm: ldwork = A.mb*A.mt; for (int n = 0; n < A.nt; n++ ) { int nvan = plasma_tile_nview(A, n); int m_start = (imax(0, n*A.nb-A.ku)) / A.nb; int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb; for (int m = m_start; m <= m_end; m++ ) { int ldam = plasma_tile_mmain_band(A, m, n); int mvam = plasma_tile_mview(A, m); plasma_core_omp_zlange_aux(PlasmaInfNorm, mvam, nvan, A(m,n), ldam, &work[m*A.mb+n*ldwork], sequence, request); } } #pragma omp taskwait //nwork = A.nt; workspace = &work[ldwork*A.nt]; plasma_core_omp_dlange(PlasmaInfNorm, ldwork, A.nt, work, ldwork, workspace, value, sequence, request); break; //====================== // PlasmaFrobeniusNorm //====================== case PlasmaFrobeniusNorm: kut = (A.ku+A.nb-1)/A.nb; // # of tiles in upper band (not including diagonal) klt = (A.kl+A.nb-1)/A.nb; // # of tiles in lower band (not including diagonal) ldwork = kut+klt+1; scale = work; sumsq = &work[ldwork*A.nt]; for (int n = 0; n < A.nt; n++ ) { int nvan = plasma_tile_nview(A, n); int m_start = (imax(0, n*A.nb-A.ku)) / A.nb; int m_end = (imin(A.m-1, (n+1)*A.nb+A.kl-1)) / A.nb; for (int m = m_start; m <= m_end; m++ ) { int ldam = plasma_tile_mmain_band(A, m, n); int mvam = plasma_tile_mview(A, m); plasma_core_omp_zgessq(mvam, nvan, A(m,n), ldam, &scale[n*ldwork+m-m_start], &sumsq[n*ldwork+m-m_start], sequence, request); } } #pragma omp taskwait plasma_core_omp_dgessq_aux(ldwork*A.nt, scale, sumsq, value, sequence, request); break; default: assert(0); } }
main.c
#define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <regex.h> #include <time.h> #include <omp.h> #include "stb_image.h" #include "stb_image_write.h" int main(int argc, char *argv[]){ // parameters: image path, filter path, resulting image path, filter size, thead count, scheduler type, chunk size if (argc == 8){ //Variable declaration FILE *pf; char *imgpath = argv[1]; char *filterpath = argv[2]; char *imgrespath = argv[3]; char *filtsize = argv[4]; char *threadcount = argv[5]; char *scheduler = argv[6]; char *chunksize = argv[7]; //Time and date of the calculation time_t now; struct tm *local; int hours, minutes, seconds, day, month, year; int w, h, bpp, cc = 3, wc, hc, crop_img_size, j; double start, end, *tmp, *a = malloc(atoi(filtsize)*atoi(filtsize)*sizeof(double *)); unsigned char *image, *gray_img, *new_img_gray; size_t img_size, gray_img_size, i; int gray_channels = 1; // Explicitly disable dynamic teams omp_set_dynamic(0); //Reading the filter from a file pf = fopen (filterpath, "r"); if (pf == NULL){ return 0; } for(i = 0, tmp = a; i < atoi(filtsize)*atoi(filtsize); ++i){ fscanf(pf, "%lf", tmp++); } fclose (pf); //Image loading image = stbi_load(imgpath, &w, &h, &bpp, cc); img_size = w * h * cc; gray_img_size = w * h * gray_channels; wc = w - (atoi(filtsize)-1); hc = h - (atoi(filtsize)-1); crop_img_size = wc* hc; //New image memory allocation gray_img = malloc(gray_img_size); new_img_gray = malloc(crop_img_size); //Grayscale conversion (serial execution) for(i = 0; i < gray_img_size; i++) { unsigned char *pt = image+(i*3); unsigned char *pgt = gray_img+i; *pgt = (uint8_t)((*pt + *(pt + 1) + *(pt + 2))/3.0); } //Obtain current time for testbench reports time(&now); local = localtime(&now); hours = local->tm_hour; // Hours since midnight (0-23) minutes = local->tm_min; // Minutes passed after the hour (0-59) seconds = local->tm_sec; // Seconds passed after minute (0-59) day = local->tm_mday; // Day of month (1 to 31) month = local->tm_mon + 1; // Month of year (0 to 11) year = local->tm_year + 1900; // Year since 1900 // Measure initial time for parallel calculations start = omp_get_wtime(); //Convolution in parallel //Configuring schedule type if (scheduler == "static") omp_set_schedule(omp_sched_static, atoi(chunksize)); else if(scheduler == "dynamic") omp_set_schedule(omp_sched_dynamic, atoi(chunksize)); else if (scheduler == "guided") omp_set_schedule(omp_sched_guided, atoi(chunksize)); else if (scheduler = "auto") omp_set_schedule(omp_sched_auto, atoi(chunksize)); #pragma omp parallel for shared(gray_img, new_img_gray, a, w, wc, crop_img_size) num_threads(atoi(threadcount)) for (j = 0; j < crop_img_size; j++){ int filts = atoi(filtsize); unsigned char *p = gray_img+j + ((int)(j/wc)*(filts-1)); unsigned char *pg = new_img_gray+j; unsigned char sum = 0; int tmpcont = 0; int at; for (at = (filts*filts)-1; at >= 0; at--){ sum += *(a+at) * *(p + tmpcont + (w*(filts-((at/filts)+1)))); if (tmpcont == (filts-1)){ tmpcont = 0; } else { tmpcont++; } } *pg = (uint8_t)sum; } //Measure final time of parallel convolution end = omp_get_wtime(); //Write convolution result in file stbi_write_jpg(imgrespath, wc, hc, gray_channels, new_img_gray, wc * gray_channels); //Free memory stbi_image_free(image); free(gray_img); free(new_img_gray); //Print to stdout with csv format, for testbench printf("%02d-%02d-%d_%02d:%02d,ImgName:%s FiltType:%s FiltSize:%s ThreadCount:%s Scheduler:%s,%f,%s,%s,%s,%s\n", day, month, year, minutes, seconds, imgpath, filterpath, filtsize, threadcount, scheduler, end - start, filtsize, threadcount, scheduler, chunksize); } else { printf("Incorrect number of arguments\n"); } return 0; }
graph_decomposition.h
#ifndef __GRAPH_DECOMPOSITION_H__ #define __GRAPH_DECOMPOSITION_H__ #include "graph.h" #include <random> #include <math.h> #include <mutex> #include <omp.h> static float* genExp(int n, float rate, float* maxVal, int* maxId) { std::default_random_engine generator; // note this will always generate the same values - which we want - for grading std::exponential_distribution<double> distribution(rate); float maxdu = -1.f; int id = -1; std::mutex mtx; float* vals = (float*) malloc(sizeof(float) * n); for (int i = 0; i < n; i++) { float val = distribution(generator); if (val > maxdu) { mtx.lock(); if (val > maxdu) { maxdu = val; id = i; } mtx.unlock(); } vals[i] = val; } *maxVal = maxdu; *maxId = id; return vals; } /** * Given an array of floats, casts them all into **/ static int* chopToInt(float* fdus, int n) { int* dus = (int*)malloc(sizeof(int) * n); #pragma omp parallel for schedule(dynamic, 512) for (int i = 0; i < n; i++) { dus[i] = (int)fdus[i]; } return dus; } static int* getDus(int n, float rate, int* maxVal, int* maxId) { float fmaxVal; float* expVals = genExp(n, rate, &fmaxVal, maxId); int* dus = chopToInt(expVals, n); free(expVals); *maxVal = (int)fmaxVal; return dus; } void decompose(graph *g, int *decomp, int* dus, int maxVal, int maxId); #endif
VolumetricDilatedMaxPooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/VolumetricDilatedMaxPooling.c" #else static inline void THNN_(VolumetricDilatedMaxPooling_shapeCheck)( THNNState *state, THTensor *input, THTensor *gradOutput, THIndexTensor *indices, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH, bool ceilMode) { int ndim = input->dim(); int dimN = 0; int dimt = 1; int dimh = 2; int dimw = 3; int64_t nslices; int64_t itime; int64_t iheight; int64_t iwidth; int64_t otime; int64_t oheight; int64_t owidth; THArgCheck(kT > 0 && kW > 0 && kH > 0, 5, "kernel size should be greater than zero, but got kT: %d kH: %d kW: %d", kT, kH, kW); THArgCheck(dT > 0 && dW > 0 && dH > 0, 8, "stride should be greater than zero, but got dT: %d dH: %d dW: %d", dT, dH, dW); THArgCheck(dilationT > 0 && dilationW > 0 && dilationH > 0, 14, "dilation should be greater than 0, but got dilationT: %d dilationH: %d dilationW: %d", dilationT, dilationH, dilationW); THNN_ARGCHECK(!input->is_empty() && (input->dim() == 4 || input->dim() == 5), 2, input, "non-empty 4D or 5D (batch mode) tensor expected for input, but got: %s"); if (input->dim() == 5) { dimN++; dimt++; dimh++; dimw++; } THArgCheck(kT/2 >= pT && kW/2 >= pW && kH/2 >= pH, 2, "pad should be smaller than half of kernel size, but got " "kT: %d kW: %d, kH: %d, padT: %d, padW: %d, padH: %d", kT, kW, kH, pT, pW, pH); nslices = input->size(dimN); itime = input->size(dimt); iheight = input->size(dimh); iwidth = input->size(dimw); if (ceilMode) { otime = (int)(ceil((float)(itime - (dilationT * (kT - 1) + 1) + 2*pT) / dT)) + 1; oheight = (int)(ceil((float)(iheight - (dilationH * (kH - 1) + 1) + 2*pH) / dH)) + 1; owidth = (int)(ceil((float)(iwidth - (dilationW * (kW - 1) + 1) + 2*pW) / dW)) + 1; } else { otime = (int)(floor((float)(itime - (dilationT * (kT - 1) + 1) + 2*pT) / dT)) + 1; oheight = (int)(floor((float)(iheight - (dilationH * (kH - 1) + 1) + 2*pH) / dH)) + 1; owidth = (int)(floor((float)(iwidth - (dilationW * (kW - 1) + 1) + 2*pW) / dW)) + 1; } if (pT || pW || pH) { // ensure that the last pooling starts inside the image if ((otime - 1)*dT >= itime + pT) --otime; if ((oheight - 1)*dH >= iheight + pH) --oheight; if ((owidth - 1)*dW >= iwidth + pW) --owidth; } if (otime < 1 || owidth < 1 || oheight < 1) THError("Given input size: (%dx%dx%dx%d). Calculated output size: (%dx%dx%dx%d). Output size is too small", nslices,itime,iheight,iwidth,nslices,otime,oheight,owidth); if (gradOutput != NULL) { THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimN, nslices); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimt, otime); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, oheight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, owidth); } if (indices != NULL) { THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimN, nslices); THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimt, otime); THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimh, oheight); THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimw, owidth); } } static void THNN_(VolumetricDilatedMaxPooling_updateOutput_frame)( real *input_p, real *output_p, THIndex_t *indz_p, int64_t nslices, int64_t itime, int64_t iwidth, int64_t iheight, int64_t otime, int64_t owidth, int64_t oheight, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH) { int64_t k; #pragma omp parallel for private(k) for (k = 0; k < nslices; k++) { /* loop over output */ int64_t i, j, ti; real *ip = input_p + k * itime * iwidth * iheight; for (ti = 0; ti < otime; ti++) { for (i = 0; i < oheight; i++) { for (j = 0; j < owidth; j++) { /* local pointers */ int64_t start_t = ti * dT - pT; int64_t start_h = i * dH - pH; int64_t start_w = j * dW - pW; int64_t end_t = fminf(start_t + (kT - 1) * dilationT + 1, itime); int64_t end_h = fminf(start_h + (kH - 1) * dilationH + 1, iheight); int64_t end_w = fminf(start_w + (kW - 1) * dilationW + 1, iwidth); while(start_t < 0) start_t += dilationT; while(start_h < 0) start_h += dilationH; while(start_w < 0) start_w += dilationW; real *op = output_p + k * otime * owidth * oheight + ti * owidth * oheight + i * owidth + j; THIndex_t *indzp = indz_p + k * otime * owidth * oheight + ti * owidth * oheight + i * owidth + j; /* compute local max: */ int64_t maxindex = -1; real maxval = -THInf; int64_t x,y,z; int64_t index = 0; for (z = start_t; z < end_t; z += dilationT) { for (y = start_h; y < end_h; y += dilationH) { for (x = start_w; x < end_w; x += dilationW) { index = z * iwidth * iheight + y * iwidth + x; real val = ip[index]; if ((val > maxval) || std::isnan(val)) { maxval = val; maxindex = index; } } } } // store location of max *indzp = maxindex + TH_INDEX_BASE; /* set output to local max */ *op = maxval; } } } } } void THNN_(VolumetricDilatedMaxPooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THIndexTensor *indices, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH, bool ceilMode) { int64_t nslices; int64_t itime; int64_t iheight; int64_t iwidth; int64_t otime; int64_t oheight; int64_t owidth; real *input_data; real *output_data; THIndex_t *indices_data; int dimN = 0; int dimt = 1; int dimh = 2; int dimw = 3; if (input->dim() == 5) { dimN++; dimt++; dimh++; dimw++; } THNN_(VolumetricDilatedMaxPooling_shapeCheck)( state, input, NULL, NULL, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH, ceilMode); /* sizes */ nslices = input->size(dimN); itime = input->size(dimt); iheight = input->size(dimh); iwidth = input->size(dimw); if (ceilMode) { otime = (int)(ceil((float)(itime - (dilationT * (kT - 1) + 1) + 2*pT) / dT)) + 1; oheight = (int)(ceil((float)(iheight - (dilationH * (kH - 1) + 1) + 2*pH) / dH)) + 1; owidth = (int)(ceil((float)(iwidth - (dilationW * (kW - 1) + 1) + 2*pW) / dW)) + 1; } else { otime = (int)(floor((float)(itime - (dilationT * (kT - 1) + 1) + 2*pT) / dT)) + 1; oheight = (int)(floor((float)(iheight - (dilationH * (kH - 1) + 1) + 2*pH) / dH)) + 1; owidth = (int)(floor((float)(iwidth - (dilationW * (kW - 1) + 1) + 2*pW) / dW)) + 1; } if (pT || pW || pH) { // ensure that the last pooling starts inside the image if ((otime - 1)*dT >= itime + pT) --otime; if ((oheight - 1)*dH >= iheight + pH) --oheight; if ((owidth - 1)*dW >= iwidth + pW) --owidth; } /* get contiguous input */ input = THTensor_(newContiguous)(input); if (input->dim() == 4) /* non-batch mode */ { /* resize output */ THTensor_(resize4d)(output, nslices, otime, oheight, owidth); /* indices will contain ti,i,j uchar locations packed into float/double */ THIndexTensor_(resize4d)(indices, nslices, otime, oheight, owidth); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); indices_data = THIndexTensor_(data)(indices); THNN_(VolumetricDilatedMaxPooling_updateOutput_frame)( input_data, output_data, indices_data, nslices, itime, iwidth, iheight, otime, owidth, oheight, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } else /* batch mode */ { int64_t p; int64_t nBatch = input->size(0); int64_t istride = nslices * itime * iwidth * iheight; int64_t ostride = nslices * otime * owidth * oheight; /* resize output */ THTensor_(resize5d)(output, nBatch, nslices, otime, oheight, owidth); /* indices will contain ti,i,j locations for each output point */ THIndexTensor_(resize5d)(indices, nBatch, nslices, otime, oheight, owidth); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); indices_data = THIndexTensor_(data)(indices); #pragma omp parallel for private(p) for (p=0; p < nBatch; p++) { THNN_(VolumetricDilatedMaxPooling_updateOutput_frame)( input_data + p * istride, output_data + p * ostride, indices_data + p * ostride, nslices, itime, iwidth, iheight, otime, owidth, oheight, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } } /* cleanup */ THTensor_(free)(input); } static void THNN_(VolumetricDilatedMaxPooling_updateGradInput_frame)( real *gradInput_p, real *gradOutput_p, THIndex_t *indz_p, int64_t nslices, int64_t itime, int64_t iwidth, int64_t iheight, int64_t otime, int64_t owidth, int64_t oheight, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH) { int64_t k; #pragma omp parallel for private(k) for (k = 0; k < nslices; k++) { real *gradInput_p_k = gradInput_p + k * itime * iwidth * iheight; real *gradOutput_p_k = gradOutput_p + k * otime * owidth * oheight; THIndex_t *indz_p_k = indz_p + k * otime * owidth * oheight; /* calculate max points */ int64_t ti, i, j; for (ti = 0; ti < otime; ti++) { for (i = 0; i < oheight; i++) { for (j = 0; j < owidth; j++) { /* retrieve position of max */ int64_t index = ti * oheight * owidth + i * owidth + j; int64_t maxp = indz_p_k[index] - TH_INDEX_BASE; if (maxp != -1) { /* update gradient */ gradInput_p_k[maxp] += gradOutput_p_k[index]; } } } } } } void THNN_(VolumetricDilatedMaxPooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THIndexTensor *indices, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH, bool ceilMode) { int nslices; int itime; int iheight; int iwidth; int otime; int oheight; int owidth; real *gradInput_data; real *gradOutput_data; THIndex_t *indices_data; int dimN = 0; int dimt = 1; int dimh = 2; int dimw = 3; THNN_(VolumetricDilatedMaxPooling_shapeCheck)( state, input, gradOutput, indices, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH, ceilMode); // TODO: gradOutput shape check /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); if (input->dim() == 5) { dimN++; dimt++; dimh++; dimw++; } /* sizes */ nslices = input->size(dimN); itime = input->size(dimt); iheight = input->size(dimh); iwidth = input->size(dimw); otime = gradOutput->size(dimt); oheight = gradOutput->size(dimh); owidth = gradOutput->size(dimw); /* get raw pointers */ gradInput_data = THTensor_(data)(gradInput); gradOutput_data = THTensor_(data)(gradOutput); indices_data = THIndexTensor_(data)(indices); /* backprop */ if (input->dim() == 4) /* non-batch mode*/ { THNN_(VolumetricDilatedMaxPooling_updateGradInput_frame)( gradInput_data, gradOutput_data, indices_data, nslices, itime, iwidth, iheight, otime, owidth, oheight, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } else /* batch mode */ { int64_t p; int64_t nBatch = input->size(0); int64_t istride = nslices * itime * iwidth * iheight; int64_t ostride = nslices * otime * owidth * oheight; #pragma omp parallel for private(p) for (p = 0; p < nBatch; p++) { THNN_(VolumetricDilatedMaxPooling_updateGradInput_frame)( gradInput_data + p * istride, gradOutput_data + p * ostride, indices_data + p * ostride, nslices, itime, iwidth, iheight, otime, owidth, oheight, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } } /* cleanup */ THTensor_(free)(gradOutput); } #endif
omp_calloc_size_0.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <omp.h> int main() { omp_alloctrait_t at[2]; omp_allocator_handle_t a; void *p[2]; at[0].key = omp_atk_pool_size; at[0].value = 2*1024*1024; at[1].key = omp_atk_fallback; at[1].value = omp_atv_default_mem_fb; a = omp_init_allocator(omp_large_cap_mem_space, 2, at); printf("allocator large created: %p\n", (void *)a); #pragma omp parallel num_threads(2) { int i = omp_get_thread_num(); p[i] = omp_calloc(1024, 0, a); #pragma omp barrier printf("th %d, ptr %p\n", i, p[i]); omp_free(p[i], a); } // Both pointers should be NULL if (p[0] == NULL && p[1] == NULL) { printf("passed\n"); return 0; } else { printf("failed: pointers %p %p\n", p[0], p[1]); return 1; } }
descriptor.h
#pragma once #include <volk.h> #include <glm/glm.hpp> #include <utility> #include <vector> #include <string_view> #include <map> #include "device.h" #include "locator.h" #include "swapchain.h" #include "mesh.h" struct StructDescriptorSetLayout { VkDescriptorSetLayout layout; std::vector<VkDescriptorType> types; }; class Descriptor { public: VkDescriptorSetLayout& layout(uint32_t index) { return layoutTypes[index].layout; } VkPipelineLayout& pipeLayout(uint32_t index) { return pipeLayouts[index]; } void addLayout(const std::vector<std::pair<VkDescriptorType, VkShaderStageFlagBits>> types) { std::vector<VkDescriptorSetLayoutBinding> bindings(types.size()); StructDescriptorSetLayout mew; uint32_t index = 0; for (auto& binding : bindings) { mew.types.push_back(types[index].first); binding.binding = index; binding.descriptorCount = 1; binding.descriptorType = types[index].first; binding.pImmutableSamplers = nullptr; binding.stageFlags = types[index].second; index++; } VkDescriptorSetLayoutCreateInfo layoutInfo = {}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = bindings.size(); layoutInfo.pBindings = bindings.data(); hw::loc::device()->create(layoutInfo, mew.layout); layoutTypes.push_back(mew); } void addPipeLayout(const std::vector<uint32_t> layouts) { std::vector<VkDescriptorSetLayout> theChosen; theChosen.reserve(layouts.size()); for (auto& layout: layouts) theChosen.push_back(layoutTypes[layout].layout); VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = static_cast<uint32_t>(theChosen.size()); pipelineLayoutInfo.pSetLayouts = theChosen.data(); VkPipelineLayout pipelineLayout; hw::loc::device()->create(pipelineLayoutInfo, pipelineLayout); pipeLayouts.push_back(pipelineLayout); } void addPipeLayout(const std::vector<uint32_t> layouts, const std::vector<VkPushConstantRange> ranges) { std::vector<VkDescriptorSetLayout> theChosen; theChosen.reserve(layouts.size()); for (auto& layout: layouts) theChosen.push_back(layoutTypes[layout].layout); VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = static_cast<uint32_t>(theChosen.size()); pipelineLayoutInfo.pSetLayouts = theChosen.data(); pipelineLayoutInfo.pushConstantRangeCount = ranges.size(); pipelineLayoutInfo.pPushConstantRanges = ranges.data(); VkPipelineLayout pipelineLayout; hw::loc::device()->create(pipelineLayoutInfo, pipelineLayout); pipeLayouts.push_back(pipelineLayout); } void addMesh(std::string_view _tag, const std::vector<uint32_t> _sets, glm::vec2 _dimensions, glm::vec3 _transform=glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 _rotation=glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 _scale=glm::vec3(1.0f, 1.0f, 1.0f)) { meshes.push_back(new Mesh(_tag, descriptorLayouts.size(), _sets.size(), _dimensions, _transform, _rotation, _scale)); #pragma omp parallel for for (auto& set: _sets) { for (auto& type: layoutTypes[set].types) { descriptorTypes[type]++; if (type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) { if (meshes[meshes.size() - 1]->uniform.start == -1) { meshes[meshes.size() - 1]->uniform.start = uniIndex; meshes[meshes.size() - 1]->uniform.size = 1; } else meshes[meshes.size() - 1]->uniform.size++; uniIndex++; } } descriptorLayouts.push_back(layoutTypes[set].layout); } } void addMesh(std::string_view _tag, const std::vector<uint32_t> _sets, glm::vec3 _transform=glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 _rotation=glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 _scale=glm::vec3(1.0f, 1.0f, 1.0f)) { meshes.push_back(new Mesh(_tag, descriptorLayouts.size(), _sets.size(), _transform, _rotation, _scale)); #pragma omp parallel for for (auto& set: _sets) { for (auto& type: layoutTypes[set].types) { descriptorTypes[type]++; if (type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) { if (meshes[meshes.size() - 1]->uniform.start == -1) { meshes[meshes.size() - 1]->uniform.start = uniIndex; meshes[meshes.size() - 1]->uniform.size = 1; } else meshes[meshes.size() - 1]->uniform.size++; uniIndex++; } } descriptorLayouts.push_back(layoutTypes[set].layout); } } void addMesh(std::string_view _tag, const std::vector<uint32_t> _sets, std::string_view model, Image* _texture, glm::vec3 _transform=glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 _rotation=glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 _scale=glm::vec3(1.0f, 1.0f, 1.0f)) { meshes.push_back(new Mesh(_tag, descriptorLayouts.size(), _sets.size(), model, _texture, _transform, _rotation, _scale)); #pragma omp parallel for for (auto& set: _sets) { for (auto& type: layoutTypes[set].types) { descriptorTypes[type]++; if (type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) { if (meshes[meshes.size() - 1]->uniform.start == -1) { meshes[meshes.size() - 1]->uniform.start = uniIndex; meshes[meshes.size() - 1]->uniform.size = 1; } else meshes[meshes.size() - 1]->uniform.size++; uniIndex++; } } descriptorLayouts.push_back(layoutTypes[set].layout); } } void allocate() { std::vector<VkDescriptorPoolSize> poolSizes; poolSizes.reserve(descriptorTypes.size()); for (auto& [key, val]: descriptorTypes) { poolSizes.push_back({key, val * hw::loc::swapChain()->size()}); } VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); poolInfo.maxSets = hw::loc::swapChain()->size() * descriptorLayouts.size(); hw::loc::device()->create(poolInfo, pool); descriptorSets.resize(hw::loc::swapChain()->size()); #pragma omp parallel for for (auto& sets: descriptorSets) { VkDescriptorSetAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = pool; allocInfo.descriptorSetCount = descriptorLayouts.size(); allocInfo.pSetLayouts = descriptorLayouts.data(); sets.resize(descriptorLayouts.size()); hw::loc::device()->allocate(allocInfo, sets.data()); } uniBuffers.resize(hw::loc::swapChain()->size()); uniMemory.resize(hw::loc::swapChain()->size()); for (uint32_t i = 0; i < hw::loc::swapChain()->size(); i++) { uniBuffers[i].resize(uniIndex); uniMemory[i].resize(uniIndex); } } void freePool() { hw::loc::device()->destroy(pool); #pragma omp parallel for for (uint32_t j = 0; j < uniBuffers.size(); j++) for (uint32_t i = 0; i < uniBuffers[j].size(); i++) { hw::loc::device()->destroy(uniBuffers[j][i]); hw::loc::device()->free(uniMemory[j][i]); } } Descriptor() { descriptorTypes[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] = 0; descriptorTypes[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] = 0; descriptorTypes[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] = 0; } ~Descriptor() { for (auto& layout: layoutTypes) hw::loc::device()->destroy(layout.layout); for (auto& layout: pipeLayouts) hw::loc::device()->destroy(layout); for (auto& mesh: meshes) delete mesh; } VkDescriptorSet& getDescriptor(Mesh* mesh, uint32_t frame, uint32_t descriptor) { if (mesh->descriptor.size <= descriptor) std::runtime_error("No more descriptors for mesh"); return descriptorSets[frame][mesh->descriptor.start + descriptor]; } void bindDescriptors(VkCommandBuffer& buffer, Mesh* mesh, uint32_t frame, uint32_t layout, bool compute=false) { if (compute) vkCmdBindDescriptorSets(buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeLayout(layout), 0, mesh->descriptor.size, &descriptorSets[frame][mesh->descriptor.start], 0, nullptr); else vkCmdBindDescriptorSets(buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeLayout(layout), 0, mesh->descriptor.size, &descriptorSets[frame][mesh->descriptor.start], 0, nullptr); } VkBuffer& getUniBuffer(Mesh* mesh, uint32_t frame, uint32_t buffer) { if (mesh->uniform.size <= buffer) std::runtime_error("No more descriptors for mesh"); return uniBuffers[frame][mesh->uniform.start + buffer]; } VkDeviceMemory& getUniMemory(Mesh* mesh, uint32_t frame, uint32_t buffer) { if (mesh->uniform.size <= buffer) std::runtime_error("No more descriptors for mesh"); return uniMemory[frame][mesh->uniform.start + buffer]; } static VkWriteDescriptorSet writeSet(VkDescriptorType descriptorType, uint32_t binding) { VkWriteDescriptorSet descriptorWrite = {}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstBinding = binding; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = descriptorType; descriptorWrite.descriptorCount = 1; return descriptorWrite; } std::vector<Mesh*> meshes; private: std::vector<StructDescriptorSetLayout> layoutTypes; std::map<VkDescriptorType, uint32_t> descriptorTypes; VkDescriptorPool pool; uint32_t uniIndex = 0; std::vector<std::vector<VkBuffer>> uniBuffers; std::vector<std::vector<VkDeviceMemory>> uniMemory; std::vector<VkDescriptorSetLayout> descriptorLayouts; std::vector<std::vector<VkDescriptorSet>> descriptorSets; std::vector<VkPipelineLayout> pipeLayouts; };
3d7pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 32; 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; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,4);t1++) { lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8)); ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-7,8)),ceild(8*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(4*t1+Ny+5,32)),floord(8*t2+Ny+4,32)),floord(8*t1-8*t2+Nz+Ny+3,32));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(8*t2-Nz-60,64)),ceild(32*t3-Ny-60,64));t4<=min(min(min(min(floord(Nt+Nx-4,64),floord(4*t1+Nx+5,64)),floord(8*t2+Nx+4,64)),floord(32*t3+Nx+28,64)),floord(8*t1-8*t2+Nz+Nx+3,64));t4++) { for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),32*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),32*t3+30),64*t4+62),8*t1-8*t2+Nz+5);t5++) { for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) { lbv=max(64*t4,t5+1); ubv=min(64*t4+63,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
core.c
/* Generated by Cython 0.29.24 */ /* BEGIN: Cython Metadata { "distutils": { "name": "monotonic_align.core", "sources": [ "core.pyx" ] }, "module_name": "monotonic_align.core" } END: Cython Metadata */ #ifndef PY_SSIZE_T_CLEAN #define PY_SSIZE_T_CLEAN #endif /* PY_SSIZE_T_CLEAN */ #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) #error Cython requires Python 2.6+ or Python 3.3+. #else #define CYTHON_ABI "0_29_24" #define CYTHON_HEX_VERSION 0x001D18F0 #define CYTHON_FUTURE_DIVISION 0 #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #define __PYX_COMMA , #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x02070000 #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #if PY_VERSION_HEX < 0x03050000 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #undef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS 0 #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) #define CYTHON_USE_PYTYPE_LOOKUP 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) #endif #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) #endif #ifndef CYTHON_USE_DICT_VERSIONS #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) #endif #ifndef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #ifdef SIZEOF_VOID_P enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; #endif #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifdef _MSC_VER #ifndef _MSC_STDINT_H_ #if _MSC_VER < 1300 typedef unsigned char uint8_t; typedef unsigned int uint32_t; #else typedef unsigned __int8 uint8_t; typedef unsigned __int32 uint32_t; #endif #endif #else #include <stdint.h> #endif #ifndef CYTHON_FALLTHROUGH #if defined(__cplusplus) && __cplusplus >= 201103L #if __has_cpp_attribute(fallthrough) #define CYTHON_FALLTHROUGH [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) #define CYTHON_FALLTHROUGH [[clang::fallthrough]] #elif __has_cpp_attribute(gnu::fallthrough) #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_attribute(fallthrough) #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) #else #define CYTHON_FALLTHROUGH #endif #endif #if defined(__clang__ ) && defined(__apple_build_version__) #if __apple_build_version__ < 7000000 #undef CYTHON_FALLTHROUGH #define CYTHON_FALLTHROUGH #endif #endif #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #elif defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #else #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #endif #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_STACKLESS #define METH_STACKLESS 0 #endif #if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 #endif typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 #define PyMem_RawMalloc(n) PyMem_Malloc(n) #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) #define PyMem_RawFree(p) PyMem_Free(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #elif PY_VERSION_HEX >= 0x03060000 #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() #elif PY_VERSION_HEX >= 0x03000000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #else #define __Pyx_PyThreadState_Current _PyThreadState_Current #endif #if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) #include "pythread.h" #define Py_tss_NEEDS_INIT 0 typedef int Py_tss_t; static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { *key = PyThread_create_key(); return 0; } static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); *key = Py_tss_NEEDS_INIT; return key; } static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { PyObject_Free(key); } static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { return *key != Py_tss_NEEDS_INIT; } static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { PyThread_delete_key(*key); *key = Py_tss_NEEDS_INIT; } static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { return PyThread_set_key_value(*key, value); } static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { return PyThread_get_key_value(*key); } #endif #if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) #define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) #else #define __Pyx_PyDict_NewPresized(n) PyDict_New() #endif #if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS #define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) #else #define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #if defined(PyUnicode_IS_READY) #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #else #define __Pyx_PyUnicode_READY(op) (0) #endif #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) #else #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #endif #else #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) #endif #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #ifndef PyObject_Unicode #define PyObject_Unicode PyObject_Str #endif #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #if PY_VERSION_HEX >= 0x030900A4 #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) #else #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) #endif #if CYTHON_ASSUME_SAFE_MACROS #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) #else #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) #endif #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef __Pyx_PyAsyncMethodsStruct typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_MARK_ERR_POS(f_index, lineno) \ { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } #define __PYX_ERR(f_index, lineno, Ln_error) \ { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__monotonic_align__core #define __PYX_HAVE_API__monotonic_align__core /* Early includes */ #include "pythread.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include "pystate.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { return (size_t) i < (size_t) limit; } #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); #define __Pyx_PySequence_Tuple(obj)\ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; static const char *__pyx_f[] = { "core.pyx", "stringsource", }; /* NoFastGil.proto */ #define __Pyx_PyGILState_Ensure PyGILState_Ensure #define __Pyx_PyGILState_Release PyGILState_Release #define __Pyx_FastGIL_Remember() #define __Pyx_FastGIL_Forget() #define __Pyx_FastGilFuncInit() /* MemviewSliceStruct.proto */ struct __pyx_memoryview_obj; typedef struct { struct __pyx_memoryview_obj *memview; char *data; Py_ssize_t shape[8]; Py_ssize_t strides[8]; Py_ssize_t suboffsets[8]; } __Pyx_memviewslice; #define __Pyx_MemoryView_Len(m) (m.shape[0]) /* Atomics.proto */ #include <pythread.h> #ifndef CYTHON_ATOMICS #define CYTHON_ATOMICS 1 #endif #define __pyx_atomic_int_type int #if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 ||\ (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) &&\ !defined(__i386__) #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) #ifdef __PYX_DEBUG_ATOMICS #warning "Using GNU atomics" #endif #elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 #include <Windows.h> #undef __pyx_atomic_int_type #define __pyx_atomic_int_type LONG #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) #ifdef __PYX_DEBUG_ATOMICS #pragma message ("Using MSVC atomics") #endif #elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) #ifdef __PYX_DEBUG_ATOMICS #warning "Using Intel atomics" #endif #else #undef CYTHON_ATOMICS #define CYTHON_ATOMICS 0 #ifdef __PYX_DEBUG_ATOMICS #warning "Not using atomics" #endif #endif typedef volatile __pyx_atomic_int_type __pyx_atomic_int; #if CYTHON_ATOMICS #define __pyx_add_acquisition_count(memview)\ __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) #define __pyx_sub_acquisition_count(memview)\ __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) #else #define __pyx_add_acquisition_count(memview)\ __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #define __pyx_sub_acquisition_count(memview)\ __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #endif /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* BufferFormatStructs.proto */ #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; /*--- Type declarations ---*/ struct __pyx_array_obj; struct __pyx_MemviewEnum_obj; struct __pyx_memoryview_obj; struct __pyx_memoryviewslice_obj; struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each; struct __pyx_opt_args_15monotonic_align_4core_maximum_path_gradtts_c; /* "monotonic_align/core.pyx":7 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int x * cdef int y */ struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each { int __pyx_n; float max_neg_val; }; /* "monotonic_align/core.pyx":75 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void maximum_path_gradtts_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int b = values.shape[0] * */ struct __pyx_opt_args_15monotonic_align_4core_maximum_path_gradtts_c { int __pyx_n; float max_neg_val; }; /* "View.MemoryView":105 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_array_obj { PyObject_HEAD struct __pyx_vtabstruct_array *__pyx_vtab; char *data; Py_ssize_t len; char *format; int ndim; Py_ssize_t *_shape; Py_ssize_t *_strides; Py_ssize_t itemsize; PyObject *mode; PyObject *_format; void (*callback_free_data)(void *); int free_data; int dtype_is_object; }; /* "View.MemoryView":279 * * @cname('__pyx_MemviewEnum') * cdef class Enum(object): # <<<<<<<<<<<<<< * cdef object name * def __init__(self, name): */ struct __pyx_MemviewEnum_obj { PyObject_HEAD PyObject *name; }; /* "View.MemoryView":330 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< * * cdef object obj */ struct __pyx_memoryview_obj { PyObject_HEAD struct __pyx_vtabstruct_memoryview *__pyx_vtab; PyObject *obj; PyObject *_size; PyObject *_array_interface; PyThread_type_lock lock; __pyx_atomic_int acquisition_count[2]; __pyx_atomic_int *acquisition_count_aligned_p; Py_buffer view; int flags; int dtype_is_object; __Pyx_TypeInfo *typeinfo; }; /* "View.MemoryView":965 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< * "Internal class for passing memoryview slices to Python" * */ struct __pyx_memoryviewslice_obj { struct __pyx_memoryview_obj __pyx_base; __Pyx_memviewslice from_slice; PyObject *from_object; PyObject *(*to_object_func)(char *); int (*to_dtype_func)(char *, PyObject *); }; /* "View.MemoryView":105 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_vtabstruct_array { PyObject *(*get_memview)(struct __pyx_array_obj *); }; static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; /* "View.MemoryView":330 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< * * cdef object obj */ struct __pyx_vtabstruct_memoryview { char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); }; static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; /* "View.MemoryView":965 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< * "Internal class for passing memoryview slices to Python" * */ struct __pyx_vtabstruct__memoryviewslice { struct __pyx_vtabstruct_memoryview __pyx_base; }; static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* MemviewSliceInit.proto */ #define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d #define __Pyx_MEMVIEW_DIRECT 1 #define __Pyx_MEMVIEW_PTR 2 #define __Pyx_MEMVIEW_FULL 4 #define __Pyx_MEMVIEW_CONTIG 8 #define __Pyx_MEMVIEW_STRIDED 16 #define __Pyx_MEMVIEW_FOLLOW 32 #define __Pyx_IS_C_CONTIG 1 #define __Pyx_IS_F_CONTIG 2 static int __Pyx_init_memviewslice( struct __pyx_memoryview_obj *memview, int ndim, __Pyx_memviewslice *memviewslice, int memview_is_new_reference); static CYTHON_INLINE int __pyx_add_acquisition_count_locked( __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); #define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) #define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) #define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) #define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* None.proto */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); /* ArgTypeTest.proto */ #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ __Pyx__ArgTypeTest(obj, type, name, exact)) static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; #define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #define __Pyx_PyErr_Occurred() PyErr_Occurred() #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #endif #else #define __Pyx_PyErr_Clear() PyErr_Clear() #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* PyCFunctionFastCall.proto */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else #define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) #endif /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); #else #define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) #endif #define __Pyx_BUILD_ASSERT_EXPR(cond)\ (sizeof(char [1 - 2*!(cond)]) - 1) #ifndef Py_MEMBER_SIZE #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) #endif static size_t __pyx_pyframe_localsplus_offset = 0; #include "frameobject.h" #define __Pxy_PyFrame_Initialize_Offsets()\ ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) #define __Pyx_PyFrame_GetLocalsplus(frame)\ (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) #endif /* PyObjectCall2Args.proto */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); /* IncludeStringH.proto */ #include <string.h> /* BytesEquals.proto */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /* UnicodeEquals.proto */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /* StrEquals.proto */ #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals #else #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals #endif /* None.proto */ static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* UnaryNegOverflows.proto */ #define UNARY_NEG_WOULD_OVERFLOW(x)\ (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ /* GetAttr.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /* GetItemInt.proto */ #define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ __Pyx_GetItemInt_Generic(o, to_py_func(i)))) #define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); /* ObjectGetItem.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); #else #define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) #endif /* decode_c_string_utf16.proto */ static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 0; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = -1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { int byteorder = 1; return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); } /* decode_c_string.proto */ static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* GetAttr3.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /* PyDictVersioning.proto */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS #define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) #define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ (version_var) = __PYX_GET_DICT_VERSION(dict);\ (cache_var) = (value); #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ (VAR) = __pyx_dict_cached_value;\ } else {\ (VAR) = __pyx_dict_cached_value = (LOOKUP);\ __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ }\ } static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); #else #define __PYX_GET_DICT_VERSION(dict) (0) #define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) #define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); #endif /* GetModuleGlobalName.proto */ #if CYTHON_USE_DICT_VERSIONS #define __Pyx_GetModuleGlobalName(var, name) {\ static PY_UINT64_T __pyx_dict_version = 0;\ static PyObject *__pyx_dict_cached_value = NULL;\ (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } #define __Pyx_GetModuleGlobalNameUncached(var, name) {\ PY_UINT64_T __pyx_dict_version;\ PyObject *__pyx_dict_cached_value;\ (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ } static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); #else #define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) #define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* GetTopmostException.proto */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); #endif /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* SwapException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); #endif /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); #else #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) #define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) #endif #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ /* ListCompAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len)) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); __Pyx_SET_SIZE(list, len + 1); return 0; } return PyList_Append(list, x); } #else #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); #else #define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace, zerodivision_check)\ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) #endif /* ListExtend.proto */ static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { #if CYTHON_COMPILING_IN_CPYTHON PyObject* none = _PyList_Extend((PyListObject*)L, v); if (unlikely(!none)) return -1; Py_DECREF(none); return 0; #else return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); #endif } /* ListAppend.proto */ #if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); __Pyx_SET_SIZE(list, len + 1); return 0; } return PyList_Append(list, x); } #else #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif /* None.proto */ static CYTHON_INLINE long __Pyx_div_long(long, long); /* ImportFrom.proto */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /* HasAttr.proto */ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); /* PyObject_GenericGetAttrNoDict.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr #endif /* PyObject_GenericGetAttr.proto */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); #else #define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr #endif /* SetVTable.proto */ static int __Pyx_SetVtable(PyObject *dict, void *vtable); /* PyObjectGetAttrStrNoError.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); /* SetupReduce.proto */ static int __Pyx_setup_reduce(PyObject* type_obj); /* CLineInTraceback.proto */ #ifdef CYTHON_CLINE_IN_TRACEBACK #define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) #else static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); #endif /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif /* BufferStructDeclare.proto */ typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; /* MemviewSliceIsContig.proto */ static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); /* OverlappingSlices.proto */ static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize); /* Capsule.proto */ static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); /* IsLittleEndian.proto */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); /* BufferFormatCheck.proto */ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); /* TypeInfoCompare.proto */ static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); /* MemviewSliceValidateAndInit.proto */ static int __Pyx_ValidateAndInit_memviewslice( int *axes_specs, int c_or_f_flag, int buf_flags, int ndim, __Pyx_TypeInfo *dtype, __Pyx_BufFmt_StackElem stack[], __Pyx_memviewslice *memviewslice, PyObject *original_obj); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(PyObject *, int writable_flag); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(PyObject *, int writable_flag); /* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *, int writable_flag); /* GCCDiagnostics.proto */ #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) #define __Pyx_HAS_GCC_DIAGNOSTIC #endif /* MemviewSliceCopyTemplate.proto */ static __Pyx_memviewslice __pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, const char *mode, int ndim, size_t sizeof_dtype, int contig_flag, int dtype_is_object); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ /* Module declarations from 'cython.view' */ /* Module declarations from 'cython' */ /* Module declarations from 'monotonic_align.core' */ static PyTypeObject *__pyx_array_type = 0; static PyTypeObject *__pyx_MemviewEnum_type = 0; static PyTypeObject *__pyx_memoryview_type = 0; static PyTypeObject *__pyx_memoryviewslice_type = 0; static PyObject *generic = 0; static PyObject *strided = 0; static PyObject *indirect = 0; static PyObject *contiguous = 0; static PyObject *indirect_contiguous = 0; static int __pyx_memoryview_thread_locks_used; static PyThread_type_lock __pyx_memoryview_thread_locks[8]; static void __pyx_f_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice, __Pyx_memviewslice, int, int, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each *__pyx_optional_args); /*proto*/ static void __pyx_f_15monotonic_align_4core_maximum_path_each_gradtts(__Pyx_memviewslice, __Pyx_memviewslice, int, int, float); /*proto*/ static void __pyx_f_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch); /*proto*/ static void __pyx_f_15monotonic_align_4core_maximum_path_gradtts_c(__Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, __Pyx_memviewslice, int __pyx_skip_dispatch, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_gradtts_c *__pyx_optional_args); /*proto*/ static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ static void *__pyx_align_pointer(void *, size_t); /*proto*/ static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ static PyObject *_unellipsify(PyObject *, int); /*proto*/ static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "monotonic_align.core" extern int __pyx_module_is_main_monotonic_align__core; int __pyx_module_is_main_monotonic_align__core = 0; /* Implementation of 'monotonic_align.core' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_Ellipsis; static PyObject *__pyx_builtin_id; static PyObject *__pyx_builtin_IndexError; static const char __pyx_k_O[] = "O"; static const char __pyx_k_c[] = "c"; static const char __pyx_k_id[] = "id"; static const char __pyx_k_new[] = "__new__"; static const char __pyx_k_obj[] = "obj"; static const char __pyx_k_base[] = "base"; static const char __pyx_k_dict[] = "__dict__"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mode[] = "mode"; static const char __pyx_k_name[] = "name"; static const char __pyx_k_ndim[] = "ndim"; static const char __pyx_k_pack[] = "pack"; static const char __pyx_k_size[] = "size"; static const char __pyx_k_step[] = "step"; static const char __pyx_k_stop[] = "stop"; static const char __pyx_k_t_xs[] = "t_xs"; static const char __pyx_k_t_ys[] = "t_ys"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_ASCII[] = "ASCII"; static const char __pyx_k_class[] = "__class__"; static const char __pyx_k_error[] = "error"; static const char __pyx_k_flags[] = "flags"; static const char __pyx_k_paths[] = "paths"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_shape[] = "shape"; static const char __pyx_k_start[] = "start"; static const char __pyx_k_encode[] = "encode"; static const char __pyx_k_format[] = "format"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_name_2[] = "__name__"; static const char __pyx_k_pickle[] = "pickle"; static const char __pyx_k_reduce[] = "__reduce__"; static const char __pyx_k_struct[] = "struct"; static const char __pyx_k_unpack[] = "unpack"; static const char __pyx_k_update[] = "update"; static const char __pyx_k_values[] = "values"; static const char __pyx_k_fortran[] = "fortran"; static const char __pyx_k_memview[] = "memview"; static const char __pyx_k_Ellipsis[] = "Ellipsis"; static const char __pyx_k_getstate[] = "__getstate__"; static const char __pyx_k_itemsize[] = "itemsize"; static const char __pyx_k_pyx_type[] = "__pyx_type"; static const char __pyx_k_setstate[] = "__setstate__"; static const char __pyx_k_TypeError[] = "TypeError"; static const char __pyx_k_enumerate[] = "enumerate"; static const char __pyx_k_pyx_state[] = "__pyx_state"; static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; static const char __pyx_k_IndexError[] = "IndexError"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_pyx_result[] = "__pyx_result"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_MemoryError[] = "MemoryError"; static const char __pyx_k_PickleError[] = "PickleError"; static const char __pyx_k_max_neg_val[] = "max_neg_val"; static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; static const char __pyx_k_stringsource[] = "stringsource"; static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; static const char __pyx_k_strided_and_direct[] = "<strided and direct>"; static const char __pyx_k_strided_and_indirect[] = "<strided and indirect>"; static const char __pyx_k_contiguous_and_direct[] = "<contiguous and direct>"; static const char __pyx_k_MemoryView_of_r_object[] = "<MemoryView of %r object>"; static const char __pyx_k_MemoryView_of_r_at_0x_x[] = "<MemoryView of %r at 0x%x>"; static const char __pyx_k_contiguous_and_indirect[] = "<contiguous and indirect>"; static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; static const char __pyx_k_strided_and_direct_or_indirect[] = "<strided and direct or indirect>"; static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; static const char __pyx_k_Cannot_assign_to_read_only_memor[] = "Cannot assign to read-only memoryview"; static const char __pyx_k_Cannot_create_writable_memory_vi[] = "Cannot create writable memory view from read-only memoryview"; static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; static const char __pyx_k_Incompatible_checksums_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (name))"; static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; static PyObject *__pyx_n_s_ASCII; static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; static PyObject *__pyx_kp_s_Cannot_assign_to_read_only_memor; static PyObject *__pyx_kp_s_Cannot_create_writable_memory_vi; static PyObject *__pyx_kp_s_Cannot_index_with_type_s; static PyObject *__pyx_n_s_Ellipsis; static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; static PyObject *__pyx_n_s_IndexError; static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; static PyObject *__pyx_n_s_MemoryError; static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; static PyObject *__pyx_kp_s_MemoryView_of_r_object; static PyObject *__pyx_n_b_O; static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; static PyObject *__pyx_n_s_PickleError; static PyObject *__pyx_n_s_TypeError; static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_View_MemoryView; static PyObject *__pyx_n_s_allocate_buffer; static PyObject *__pyx_n_s_base; static PyObject *__pyx_n_s_c; static PyObject *__pyx_n_u_c; static PyObject *__pyx_n_s_class; static PyObject *__pyx_n_s_cline_in_traceback; static PyObject *__pyx_kp_s_contiguous_and_direct; static PyObject *__pyx_kp_s_contiguous_and_indirect; static PyObject *__pyx_n_s_dict; static PyObject *__pyx_n_s_dtype_is_object; static PyObject *__pyx_n_s_encode; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_error; static PyObject *__pyx_n_s_flags; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_fortran; static PyObject *__pyx_n_u_fortran; static PyObject *__pyx_n_s_getstate; static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; static PyObject *__pyx_n_s_id; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_itemsize; static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_max_neg_val; static PyObject *__pyx_n_s_memview; static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_name; static PyObject *__pyx_n_s_name_2; static PyObject *__pyx_n_s_ndim; static PyObject *__pyx_n_s_new; static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; static PyObject *__pyx_n_s_obj; static PyObject *__pyx_n_s_pack; static PyObject *__pyx_n_s_paths; static PyObject *__pyx_n_s_pickle; static PyObject *__pyx_n_s_pyx_PickleError; static PyObject *__pyx_n_s_pyx_checksum; static PyObject *__pyx_n_s_pyx_getbuffer; static PyObject *__pyx_n_s_pyx_result; static PyObject *__pyx_n_s_pyx_state; static PyObject *__pyx_n_s_pyx_type; static PyObject *__pyx_n_s_pyx_unpickle_Enum; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_reduce; static PyObject *__pyx_n_s_reduce_cython; static PyObject *__pyx_n_s_reduce_ex; static PyObject *__pyx_n_s_setstate; static PyObject *__pyx_n_s_setstate_cython; static PyObject *__pyx_n_s_shape; static PyObject *__pyx_n_s_size; static PyObject *__pyx_n_s_start; static PyObject *__pyx_n_s_step; static PyObject *__pyx_n_s_stop; static PyObject *__pyx_kp_s_strided_and_direct; static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; static PyObject *__pyx_kp_s_strided_and_indirect; static PyObject *__pyx_kp_s_stringsource; static PyObject *__pyx_n_s_struct; static PyObject *__pyx_n_s_t_xs; static PyObject *__pyx_n_s_t_ys; static PyObject *__pyx_n_s_test; static PyObject *__pyx_kp_s_unable_to_allocate_array_data; static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; static PyObject *__pyx_n_s_unpack; static PyObject *__pyx_n_s_update; static PyObject *__pyx_n_s_values; static PyObject *__pyx_pf_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs); /* proto */ static PyObject *__pyx_pf_15monotonic_align_4core_2maximum_path_gradtts_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_xs, __Pyx_memviewslice __pyx_v_t_ys, float __pyx_v_max_neg_val); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_184977713; static PyObject *__pyx_int_neg_1; static float __pyx_k_; static float __pyx_k__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; static PyObject *__pyx_tuple__9; static PyObject *__pyx_slice__17; static PyObject *__pyx_tuple__10; static PyObject *__pyx_tuple__11; static PyObject *__pyx_tuple__12; static PyObject *__pyx_tuple__13; static PyObject *__pyx_tuple__14; static PyObject *__pyx_tuple__15; static PyObject *__pyx_tuple__16; static PyObject *__pyx_tuple__18; static PyObject *__pyx_tuple__19; static PyObject *__pyx_tuple__20; static PyObject *__pyx_tuple__21; static PyObject *__pyx_tuple__22; static PyObject *__pyx_tuple__23; static PyObject *__pyx_tuple__24; static PyObject *__pyx_tuple__25; static PyObject *__pyx_tuple__26; static PyObject *__pyx_codeobj__27; /* Late includes */ /* "monotonic_align/core.pyx":7 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int x * cdef int y */ static void __pyx_f_15monotonic_align_4core_maximum_path_each(__Pyx_memviewslice __pyx_v_path, __Pyx_memviewslice __pyx_v_value, int __pyx_v_t_y, int __pyx_v_t_x, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_each *__pyx_optional_args) { float __pyx_v_max_neg_val = __pyx_k_; int __pyx_v_x; int __pyx_v_y; float __pyx_v_v_prev; float __pyx_v_v_cur; int __pyx_v_index; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; long __pyx_t_4; int __pyx_t_5; long __pyx_t_6; long __pyx_t_7; int __pyx_t_8; Py_ssize_t __pyx_t_9; Py_ssize_t __pyx_t_10; float __pyx_t_11; float __pyx_t_12; float __pyx_t_13; int __pyx_t_14; Py_ssize_t __pyx_t_15; Py_ssize_t __pyx_t_16; if (__pyx_optional_args) { if (__pyx_optional_args->__pyx_n > 0) { __pyx_v_max_neg_val = __pyx_optional_args->max_neg_val; } } /* "monotonic_align/core.pyx":13 * cdef float v_cur * cdef float tmp * cdef int index = t_x - 1 # <<<<<<<<<<<<<< * * for y in range(t_y): */ __pyx_v_index = (__pyx_v_t_x - 1); /* "monotonic_align/core.pyx":15 * cdef int index = t_x - 1 * * for y in range(t_y): # <<<<<<<<<<<<<< * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: */ __pyx_t_1 = __pyx_v_t_y; __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_y = __pyx_t_3; /* "monotonic_align/core.pyx":16 * * for y in range(t_y): * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): # <<<<<<<<<<<<<< * if x == y: * v_cur = max_neg_val */ __pyx_t_4 = (__pyx_v_y + 1); __pyx_t_5 = __pyx_v_t_x; if (((__pyx_t_4 < __pyx_t_5) != 0)) { __pyx_t_6 = __pyx_t_4; } else { __pyx_t_6 = __pyx_t_5; } __pyx_t_4 = __pyx_t_6; __pyx_t_5 = ((__pyx_v_t_x + __pyx_v_y) - __pyx_v_t_y); __pyx_t_6 = 0; if (((__pyx_t_5 > __pyx_t_6) != 0)) { __pyx_t_7 = __pyx_t_5; } else { __pyx_t_7 = __pyx_t_6; } __pyx_t_6 = __pyx_t_4; for (__pyx_t_5 = __pyx_t_7; __pyx_t_5 < __pyx_t_6; __pyx_t_5+=1) { __pyx_v_x = __pyx_t_5; /* "monotonic_align/core.pyx":17 * for y in range(t_y): * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: # <<<<<<<<<<<<<< * v_cur = max_neg_val * else: */ __pyx_t_8 = ((__pyx_v_x == __pyx_v_y) != 0); if (__pyx_t_8) { /* "monotonic_align/core.pyx":18 * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: * v_cur = max_neg_val # <<<<<<<<<<<<<< * else: * v_cur = value[y-1, x] */ __pyx_v_v_cur = __pyx_v_max_neg_val; /* "monotonic_align/core.pyx":17 * for y in range(t_y): * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: # <<<<<<<<<<<<<< * v_cur = max_neg_val * else: */ goto __pyx_L7; } /* "monotonic_align/core.pyx":20 * v_cur = max_neg_val * else: * v_cur = value[y-1, x] # <<<<<<<<<<<<<< * if x == 0: * if y == 0: */ /*else*/ { __pyx_t_9 = (__pyx_v_y - 1); __pyx_t_10 = __pyx_v_x; __pyx_v_v_cur = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))); } __pyx_L7:; /* "monotonic_align/core.pyx":21 * else: * v_cur = value[y-1, x] * if x == 0: # <<<<<<<<<<<<<< * if y == 0: * v_prev = 0. */ __pyx_t_8 = ((__pyx_v_x == 0) != 0); if (__pyx_t_8) { /* "monotonic_align/core.pyx":22 * v_cur = value[y-1, x] * if x == 0: * if y == 0: # <<<<<<<<<<<<<< * v_prev = 0. * else: */ __pyx_t_8 = ((__pyx_v_y == 0) != 0); if (__pyx_t_8) { /* "monotonic_align/core.pyx":23 * if x == 0: * if y == 0: * v_prev = 0. # <<<<<<<<<<<<<< * else: * v_prev = max_neg_val */ __pyx_v_v_prev = 0.; /* "monotonic_align/core.pyx":22 * v_cur = value[y-1, x] * if x == 0: * if y == 0: # <<<<<<<<<<<<<< * v_prev = 0. * else: */ goto __pyx_L9; } /* "monotonic_align/core.pyx":25 * v_prev = 0. * else: * v_prev = max_neg_val # <<<<<<<<<<<<<< * else: * v_prev = value[y-1, x-1] */ /*else*/ { __pyx_v_v_prev = __pyx_v_max_neg_val; } __pyx_L9:; /* "monotonic_align/core.pyx":21 * else: * v_cur = value[y-1, x] * if x == 0: # <<<<<<<<<<<<<< * if y == 0: * v_prev = 0. */ goto __pyx_L8; } /* "monotonic_align/core.pyx":27 * v_prev = max_neg_val * else: * v_prev = value[y-1, x-1] # <<<<<<<<<<<<<< * value[y, x] += max(v_prev, v_cur) * */ /*else*/ { __pyx_t_10 = (__pyx_v_y - 1); __pyx_t_9 = (__pyx_v_x - 1); __pyx_v_v_prev = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_10 * __pyx_v_value.strides[0]) )) + __pyx_t_9)) ))); } __pyx_L8:; /* "monotonic_align/core.pyx":28 * else: * v_prev = value[y-1, x-1] * value[y, x] += max(v_prev, v_cur) # <<<<<<<<<<<<<< * * for y in range(t_y - 1, -1, -1): */ __pyx_t_11 = __pyx_v_v_cur; __pyx_t_12 = __pyx_v_v_prev; if (((__pyx_t_11 > __pyx_t_12) != 0)) { __pyx_t_13 = __pyx_t_11; } else { __pyx_t_13 = __pyx_t_12; } __pyx_t_9 = __pyx_v_y; __pyx_t_10 = __pyx_v_x; *((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) )) += __pyx_t_13; } } /* "monotonic_align/core.pyx":30 * value[y, x] += max(v_prev, v_cur) * * for y in range(t_y - 1, -1, -1): # <<<<<<<<<<<<<< * path[y, index] = 1 * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): */ for (__pyx_t_1 = (__pyx_v_t_y - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_y = __pyx_t_1; /* "monotonic_align/core.pyx":31 * * for y in range(t_y - 1, -1, -1): * path[y, index] = 1 # <<<<<<<<<<<<<< * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): * index = index - 1 */ __pyx_t_10 = __pyx_v_y; __pyx_t_9 = __pyx_v_index; *((int *) ( /* dim=1 */ ((char *) (((int *) ( /* dim=0 */ (__pyx_v_path.data + __pyx_t_10 * __pyx_v_path.strides[0]) )) + __pyx_t_9)) )) = 1; /* "monotonic_align/core.pyx":32 * for y in range(t_y - 1, -1, -1): * path[y, index] = 1 * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): # <<<<<<<<<<<<<< * index = index - 1 * */ __pyx_t_14 = ((__pyx_v_index != 0) != 0); if (__pyx_t_14) { } else { __pyx_t_8 = __pyx_t_14; goto __pyx_L13_bool_binop_done; } __pyx_t_14 = ((__pyx_v_index == __pyx_v_y) != 0); if (!__pyx_t_14) { } else { __pyx_t_8 = __pyx_t_14; goto __pyx_L13_bool_binop_done; } __pyx_t_9 = (__pyx_v_y - 1); __pyx_t_10 = __pyx_v_index; __pyx_t_15 = (__pyx_v_y - 1); __pyx_t_16 = (__pyx_v_index - 1); __pyx_t_14 = (((*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))) < (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_15 * __pyx_v_value.strides[0]) )) + __pyx_t_16)) )))) != 0); __pyx_t_8 = __pyx_t_14; __pyx_L13_bool_binop_done:; if (__pyx_t_8) { /* "monotonic_align/core.pyx":33 * path[y, index] = 1 * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): * index = index - 1 # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __pyx_v_index = (__pyx_v_index - 1); /* "monotonic_align/core.pyx":32 * for y in range(t_y - 1, -1, -1): * path[y, index] = 1 * if index != 0 and (index == y or value[y-1, index] < value[y-1, index-1]): # <<<<<<<<<<<<<< * index = index - 1 * */ } } /* "monotonic_align/core.pyx":7 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int x * cdef int y */ /* function exit code */ } /* "monotonic_align/core.pyx":37 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef void maximum_path_each_gradtts(int[:,::1] path, float[:,::1] value, int t_x, int t_y, float max_neg_val) nogil: # <<<<<<<<<<<<<< * cdef int x * cdef int y */ static void __pyx_f_15monotonic_align_4core_maximum_path_each_gradtts(__Pyx_memviewslice __pyx_v_path, __Pyx_memviewslice __pyx_v_value, int __pyx_v_t_x, int __pyx_v_t_y, float __pyx_v_max_neg_val) { int __pyx_v_x; int __pyx_v_y; float __pyx_v_v_prev; float __pyx_v_v_cur; int __pyx_v_index; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; long __pyx_t_4; int __pyx_t_5; long __pyx_t_6; long __pyx_t_7; int __pyx_t_8; Py_ssize_t __pyx_t_9; Py_ssize_t __pyx_t_10; float __pyx_t_11; float __pyx_t_12; float __pyx_t_13; Py_ssize_t __pyx_t_14; Py_ssize_t __pyx_t_15; int __pyx_t_16; /* "monotonic_align/core.pyx":43 * cdef float v_cur * cdef float tmp * cdef int index = t_x - 1 # <<<<<<<<<<<<<< * * for y in range(t_y): */ __pyx_v_index = (__pyx_v_t_x - 1); /* "monotonic_align/core.pyx":45 * cdef int index = t_x - 1 * * for y in range(t_y): # <<<<<<<<<<<<<< * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: */ __pyx_t_1 = __pyx_v_t_y; __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_y = __pyx_t_3; /* "monotonic_align/core.pyx":46 * * for y in range(t_y): * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): # <<<<<<<<<<<<<< * if x == y: * v_cur = max_neg_val */ __pyx_t_4 = (__pyx_v_y + 1); __pyx_t_5 = __pyx_v_t_x; if (((__pyx_t_4 < __pyx_t_5) != 0)) { __pyx_t_6 = __pyx_t_4; } else { __pyx_t_6 = __pyx_t_5; } __pyx_t_4 = __pyx_t_6; __pyx_t_5 = ((__pyx_v_t_x + __pyx_v_y) - __pyx_v_t_y); __pyx_t_6 = 0; if (((__pyx_t_5 > __pyx_t_6) != 0)) { __pyx_t_7 = __pyx_t_5; } else { __pyx_t_7 = __pyx_t_6; } __pyx_t_6 = __pyx_t_4; for (__pyx_t_5 = __pyx_t_7; __pyx_t_5 < __pyx_t_6; __pyx_t_5+=1) { __pyx_v_x = __pyx_t_5; /* "monotonic_align/core.pyx":47 * for y in range(t_y): * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: # <<<<<<<<<<<<<< * v_cur = max_neg_val * else: */ __pyx_t_8 = ((__pyx_v_x == __pyx_v_y) != 0); if (__pyx_t_8) { /* "monotonic_align/core.pyx":48 * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: * v_cur = max_neg_val # <<<<<<<<<<<<<< * else: * v_cur = value[x, y-1] */ __pyx_v_v_cur = __pyx_v_max_neg_val; /* "monotonic_align/core.pyx":47 * for y in range(t_y): * for x in range(max(0, t_x + y - t_y), min(t_x, y + 1)): * if x == y: # <<<<<<<<<<<<<< * v_cur = max_neg_val * else: */ goto __pyx_L7; } /* "monotonic_align/core.pyx":50 * v_cur = max_neg_val * else: * v_cur = value[x, y-1] # <<<<<<<<<<<<<< * if x == 0: * if y == 0: */ /*else*/ { __pyx_t_9 = __pyx_v_x; __pyx_t_10 = (__pyx_v_y - 1); __pyx_v_v_cur = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))); } __pyx_L7:; /* "monotonic_align/core.pyx":51 * else: * v_cur = value[x, y-1] * if x == 0: # <<<<<<<<<<<<<< * if y == 0: * v_prev = 0. */ __pyx_t_8 = ((__pyx_v_x == 0) != 0); if (__pyx_t_8) { /* "monotonic_align/core.pyx":52 * v_cur = value[x, y-1] * if x == 0: * if y == 0: # <<<<<<<<<<<<<< * v_prev = 0. * else: */ __pyx_t_8 = ((__pyx_v_y == 0) != 0); if (__pyx_t_8) { /* "monotonic_align/core.pyx":53 * if x == 0: * if y == 0: * v_prev = 0. # <<<<<<<<<<<<<< * else: * v_prev = max_neg_val */ __pyx_v_v_prev = 0.; /* "monotonic_align/core.pyx":52 * v_cur = value[x, y-1] * if x == 0: * if y == 0: # <<<<<<<<<<<<<< * v_prev = 0. * else: */ goto __pyx_L9; } /* "monotonic_align/core.pyx":55 * v_prev = 0. * else: * v_prev = max_neg_val # <<<<<<<<<<<<<< * else: * v_prev = value[x-1, y-1] */ /*else*/ { __pyx_v_v_prev = __pyx_v_max_neg_val; } __pyx_L9:; /* "monotonic_align/core.pyx":51 * else: * v_cur = value[x, y-1] * if x == 0: # <<<<<<<<<<<<<< * if y == 0: * v_prev = 0. */ goto __pyx_L8; } /* "monotonic_align/core.pyx":57 * v_prev = max_neg_val * else: * v_prev = value[x-1, y-1] # <<<<<<<<<<<<<< * value[x, y] = max(v_cur, v_prev) + value[x, y] * */ /*else*/ { __pyx_t_10 = (__pyx_v_x - 1); __pyx_t_9 = (__pyx_v_y - 1); __pyx_v_v_prev = (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_10 * __pyx_v_value.strides[0]) )) + __pyx_t_9)) ))); } __pyx_L8:; /* "monotonic_align/core.pyx":58 * else: * v_prev = value[x-1, y-1] * value[x, y] = max(v_cur, v_prev) + value[x, y] # <<<<<<<<<<<<<< * * for y in range(t_y - 1, -1, -1): */ __pyx_t_11 = __pyx_v_v_prev; __pyx_t_12 = __pyx_v_v_cur; if (((__pyx_t_11 > __pyx_t_12) != 0)) { __pyx_t_13 = __pyx_t_11; } else { __pyx_t_13 = __pyx_t_12; } __pyx_t_9 = __pyx_v_x; __pyx_t_10 = __pyx_v_y; __pyx_t_14 = __pyx_v_x; __pyx_t_15 = __pyx_v_y; *((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_14 * __pyx_v_value.strides[0]) )) + __pyx_t_15)) )) = (__pyx_t_13 + (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) )))); } } /* "monotonic_align/core.pyx":60 * value[x, y] = max(v_cur, v_prev) + value[x, y] * * for y in range(t_y - 1, -1, -1): # <<<<<<<<<<<<<< * path[index, y] = 1 * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): */ for (__pyx_t_1 = (__pyx_v_t_y - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_y = __pyx_t_1; /* "monotonic_align/core.pyx":61 * * for y in range(t_y - 1, -1, -1): * path[index, y] = 1 # <<<<<<<<<<<<<< * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): * index = index - 1 */ __pyx_t_10 = __pyx_v_index; __pyx_t_9 = __pyx_v_y; *((int *) ( /* dim=1 */ ((char *) (((int *) ( /* dim=0 */ (__pyx_v_path.data + __pyx_t_10 * __pyx_v_path.strides[0]) )) + __pyx_t_9)) )) = 1; /* "monotonic_align/core.pyx":62 * for y in range(t_y - 1, -1, -1): * path[index, y] = 1 * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): # <<<<<<<<<<<<<< * index = index - 1 * */ __pyx_t_16 = ((__pyx_v_index != 0) != 0); if (__pyx_t_16) { } else { __pyx_t_8 = __pyx_t_16; goto __pyx_L13_bool_binop_done; } __pyx_t_16 = ((__pyx_v_index == __pyx_v_y) != 0); if (!__pyx_t_16) { } else { __pyx_t_8 = __pyx_t_16; goto __pyx_L13_bool_binop_done; } __pyx_t_9 = __pyx_v_index; __pyx_t_10 = (__pyx_v_y - 1); __pyx_t_15 = (__pyx_v_index - 1); __pyx_t_14 = (__pyx_v_y - 1); __pyx_t_16 = (((*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_9 * __pyx_v_value.strides[0]) )) + __pyx_t_10)) ))) < (*((float *) ( /* dim=1 */ ((char *) (((float *) ( /* dim=0 */ (__pyx_v_value.data + __pyx_t_15 * __pyx_v_value.strides[0]) )) + __pyx_t_14)) )))) != 0); __pyx_t_8 = __pyx_t_16; __pyx_L13_bool_binop_done:; if (__pyx_t_8) { /* "monotonic_align/core.pyx":63 * path[index, y] = 1 * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): * index = index - 1 # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __pyx_v_index = (__pyx_v_index - 1); /* "monotonic_align/core.pyx":62 * for y in range(t_y - 1, -1, -1): * path[index, y] = 1 * if index != 0 and (index == y or value[index, y-1] < value[index-1, y-1]): # <<<<<<<<<<<<<< * index = index - 1 * */ } } /* "monotonic_align/core.pyx":37 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef void maximum_path_each_gradtts(int[:,::1] path, float[:,::1] value, int t_x, int t_y, float max_neg_val) nogil: # <<<<<<<<<<<<<< * cdef int x * cdef int y */ /* function exit code */ } /* "monotonic_align/core.pyx":67 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: # <<<<<<<<<<<<<< * cdef int b = paths.shape[0] * cdef int i */ static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static void __pyx_f_15monotonic_align_4core_maximum_path_c(__Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs, CYTHON_UNUSED int __pyx_skip_dispatch) { CYTHON_UNUSED int __pyx_v_b; int __pyx_v_i; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; /* "monotonic_align/core.pyx":68 * @cython.wraparound(False) * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: * cdef int b = paths.shape[0] # <<<<<<<<<<<<<< * cdef int i * for i in prange(b, nogil=True): */ __pyx_v_b = (__pyx_v_paths.shape[0]); /* "monotonic_align/core.pyx":70 * cdef int b = paths.shape[0] * cdef int i * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) * */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { __pyx_t_1 = __pyx_v_b; if ((1 == 0)) abort(); { #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) (x) #define unlikely(x) (x) #endif __pyx_t_3 = (__pyx_t_1 - 0 + 1 - 1/abs(1)) / 1; if (__pyx_t_3 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_6, __pyx_t_7) firstprivate(__pyx_t_4, __pyx_t_5) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) #endif /* _OPENMP */ for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){ { __pyx_v_i = (int)(0 + 1 * __pyx_t_2); /* "monotonic_align/core.pyx":71 * cdef int i * for i in prange(b, nogil=True): * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __pyx_t_4.data = __pyx_v_paths.data; __pyx_t_4.memview = __pyx_v_paths.memview; __PYX_INC_MEMVIEW(&__pyx_t_4, 0); { Py_ssize_t __pyx_tmp_idx = __pyx_v_i; Py_ssize_t __pyx_tmp_stride = __pyx_v_paths.strides[0]; __pyx_t_4.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_4.shape[0] = __pyx_v_paths.shape[1]; __pyx_t_4.strides[0] = __pyx_v_paths.strides[1]; __pyx_t_4.suboffsets[0] = -1; __pyx_t_4.shape[1] = __pyx_v_paths.shape[2]; __pyx_t_4.strides[1] = __pyx_v_paths.strides[2]; __pyx_t_4.suboffsets[1] = -1; __pyx_t_5.data = __pyx_v_values.data; __pyx_t_5.memview = __pyx_v_values.memview; __PYX_INC_MEMVIEW(&__pyx_t_5, 0); { Py_ssize_t __pyx_tmp_idx = __pyx_v_i; Py_ssize_t __pyx_tmp_stride = __pyx_v_values.strides[0]; __pyx_t_5.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_5.shape[0] = __pyx_v_values.shape[1]; __pyx_t_5.strides[0] = __pyx_v_values.strides[1]; __pyx_t_5.suboffsets[0] = -1; __pyx_t_5.shape[1] = __pyx_v_values.shape[2]; __pyx_t_5.strides[1] = __pyx_v_values.strides[2]; __pyx_t_5.suboffsets[1] = -1; __pyx_t_6 = __pyx_v_i; __pyx_t_7 = __pyx_v_i; __pyx_f_15monotonic_align_4core_maximum_path_each(__pyx_t_4, __pyx_t_5, (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_ys.data) + __pyx_t_6)) ))), (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_xs.data) + __pyx_t_7)) ))), NULL); __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0); __pyx_t_4.memview = NULL; __pyx_t_4.data = NULL; __PYX_XDEC_MEMVIEW(&__pyx_t_5, 0); __pyx_t_5.memview = NULL; __pyx_t_5.data = NULL; } } } } } #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #endif } /* "monotonic_align/core.pyx":70 * cdef int b = paths.shape[0] * cdef int i * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< * maximum_path_each(paths[i], values[i], t_ys[i], t_xs[i]) * */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "monotonic_align/core.pyx":67 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void maximum_path_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_ys, int[::1] t_xs) nogil: # <<<<<<<<<<<<<< * cdef int b = paths.shape[0] * cdef int i */ /* function exit code */ } /* Python wrapper */ static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_15monotonic_align_4core_1maximum_path_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_paths = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_values = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_t_ys = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_t_xs = { 0, 0, { 0 }, { 0 }, { 0 } }; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("maximum_path_c (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_paths,&__pyx_n_s_values,&__pyx_n_s_t_ys,&__pyx_n_s_t_xs,0}; PyObject* values[4] = {0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_paths)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_values)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 1); __PYX_ERR(0, 67, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_ys)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 2); __PYX_ERR(0, 67, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_xs)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, 3); __PYX_ERR(0, 67, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "maximum_path_c") < 0)) __PYX_ERR(0, 67, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); } __pyx_v_paths = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_paths.memview)) __PYX_ERR(0, 67, __pyx_L3_error) __pyx_v_values = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_values.memview)) __PYX_ERR(0, 67, __pyx_L3_error) __pyx_v_t_ys = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_ys.memview)) __PYX_ERR(0, 67, __pyx_L3_error) __pyx_v_t_xs = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_xs.memview)) __PYX_ERR(0, 67, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("maximum_path_c", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 67, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_15monotonic_align_4core_maximum_path_c(__pyx_self, __pyx_v_paths, __pyx_v_values, __pyx_v_t_ys, __pyx_v_t_xs); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15monotonic_align_4core_maximum_path_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_ys, __Pyx_memviewslice __pyx_v_t_xs) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("maximum_path_c", 0); __Pyx_XDECREF(__pyx_r); if (unlikely(!__pyx_v_paths.memview)) { __Pyx_RaiseUnboundLocalError("paths"); __PYX_ERR(0, 67, __pyx_L1_error) } if (unlikely(!__pyx_v_values.memview)) { __Pyx_RaiseUnboundLocalError("values"); __PYX_ERR(0, 67, __pyx_L1_error) } if (unlikely(!__pyx_v_t_ys.memview)) { __Pyx_RaiseUnboundLocalError("t_ys"); __PYX_ERR(0, 67, __pyx_L1_error) } if (unlikely(!__pyx_v_t_xs.memview)) { __Pyx_RaiseUnboundLocalError("t_xs"); __PYX_ERR(0, 67, __pyx_L1_error) } __pyx_t_1 = __Pyx_void_to_None(__pyx_f_15monotonic_align_4core_maximum_path_c(__pyx_v_paths, __pyx_v_values, __pyx_v_t_ys, __pyx_v_t_xs, 0)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("monotonic_align.core.maximum_path_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_paths, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_values, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_t_ys, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_t_xs, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "monotonic_align/core.pyx":75 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void maximum_path_gradtts_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int b = values.shape[0] * */ static PyObject *__pyx_pw_15monotonic_align_4core_3maximum_path_gradtts_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static void __pyx_f_15monotonic_align_4core_maximum_path_gradtts_c(__Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_xs, __Pyx_memviewslice __pyx_v_t_ys, CYTHON_UNUSED int __pyx_skip_dispatch, struct __pyx_opt_args_15monotonic_align_4core_maximum_path_gradtts_c *__pyx_optional_args) { float __pyx_v_max_neg_val = __pyx_k__2; CYTHON_UNUSED int __pyx_v_b; int __pyx_v_i; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; __Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_t_5 = { 0, 0, { 0 }, { 0 }, { 0 } }; Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; if (__pyx_optional_args) { if (__pyx_optional_args->__pyx_n > 0) { __pyx_v_max_neg_val = __pyx_optional_args->max_neg_val; } } /* "monotonic_align/core.pyx":76 * @cython.wraparound(False) * cpdef void maximum_path_gradtts_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: * cdef int b = values.shape[0] # <<<<<<<<<<<<<< * * cdef int i */ __pyx_v_b = (__pyx_v_values.shape[0]); /* "monotonic_align/core.pyx":79 * * cdef int i * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< * maximum_path_each_gradtts(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val) */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { __pyx_t_1 = __pyx_v_b; if ((1 == 0)) abort(); { #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) (x) #define unlikely(x) (x) #endif __pyx_t_3 = (__pyx_t_1 - 0 + 1 - 1/abs(1)) / 1; if (__pyx_t_3 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_6, __pyx_t_7) firstprivate(__pyx_t_4, __pyx_t_5) #endif /* _OPENMP */ { #ifdef _OPENMP #pragma omp for firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) #endif /* _OPENMP */ for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){ { __pyx_v_i = (int)(0 + 1 * __pyx_t_2); /* "monotonic_align/core.pyx":80 * cdef int i * for i in prange(b, nogil=True): * maximum_path_each_gradtts(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val) # <<<<<<<<<<<<<< */ __pyx_t_4.data = __pyx_v_paths.data; __pyx_t_4.memview = __pyx_v_paths.memview; __PYX_INC_MEMVIEW(&__pyx_t_4, 0); { Py_ssize_t __pyx_tmp_idx = __pyx_v_i; Py_ssize_t __pyx_tmp_stride = __pyx_v_paths.strides[0]; __pyx_t_4.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_4.shape[0] = __pyx_v_paths.shape[1]; __pyx_t_4.strides[0] = __pyx_v_paths.strides[1]; __pyx_t_4.suboffsets[0] = -1; __pyx_t_4.shape[1] = __pyx_v_paths.shape[2]; __pyx_t_4.strides[1] = __pyx_v_paths.strides[2]; __pyx_t_4.suboffsets[1] = -1; __pyx_t_5.data = __pyx_v_values.data; __pyx_t_5.memview = __pyx_v_values.memview; __PYX_INC_MEMVIEW(&__pyx_t_5, 0); { Py_ssize_t __pyx_tmp_idx = __pyx_v_i; Py_ssize_t __pyx_tmp_stride = __pyx_v_values.strides[0]; __pyx_t_5.data += __pyx_tmp_idx * __pyx_tmp_stride; } __pyx_t_5.shape[0] = __pyx_v_values.shape[1]; __pyx_t_5.strides[0] = __pyx_v_values.strides[1]; __pyx_t_5.suboffsets[0] = -1; __pyx_t_5.shape[1] = __pyx_v_values.shape[2]; __pyx_t_5.strides[1] = __pyx_v_values.strides[2]; __pyx_t_5.suboffsets[1] = -1; __pyx_t_6 = __pyx_v_i; __pyx_t_7 = __pyx_v_i; __pyx_f_15monotonic_align_4core_maximum_path_each_gradtts(__pyx_t_4, __pyx_t_5, (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_xs.data) + __pyx_t_6)) ))), (*((int *) ( /* dim=0 */ ((char *) (((int *) __pyx_v_t_ys.data) + __pyx_t_7)) ))), __pyx_v_max_neg_val); __PYX_XDEC_MEMVIEW(&__pyx_t_4, 0); __pyx_t_4.memview = NULL; __pyx_t_4.data = NULL; __PYX_XDEC_MEMVIEW(&__pyx_t_5, 0); __pyx_t_5.memview = NULL; __pyx_t_5.data = NULL; } } } } } #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #endif } /* "monotonic_align/core.pyx":79 * * cdef int i * for i in prange(b, nogil=True): # <<<<<<<<<<<<<< * maximum_path_each_gradtts(paths[i], values[i], t_xs[i], t_ys[i], max_neg_val) */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "monotonic_align/core.pyx":75 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void maximum_path_gradtts_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int b = values.shape[0] * */ /* function exit code */ } /* Python wrapper */ static PyObject *__pyx_pw_15monotonic_align_4core_3maximum_path_gradtts_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyObject *__pyx_pw_15monotonic_align_4core_3maximum_path_gradtts_c(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { __Pyx_memviewslice __pyx_v_paths = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_values = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_t_xs = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_t_ys = { 0, 0, { 0 }, { 0 }, { 0 } }; float __pyx_v_max_neg_val; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("maximum_path_gradtts_c (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_paths,&__pyx_n_s_values,&__pyx_n_s_t_xs,&__pyx_n_s_t_ys,&__pyx_n_s_max_neg_val,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_paths)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_values)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("maximum_path_gradtts_c", 0, 4, 5, 1); __PYX_ERR(0, 75, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_xs)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("maximum_path_gradtts_c", 0, 4, 5, 2); __PYX_ERR(0, 75, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_t_ys)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("maximum_path_gradtts_c", 0, 4, 5, 3); __PYX_ERR(0, 75, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 4: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_neg_val); if (value) { values[4] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "maximum_path_gradtts_c") < 0)) __PYX_ERR(0, 75, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_paths = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(values[0], PyBUF_WRITABLE); if (unlikely(!__pyx_v_paths.memview)) __PYX_ERR(0, 75, __pyx_L3_error) __pyx_v_values = __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(values[1], PyBUF_WRITABLE); if (unlikely(!__pyx_v_values.memview)) __PYX_ERR(0, 75, __pyx_L3_error) __pyx_v_t_xs = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[2], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_xs.memview)) __PYX_ERR(0, 75, __pyx_L3_error) __pyx_v_t_ys = __Pyx_PyObject_to_MemoryviewSlice_dc_int(values[3], PyBUF_WRITABLE); if (unlikely(!__pyx_v_t_ys.memview)) __PYX_ERR(0, 75, __pyx_L3_error) if (values[4]) { __pyx_v_max_neg_val = __pyx_PyFloat_AsFloat(values[4]); if (unlikely((__pyx_v_max_neg_val == (float)-1) && PyErr_Occurred())) __PYX_ERR(0, 75, __pyx_L3_error) } else { __pyx_v_max_neg_val = __pyx_k__2; } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("maximum_path_gradtts_c", 0, 4, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 75, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("monotonic_align.core.maximum_path_gradtts_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_15monotonic_align_4core_2maximum_path_gradtts_c(__pyx_self, __pyx_v_paths, __pyx_v_values, __pyx_v_t_xs, __pyx_v_t_ys, __pyx_v_max_neg_val); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15monotonic_align_4core_2maximum_path_gradtts_c(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_paths, __Pyx_memviewslice __pyx_v_values, __Pyx_memviewslice __pyx_v_t_xs, __Pyx_memviewslice __pyx_v_t_ys, float __pyx_v_max_neg_val) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations struct __pyx_opt_args_15monotonic_align_4core_maximum_path_gradtts_c __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("maximum_path_gradtts_c", 0); __Pyx_XDECREF(__pyx_r); if (unlikely(!__pyx_v_paths.memview)) { __Pyx_RaiseUnboundLocalError("paths"); __PYX_ERR(0, 75, __pyx_L1_error) } if (unlikely(!__pyx_v_values.memview)) { __Pyx_RaiseUnboundLocalError("values"); __PYX_ERR(0, 75, __pyx_L1_error) } if (unlikely(!__pyx_v_t_xs.memview)) { __Pyx_RaiseUnboundLocalError("t_xs"); __PYX_ERR(0, 75, __pyx_L1_error) } if (unlikely(!__pyx_v_t_ys.memview)) { __Pyx_RaiseUnboundLocalError("t_ys"); __PYX_ERR(0, 75, __pyx_L1_error) } __pyx_t_1.__pyx_n = 1; __pyx_t_1.max_neg_val = __pyx_v_max_neg_val; __pyx_f_15monotonic_align_4core_maximum_path_gradtts_c(__pyx_v_paths, __pyx_v_values, __pyx_v_t_xs, __pyx_v_t_ys, 0, &__pyx_t_1); __pyx_t_2 = __Pyx_void_to_None(NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 75, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("monotonic_align.core.maximum_path_gradtts_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __PYX_XDEC_MEMVIEW(&__pyx_v_paths, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_values, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_t_xs, 1); __PYX_XDEC_MEMVIEW(&__pyx_v_t_ys, 1); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":122 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* Python wrapper */ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_shape = 0; Py_ssize_t __pyx_v_itemsize; PyObject *__pyx_v_format = 0; PyObject *__pyx_v_mode = 0; int __pyx_v_allocate_buffer; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; PyObject* values[5] = {0,0,0,0,0}; values[3] = ((PyObject *)__pyx_n_s_c); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(1, 122, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(1, 122, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mode); if (value) { values[3] = value; kw_args--; } } CYTHON_FALLTHROUGH; case 4: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_allocate_buffer); if (value) { values[4] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 122, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_shape = ((PyObject*)values[0]); __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 122, __pyx_L3_error) __pyx_v_format = values[2]; __pyx_v_mode = values[3]; if (values[4]) { __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 123, __pyx_L3_error) } else { /* "View.MemoryView":123 * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< * * cdef int idx */ __pyx_v_allocate_buffer = ((int)1); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 122, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) __PYX_ERR(1, 122, __pyx_L1_error) if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(1, 122, __pyx_L1_error) } __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); /* "View.MemoryView":122 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { int __pyx_v_idx; Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_dim; PyObject **__pyx_v_p; char __pyx_v_order; int __pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; int __pyx_t_8; Py_ssize_t __pyx_t_9; PyObject *__pyx_t_10 = NULL; Py_ssize_t __pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF(__pyx_v_format); /* "View.MemoryView":129 * cdef PyObject **p * * self.ndim = <int> len(shape) # <<<<<<<<<<<<<< * self.itemsize = itemsize * */ if (unlikely(__pyx_v_shape == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(1, 129, __pyx_L1_error) } __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(1, 129, __pyx_L1_error) __pyx_v_self->ndim = ((int)__pyx_t_1); /* "View.MemoryView":130 * * self.ndim = <int> len(shape) * self.itemsize = itemsize # <<<<<<<<<<<<<< * * if not self.ndim: */ __pyx_v_self->itemsize = __pyx_v_itemsize; /* "View.MemoryView":132 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); if (unlikely(__pyx_t_2)) { /* "View.MemoryView":133 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 133, __pyx_L1_error) /* "View.MemoryView":132 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ } /* "View.MemoryView":135 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); if (unlikely(__pyx_t_2)) { /* "View.MemoryView":136 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 136, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 136, __pyx_L1_error) /* "View.MemoryView":135 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ } /* "View.MemoryView":138 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ __pyx_t_2 = PyBytes_Check(__pyx_v_format); __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":139 * * if not isinstance(format, bytes): * format = format.encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 139, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_6)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_6); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); } } __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_5, __pyx_t_6, __pyx_n_s_ASCII) : __Pyx_PyObject_CallOneArg(__pyx_t_5, __pyx_n_s_ASCII); __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 139, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":138 * raise ValueError("itemsize <= 0 for cython.array") * * if not isinstance(format, bytes): # <<<<<<<<<<<<<< * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ } /* "View.MemoryView":140 * if not isinstance(format, bytes): * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< * self.format = self._format * */ if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(1, 140, __pyx_L1_error) __pyx_t_3 = __pyx_v_format; __Pyx_INCREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __Pyx_GOTREF(__pyx_v_self->_format); __Pyx_DECREF(__pyx_v_self->_format); __pyx_v_self->_format = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":141 * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string * self.format = self._format # <<<<<<<<<<<<<< * * */ if (unlikely(__pyx_v_self->_format == Py_None)) { PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); __PYX_ERR(1, 141, __pyx_L1_error) } __pyx_t_7 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(1, 141, __pyx_L1_error) __pyx_v_self->format = __pyx_t_7; /* "View.MemoryView":144 * * * self._shape = <Py_ssize_t *> PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< * self._strides = self._shape + self.ndim * */ __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); /* "View.MemoryView":145 * * self._shape = <Py_ssize_t *> PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< * * if not self._shape: */ __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); /* "View.MemoryView":147 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); if (unlikely(__pyx_t_4)) { /* "View.MemoryView":148 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 148, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 148, __pyx_L1_error) /* "View.MemoryView":147 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ } /* "View.MemoryView":151 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ __pyx_t_8 = 0; __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; for (;;) { if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_5); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(1, 151, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_5); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 151, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_dim = __pyx_t_9; __pyx_v_idx = __pyx_t_8; __pyx_t_8 = (__pyx_t_8 + 1); /* "View.MemoryView":152 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); if (unlikely(__pyx_t_4)) { /* "View.MemoryView":153 * for idx, dim in enumerate(shape): * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< * self._shape[idx] = dim * */ __pyx_t_5 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_6); __pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_6); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 153, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(1, 153, __pyx_L1_error) /* "View.MemoryView":152 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ } /* "View.MemoryView":154 * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim # <<<<<<<<<<<<<< * * cdef char order */ (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; /* "View.MemoryView":151 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":157 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 157, __pyx_L1_error) if (__pyx_t_4) { /* "View.MemoryView":158 * cdef char order * if mode == 'fortran': * order = b'F' # <<<<<<<<<<<<<< * self.mode = u'fortran' * elif mode == 'c': */ __pyx_v_order = 'F'; /* "View.MemoryView":159 * if mode == 'fortran': * order = b'F' * self.mode = u'fortran' # <<<<<<<<<<<<<< * elif mode == 'c': * order = b'C' */ __Pyx_INCREF(__pyx_n_u_fortran); __Pyx_GIVEREF(__pyx_n_u_fortran); __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_fortran; /* "View.MemoryView":157 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ goto __pyx_L10; } /* "View.MemoryView":160 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 160, __pyx_L1_error) if (likely(__pyx_t_4)) { /* "View.MemoryView":161 * self.mode = u'fortran' * elif mode == 'c': * order = b'C' # <<<<<<<<<<<<<< * self.mode = u'c' * else: */ __pyx_v_order = 'C'; /* "View.MemoryView":162 * elif mode == 'c': * order = b'C' * self.mode = u'c' # <<<<<<<<<<<<<< * else: * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) */ __Pyx_INCREF(__pyx_n_u_c); __Pyx_GIVEREF(__pyx_n_u_c); __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_c; /* "View.MemoryView":160 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ goto __pyx_L10; } /* "View.MemoryView":164 * self.mode = u'c' * else: * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< * * self.len = fill_contig_strides_array(self._shape, self._strides, */ /*else*/ { __pyx_t_3 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 164, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 164, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(1, 164, __pyx_L1_error) } __pyx_L10:; /* "View.MemoryView":166 * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) * * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< * itemsize, self.ndim, order) * */ __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); /* "View.MemoryView":169 * itemsize, self.ndim, order) * * self.free_data = allocate_buffer # <<<<<<<<<<<<<< * self.dtype_is_object = format == b'O' * if allocate_buffer: */ __pyx_v_self->free_data = __pyx_v_allocate_buffer; /* "View.MemoryView":170 * * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< * if allocate_buffer: * */ __pyx_t_10 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_10); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 170, __pyx_L1_error) __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_10); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 170, __pyx_L1_error) __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_v_self->dtype_is_object = __pyx_t_4; /* "View.MemoryView":171 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ __pyx_t_4 = (__pyx_v_allocate_buffer != 0); if (__pyx_t_4) { /* "View.MemoryView":174 * * * self.data = <char *>malloc(self.len) # <<<<<<<<<<<<<< * if not self.data: * raise MemoryError("unable to allocate array data.") */ __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); /* "View.MemoryView":175 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); if (unlikely(__pyx_t_4)) { /* "View.MemoryView":176 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); __Pyx_Raise(__pyx_t_10, 0, 0, 0); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __PYX_ERR(1, 176, __pyx_L1_error) /* "View.MemoryView":175 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ } /* "View.MemoryView":178 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< * p = <PyObject **> self.data * for i in range(self.len / itemsize): */ __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_4) { /* "View.MemoryView":179 * * if self.dtype_is_object: * p = <PyObject **> self.data # <<<<<<<<<<<<<< * for i in range(self.len / itemsize): * p[i] = Py_None */ __pyx_v_p = ((PyObject **)__pyx_v_self->data); /* "View.MemoryView":180 * if self.dtype_is_object: * p = <PyObject **> self.data * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< * p[i] = Py_None * Py_INCREF(Py_None) */ if (unlikely(__pyx_v_itemsize == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(1, 180, __pyx_L1_error) } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(1, 180, __pyx_L1_error) } __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); __pyx_t_9 = __pyx_t_1; for (__pyx_t_11 = 0; __pyx_t_11 < __pyx_t_9; __pyx_t_11+=1) { __pyx_v_i = __pyx_t_11; /* "View.MemoryView":181 * p = <PyObject **> self.data * for i in range(self.len / itemsize): * p[i] = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ (__pyx_v_p[__pyx_v_i]) = Py_None; /* "View.MemoryView":182 * for i in range(self.len / itemsize): * p[i] = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * @cname('getbuffer') */ Py_INCREF(Py_None); } /* "View.MemoryView":178 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< * p = <PyObject **> self.data * for i in range(self.len / itemsize): */ } /* "View.MemoryView":171 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":122 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_format); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":185 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * cdef int bufmode = -1 * if self.mode == u"c": */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_bufmode; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; char *__pyx_t_4; Py_ssize_t __pyx_t_5; int __pyx_t_6; Py_ssize_t *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "View.MemoryView":186 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 # <<<<<<<<<<<<<< * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS */ __pyx_v_bufmode = -1; /* "View.MemoryView":187 * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 * if self.mode == u"c": # <<<<<<<<<<<<<< * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": */ __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 187, __pyx_L1_error) __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":188 * cdef int bufmode = -1 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS */ __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); /* "View.MemoryView":187 * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 * if self.mode == u"c": # <<<<<<<<<<<<<< * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": */ goto __pyx_L3; } /* "View.MemoryView":189 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": # <<<<<<<<<<<<<< * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): */ __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 189, __pyx_L1_error) __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":190 * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") */ __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); /* "View.MemoryView":189 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": # <<<<<<<<<<<<<< * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): */ } __pyx_L3:; /* "View.MemoryView":191 * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): # <<<<<<<<<<<<<< * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data */ __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":192 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 192, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 192, __pyx_L1_error) /* "View.MemoryView":191 * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): # <<<<<<<<<<<<<< * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data */ } /* "View.MemoryView":193 * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data # <<<<<<<<<<<<<< * info.len = self.len * info.ndim = self.ndim */ __pyx_t_4 = __pyx_v_self->data; __pyx_v_info->buf = __pyx_t_4; /* "View.MemoryView":194 * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data * info.len = self.len # <<<<<<<<<<<<<< * info.ndim = self.ndim * info.shape = self._shape */ __pyx_t_5 = __pyx_v_self->len; __pyx_v_info->len = __pyx_t_5; /* "View.MemoryView":195 * info.buf = self.data * info.len = self.len * info.ndim = self.ndim # <<<<<<<<<<<<<< * info.shape = self._shape * info.strides = self._strides */ __pyx_t_6 = __pyx_v_self->ndim; __pyx_v_info->ndim = __pyx_t_6; /* "View.MemoryView":196 * info.len = self.len * info.ndim = self.ndim * info.shape = self._shape # <<<<<<<<<<<<<< * info.strides = self._strides * info.suboffsets = NULL */ __pyx_t_7 = __pyx_v_self->_shape; __pyx_v_info->shape = __pyx_t_7; /* "View.MemoryView":197 * info.ndim = self.ndim * info.shape = self._shape * info.strides = self._strides # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = self.itemsize */ __pyx_t_7 = __pyx_v_self->_strides; __pyx_v_info->strides = __pyx_t_7; /* "View.MemoryView":198 * info.shape = self._shape * info.strides = self._strides * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = self.itemsize * info.readonly = 0 */ __pyx_v_info->suboffsets = NULL; /* "View.MemoryView":199 * info.strides = self._strides * info.suboffsets = NULL * info.itemsize = self.itemsize # <<<<<<<<<<<<<< * info.readonly = 0 * */ __pyx_t_5 = __pyx_v_self->itemsize; __pyx_v_info->itemsize = __pyx_t_5; /* "View.MemoryView":200 * info.suboffsets = NULL * info.itemsize = self.itemsize * info.readonly = 0 # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ __pyx_v_info->readonly = 0; /* "View.MemoryView":202 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":203 * * if flags & PyBUF_FORMAT: * info.format = self.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_4 = __pyx_v_self->format; __pyx_v_info->format = __pyx_t_4; /* "View.MemoryView":202 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ goto __pyx_L5; } /* "View.MemoryView":205 * info.format = self.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.obj = self */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L5:; /* "View.MemoryView":207 * info.format = NULL * * info.obj = self # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "View.MemoryView":185 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * cdef int bufmode = -1 * if self.mode == u"c": */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":211 * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< * if self.callback_free_data != NULL: * self.callback_free_data(self.data) */ /* Python wrapper */ static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":212 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< * self.callback_free_data(self.data) * elif self.free_data: */ __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":213 * def __dealloc__(array self): * if self.callback_free_data != NULL: * self.callback_free_data(self.data) # <<<<<<<<<<<<<< * elif self.free_data: * if self.dtype_is_object: */ __pyx_v_self->callback_free_data(__pyx_v_self->data); /* "View.MemoryView":212 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< * self.callback_free_data(self.data) * elif self.free_data: */ goto __pyx_L3; } /* "View.MemoryView":214 * if self.callback_free_data != NULL: * self.callback_free_data(self.data) * elif self.free_data: # <<<<<<<<<<<<<< * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, */ __pyx_t_1 = (__pyx_v_self->free_data != 0); if (__pyx_t_1) { /* "View.MemoryView":215 * self.callback_free_data(self.data) * elif self.free_data: * if self.dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) */ __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":216 * elif self.free_data: * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< * self._strides, self.ndim, False) * free(self.data) */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); /* "View.MemoryView":215 * self.callback_free_data(self.data) * elif self.free_data: * if self.dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) */ } /* "View.MemoryView":218 * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) * free(self.data) # <<<<<<<<<<<<<< * PyObject_Free(self._shape) * */ free(__pyx_v_self->data); /* "View.MemoryView":214 * if self.callback_free_data != NULL: * self.callback_free_data(self.data) * elif self.free_data: # <<<<<<<<<<<<<< * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, */ } __pyx_L3:; /* "View.MemoryView":219 * self._strides, self.ndim, False) * free(self.data) * PyObject_Free(self._shape) # <<<<<<<<<<<<<< * * @property */ PyObject_Free(__pyx_v_self->_shape); /* "View.MemoryView":211 * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< * if self.callback_free_data != NULL: * self.callback_free_data(self.data) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":222 * * @property * def memview(self): # <<<<<<<<<<<<<< * return self.get_memview() * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":223 * @property * def memview(self): * return self.get_memview() # <<<<<<<<<<<<<< * * @cname('get_memview') */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 223, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":222 * * @property * def memview(self): # <<<<<<<<<<<<<< * return self.get_memview() * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":226 * * @cname('get_memview') * cdef get_memview(self): # <<<<<<<<<<<<<< * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) */ static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self) { int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_memview", 0); /* "View.MemoryView":227 * @cname('get_memview') * cdef get_memview(self): * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< * return memoryview(self, flags, self.dtype_is_object) * */ __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); /* "View.MemoryView":228 * cdef get_memview(self): * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< * * def __len__(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 228, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":226 * * @cname('get_memview') * cdef get_memview(self): # <<<<<<<<<<<<<< * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.array.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":230 * return memoryview(self, flags, self.dtype_is_object) * * def __len__(self): # <<<<<<<<<<<<<< * return self._shape[0] * */ /* Python wrapper */ static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__", 0); /* "View.MemoryView":231 * * def __len__(self): * return self._shape[0] # <<<<<<<<<<<<<< * * def __getattr__(self, attr): */ __pyx_r = (__pyx_v_self->_shape[0]); goto __pyx_L0; /* "View.MemoryView":230 * return memoryview(self, flags, self.dtype_is_object) * * def __len__(self): # <<<<<<<<<<<<<< * return self._shape[0] * */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":233 * return self._shape[0] * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) * */ /* Python wrapper */ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getattr__", 0); /* "View.MemoryView":234 * * def __getattr__(self, attr): * return getattr(self.memview, attr) # <<<<<<<<<<<<<< * * def __getitem__(self, item): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 234, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 234, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":233 * return self._shape[0] * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":236 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< * return self.memview[item] * */ /* Python wrapper */ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":237 * * def __getitem__(self, item): * return self.memview[item] # <<<<<<<<<<<<<< * * def __setitem__(self, item, value): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 237, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 237, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":236 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< * return self.memview[item] * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":239 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* Python wrapper */ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); /* "View.MemoryView":240 * * def __setitem__(self, item, value): * self.memview[item] = value # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 240, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(1, 240, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":239 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":244 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< * char *mode, char *buf): * cdef array result */ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { struct __pyx_array_obj *__pyx_v_result = 0; struct __pyx_array_obj *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("array_cwrapper", 0); /* "View.MemoryView":248 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":249 * * if buf == NULL: * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), */ __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":248 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ goto __pyx_L3; } /* "View.MemoryView":251 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ /*else*/ { __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_3 = 0; /* "View.MemoryView":252 * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) # <<<<<<<<<<<<<< * result.data = buf * */ __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 252, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(1, 252, __pyx_L1_error) /* "View.MemoryView":251 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":253 * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) * result.data = buf # <<<<<<<<<<<<<< * * return result */ __pyx_v_result->data = __pyx_v_buf; } __pyx_L3:; /* "View.MemoryView":255 * result.data = buf * * return result # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":244 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< * char *mode, char *buf): * cdef array result */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":281 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< * self.name = name * def __repr__(self): */ /* Python wrapper */ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_name = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(1, 281, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); } __pyx_v_name = values[0]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 281, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__", 0); /* "View.MemoryView":282 * cdef object name * def __init__(self, name): * self.name = name # <<<<<<<<<<<<<< * def __repr__(self): * return self.name */ __Pyx_INCREF(__pyx_v_name); __Pyx_GIVEREF(__pyx_v_name); __Pyx_GOTREF(__pyx_v_self->name); __Pyx_DECREF(__pyx_v_self->name); __pyx_v_self->name = __pyx_v_name; /* "View.MemoryView":281 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< * self.name = name * def __repr__(self): */ /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":283 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< * return self.name * */ /* Python wrapper */ static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__", 0); /* "View.MemoryView":284 * self.name = name * def __repr__(self): * return self.name # <<<<<<<<<<<<<< * * cdef generic = Enum("<strided and direct or indirect>") */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->name); __pyx_r = __pyx_v_self->name; goto __pyx_L0; /* "View.MemoryView":283 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< * return self.name * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * cdef tuple state * cdef object _dict */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { PyObject *__pyx_v_state = 0; PyObject *__pyx_v__dict = 0; int __pyx_v_use_setstate; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":5 * cdef object _dict * cdef bint use_setstate * state = (self.name,) # <<<<<<<<<<<<<< * _dict = getattr(self, '__dict__', None) * if _dict is not None: */ __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_self->name); __Pyx_GIVEREF(__pyx_v_self->name); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); __pyx_v_state = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":6 * cdef bint use_setstate * state = (self.name,) * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< * if _dict is not None: * state += (_dict,) */ __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v__dict = __pyx_t_1; __pyx_t_1 = 0; /* "(tree fragment)":7 * state = (self.name,) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< * state += (_dict,) * use_setstate = True */ __pyx_t_2 = (__pyx_v__dict != Py_None); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { /* "(tree fragment)":8 * _dict = getattr(self, '__dict__', None) * if _dict is not None: * state += (_dict,) # <<<<<<<<<<<<<< * use_setstate = True * else: */ __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v__dict); __Pyx_GIVEREF(__pyx_v__dict); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); __pyx_t_4 = 0; /* "(tree fragment)":9 * if _dict is not None: * state += (_dict,) * use_setstate = True # <<<<<<<<<<<<<< * else: * use_setstate = self.name is not None */ __pyx_v_use_setstate = 1; /* "(tree fragment)":7 * state = (self.name,) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< * state += (_dict,) * use_setstate = True */ goto __pyx_L3; } /* "(tree fragment)":11 * use_setstate = True * else: * use_setstate = self.name is not None # <<<<<<<<<<<<<< * if use_setstate: * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state */ /*else*/ { __pyx_t_3 = (__pyx_v_self->name != Py_None); __pyx_v_use_setstate = __pyx_t_3; } __pyx_L3:; /* "(tree fragment)":12 * else: * use_setstate = self.name is not None * if use_setstate: # <<<<<<<<<<<<<< * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: */ __pyx_t_3 = (__pyx_v_use_setstate != 0); if (__pyx_t_3) { /* "(tree fragment)":13 * use_setstate = self.name is not None * if use_setstate: * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) */ __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_INCREF(__pyx_int_184977713); __Pyx_GIVEREF(__pyx_int_184977713); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); __Pyx_INCREF(__pyx_v_state); __Pyx_GIVEREF(__pyx_v_state); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); __pyx_t_4 = 0; __pyx_t_1 = 0; __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "(tree fragment)":12 * else: * use_setstate = self.name is not None * if use_setstate: # <<<<<<<<<<<<<< * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: */ } /* "(tree fragment)":15 * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); __Pyx_INCREF(__pyx_int_184977713); __Pyx_GIVEREF(__pyx_int_184977713); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); __Pyx_INCREF(__pyx_v_state); __Pyx_GIVEREF(__pyx_v_state); PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); __pyx_t_5 = 0; __pyx_t_1 = 0; __pyx_r = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L0; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * cdef tuple state * cdef object _dict */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_state); __Pyx_XDECREF(__pyx_v__dict); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":16 * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":17 * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< */ if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 17, __pyx_L1_error) __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":16 * else: * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(self, __pyx_state) */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":298 * * @cname('__pyx_align_pointer') * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory */ static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { Py_intptr_t __pyx_v_aligned_p; size_t __pyx_v_offset; void *__pyx_r; int __pyx_t_1; /* "View.MemoryView":300 * cdef void *align_pointer(void *memory, size_t alignment) nogil: * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory # <<<<<<<<<<<<<< * cdef size_t offset * */ __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); /* "View.MemoryView":304 * * with cython.cdivision(True): * offset = aligned_p % alignment # <<<<<<<<<<<<<< * * if offset > 0: */ __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); /* "View.MemoryView":306 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ __pyx_t_1 = ((__pyx_v_offset > 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":307 * * if offset > 0: * aligned_p += alignment - offset # <<<<<<<<<<<<<< * * return <void *> aligned_p */ __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); /* "View.MemoryView":306 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ } /* "View.MemoryView":309 * aligned_p += alignment - offset * * return <void *> aligned_p # <<<<<<<<<<<<<< * * */ __pyx_r = ((void *)__pyx_v_aligned_p); goto __pyx_L0; /* "View.MemoryView":298 * * @cname('__pyx_align_pointer') * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":345 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< * self.obj = obj * self.flags = flags */ /* Python wrapper */ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_obj = 0; int __pyx_v_flags; int __pyx_v_dtype_is_object; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(1, 345, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (kw_args > 0) { PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_dtype_is_object); if (value) { values[2] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 345, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_obj = values[0]; __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 345, __pyx_L3_error) if (values[2]) { __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 345, __pyx_L3_error) } else { __pyx_v_dtype_is_object = ((int)0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 345, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); /* "View.MemoryView":346 * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj # <<<<<<<<<<<<<< * self.flags = flags * if type(self) is memoryview or obj is not None: */ __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); __Pyx_GOTREF(__pyx_v_self->obj); __Pyx_DECREF(__pyx_v_self->obj); __pyx_v_self->obj = __pyx_v_obj; /* "View.MemoryView":347 * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj * self.flags = flags # <<<<<<<<<<<<<< * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) */ __pyx_v_self->flags = __pyx_v_flags; /* "View.MemoryView":348 * self.obj = obj * self.flags = flags * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: */ __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)__pyx_memoryview_type)); __pyx_t_3 = (__pyx_t_2 != 0); if (!__pyx_t_3) { } else { __pyx_t_1 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } __pyx_t_3 = (__pyx_v_obj != Py_None); __pyx_t_2 = (__pyx_t_3 != 0); __pyx_t_1 = __pyx_t_2; __pyx_L4_bool_binop_done:; if (__pyx_t_1) { /* "View.MemoryView":349 * self.flags = flags * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None */ __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 349, __pyx_L1_error) /* "View.MemoryView":350 * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: # <<<<<<<<<<<<<< * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) */ __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":351 * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; /* "View.MemoryView":352 * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * global __pyx_memoryview_thread_locks_used */ Py_INCREF(Py_None); /* "View.MemoryView":350 * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: # <<<<<<<<<<<<<< * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) */ } /* "View.MemoryView":348 * self.obj = obj * self.flags = flags * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: */ } /* "View.MemoryView":355 * * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 */ __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); if (__pyx_t_1) { /* "View.MemoryView":356 * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: */ __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); /* "View.MemoryView":357 * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< * if self.lock is NULL: * self.lock = PyThread_allocate_lock() */ __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); /* "View.MemoryView":355 * * global __pyx_memoryview_thread_locks_used * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 */ } /* "View.MemoryView":358 * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: # <<<<<<<<<<<<<< * self.lock = PyThread_allocate_lock() * if self.lock is NULL: */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":359 * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< * if self.lock is NULL: * raise MemoryError */ __pyx_v_self->lock = PyThread_allocate_lock(); /* "View.MemoryView":360 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() * if self.lock is NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":361 * self.lock = PyThread_allocate_lock() * if self.lock is NULL: * raise MemoryError # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ PyErr_NoMemory(); __PYX_ERR(1, 361, __pyx_L1_error) /* "View.MemoryView":360 * if self.lock is NULL: * self.lock = PyThread_allocate_lock() * if self.lock is NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ } /* "View.MemoryView":358 * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] * __pyx_memoryview_thread_locks_used += 1 * if self.lock is NULL: # <<<<<<<<<<<<<< * self.lock = PyThread_allocate_lock() * if self.lock is NULL: */ } /* "View.MemoryView":363 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":364 * * if flags & PyBUF_FORMAT: * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< * else: * self.dtype_is_object = dtype_is_object */ __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L11_bool_binop_done; } __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); __pyx_t_1 = __pyx_t_2; __pyx_L11_bool_binop_done:; __pyx_v_self->dtype_is_object = __pyx_t_1; /* "View.MemoryView":363 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: */ goto __pyx_L10; } /* "View.MemoryView":366 * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( */ /*else*/ { __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; } __pyx_L10:; /* "View.MemoryView":368 * self.dtype_is_object = dtype_is_object * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< * <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) * self.typeinfo = NULL */ __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); /* "View.MemoryView":370 * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( * <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) * self.typeinfo = NULL # <<<<<<<<<<<<<< * * def __dealloc__(memoryview self): */ __pyx_v_self->typeinfo = NULL; /* "View.MemoryView":345 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< * self.obj = obj * self.flags = flags */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":372 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* Python wrapper */ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { int __pyx_v_i; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; PyThread_type_lock __pyx_t_6; PyThread_type_lock __pyx_t_7; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":373 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: */ __pyx_t_1 = (__pyx_v_self->obj != Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":374 * def __dealloc__(memoryview self): * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< * elif (<__pyx_buffer *> &self.view).obj == Py_None: * */ __Pyx_ReleaseBuffer((&__pyx_v_self->view)); /* "View.MemoryView":373 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: */ goto __pyx_L3; } /* "View.MemoryView":375 * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< * * (<__pyx_buffer *> &self.view).obj = NULL */ __pyx_t_2 = ((((Py_buffer *)(&__pyx_v_self->view))->obj == Py_None) != 0); if (__pyx_t_2) { /* "View.MemoryView":377 * elif (<__pyx_buffer *> &self.view).obj == Py_None: * * (<__pyx_buffer *> &self.view).obj = NULL # <<<<<<<<<<<<<< * Py_DECREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_self->view))->obj = NULL; /* "View.MemoryView":378 * * (<__pyx_buffer *> &self.view).obj = NULL * Py_DECREF(Py_None) # <<<<<<<<<<<<<< * * cdef int i */ Py_DECREF(Py_None); /* "View.MemoryView":375 * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) * elif (<__pyx_buffer *> &self.view).obj == Py_None: # <<<<<<<<<<<<<< * * (<__pyx_buffer *> &self.view).obj = NULL */ } __pyx_L3:; /* "View.MemoryView":382 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: */ __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":383 * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 */ __pyx_t_3 = __pyx_memoryview_thread_locks_used; __pyx_t_4 = __pyx_t_3; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":384 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: */ __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); if (__pyx_t_2) { /* "View.MemoryView":385 * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( */ __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); /* "View.MemoryView":386 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) */ __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); if (__pyx_t_2) { /* "View.MemoryView":388 * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< * break * else: */ __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); __pyx_t_7 = (__pyx_memoryview_thread_locks[__pyx_v_i]); /* "View.MemoryView":387 * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) * break */ (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_6; (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_7; /* "View.MemoryView":386 * if __pyx_memoryview_thread_locks[i] is self.lock: * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) */ } /* "View.MemoryView":389 * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) * break # <<<<<<<<<<<<<< * else: * PyThread_free_lock(self.lock) */ goto __pyx_L6_break; /* "View.MemoryView":384 * if self.lock != NULL: * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< * __pyx_memoryview_thread_locks_used -= 1 * if i != __pyx_memoryview_thread_locks_used: */ } } /*else*/ { /* "View.MemoryView":391 * break * else: * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< * * cdef char *get_item_pointer(memoryview self, object index) except NULL: */ PyThread_free_lock(__pyx_v_self->lock); } __pyx_L6_break:; /* "View.MemoryView":382 * cdef int i * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< * for i in range(__pyx_memoryview_thread_locks_used): * if __pyx_memoryview_thread_locks[i] is self.lock: */ } /* "View.MemoryView":372 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":393 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf */ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { Py_ssize_t __pyx_v_dim; char *__pyx_v_itemp; PyObject *__pyx_v_idx = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; Py_ssize_t __pyx_t_3; PyObject *(*__pyx_t_4)(PyObject *); PyObject *__pyx_t_5 = NULL; Py_ssize_t __pyx_t_6; char *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_item_pointer", 0); /* "View.MemoryView":395 * cdef char *get_item_pointer(memoryview self, object index) except NULL: * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf # <<<<<<<<<<<<<< * * for dim, idx in enumerate(index): */ __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); /* "View.MemoryView":397 * cdef char *itemp = <char *> self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< * itemp = pybuffer_index(&self.view, itemp, idx, dim) * */ __pyx_t_1 = 0; if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; __pyx_t_4 = NULL; } else { __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 397, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 397, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_4)) { if (likely(PyList_CheckExact(__pyx_t_2))) { if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 397, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif } else { if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 397, __pyx_L1_error) #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 397, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif } } else { __pyx_t_5 = __pyx_t_4(__pyx_t_2); if (unlikely(!__pyx_t_5)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(1, 397, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_5); } __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); __pyx_t_5 = 0; __pyx_v_dim = __pyx_t_1; __pyx_t_1 = (__pyx_t_1 + 1); /* "View.MemoryView":398 * * for dim, idx in enumerate(index): * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< * * return itemp */ __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 398, __pyx_L1_error) __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == ((char *)NULL))) __PYX_ERR(1, 398, __pyx_L1_error) __pyx_v_itemp = __pyx_t_7; /* "View.MemoryView":397 * cdef char *itemp = <char *> self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< * itemp = pybuffer_index(&self.view, itemp, idx, dim) * */ } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":400 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_itemp; goto __pyx_L0; /* "View.MemoryView":393 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_idx); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":403 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< * if index is Ellipsis: * return self */ /* Python wrapper */ static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_indices = NULL; char *__pyx_v_itemp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; char *__pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":404 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":405 * def __getitem__(memoryview self, object index): * if index is Ellipsis: * return self # <<<<<<<<<<<<<< * * have_slices, indices = _unellipsify(index, self.view.ndim) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __pyx_r = ((PyObject *)__pyx_v_self); goto __pyx_L0; /* "View.MemoryView":404 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ } /* "View.MemoryView":407 * return self * * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * cdef char *itemp */ __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 407, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); #else __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 407, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 407, __pyx_L1_error) } __pyx_v_have_slices = __pyx_t_4; __pyx_t_4 = 0; __pyx_v_indices = __pyx_t_5; __pyx_t_5 = 0; /* "View.MemoryView":410 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 410, __pyx_L1_error) if (__pyx_t_2) { /* "View.MemoryView":411 * cdef char *itemp * if have_slices: * return memview_slice(self, indices) # <<<<<<<<<<<<<< * else: * itemp = self.get_item_pointer(indices) */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 411, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":410 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ } /* "View.MemoryView":413 * return memview_slice(self, indices) * else: * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< * return self.convert_item_to_object(itemp) * */ /*else*/ { __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == ((char *)NULL))) __PYX_ERR(1, 413, __pyx_L1_error) __pyx_v_itemp = __pyx_t_6; /* "View.MemoryView":414 * else: * itemp = self.get_item_pointer(indices) * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< * * def __setitem__(memoryview self, object index, object value): */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 414, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":403 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< * if index is Ellipsis: * return self */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_have_slices); __Pyx_XDECREF(__pyx_v_indices); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":416 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") */ /* Python wrapper */ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_obj = NULL; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); /* "View.MemoryView":417 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< * raise TypeError("Cannot assign to read-only memoryview") * */ __pyx_t_1 = (__pyx_v_self->view.readonly != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":418 * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< * * have_slices, index = _unellipsify(index, self.view.ndim) */ __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 418, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(1, 418, __pyx_L1_error) /* "View.MemoryView":417 * * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: # <<<<<<<<<<<<<< * raise TypeError("Cannot assign to read-only memoryview") * */ } /* "View.MemoryView":420 * raise TypeError("Cannot assign to read-only memoryview") * * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * if have_slices: */ __pyx_t_2 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (likely(__pyx_t_2 != Py_None)) { PyObject* sequence = __pyx_t_2; Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 420, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 420, __pyx_L1_error) } __pyx_v_have_slices = __pyx_t_3; __pyx_t_3 = 0; __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":422 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 422, __pyx_L1_error) if (__pyx_t_1) { /* "View.MemoryView":423 * * if have_slices: * obj = self.is_slice(value) # <<<<<<<<<<<<<< * if obj: * self.setitem_slice_assignment(self[index], obj) */ __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 423, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_v_obj = __pyx_t_2; __pyx_t_2 = 0; /* "View.MemoryView":424 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 424, __pyx_L1_error) if (__pyx_t_1) { /* "View.MemoryView":425 * obj = self.is_slice(value) * if obj: * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< * else: * self.setitem_slice_assign_scalar(self[index], value) */ __pyx_t_2 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 425, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_2, __pyx_v_obj); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 425, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":424 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ goto __pyx_L5; } /* "View.MemoryView":427 * self.setitem_slice_assignment(self[index], obj) * else: * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< * else: * self.setitem_indexed(index, value) */ /*else*/ { __pyx_t_4 = __Pyx_PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 427, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_memoryview_type))))) __PYX_ERR(1, 427, __pyx_L1_error) __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_4), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 427, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L5:; /* "View.MemoryView":422 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ goto __pyx_L4; } /* "View.MemoryView":429 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< * * cdef is_slice(self, obj): */ /*else*/ { __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 429, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L4:; /* "View.MemoryView":416 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_have_slices); __Pyx_XDECREF(__pyx_v_obj); __Pyx_XDECREF(__pyx_v_index); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":431 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< * if not isinstance(obj, memoryview): * try: */ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_slice", 0); __Pyx_INCREF(__pyx_v_obj); /* "View.MemoryView":432 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); __Pyx_XGOTREF(__pyx_t_5); /*try:*/ { /* "View.MemoryView":434 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_6 = __Pyx_PyInt_From_int(((__pyx_v_self->flags & (~PyBUF_WRITABLE)) | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 434, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":435 * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) # <<<<<<<<<<<<<< * except TypeError: * return None */ __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 435, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); /* "View.MemoryView":434 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 434, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 434, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ } __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L9_try_end; __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; /* "View.MemoryView":436 * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) * except TypeError: # <<<<<<<<<<<<<< * return None * */ __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_TypeError); if (__pyx_t_9) { __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) __PYX_ERR(1, 436, __pyx_L6_except_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":437 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< * * return obj */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; goto __pyx_L7_except_return; } goto __pyx_L6_except_error; __pyx_L6_except_error:; /* "View.MemoryView":433 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L1_error; __pyx_L7_except_return:; __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L0; __pyx_L9_try_end:; } /* "View.MemoryView":432 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags & ~PyBUF_WRITABLE | PyBUF_ANY_CONTIGUOUS, */ } /* "View.MemoryView":439 * return None * * return obj # <<<<<<<<<<<<<< * * cdef setitem_slice_assignment(self, dst, src): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_obj); __pyx_r = __pyx_v_obj; goto __pyx_L0; /* "View.MemoryView":431 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< * if not isinstance(obj, memoryview): * try: */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_obj); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":441 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice dst_slice * cdef __Pyx_memviewslice src_slice */ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { __Pyx_memviewslice __pyx_v_dst_slice; __Pyx_memviewslice __pyx_v_src_slice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice *__pyx_t_1; __Pyx_memviewslice *__pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; int __pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); /* "View.MemoryView":445 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) __PYX_ERR(1, 445, __pyx_L1_error) __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 445, __pyx_L1_error) /* "View.MemoryView":446 * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< * src.ndim, dst.ndim, self.dtype_is_object) * */ if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) __PYX_ERR(1, 446, __pyx_L1_error) __pyx_t_2 = __pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice)); if (unlikely(__pyx_t_2 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 446, __pyx_L1_error) /* "View.MemoryView":447 * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): */ __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 447, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":445 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ __pyx_t_6 = __pyx_memoryview_copy_contents((__pyx_t_1[0]), (__pyx_t_2[0]), __pyx_t_4, __pyx_t_5, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 445, __pyx_L1_error) /* "View.MemoryView":441 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice dst_slice * cdef __Pyx_memviewslice src_slice */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":449 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< * cdef int array[128] * cdef void *tmp = NULL */ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { int __pyx_v_array[0x80]; void *__pyx_v_tmp; void *__pyx_v_item; __Pyx_memviewslice *__pyx_v_dst_slice; __Pyx_memviewslice __pyx_v_tmp_slice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice *__pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; char const *__pyx_t_6; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyObject *__pyx_t_12 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); /* "View.MemoryView":451 * cdef setitem_slice_assign_scalar(self, memoryview dst, value): * cdef int array[128] * cdef void *tmp = NULL # <<<<<<<<<<<<<< * cdef void *item * */ __pyx_v_tmp = NULL; /* "View.MemoryView":456 * cdef __Pyx_memviewslice *dst_slice * cdef __Pyx_memviewslice tmp_slice * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< * * if <size_t>self.view.itemsize > sizeof(array): */ __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 456, __pyx_L1_error) __pyx_v_dst_slice = __pyx_t_1; /* "View.MemoryView":458 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if <size_t>self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: */ __pyx_t_2 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); if (__pyx_t_2) { /* "View.MemoryView":459 * * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< * if tmp == NULL: * raise MemoryError */ __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); /* "View.MemoryView":460 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ __pyx_t_2 = ((__pyx_v_tmp == NULL) != 0); if (unlikely(__pyx_t_2)) { /* "View.MemoryView":461 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ PyErr_NoMemory(); __PYX_ERR(1, 461, __pyx_L1_error) /* "View.MemoryView":460 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ } /* "View.MemoryView":462 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< * else: * item = <void *> array */ __pyx_v_item = __pyx_v_tmp; /* "View.MemoryView":458 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if <size_t>self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: */ goto __pyx_L3; } /* "View.MemoryView":464 * item = tmp * else: * item = <void *> array # <<<<<<<<<<<<<< * * try: */ /*else*/ { __pyx_v_item = ((void *)__pyx_v_array); } __pyx_L3:; /* "View.MemoryView":466 * item = <void *> array * * try: # <<<<<<<<<<<<<< * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value */ /*try:*/ { /* "View.MemoryView":467 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ __pyx_t_2 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_2) { /* "View.MemoryView":468 * try: * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value # <<<<<<<<<<<<<< * else: * self.assign_item_from_object(<char *> item, value) */ (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); /* "View.MemoryView":467 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ goto __pyx_L8; } /* "View.MemoryView":470 * (<PyObject **> item)[0] = <PyObject *> value * else: * self.assign_item_from_object(<char *> item, value) # <<<<<<<<<<<<<< * * */ /*else*/ { __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 470, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L8:; /* "View.MemoryView":474 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, */ __pyx_t_2 = ((__pyx_v_self->view.suboffsets != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":475 * * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, * item, self.dtype_is_object) */ __pyx_t_3 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 475, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":474 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, */ } /* "View.MemoryView":476 * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< * item, self.dtype_is_object) * finally: */ __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); } /* "View.MemoryView":479 * item, self.dtype_is_object) * finally: * PyMem_Free(tmp) # <<<<<<<<<<<<<< * * cdef setitem_indexed(self, index, value): */ /*finally:*/ { /*normal exit:*/{ PyMem_Free(__pyx_v_tmp); goto __pyx_L7; } __pyx_L6_error:; /*exception exit:*/{ __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9) < 0)) __Pyx_ErrFetch(&__pyx_t_7, &__pyx_t_8, &__pyx_t_9); __Pyx_XGOTREF(__pyx_t_7); __Pyx_XGOTREF(__pyx_t_8); __Pyx_XGOTREF(__pyx_t_9); __Pyx_XGOTREF(__pyx_t_10); __Pyx_XGOTREF(__pyx_t_11); __Pyx_XGOTREF(__pyx_t_12); __pyx_t_4 = __pyx_lineno; __pyx_t_5 = __pyx_clineno; __pyx_t_6 = __pyx_filename; { PyMem_Free(__pyx_v_tmp); } if (PY_MAJOR_VERSION >= 3) { __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_XGIVEREF(__pyx_t_12); __Pyx_ExceptionReset(__pyx_t_10, __pyx_t_11, __pyx_t_12); } __Pyx_XGIVEREF(__pyx_t_7); __Pyx_XGIVEREF(__pyx_t_8); __Pyx_XGIVEREF(__pyx_t_9); __Pyx_ErrRestore(__pyx_t_7, __pyx_t_8, __pyx_t_9); __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_lineno = __pyx_t_4; __pyx_clineno = __pyx_t_5; __pyx_filename = __pyx_t_6; goto __pyx_L1_error; } __pyx_L7:; } /* "View.MemoryView":449 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< * cdef int array[128] * cdef void *tmp = NULL */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":481 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) */ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { char *__pyx_v_itemp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations char *__pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_indexed", 0); /* "View.MemoryView":482 * * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< * self.assign_item_from_object(itemp, value) * */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == ((char *)NULL))) __PYX_ERR(1, 482, __pyx_L1_error) __pyx_v_itemp = __pyx_t_1; /* "View.MemoryView":483 * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< * * cdef convert_item_to_object(self, char *itemp): */ __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 483, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":481 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":485 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { PyObject *__pyx_v_struct = NULL; PyObject *__pyx_v_bytesitem = 0; PyObject *__pyx_v_result = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; int __pyx_t_8; PyObject *__pyx_t_9 = NULL; size_t __pyx_t_10; int __pyx_t_11; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":488 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef bytes bytesitem * */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 488, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":491 * cdef bytes bytesitem * * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< * try: * result = struct.unpack(self.view.format, bytesitem) */ __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 491, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); /*try:*/ { /* "View.MemoryView":493 * bytesitem = itemp[:self.view.itemsize] * try: * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< * except struct.error: * raise ValueError("Unable to convert item to object") */ __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; __pyx_t_8 = 0; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_7)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_7); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); __pyx_t_8 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else #endif { __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_7) { __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; } __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); __Pyx_INCREF(__pyx_v_bytesitem); __Pyx_GIVEREF(__pyx_v_bytesitem); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); __pyx_t_6 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 493, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ } /* "View.MemoryView":497 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ /*else:*/ { __pyx_t_10 = strlen(__pyx_v_self->view.format); __pyx_t_11 = ((__pyx_t_10 == 1) != 0); if (__pyx_t_11) { /* "View.MemoryView":498 * else: * if len(self.view.format) == 1: * return result[0] # <<<<<<<<<<<<<< * return result * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 498, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L6_except_return; /* "View.MemoryView":497 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ } /* "View.MemoryView":499 * if len(self.view.format) == 1: * return result[0] * return result # <<<<<<<<<<<<<< * * cdef assign_item_from_object(self, char *itemp, object value): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_result); __pyx_r = __pyx_v_result; goto __pyx_L6_except_return; } __pyx_L3_error:; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; /* "View.MemoryView":494 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< * raise ValueError("Unable to convert item to object") * else: */ __Pyx_ErrFetch(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9); __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 494, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = __Pyx_PyErr_GivenExceptionMatches(__pyx_t_1, __pyx_t_6); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_ErrRestore(__pyx_t_1, __pyx_t_5, __pyx_t_9); __pyx_t_1 = 0; __pyx_t_5 = 0; __pyx_t_9 = 0; if (__pyx_t_8) { __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_9, &__pyx_t_5, &__pyx_t_1) < 0) __PYX_ERR(1, 494, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_1); /* "View.MemoryView":495 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 495, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __PYX_ERR(1, 495, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "View.MemoryView":492 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); goto __pyx_L1_error; __pyx_L6_except_return:; __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); goto __pyx_L0; } /* "View.MemoryView":485 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_struct); __Pyx_XDECREF(__pyx_v_bytesitem); __Pyx_XDECREF(__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":501 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { PyObject *__pyx_v_struct = NULL; char __pyx_v_c; PyObject *__pyx_v_bytesvalue = 0; Py_ssize_t __pyx_v_i; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; Py_ssize_t __pyx_t_9; PyObject *__pyx_t_10 = NULL; char *__pyx_t_11; char *__pyx_t_12; char *__pyx_t_13; char *__pyx_t_14; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":504 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef char c * cdef bytes bytesvalue */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 504, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":509 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ __pyx_t_2 = PyTuple_Check(__pyx_v_value); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { /* "View.MemoryView":510 * * if isinstance(value, tuple): * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< * else: * bytesvalue = struct.pack(self.view.format, value) */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 510, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 510, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; /* "View.MemoryView":509 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ goto __pyx_L3; } /* "View.MemoryView":512 * bytesvalue = struct.pack(self.view.format, *value) * else: * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< * * for i, c in enumerate(bytesvalue): */ /*else*/ { __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 512, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 512, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = NULL; __pyx_t_7 = 0; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_6, function); __pyx_t_7 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else #endif { __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 512, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_8); if (__pyx_t_5) { __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; } __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); __Pyx_INCREF(__pyx_v_value); __Pyx_GIVEREF(__pyx_v_value); PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); __pyx_t_1 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 512, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 512, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; /* "View.MemoryView":514 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_9 = 0; if (unlikely(__pyx_v_bytesvalue == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); __PYX_ERR(1, 514, __pyx_L1_error) } __Pyx_INCREF(__pyx_v_bytesvalue); __pyx_t_10 = __pyx_v_bytesvalue; __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { __pyx_t_11 = __pyx_t_14; __pyx_v_c = (__pyx_t_11[0]); /* "View.MemoryView":515 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ __pyx_v_i = __pyx_t_9; /* "View.MemoryView":514 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_9 = (__pyx_t_9 + 1); /* "View.MemoryView":515 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; } __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; /* "View.MemoryView":501 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_8); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_struct); __Pyx_XDECREF(__pyx_v_bytesvalue); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":518 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; Py_ssize_t *__pyx_t_4; char *__pyx_t_5; void *__pyx_t_6; int __pyx_t_7; Py_ssize_t __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; if (__pyx_v_info == NULL) { PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); return -1; } __Pyx_RefNannySetupContext("__getbuffer__", 0); __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); /* "View.MemoryView":519 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< * raise ValueError("Cannot create writable memory view from read-only memoryview") * */ __pyx_t_2 = ((__pyx_v_flags & PyBUF_WRITABLE) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L4_bool_binop_done; } __pyx_t_2 = (__pyx_v_self->view.readonly != 0); __pyx_t_1 = __pyx_t_2; __pyx_L4_bool_binop_done:; if (unlikely(__pyx_t_1)) { /* "View.MemoryView":520 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< * * if flags & PyBUF_ND: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 520, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 520, __pyx_L1_error) /* "View.MemoryView":519 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: # <<<<<<<<<<<<<< * raise ValueError("Cannot create writable memory view from read-only memoryview") * */ } /* "View.MemoryView":522 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_ND) != 0); if (__pyx_t_1) { /* "View.MemoryView":523 * * if flags & PyBUF_ND: * info.shape = self.view.shape # <<<<<<<<<<<<<< * else: * info.shape = NULL */ __pyx_t_4 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_4; /* "View.MemoryView":522 * raise ValueError("Cannot create writable memory view from read-only memoryview") * * if flags & PyBUF_ND: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ goto __pyx_L6; } /* "View.MemoryView":525 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_STRIDES: */ /*else*/ { __pyx_v_info->shape = NULL; } __pyx_L6:; /* "View.MemoryView":527 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { /* "View.MemoryView":528 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< * else: * info.strides = NULL */ __pyx_t_4 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_4; /* "View.MemoryView":527 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ goto __pyx_L7; } /* "View.MemoryView":530 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_INDIRECT: */ /*else*/ { __pyx_v_info->strides = NULL; } __pyx_L7:; /* "View.MemoryView":532 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); if (__pyx_t_1) { /* "View.MemoryView":533 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< * else: * info.suboffsets = NULL */ __pyx_t_4 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_4; /* "View.MemoryView":532 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ goto __pyx_L8; } /* "View.MemoryView":535 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ /*else*/ { __pyx_v_info->suboffsets = NULL; } __pyx_L8:; /* "View.MemoryView":537 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":538 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_5 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_5; /* "View.MemoryView":537 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ goto __pyx_L9; } /* "View.MemoryView":540 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.buf = self.view.buf */ /*else*/ { __pyx_v_info->format = NULL; } __pyx_L9:; /* "View.MemoryView":542 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize */ __pyx_t_6 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_6; /* "View.MemoryView":543 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< * info.itemsize = self.view.itemsize * info.len = self.view.len */ __pyx_t_7 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_7; /* "View.MemoryView":544 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< * info.len = self.view.len * info.readonly = self.view.readonly */ __pyx_t_8 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_8; /* "View.MemoryView":545 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< * info.readonly = self.view.readonly * info.obj = self */ __pyx_t_8 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_8; /* "View.MemoryView":546 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = self.view.readonly # <<<<<<<<<<<<<< * info.obj = self * */ __pyx_t_1 = __pyx_v_self->view.readonly; __pyx_v_info->readonly = __pyx_t_1; /* "View.MemoryView":547 * info.len = self.view.len * info.readonly = self.view.readonly * info.obj = self # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "View.MemoryView":518 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info->obj == Py_None) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":553 * * @property * def T(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":554 * @property * def T(self): * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< * transpose_memslice(&result.from_slice) * return result */ __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 554, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) __PYX_ERR(1, 554, __pyx_L1_error) __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":555 * def T(self): * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< * return result * */ __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 555, __pyx_L1_error) /* "View.MemoryView":556 * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) * return result # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":553 * * @property * def T(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":559 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.obj * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":560 * @property * def base(self): * return self.obj # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->obj); __pyx_r = __pyx_v_self->obj; goto __pyx_L0; /* "View.MemoryView":559 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.obj * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":563 * * @property * def shape(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_length; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":564 * @property * def shape(self): * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 564, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { __pyx_t_2 = __pyx_t_4; __pyx_v_length = (__pyx_t_2[0]); __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 564, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 564, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":563 * * @property * def shape(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":567 * * @property * def strides(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_stride; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":568 * @property * def strides(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":570 * if self.view.strides == NULL: * * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 570, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(1, 570, __pyx_L1_error) /* "View.MemoryView":568 * @property * def strides(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ } /* "View.MemoryView":572 * raise ValueError("Buffer view does not expose strides") * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 572, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { __pyx_t_3 = __pyx_t_5; __pyx_v_stride = (__pyx_t_3[0]); __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 572, __pyx_L1_error) __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 572, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_6; __pyx_t_6 = 0; goto __pyx_L0; /* "View.MemoryView":567 * * @property * def strides(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":575 * * @property * def suboffsets(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; Py_ssize_t *__pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":576 * @property * def suboffsets(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":577 * def suboffsets(self): * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 577, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__14, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 577, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":576 * @property * def suboffsets(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ } /* "View.MemoryView":579 * return (-1,) * self.view.ndim * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { __pyx_t_4 = __pyx_t_6; __pyx_v_suboffset = (__pyx_t_4[0]); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":575 * * @property * def suboffsets(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":582 * * @property * def ndim(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":583 * @property * def ndim(self): * return self.view.ndim # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 583, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":582 * * @property * def ndim(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":586 * * @property * def itemsize(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":587 * @property * def itemsize(self): * return self.view.itemsize # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 587, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":586 * * @property * def itemsize(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":590 * * @property * def nbytes(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":591 * @property * def nbytes(self): * return self.size * self.view.itemsize # <<<<<<<<<<<<<< * * @property */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 591, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 591, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 591, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":590 * * @property * def nbytes(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":594 * * @property * def size(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_v_result = NULL; PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":595 * @property * def size(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ __pyx_t_1 = (__pyx_v_self->_size == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":596 * def size(self): * if self._size is None: * result = 1 # <<<<<<<<<<<<<< * * for length in self.view.shape[:self.view.ndim]: */ __Pyx_INCREF(__pyx_int_1); __pyx_v_result = __pyx_int_1; /* "View.MemoryView":598 * result = 1 * * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< * result *= length * */ __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { __pyx_t_3 = __pyx_t_5; __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 598, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); __pyx_t_6 = 0; /* "View.MemoryView":599 * * for length in self.view.shape[:self.view.ndim]: * result *= length # <<<<<<<<<<<<<< * * self._size = result */ __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 599, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); __pyx_t_6 = 0; } /* "View.MemoryView":601 * result *= length * * self._size = result # <<<<<<<<<<<<<< * * return self._size */ __Pyx_INCREF(__pyx_v_result); __Pyx_GIVEREF(__pyx_v_result); __Pyx_GOTREF(__pyx_v_self->_size); __Pyx_DECREF(__pyx_v_self->_size); __pyx_v_self->_size = __pyx_v_result; /* "View.MemoryView":595 * @property * def size(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ } /* "View.MemoryView":603 * self._size = result * * return self._size # <<<<<<<<<<<<<< * * def __len__(self): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->_size); __pyx_r = __pyx_v_self->_size; goto __pyx_L0; /* "View.MemoryView":594 * * @property * def size(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_result); __Pyx_XDECREF(__pyx_v_length); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":605 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: * return self.view.shape[0] */ /* Python wrapper */ static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__len__", 0); /* "View.MemoryView":606 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":607 * def __len__(self): * if self.view.ndim >= 1: * return self.view.shape[0] # <<<<<<<<<<<<<< * * return 0 */ __pyx_r = (__pyx_v_self->view.shape[0]); goto __pyx_L0; /* "View.MemoryView":606 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ } /* "View.MemoryView":609 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< * * def __repr__(self): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":605 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: * return self.view.shape[0] */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":611 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) */ /* Python wrapper */ static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__repr__", 0); /* "View.MemoryView":612 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":613 * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) # <<<<<<<<<<<<<< * * def __str__(self): */ __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_builtin_id, ((PyObject *)__pyx_v_self)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 613, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); /* "View.MemoryView":612 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 612, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":611 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":615 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) * */ /* Python wrapper */ static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__str__", 0); /* "View.MemoryView":616 * * def __str__(self): * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 616, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 616, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":615 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":619 * * * def is_c_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* Python wrapper */ static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice *__pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_c_contig", 0); /* "View.MemoryView":622 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice[0], 'C', self.view.ndim) * */ __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 622, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":623 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< * * def is_f_contig(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 623, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":619 * * * def is_c_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":625 * return slice_is_contig(mslice[0], 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* Python wrapper */ static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice *__pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_f_contig", 0); /* "View.MemoryView":628 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice[0], 'F', self.view.ndim) * */ __pyx_t_1 = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); if (unlikely(__pyx_t_1 == ((__Pyx_memviewslice *)NULL))) __PYX_ERR(1, 628, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":629 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< * * def copy(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 629, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":625 * return slice_is_contig(mslice[0], 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":631 * return slice_is_contig(mslice[0], 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS */ /* Python wrapper */ static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_mslice; int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy", 0); /* "View.MemoryView":633 * def copy(self): * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< * * slice_copy(self, &mslice) */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); /* "View.MemoryView":635 * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS * * slice_copy(self, &mslice) # <<<<<<<<<<<<<< * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, * self.view.itemsize, */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); /* "View.MemoryView":636 * * slice_copy(self, &mslice) * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_C_CONTIGUOUS, */ __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), ((char *)"c"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 636, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":641 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< * * def copy_fortran(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 641, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":631 * return slice_is_contig(mslice[0], 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":643 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS */ /* Python wrapper */ static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_src; __Pyx_memviewslice __pyx_v_dst; int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy_fortran", 0); /* "View.MemoryView":645 * def copy_fortran(self): * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< * * slice_copy(self, &src) */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); /* "View.MemoryView":647 * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS * * slice_copy(self, &src) # <<<<<<<<<<<<<< * dst = slice_copy_contig(&src, "fortran", self.view.ndim, * self.view.itemsize, */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); /* "View.MemoryView":648 * * slice_copy(self, &src) * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_F_CONTIGUOUS, */ __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), ((char *)"fortran"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 648, __pyx_L1_error) __pyx_v_dst = __pyx_t_1; /* "View.MemoryView":653 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 653, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":643 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":657 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo */ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { struct __pyx_memoryview_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); /* "View.MemoryView":658 * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< * result.typeinfo = typeinfo * return result */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_o); __Pyx_GIVEREF(__pyx_v_o); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 658, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":659 * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo # <<<<<<<<<<<<<< * return result * */ __pyx_v_result->typeinfo = __pyx_v_typeinfo; /* "View.MemoryView":660 * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo * return result # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_check') */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":657 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":663 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< * return isinstance(o, memoryview) * */ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("memoryview_check", 0); /* "View.MemoryView":664 * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): * return isinstance(o, memoryview) # <<<<<<<<<<<<<< * * cdef tuple _unellipsify(object index, int ndim): */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, __pyx_memoryview_type); __pyx_r = __pyx_t_1; goto __pyx_L0; /* "View.MemoryView":663 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< * return isinstance(o, memoryview) * */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":666 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< * """ * Replace all ellipses with full slices and fill incomplete indices with */ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { PyObject *__pyx_v_tup = NULL; PyObject *__pyx_v_result = NULL; int __pyx_v_have_slices; int __pyx_v_seen_ellipsis; CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; PyObject *__pyx_v_item = NULL; Py_ssize_t __pyx_v_nslices; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; Py_ssize_t __pyx_t_5; PyObject *(*__pyx_t_6)(PyObject *); PyObject *__pyx_t_7 = NULL; Py_ssize_t __pyx_t_8; int __pyx_t_9; int __pyx_t_10; PyObject *__pyx_t_11 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_unellipsify", 0); /* "View.MemoryView":671 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ __pyx_t_1 = PyTuple_Check(__pyx_v_index); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":672 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 672, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_index); __Pyx_GIVEREF(__pyx_v_index); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); __pyx_v_tup = __pyx_t_3; __pyx_t_3 = 0; /* "View.MemoryView":671 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ goto __pyx_L3; } /* "View.MemoryView":674 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< * * result = [] */ /*else*/ { __Pyx_INCREF(__pyx_v_index); __pyx_v_tup = __pyx_v_index; } __pyx_L3:; /* "View.MemoryView":676 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 676, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":677 * * result = [] * have_slices = False # <<<<<<<<<<<<<< * seen_ellipsis = False * for idx, item in enumerate(tup): */ __pyx_v_have_slices = 0; /* "View.MemoryView":678 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< * for idx, item in enumerate(tup): * if item is Ellipsis: */ __pyx_v_seen_ellipsis = 0; /* "View.MemoryView":679 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< * if item is Ellipsis: * if not seen_ellipsis: */ __Pyx_INCREF(__pyx_int_0); __pyx_t_3 = __pyx_int_0; if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; __pyx_t_6 = NULL; } else { __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 679, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_6)) { if (likely(PyList_CheckExact(__pyx_t_4))) { if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 679, __pyx_L1_error) #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #endif } else { if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 679, __pyx_L1_error) #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); #endif } } else { __pyx_t_7 = __pyx_t_6(__pyx_t_4); if (unlikely(!__pyx_t_7)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(1, 679, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_7); } __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); __pyx_t_7 = 0; __Pyx_INCREF(__pyx_t_3); __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 679, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = __pyx_t_7; __pyx_t_7 = 0; /* "View.MemoryView":680 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) */ __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":681 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True */ __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":682 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == ((Py_ssize_t)-1))) __PYX_ERR(1, 682, __pyx_L1_error) __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 682, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { __Pyx_INCREF(__pyx_slice__17); __Pyx_GIVEREF(__pyx_slice__17); PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__17); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 682, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":683 * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True # <<<<<<<<<<<<<< * else: * result.append(slice(None)) */ __pyx_v_seen_ellipsis = 1; /* "View.MemoryView":681 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True */ goto __pyx_L7; } /* "View.MemoryView":685 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ /*else*/ { __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__17); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 685, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":686 * else: * result.append(slice(None)) * have_slices = True # <<<<<<<<<<<<<< * else: * if not isinstance(item, slice) and not PyIndex_Check(item): */ __pyx_v_have_slices = 1; /* "View.MemoryView":680 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) */ goto __pyx_L6; } /* "View.MemoryView":688 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ /*else*/ { __pyx_t_2 = PySlice_Check(__pyx_v_item); __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_10) { } else { __pyx_t_1 = __pyx_t_10; goto __pyx_L9_bool_binop_done; } __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); __pyx_t_1 = __pyx_t_10; __pyx_L9_bool_binop_done:; if (unlikely(__pyx_t_1)) { /* "View.MemoryView":689 * else: * if not isinstance(item, slice) and not PyIndex_Check(item): * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< * * have_slices = have_slices or isinstance(item, slice) */ __pyx_t_7 = __Pyx_PyString_FormatSafe(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 689, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_11 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_7); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 689, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_Raise(__pyx_t_11, 0, 0, 0); __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; __PYX_ERR(1, 689, __pyx_L1_error) /* "View.MemoryView":688 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ } /* "View.MemoryView":691 * raise TypeError("Cannot index with type '%s'" % type(item)) * * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< * result.append(item) * */ __pyx_t_10 = (__pyx_v_have_slices != 0); if (!__pyx_t_10) { } else { __pyx_t_1 = __pyx_t_10; goto __pyx_L11_bool_binop_done; } __pyx_t_10 = PySlice_Check(__pyx_v_item); __pyx_t_2 = (__pyx_t_10 != 0); __pyx_t_1 = __pyx_t_2; __pyx_L11_bool_binop_done:; __pyx_v_have_slices = __pyx_t_1; /* "View.MemoryView":692 * * have_slices = have_slices or isinstance(item, slice) * result.append(item) # <<<<<<<<<<<<<< * * nslices = ndim - len(result) */ __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 692, __pyx_L1_error) } __pyx_L6:; /* "View.MemoryView":679 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< * if item is Ellipsis: * if not seen_ellipsis: */ } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":694 * result.append(item) * * nslices = ndim - len(result) # <<<<<<<<<<<<<< * if nslices: * result.extend([slice(None)] * nslices) */ __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(1, 694, __pyx_L1_error) __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); /* "View.MemoryView":695 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { /* "View.MemoryView":696 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 696, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { __Pyx_INCREF(__pyx_slice__17); __Pyx_GIVEREF(__pyx_slice__17); PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__17); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 696, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":695 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ } /* "View.MemoryView":698 * result.extend([slice(None)] * nslices) * * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): */ __Pyx_XDECREF(__pyx_r); if (!__pyx_v_have_slices) { } else { __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L14_bool_binop_done; } __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; __pyx_L14_bool_binop_done:; __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_11 = PyTuple_New(2); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 698, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_11, 1, __pyx_t_4); __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_r = ((PyObject*)__pyx_t_11); __pyx_t_11 = 0; goto __pyx_L0; /* "View.MemoryView":666 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< * """ * Replace all ellipses with full slices and fill incomplete indices with */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_11); __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_tup); __Pyx_XDECREF(__pyx_v_result); __Pyx_XDECREF(__pyx_v_idx); __Pyx_XDECREF(__pyx_v_item); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":700 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: */ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t *__pyx_t_1; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); /* "View.MemoryView":701 * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") */ __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { __pyx_t_1 = __pyx_t_3; __pyx_v_suboffset = (__pyx_t_1[0]); /* "View.MemoryView":702 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); if (unlikely(__pyx_t_4)) { /* "View.MemoryView":703 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 703, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __PYX_ERR(1, 703, __pyx_L1_error) /* "View.MemoryView":702 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ } } /* "View.MemoryView":700 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":710 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< * cdef int new_ndim = 0, suboffset_dim = -1, dim * cdef bint negative_step */ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { int __pyx_v_new_ndim; int __pyx_v_suboffset_dim; int __pyx_v_dim; __Pyx_memviewslice __pyx_v_src; __Pyx_memviewslice __pyx_v_dst; __Pyx_memviewslice *__pyx_v_p_src; struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; __Pyx_memviewslice *__pyx_v_p_dst; int *__pyx_v_p_suboffset_dim; Py_ssize_t __pyx_v_start; Py_ssize_t __pyx_v_stop; Py_ssize_t __pyx_v_step; int __pyx_v_have_start; int __pyx_v_have_stop; int __pyx_v_have_step; PyObject *__pyx_v_index = NULL; struct __pyx_memoryview_obj *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; struct __pyx_memoryview_obj *__pyx_t_4; char *__pyx_t_5; int __pyx_t_6; Py_ssize_t __pyx_t_7; PyObject *(*__pyx_t_8)(PyObject *); PyObject *__pyx_t_9 = NULL; Py_ssize_t __pyx_t_10; int __pyx_t_11; Py_ssize_t __pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memview_slice", 0); /* "View.MemoryView":711 * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< * cdef bint negative_step * cdef __Pyx_memviewslice src, dst */ __pyx_v_new_ndim = 0; __pyx_v_suboffset_dim = -1; /* "View.MemoryView":718 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< * * cdef _memoryviewslice memviewsliceobj */ (void)(memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)))); /* "View.MemoryView":722 * cdef _memoryviewslice memviewsliceobj * * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< * * if isinstance(memview, _memoryviewslice): */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(1, 722, __pyx_L1_error) } } #endif /* "View.MemoryView":724 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":725 * * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview # <<<<<<<<<<<<<< * p_src = &memviewsliceobj.from_slice * else: */ if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 725, __pyx_L1_error) __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":726 * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< * else: * slice_copy(memview, &src) */ __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); /* "View.MemoryView":724 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ goto __pyx_L3; } /* "View.MemoryView":728 * p_src = &memviewsliceobj.from_slice * else: * slice_copy(memview, &src) # <<<<<<<<<<<<<< * p_src = &src * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); /* "View.MemoryView":729 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< * * */ __pyx_v_p_src = (&__pyx_v_src); } __pyx_L3:; /* "View.MemoryView":735 * * * dst.memview = p_src.memview # <<<<<<<<<<<<<< * dst.data = p_src.data * */ __pyx_t_4 = __pyx_v_p_src->memview; __pyx_v_dst.memview = __pyx_t_4; /* "View.MemoryView":736 * * dst.memview = p_src.memview * dst.data = p_src.data # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __pyx_v_p_src->data; __pyx_v_dst.data = __pyx_t_5; /* "View.MemoryView":741 * * * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< * cdef int *p_suboffset_dim = &suboffset_dim * cdef Py_ssize_t start, stop, step */ __pyx_v_p_dst = (&__pyx_v_dst); /* "View.MemoryView":742 * * cdef __Pyx_memviewslice *p_dst = &dst * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< * cdef Py_ssize_t start, stop, step * cdef bint have_start, have_stop, have_step */ __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); /* "View.MemoryView":746 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< * if PyIndex_Check(index): * slice_memviewslice( */ __pyx_t_6 = 0; if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; __pyx_t_8 = NULL; } else { __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 746, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_8)) { if (likely(PyList_CheckExact(__pyx_t_3))) { if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 746, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif } else { if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 746, __pyx_L1_error) #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 746, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); #endif } } else { __pyx_t_9 = __pyx_t_8(__pyx_t_3); if (unlikely(!__pyx_t_9)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else __PYX_ERR(1, 746, __pyx_L1_error) } break; } __Pyx_GOTREF(__pyx_t_9); } __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); __pyx_t_9 = 0; __pyx_v_dim = __pyx_t_6; __pyx_t_6 = (__pyx_t_6 + 1); /* "View.MemoryView":747 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< * slice_memviewslice( * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], */ __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); if (__pyx_t_2) { /* "View.MemoryView":751 * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< * 0, 0, 0, # have_{start,stop,step} * False) */ __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 751, __pyx_L1_error) /* "View.MemoryView":748 * for dim, index in enumerate(indices): * if PyIndex_Check(index): * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 748, __pyx_L1_error) /* "View.MemoryView":747 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< * slice_memviewslice( * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], */ goto __pyx_L6; } /* "View.MemoryView":754 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 */ __pyx_t_2 = (__pyx_v_index == Py_None); __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":755 * False) * elif index is None: * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 */ (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; /* "View.MemoryView":756 * elif index is None: * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 */ (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; /* "View.MemoryView":757 * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< * new_ndim += 1 * else: */ (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; /* "View.MemoryView":758 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 # <<<<<<<<<<<<<< * else: * start = index.start or 0 */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); /* "View.MemoryView":754 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 */ goto __pyx_L6; } /* "View.MemoryView":760 * new_ndim += 1 * else: * start = index.start or 0 # <<<<<<<<<<<<<< * stop = index.stop or 0 * step = index.step or 0 */ /*else*/ { __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 760, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 760, __pyx_L1_error) if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 760, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L7_bool_binop_done; } __pyx_t_10 = 0; __pyx_L7_bool_binop_done:; __pyx_v_start = __pyx_t_10; /* "View.MemoryView":761 * else: * start = index.start or 0 * stop = index.stop or 0 # <<<<<<<<<<<<<< * step = index.step or 0 * */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 761, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 761, __pyx_L1_error) if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 761, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L9_bool_binop_done; } __pyx_t_10 = 0; __pyx_L9_bool_binop_done:; __pyx_v_stop = __pyx_t_10; /* "View.MemoryView":762 * start = index.start or 0 * stop = index.stop or 0 * step = index.step or 0 # <<<<<<<<<<<<<< * * have_start = index.start is not None */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 762, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 762, __pyx_L1_error) if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 762, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L11_bool_binop_done; } __pyx_t_10 = 0; __pyx_L11_bool_binop_done:; __pyx_v_step = __pyx_t_10; /* "View.MemoryView":764 * step = index.step or 0 * * have_start = index.start is not None # <<<<<<<<<<<<<< * have_stop = index.stop is not None * have_step = index.step is not None */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 764, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_start = __pyx_t_1; /* "View.MemoryView":765 * * have_start = index.start is not None * have_stop = index.stop is not None # <<<<<<<<<<<<<< * have_step = index.step is not None * */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 765, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_stop = __pyx_t_1; /* "View.MemoryView":766 * have_start = index.start is not None * have_stop = index.stop is not None * have_step = index.step is not None # <<<<<<<<<<<<<< * * slice_memviewslice( */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 766, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_step = __pyx_t_1; /* "View.MemoryView":768 * have_step = index.step is not None * * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 768, __pyx_L1_error) /* "View.MemoryView":774 * have_start, have_stop, have_step, * True) * new_ndim += 1 # <<<<<<<<<<<<<< * * if isinstance(memview, _memoryviewslice): */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); } __pyx_L6:; /* "View.MemoryView":746 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< * if PyIndex_Check(index): * slice_memviewslice( */ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":776 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":777 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, */ __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":778 * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< * memviewsliceobj.to_dtype_func, * memview.dtype_is_object) */ if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 778, __pyx_L1_error) } /* "View.MemoryView":779 * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< * memview.dtype_is_object) * else: */ if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 779, __pyx_L1_error) } /* "View.MemoryView":777 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, */ __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 777, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 777, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":776 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ } /* "View.MemoryView":782 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ /*else*/ { __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":783 * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 782, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); /* "View.MemoryView":782 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 782, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":710 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< * cdef int new_ndim = 0, suboffset_dim = -1, dim * cdef bint negative_step */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); __Pyx_XDECREF(__pyx_v_index); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":807 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, */ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { Py_ssize_t __pyx_v_new_shape; int __pyx_v_negative_step; int __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":827 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":829 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ __pyx_t_1 = ((__pyx_v_start < 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":830 * * if start < 0: * start += shape # <<<<<<<<<<<<<< * if not 0 <= start < shape: * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":829 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ } /* "View.MemoryView":831 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ __pyx_t_1 = (0 <= __pyx_v_start); if (__pyx_t_1) { __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); } __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":832 * start += shape * if not 0 <= start < shape: * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< * else: * */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 832, __pyx_L1_error) /* "View.MemoryView":831 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ } /* "View.MemoryView":827 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ goto __pyx_L3; } /* "View.MemoryView":835 * else: * * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< * * if have_step and step == 0: */ /*else*/ { __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); if (__pyx_t_1) { } else { __pyx_t_2 = __pyx_t_1; goto __pyx_L6_bool_binop_done; } __pyx_t_1 = ((__pyx_v_step < 0) != 0); __pyx_t_2 = __pyx_t_1; __pyx_L6_bool_binop_done:; __pyx_v_negative_step = __pyx_t_2; /* "View.MemoryView":837 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) * */ __pyx_t_1 = (__pyx_v_have_step != 0); if (__pyx_t_1) { } else { __pyx_t_2 = __pyx_t_1; goto __pyx_L9_bool_binop_done; } __pyx_t_1 = ((__pyx_v_step == 0) != 0); __pyx_t_2 = __pyx_t_1; __pyx_L9_bool_binop_done:; if (__pyx_t_2) { /* "View.MemoryView":838 * * if have_step and step == 0: * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 838, __pyx_L1_error) /* "View.MemoryView":837 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) * */ } /* "View.MemoryView":841 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { /* "View.MemoryView":842 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":843 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< * if start < 0: * start = 0 */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":844 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":845 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< * elif start >= shape: * if negative_step: */ __pyx_v_start = 0; /* "View.MemoryView":844 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ } /* "View.MemoryView":842 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ goto __pyx_L12; } /* "View.MemoryView":846 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":847 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":848 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = shape */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":847 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L14; } /* "View.MemoryView":850 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ /*else*/ { __pyx_v_start = __pyx_v_shape; } __pyx_L14:; /* "View.MemoryView":846 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ } __pyx_L12:; /* "View.MemoryView":841 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ goto __pyx_L11; } /* "View.MemoryView":852 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":853 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = 0 */ __pyx_v_start = (__pyx_v_shape - 1); /* "View.MemoryView":852 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ goto __pyx_L15; } /* "View.MemoryView":855 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< * * if have_stop: */ /*else*/ { __pyx_v_start = 0; } __pyx_L15:; } __pyx_L11:; /* "View.MemoryView":857 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { /* "View.MemoryView":858 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":859 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< * if stop < 0: * stop = 0 */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); /* "View.MemoryView":860 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":861 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< * elif stop > shape: * stop = shape */ __pyx_v_stop = 0; /* "View.MemoryView":860 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ } /* "View.MemoryView":858 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ goto __pyx_L17; } /* "View.MemoryView":862 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":863 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ __pyx_v_stop = __pyx_v_shape; /* "View.MemoryView":862 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ } __pyx_L17:; /* "View.MemoryView":857 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ goto __pyx_L16; } /* "View.MemoryView":865 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":866 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< * else: * stop = shape */ __pyx_v_stop = -1L; /* "View.MemoryView":865 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ goto __pyx_L19; } /* "View.MemoryView":868 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< * * if not have_step: */ /*else*/ { __pyx_v_stop = __pyx_v_shape; } __pyx_L19:; } __pyx_L16:; /* "View.MemoryView":870 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":871 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< * * */ __pyx_v_step = 1; /* "View.MemoryView":870 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ } /* "View.MemoryView":875 * * with cython.cdivision(True): * new_shape = (stop - start) // step # <<<<<<<<<<<<<< * * if (stop - start) - step * new_shape: */ __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); /* "View.MemoryView":877 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); if (__pyx_t_2) { /* "View.MemoryView":878 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< * * if new_shape < 0: */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); /* "View.MemoryView":877 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ } /* "View.MemoryView":880 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":881 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< * * */ __pyx_v_new_shape = 0; /* "View.MemoryView":880 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ } /* "View.MemoryView":884 * * * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset */ (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); /* "View.MemoryView":885 * * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< * dst.suboffsets[new_ndim] = suboffset * */ (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; /* "View.MemoryView":886 * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< * * */ (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; } __pyx_L3:; /* "View.MemoryView":889 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":890 * * if suboffset_dim[0] < 0: * dst.data += start * stride # <<<<<<<<<<<<<< * else: * dst.suboffsets[suboffset_dim[0]] += start * stride */ __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); /* "View.MemoryView":889 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ goto __pyx_L23; } /* "View.MemoryView":892 * dst.data += start * stride * else: * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< * * if suboffset >= 0: */ /*else*/ { __pyx_t_3 = (__pyx_v_suboffset_dim[0]); (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); } __pyx_L23:; /* "View.MemoryView":894 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":895 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":896 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":897 * if not is_slice: * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset # <<<<<<<<<<<<<< * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " */ __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); /* "View.MemoryView":896 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ goto __pyx_L26; } /* "View.MemoryView":899 * dst.data = (<char **> dst.data)[0] + suboffset * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< * "must be indexed and not sliced", dim) * else: */ /*else*/ { /* "View.MemoryView":900 * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< * else: * suboffset_dim[0] = new_ndim */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 899, __pyx_L1_error) } __pyx_L26:; /* "View.MemoryView":895 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ goto __pyx_L25; } /* "View.MemoryView":902 * "must be indexed and not sliced", dim) * else: * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< * * return 0 */ /*else*/ { (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; } __pyx_L25:; /* "View.MemoryView":894 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ } /* "View.MemoryView":904 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":807 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":910 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 */ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { Py_ssize_t __pyx_v_shape; Py_ssize_t __pyx_v_stride; Py_ssize_t __pyx_v_suboffset; Py_ssize_t __pyx_v_itemsize; char *__pyx_v_resultp; char *__pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("pybuffer_index", 0); /* "View.MemoryView":912 * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< * cdef Py_ssize_t itemsize = view.itemsize * cdef char *resultp */ __pyx_v_suboffset = -1L; /* "View.MemoryView":913 * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< * cdef char *resultp * */ __pyx_t_1 = __pyx_v_view->itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":916 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":917 * * if view.ndim == 0: * shape = view.len / itemsize # <<<<<<<<<<<<<< * stride = itemsize * else: */ if (unlikely(__pyx_v_itemsize == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(1, 917, __pyx_L1_error) } else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(1, 917, __pyx_L1_error) } __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); /* "View.MemoryView":918 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< * else: * shape = view.shape[dim] */ __pyx_v_stride = __pyx_v_itemsize; /* "View.MemoryView":916 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ goto __pyx_L3; } /* "View.MemoryView":920 * stride = itemsize * else: * shape = view.shape[dim] # <<<<<<<<<<<<<< * stride = view.strides[dim] * if view.suboffsets != NULL: */ /*else*/ { __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); /* "View.MemoryView":921 * else: * shape = view.shape[dim] * stride = view.strides[dim] # <<<<<<<<<<<<<< * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] */ __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); /* "View.MemoryView":922 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":923 * stride = view.strides[dim] * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< * * if index < 0: */ __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); /* "View.MemoryView":922 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ } } __pyx_L3:; /* "View.MemoryView":925 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":926 * * if index < 0: * index += view.shape[dim] # <<<<<<<<<<<<<< * if index < 0: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) */ __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); /* "View.MemoryView":927 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (unlikely(__pyx_t_2)) { /* "View.MemoryView":928 * index += view.shape[dim] * if index < 0: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * if index >= shape: */ __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 928, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 928, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 928, __pyx_L1_error) /* "View.MemoryView":927 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ } /* "View.MemoryView":925 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ } /* "View.MemoryView":930 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); if (unlikely(__pyx_t_2)) { /* "View.MemoryView":931 * * if index >= shape: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * resultp = bufp + index * stride */ __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 931, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_IndexError, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 931, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 931, __pyx_L1_error) /* "View.MemoryView":930 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ } /* "View.MemoryView":933 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * resultp = bufp + index * stride # <<<<<<<<<<<<<< * if suboffset >= 0: * resultp = (<char **> resultp)[0] + suboffset */ __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); /* "View.MemoryView":934 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":935 * resultp = bufp + index * stride * if suboffset >= 0: * resultp = (<char **> resultp)[0] + suboffset # <<<<<<<<<<<<<< * * return resultp */ __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); /* "View.MemoryView":934 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ } /* "View.MemoryView":937 * resultp = (<char **> resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_resultp; goto __pyx_L0; /* "View.MemoryView":910 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":943 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { int __pyx_v_ndim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; int __pyx_v_i; int __pyx_v_j; int __pyx_r; int __pyx_t_1; Py_ssize_t *__pyx_t_2; long __pyx_t_3; long __pyx_t_4; Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; int __pyx_t_7; int __pyx_t_8; int __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":944 * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< * * cdef Py_ssize_t *shape = memslice.shape */ __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; __pyx_v_ndim = __pyx_t_1; /* "View.MemoryView":946 * cdef int ndim = memslice.memview.view.ndim * * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< * cdef Py_ssize_t *strides = memslice.strides * */ __pyx_t_2 = __pyx_v_memslice->shape; __pyx_v_shape = __pyx_t_2; /* "View.MemoryView":947 * * cdef Py_ssize_t *shape = memslice.shape * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< * * */ __pyx_t_2 = __pyx_v_memslice->strides; __pyx_v_strides = __pyx_t_2; /* "View.MemoryView":951 * * cdef int i, j * for i in range(ndim / 2): # <<<<<<<<<<<<<< * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] */ __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); __pyx_t_4 = __pyx_t_3; for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_4; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":952 * cdef int i, j * for i in range(ndim / 2): * j = ndim - 1 - i # <<<<<<<<<<<<<< * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] */ __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); /* "View.MemoryView":953 * for i in range(ndim / 2): * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< * shape[i], shape[j] = shape[j], shape[i] * */ __pyx_t_5 = (__pyx_v_strides[__pyx_v_j]); __pyx_t_6 = (__pyx_v_strides[__pyx_v_i]); (__pyx_v_strides[__pyx_v_i]) = __pyx_t_5; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_6; /* "View.MemoryView":954 * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: */ __pyx_t_6 = (__pyx_v_shape[__pyx_v_j]); __pyx_t_5 = (__pyx_v_shape[__pyx_v_i]); (__pyx_v_shape[__pyx_v_i]) = __pyx_t_6; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_5; /* "View.MemoryView":956 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * */ __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); if (!__pyx_t_8) { } else { __pyx_t_7 = __pyx_t_8; goto __pyx_L6_bool_binop_done; } __pyx_t_8 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); __pyx_t_7 = __pyx_t_8; __pyx_L6_bool_binop_done:; if (__pyx_t_7) { /* "View.MemoryView":957 * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< * * return 1 */ __pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 957, __pyx_L1_error) /* "View.MemoryView":956 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * */ } } /* "View.MemoryView":959 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< * * */ __pyx_r = 1; goto __pyx_L0; /* "View.MemoryView":943 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = 0; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":976 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * */ /* Python wrapper */ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":977 * * def __dealloc__(self): * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< * * cdef convert_item_to_object(self, char *itemp): */ __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); /* "View.MemoryView":976 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":979 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * if self.to_object_func != NULL: * return self.to_object_func(itemp) */ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":980 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":981 * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: * return self.to_object_func(itemp) # <<<<<<<<<<<<<< * else: * return memoryview.convert_item_to_object(self, itemp) */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 981, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":980 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ } /* "View.MemoryView":983 * return self.to_object_func(itemp) * else: * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< * * cdef assign_item_from_object(self, char *itemp, object value): */ /*else*/ { __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 983, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } /* "View.MemoryView":979 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * if self.to_object_func != NULL: * return self.to_object_func(itemp) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":985 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) */ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":986 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< * self.to_dtype_func(itemp, value) * else: */ __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":987 * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< * else: * memoryview.assign_item_from_object(self, itemp, value) */ __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 987, __pyx_L1_error) /* "View.MemoryView":986 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< * self.to_dtype_func(itemp, value) * else: */ goto __pyx_L3; } /* "View.MemoryView":989 * self.to_dtype_func(itemp, value) * else: * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< * * @property */ /*else*/ { __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 989, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; /* "View.MemoryView":985 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":992 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":993 * @property * def base(self): * return self.from_object # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->from_object); __pyx_r = __pyx_v_self->from_object; goto __pyx_L0; /* "View.MemoryView":992 * * @property * def base(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__reduce_cython__", 0); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 2, __pyx_L1_error) /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* Python wrapper */ static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setstate_cython__", 0); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 4, __pyx_L1_error) /* "(tree fragment)":3 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":999 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< * int ndim, * object (*to_object_func)(char *), */ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; __Pyx_TypeInfo *__pyx_t_4; Py_buffer __pyx_t_5; Py_ssize_t *__pyx_t_6; Py_ssize_t *__pyx_t_7; Py_ssize_t *__pyx_t_8; Py_ssize_t __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_fromslice", 0); /* "View.MemoryView":1007 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); if (__pyx_t_1) { /* "View.MemoryView":1008 * * if <PyObject *> memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; /* "View.MemoryView":1007 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ } /* "View.MemoryView":1013 * * * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< * * result.from_slice = memviewslice */ __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); __Pyx_INCREF(__pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":1015 * result = _memoryviewslice(None, 0, dtype_is_object) * * result.from_slice = memviewslice # <<<<<<<<<<<<<< * __PYX_INC_MEMVIEW(&memviewslice, 1) * */ __pyx_v_result->from_slice = __pyx_v_memviewslice; /* "View.MemoryView":1016 * * result.from_slice = memviewslice * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< * * result.from_object = (<memoryview> memviewslice.memview).base */ __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); /* "View.MemoryView":1018 * __PYX_INC_MEMVIEW(&memviewslice, 1) * * result.from_object = (<memoryview> memviewslice.memview).base # <<<<<<<<<<<<<< * result.typeinfo = memviewslice.memview.typeinfo * */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1018, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __Pyx_GOTREF(__pyx_v_result->from_object); __Pyx_DECREF(__pyx_v_result->from_object); __pyx_v_result->from_object = __pyx_t_2; __pyx_t_2 = 0; /* "View.MemoryView":1019 * * result.from_object = (<memoryview> memviewslice.memview).base * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< * * result.view = memviewslice.memview.view */ __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; /* "View.MemoryView":1021 * result.typeinfo = memviewslice.memview.typeinfo * * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim */ __pyx_t_5 = __pyx_v_memviewslice.memview->view; __pyx_v_result->__pyx_base.view = __pyx_t_5; /* "View.MemoryView":1022 * * result.view = memviewslice.memview.view * result.view.buf = <void *> memviewslice.data # <<<<<<<<<<<<<< * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None */ __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); /* "View.MemoryView":1023 * result.view = memviewslice.memview.view * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim # <<<<<<<<<<<<<< * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) */ __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; /* "View.MemoryView":1024 * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; /* "View.MemoryView":1025 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: */ Py_INCREF(Py_None); /* "View.MemoryView":1027 * Py_INCREF(Py_None) * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< * result.flags = PyBUF_RECORDS * else: */ __pyx_t_1 = ((((struct __pyx_memoryview_obj *)__pyx_v_memviewslice.memview)->flags & PyBUF_WRITABLE) != 0); if (__pyx_t_1) { /* "View.MemoryView":1028 * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< * else: * result.flags = PyBUF_RECORDS_RO */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; /* "View.MemoryView":1027 * Py_INCREF(Py_None) * * if (<memoryview>memviewslice.memview).flags & PyBUF_WRITABLE: # <<<<<<<<<<<<<< * result.flags = PyBUF_RECORDS * else: */ goto __pyx_L4; } /* "View.MemoryView":1030 * result.flags = PyBUF_RECORDS * else: * result.flags = PyBUF_RECORDS_RO # <<<<<<<<<<<<<< * * result.view.shape = <Py_ssize_t *> result.from_slice.shape */ /*else*/ { __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS_RO; } __pyx_L4:; /* "View.MemoryView":1032 * result.flags = PyBUF_RECORDS_RO * * result.view.shape = <Py_ssize_t *> result.from_slice.shape # <<<<<<<<<<<<<< * result.view.strides = <Py_ssize_t *> result.from_slice.strides * */ __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); /* "View.MemoryView":1033 * * result.view.shape = <Py_ssize_t *> result.from_slice.shape * result.view.strides = <Py_ssize_t *> result.from_slice.strides # <<<<<<<<<<<<<< * * */ __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); /* "View.MemoryView":1036 * * * result.view.suboffsets = NULL # <<<<<<<<<<<<<< * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: */ __pyx_v_result->__pyx_base.view.suboffsets = NULL; /* "View.MemoryView":1037 * * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets */ __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { __pyx_t_6 = __pyx_t_8; __pyx_v_suboffset = (__pyx_t_6[0]); /* "View.MemoryView":1038 * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break */ __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":1039 * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets # <<<<<<<<<<<<<< * break * */ __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); /* "View.MemoryView":1040 * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break # <<<<<<<<<<<<<< * * result.view.len = result.view.itemsize */ goto __pyx_L6_break; /* "View.MemoryView":1038 * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break */ } } __pyx_L6_break:; /* "View.MemoryView":1042 * break * * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< * for length in result.view.shape[:ndim]: * result.view.len *= length */ __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; /* "View.MemoryView":1043 * * result.view.len = result.view.itemsize * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< * result.view.len *= length * */ __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { __pyx_t_6 = __pyx_t_8; __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1043, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":1044 * result.view.len = result.view.itemsize * for length in result.view.shape[:ndim]: * result.view.len *= length # <<<<<<<<<<<<<< * * result.to_object_func = to_object_func */ __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1044, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1044, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 1044, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } /* "View.MemoryView":1046 * result.view.len *= length * * result.to_object_func = to_object_func # <<<<<<<<<<<<<< * result.to_dtype_func = to_dtype_func * */ __pyx_v_result->to_object_func = __pyx_v_to_object_func; /* "View.MemoryView":1047 * * result.to_object_func = to_object_func * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< * * return result */ __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; /* "View.MemoryView":1049 * result.to_dtype_func = to_dtype_func * * return result # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_get_slice_from_memoryview') */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":999 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< * int ndim, * object (*to_object_func)(char *), */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XDECREF(__pyx_v_length); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1052 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice) except NULL: * cdef _memoryviewslice obj */ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; __Pyx_memviewslice *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_slice_from_memview", 0); /* "View.MemoryView":1055 * __Pyx_memviewslice *mslice) except NULL: * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1056 * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): * obj = memview # <<<<<<<<<<<<<< * return &obj.from_slice * else: */ if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 1056, __pyx_L1_error) __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":1057 * if isinstance(memview, _memoryviewslice): * obj = memview * return &obj.from_slice # <<<<<<<<<<<<<< * else: * slice_copy(memview, mslice) */ __pyx_r = (&__pyx_v_obj->from_slice); goto __pyx_L0; /* "View.MemoryView":1055 * __Pyx_memviewslice *mslice) except NULL: * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ } /* "View.MemoryView":1059 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< * return mslice * */ /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); /* "View.MemoryView":1060 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_slice_copy') */ __pyx_r = __pyx_v_mslice; goto __pyx_L0; } /* "View.MemoryView":1052 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice) except NULL: * cdef _memoryviewslice obj */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_obj); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1063 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< * cdef int dim * cdef (Py_ssize_t*) shape, strides, suboffsets */ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { int __pyx_v_dim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; Py_ssize_t *__pyx_v_suboffsets; __Pyx_RefNannyDeclarations Py_ssize_t *__pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; Py_ssize_t __pyx_t_5; __Pyx_RefNannySetupContext("slice_copy", 0); /* "View.MemoryView":1067 * cdef (Py_ssize_t*) shape, strides, suboffsets * * shape = memview.view.shape # <<<<<<<<<<<<<< * strides = memview.view.strides * suboffsets = memview.view.suboffsets */ __pyx_t_1 = __pyx_v_memview->view.shape; __pyx_v_shape = __pyx_t_1; /* "View.MemoryView":1068 * * shape = memview.view.shape * strides = memview.view.strides # <<<<<<<<<<<<<< * suboffsets = memview.view.suboffsets * */ __pyx_t_1 = __pyx_v_memview->view.strides; __pyx_v_strides = __pyx_t_1; /* "View.MemoryView":1069 * shape = memview.view.shape * strides = memview.view.strides * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< * * dst.memview = <__pyx_memoryview *> memview */ __pyx_t_1 = __pyx_v_memview->view.suboffsets; __pyx_v_suboffsets = __pyx_t_1; /* "View.MemoryView":1071 * suboffsets = memview.view.suboffsets * * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< * dst.data = <char *> memview.view.buf * */ __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); /* "View.MemoryView":1072 * * dst.memview = <__pyx_memoryview *> memview * dst.data = <char *> memview.view.buf # <<<<<<<<<<<<<< * * for dim in range(memview.view.ndim): */ __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); /* "View.MemoryView":1074 * dst.data = <char *> memview.view.buf * * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] */ __pyx_t_2 = __pyx_v_memview->view.ndim; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_dim = __pyx_t_4; /* "View.MemoryView":1075 * * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 */ (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); /* "View.MemoryView":1076 * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 * */ (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); /* "View.MemoryView":1077 * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object') */ if ((__pyx_v_suboffsets != 0)) { __pyx_t_5 = (__pyx_v_suboffsets[__pyx_v_dim]); } else { __pyx_t_5 = -1L; } (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_5; } /* "View.MemoryView":1063 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< * cdef int dim * cdef (Py_ssize_t*) shape, strides, suboffsets */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":1080 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice */ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { __Pyx_memviewslice __pyx_v_memviewslice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_copy", 0); /* "View.MemoryView":1083 * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< * return memoryview_copy_from_slice(memview, &memviewslice) * */ __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); /* "View.MemoryView":1084 * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object_from_slice') */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1084, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":1080 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1087 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< * """ * Create a new memoryview object from a given memoryview object and slice. */ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { PyObject *(*__pyx_v_to_object_func)(char *); int (*__pyx_v_to_dtype_func)(char *, PyObject *); PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *(*__pyx_t_3)(char *); int (*__pyx_t_4)(char *, PyObject *); PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); /* "View.MemoryView":1094 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1095 * * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: */ __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; __pyx_v_to_object_func = __pyx_t_3; /* "View.MemoryView":1096 * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< * else: * to_object_func = NULL */ __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; __pyx_v_to_dtype_func = __pyx_t_4; /* "View.MemoryView":1094 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func */ goto __pyx_L3; } /* "View.MemoryView":1098 * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: * to_object_func = NULL # <<<<<<<<<<<<<< * to_dtype_func = NULL * */ /*else*/ { __pyx_v_to_object_func = NULL; /* "View.MemoryView":1099 * else: * to_object_func = NULL * to_dtype_func = NULL # <<<<<<<<<<<<<< * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, */ __pyx_v_to_dtype_func = NULL; } __pyx_L3:; /* "View.MemoryView":1101 * to_dtype_func = NULL * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< * to_object_func, to_dtype_func, * memview.dtype_is_object) */ __Pyx_XDECREF(__pyx_r); /* "View.MemoryView":1103 * return memoryview_fromslice(memviewslice[0], memview.view.ndim, * to_object_func, to_dtype_func, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 1101, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":1087 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< * """ * Create a new memoryview object from a given memoryview object and slice. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1109 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< * if arg < 0: * return -arg */ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { Py_ssize_t __pyx_r; int __pyx_t_1; /* "View.MemoryView":1110 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ __pyx_t_1 = ((__pyx_v_arg < 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":1111 * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: * return -arg # <<<<<<<<<<<<<< * else: * return arg */ __pyx_r = (-__pyx_v_arg); goto __pyx_L0; /* "View.MemoryView":1110 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ } /* "View.MemoryView":1113 * return -arg * else: * return arg # <<<<<<<<<<<<<< * * @cname('__pyx_get_best_slice_order') */ /*else*/ { __pyx_r = __pyx_v_arg; goto __pyx_L0; } /* "View.MemoryView":1109 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< * if arg < 0: * return -arg */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1116 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< * """ * Figure out the best memory access order for a given slice. */ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { int __pyx_v_i; Py_ssize_t __pyx_v_c_stride; Py_ssize_t __pyx_v_f_stride; char __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; /* "View.MemoryView":1121 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< * cdef Py_ssize_t f_stride = 0 * */ __pyx_v_c_stride = 0; /* "View.MemoryView":1122 * cdef int i * cdef Py_ssize_t c_stride = 0 * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< * * for i in range(ndim - 1, -1, -1): */ __pyx_v_f_stride = 0; /* "View.MemoryView":1124 * cdef Py_ssize_t f_stride = 0 * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] */ for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1125 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1126 * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< * break * */ __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1127 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * for i in range(ndim): */ goto __pyx_L4_break; /* "View.MemoryView":1125 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ } } __pyx_L4_break:; /* "View.MemoryView":1129 * break * * for i in range(ndim): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] */ __pyx_t_1 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_1; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1130 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1131 * for i in range(ndim): * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< * break * */ __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1132 * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): */ goto __pyx_L7_break; /* "View.MemoryView":1130 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ } } __pyx_L7_break:; /* "View.MemoryView":1134 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1135 * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): * return 'C' # <<<<<<<<<<<<<< * else: * return 'F' */ __pyx_r = 'C'; goto __pyx_L0; /* "View.MemoryView":1134 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ } /* "View.MemoryView":1137 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< * * @cython.cdivision(True) */ /*else*/ { __pyx_r = 'F'; goto __pyx_L0; } /* "View.MemoryView":1116 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< * """ * Figure out the best memory access order for a given slice. */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1140 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< * char *dst_data, Py_ssize_t *dst_strides, * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, */ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; Py_ssize_t __pyx_v_dst_extent; Py_ssize_t __pyx_v_src_stride; Py_ssize_t __pyx_v_dst_stride; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; /* "View.MemoryView":1147 * * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] */ __pyx_v_src_extent = (__pyx_v_src_shape[0]); /* "View.MemoryView":1148 * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t src_stride = src_strides[0] * cdef Py_ssize_t dst_stride = dst_strides[0] */ __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); /* "View.MemoryView":1149 * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t dst_stride = dst_strides[0] * */ __pyx_v_src_stride = (__pyx_v_src_strides[0]); /* "View.MemoryView":1150 * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< * * if ndim == 1: */ __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); /* "View.MemoryView":1152 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): */ __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":1153 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) */ __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L5_bool_binop_done; } __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L5_bool_binop_done; } /* "View.MemoryView":1154 * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): # <<<<<<<<<<<<<< * memcpy(dst_data, src_data, itemsize * dst_extent) * else: */ __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); if (__pyx_t_2) { __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); } __pyx_t_3 = (__pyx_t_2 != 0); __pyx_t_1 = __pyx_t_3; __pyx_L5_bool_binop_done:; /* "View.MemoryView":1153 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) */ if (__pyx_t_1) { /* "View.MemoryView":1155 * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent))); /* "View.MemoryView":1153 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) */ goto __pyx_L4; } /* "View.MemoryView":1157 * memcpy(dst_data, src_data, itemsize * dst_extent) * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * memcpy(dst_data, src_data, itemsize) * src_data += src_stride */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; __pyx_t_5 = __pyx_t_4; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1158 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< * src_data += src_stride * dst_data += dst_stride */ (void)(memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize)); /* "View.MemoryView":1159 * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< * dst_data += dst_stride * else: */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); /* "View.MemoryView":1160 * memcpy(dst_data, src_data, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); } } __pyx_L4:; /* "View.MemoryView":1152 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): */ goto __pyx_L3; } /* "View.MemoryView":1162 * dst_data += dst_stride * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * _copy_strided_to_strided(src_data, src_strides + 1, * dst_data, dst_strides + 1, */ /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; __pyx_t_5 = __pyx_t_4; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1163 * else: * for i in range(dst_extent): * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< * dst_data, dst_strides + 1, * src_shape + 1, dst_shape + 1, */ _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); /* "View.MemoryView":1167 * src_shape + 1, dst_shape + 1, * ndim - 1, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< * dst_data += dst_stride * */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); /* "View.MemoryView":1168 * ndim - 1, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, */ __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); } } __pyx_L3:; /* "View.MemoryView":1140 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< * char *dst_data, Py_ssize_t *dst_strides, * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, */ /* function exit code */ } /* "View.MemoryView":1170 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: */ static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { /* "View.MemoryView":1173 * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< * src.shape, dst.shape, ndim, itemsize) * */ _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); /* "View.MemoryView":1170 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: */ /* function exit code */ } /* "View.MemoryView":1177 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< * "Return the size of the memory occupied by the slice in number of bytes" * cdef Py_ssize_t shape, size = src.memview.view.itemsize */ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { Py_ssize_t __pyx_v_shape; Py_ssize_t __pyx_v_size; Py_ssize_t __pyx_r; Py_ssize_t __pyx_t_1; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; /* "View.MemoryView":1179 * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: * "Return the size of the memory occupied by the slice in number of bytes" * cdef Py_ssize_t shape, size = src.memview.view.itemsize # <<<<<<<<<<<<<< * * for shape in src.shape[:ndim]: */ __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_size = __pyx_t_1; /* "View.MemoryView":1181 * cdef Py_ssize_t shape, size = src.memview.view.itemsize * * for shape in src.shape[:ndim]: # <<<<<<<<<<<<<< * size *= shape * */ __pyx_t_3 = (__pyx_v_src->shape + __pyx_v_ndim); for (__pyx_t_4 = __pyx_v_src->shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { __pyx_t_2 = __pyx_t_4; __pyx_v_shape = (__pyx_t_2[0]); /* "View.MemoryView":1182 * * for shape in src.shape[:ndim]: * size *= shape # <<<<<<<<<<<<<< * * return size */ __pyx_v_size = (__pyx_v_size * __pyx_v_shape); } /* "View.MemoryView":1184 * size *= shape * * return size # <<<<<<<<<<<<<< * * @cname('__pyx_fill_contig_strides_array') */ __pyx_r = __pyx_v_size; goto __pyx_L0; /* "View.MemoryView":1177 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< * "Return the size of the memory occupied by the slice in number of bytes" * cdef Py_ssize_t shape, size = src.memview.view.itemsize */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1187 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, * int ndim, char order) nogil: */ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { int __pyx_v_idx; Py_ssize_t __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; /* "View.MemoryView":1196 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ __pyx_t_1 = ((__pyx_v_order == 'F') != 0); if (__pyx_t_1) { /* "View.MemoryView":1197 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< * strides[idx] = stride * stride *= shape[idx] */ __pyx_t_2 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_idx = __pyx_t_4; /* "View.MemoryView":1198 * if order == 'F': * for idx in range(ndim): * strides[idx] = stride # <<<<<<<<<<<<<< * stride *= shape[idx] * else: */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1199 * for idx in range(ndim): * strides[idx] = stride * stride *= shape[idx] # <<<<<<<<<<<<<< * else: * for idx in range(ndim - 1, -1, -1): */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } /* "View.MemoryView":1196 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ goto __pyx_L3; } /* "View.MemoryView":1201 * stride *= shape[idx] * else: * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * strides[idx] = stride * stride *= shape[idx] */ /*else*/ { for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; /* "View.MemoryView":1202 * else: * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride # <<<<<<<<<<<<<< * stride *= shape[idx] * */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1203 * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride * stride *= shape[idx] # <<<<<<<<<<<<<< * * return stride */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } } __pyx_L3:; /* "View.MemoryView":1205 * stride *= shape[idx] * * return stride # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_data_to_temp') */ __pyx_r = __pyx_v_stride; goto __pyx_L0; /* "View.MemoryView":1187 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, * int ndim, char order) nogil: */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1208 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *tmpslice, * char order, */ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { int __pyx_v_i; void *__pyx_v_result; size_t __pyx_v_itemsize; size_t __pyx_v_size; void *__pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; struct __pyx_memoryview_obj *__pyx_t_4; int __pyx_t_5; int __pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1219 * cdef void *result * * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< * cdef size_t size = slice_get_size(src, ndim) * */ __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":1220 * * cdef size_t itemsize = src.memview.view.itemsize * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< * * result = malloc(size) */ __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); /* "View.MemoryView":1222 * cdef size_t size = slice_get_size(src, ndim) * * result = malloc(size) # <<<<<<<<<<<<<< * if not result: * _err(MemoryError, NULL) */ __pyx_v_result = malloc(__pyx_v_size); /* "View.MemoryView":1223 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1224 * result = malloc(size) * if not result: * _err(MemoryError, NULL) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 1224, __pyx_L1_error) /* "View.MemoryView":1223 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ } /* "View.MemoryView":1227 * * * tmpslice.data = <char *> result # <<<<<<<<<<<<<< * tmpslice.memview = src.memview * for i in range(ndim): */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); /* "View.MemoryView":1228 * * tmpslice.data = <char *> result * tmpslice.memview = src.memview # <<<<<<<<<<<<<< * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] */ __pyx_t_4 = __pyx_v_src->memview; __pyx_v_tmpslice->memview = __pyx_t_4; /* "View.MemoryView":1229 * tmpslice.data = <char *> result * tmpslice.memview = src.memview * for i in range(ndim): # <<<<<<<<<<<<<< * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 */ __pyx_t_3 = __pyx_v_ndim; __pyx_t_5 = __pyx_t_3; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1230 * tmpslice.memview = src.memview * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< * tmpslice.suboffsets[i] = -1 * */ (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); /* "View.MemoryView":1231 * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, */ (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; } /* "View.MemoryView":1233 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< * ndim, order) * */ (void)(__pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order)); /* "View.MemoryView":1237 * * * for i in range(ndim): # <<<<<<<<<<<<<< * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 */ __pyx_t_3 = __pyx_v_ndim; __pyx_t_5 = __pyx_t_3; for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "View.MemoryView":1238 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1239 * for i in range(ndim): * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< * * if slice_is_contig(src[0], order, ndim): */ (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; /* "View.MemoryView":1238 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ } } /* "View.MemoryView":1241 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1242 * * if slice_is_contig(src[0], order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) */ (void)(memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size)); /* "View.MemoryView":1241 * tmpslice.strides[i] = 0 * * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ goto __pyx_L9; } /* "View.MemoryView":1244 * memcpy(result, src.data, size) * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< * * return result */ /*else*/ { copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); } __pyx_L9:; /* "View.MemoryView":1246 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":1208 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *tmpslice, * char order, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = NULL; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1251 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % */ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_extents", 0); /* "View.MemoryView":1254 * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % * (i, extent1, extent2)) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err_dim') */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_3 = 0; /* "View.MemoryView":1253 * cdef int _err_extents(int i, Py_ssize_t extent1, * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< * (i, extent1, extent2)) * */ __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1253, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __PYX_ERR(1, 1253, __pyx_L1_error) /* "View.MemoryView":1251 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1257 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1258 * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err') */ __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1258, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1258, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1258, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_INCREF(__pyx_v_error); __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1258, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __PYX_ERR(1, 1258, __pyx_L1_error) /* "View.MemoryView":1257 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1261 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1262 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); if (unlikely(__pyx_t_1)) { /* "View.MemoryView":1263 * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< * else: * raise error */ __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1263, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_error); __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } __pyx_t_2 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_t_3) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1263, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(1, 1263, __pyx_L1_error) /* "View.MemoryView":1262 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ } /* "View.MemoryView":1265 * raise error(msg.decode('ascii')) * else: * raise error # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_contents') */ /*else*/ { __Pyx_Raise(__pyx_v_error, 0, 0, 0); __PYX_ERR(1, 1265, __pyx_L1_error) } /* "View.MemoryView":1261 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1268 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { void *__pyx_v_tmpdata; size_t __pyx_v_itemsize; int __pyx_v_i; char __pyx_v_order; int __pyx_v_broadcasting; int __pyx_v_direct_copy; __Pyx_memviewslice __pyx_v_tmp; int __pyx_v_ndim; int __pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; int __pyx_t_6; void *__pyx_t_7; int __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1276 * Check for overlapping memory and verify the shapes. * """ * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< * cdef size_t itemsize = src.memview.view.itemsize * cdef int i */ __pyx_v_tmpdata = NULL; /* "View.MemoryView":1277 * """ * cdef void *tmpdata = NULL * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< * cdef int i * cdef char order = get_best_order(&src, src_ndim) */ __pyx_t_1 = __pyx_v_src.memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":1279 * cdef size_t itemsize = src.memview.view.itemsize * cdef int i * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< * cdef bint broadcasting = False * cdef bint direct_copy = False */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); /* "View.MemoryView":1280 * cdef int i * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False # <<<<<<<<<<<<<< * cdef bint direct_copy = False * cdef __Pyx_memviewslice tmp */ __pyx_v_broadcasting = 0; /* "View.MemoryView":1281 * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False * cdef bint direct_copy = False # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice tmp * */ __pyx_v_direct_copy = 0; /* "View.MemoryView":1284 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: */ __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1285 * * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); /* "View.MemoryView":1284 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: */ goto __pyx_L3; } /* "View.MemoryView":1286 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&dst, dst_ndim, src_ndim) * */ __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1287 * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< * * cdef int ndim = max(src_ndim, dst_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); /* "View.MemoryView":1286 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&dst, dst_ndim, src_ndim) * */ } __pyx_L3:; /* "View.MemoryView":1289 * broadcast_leading(&dst, dst_ndim, src_ndim) * * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< * * for i in range(ndim): */ __pyx_t_3 = __pyx_v_dst_ndim; __pyx_t_4 = __pyx_v_src_ndim; if (((__pyx_t_3 > __pyx_t_4) != 0)) { __pyx_t_5 = __pyx_t_3; } else { __pyx_t_5 = __pyx_t_4; } __pyx_v_ndim = __pyx_t_5; /* "View.MemoryView":1291 * cdef int ndim = max(src_ndim, dst_ndim) * * for i in range(ndim): # <<<<<<<<<<<<<< * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: */ __pyx_t_5 = __pyx_v_ndim; __pyx_t_3 = __pyx_t_5; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1292 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); if (__pyx_t_2) { /* "View.MemoryView":1293 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< * broadcasting = True * src.strides[i] = 0 */ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1294 * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: * broadcasting = True # <<<<<<<<<<<<<< * src.strides[i] = 0 * else: */ __pyx_v_broadcasting = 1; /* "View.MemoryView":1295 * if src.shape[i] == 1: * broadcasting = True * src.strides[i] = 0 # <<<<<<<<<<<<<< * else: * _err_extents(i, dst.shape[i], src.shape[i]) */ (__pyx_v_src.strides[__pyx_v_i]) = 0; /* "View.MemoryView":1293 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< * broadcasting = True * src.strides[i] = 0 */ goto __pyx_L7; } /* "View.MemoryView":1297 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< * * if src.suboffsets[i] >= 0: */ /*else*/ { __pyx_t_6 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 1297, __pyx_L1_error) } __pyx_L7:; /* "View.MemoryView":1292 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ } /* "View.MemoryView":1299 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Dimension %d is not direct", i) * */ __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":1300 * * if src.suboffsets[i] >= 0: * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< * * if slices_overlap(&src, &dst, ndim, itemsize): */ __pyx_t_6 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(1, 1300, __pyx_L1_error) /* "View.MemoryView":1299 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Dimension %d is not direct", i) * */ } } /* "View.MemoryView":1302 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * * if not slice_is_contig(src, order, ndim): */ __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); if (__pyx_t_2) { /* "View.MemoryView":1304 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ __pyx_t_2 = ((!(__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1305 * * if not slice_is_contig(src, order, ndim): * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); /* "View.MemoryView":1304 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ } /* "View.MemoryView":1307 * order = get_best_order(&dst, ndim) * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< * src = tmp * */ __pyx_t_7 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_7 == ((void *)NULL))) __PYX_ERR(1, 1307, __pyx_L1_error) __pyx_v_tmpdata = __pyx_t_7; /* "View.MemoryView":1308 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< * * if not broadcasting: */ __pyx_v_src = __pyx_v_tmp; /* "View.MemoryView":1302 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * * if not slice_is_contig(src, order, ndim): */ } /* "View.MemoryView":1310 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1313 * * * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): */ __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'C', __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1314 * * if slice_is_contig(src, 'C', ndim): * direct_copy = slice_is_contig(dst, 'C', ndim) # <<<<<<<<<<<<<< * elif slice_is_contig(src, 'F', ndim): * direct_copy = slice_is_contig(dst, 'F', ndim) */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'C', __pyx_v_ndim); /* "View.MemoryView":1313 * * * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): */ goto __pyx_L12; } /* "View.MemoryView":1315 * if slice_is_contig(src, 'C', ndim): * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(dst, 'F', ndim) * */ __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1316 * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): * direct_copy = slice_is_contig(dst, 'F', ndim) # <<<<<<<<<<<<<< * * if direct_copy: */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'F', __pyx_v_ndim); /* "View.MemoryView":1315 * if slice_is_contig(src, 'C', ndim): * direct_copy = slice_is_contig(dst, 'C', ndim) * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(dst, 'F', ndim) * */ } __pyx_L12:; /* "View.MemoryView":1318 * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ __pyx_t_2 = (__pyx_v_direct_copy != 0); if (__pyx_t_2) { /* "View.MemoryView":1320 * if direct_copy: * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1321 * * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) */ (void)(memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim))); /* "View.MemoryView":1322 * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * free(tmpdata) * return 0 */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1323 * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1324 * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * if order == 'F' == get_best_order(&dst, ndim): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1318 * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ } /* "View.MemoryView":1310 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1326 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ __pyx_t_2 = (__pyx_v_order == 'F'); if (__pyx_t_2) { __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); } __pyx_t_8 = (__pyx_t_2 != 0); if (__pyx_t_8) { /* "View.MemoryView":1329 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1329, __pyx_L1_error) /* "View.MemoryView":1330 * * transpose_memslice(&src) * transpose_memslice(&dst) # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1330, __pyx_L1_error) /* "View.MemoryView":1326 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ } /* "View.MemoryView":1332 * transpose_memslice(&dst) * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * copy_strided_to_strided(&src, &dst, ndim, itemsize) * refcount_copying(&dst, dtype_is_object, ndim, True) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1333 * * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< * refcount_copying(&dst, dtype_is_object, ndim, True) * */ copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); /* "View.MemoryView":1334 * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * * free(tmpdata) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1336 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1337 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_broadcast_leading') */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1268 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1340 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { int __pyx_v_i; int __pyx_v_offset; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1344 * int ndim_other) nogil: * cdef int i * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< * * for i in range(ndim - 1, -1, -1): */ __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); /* "View.MemoryView":1346 * cdef int offset = ndim_other - ndim * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] */ for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1347 * * for i in range(ndim - 1, -1, -1): * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< * mslice.strides[i + offset] = mslice.strides[i] * mslice.suboffsets[i + offset] = mslice.suboffsets[i] */ (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); /* "View.MemoryView":1348 * for i in range(ndim - 1, -1, -1): * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * */ (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1349 * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< * * for i in range(offset): */ (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); } /* "View.MemoryView":1351 * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * * for i in range(offset): # <<<<<<<<<<<<<< * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] */ __pyx_t_1 = __pyx_v_offset; __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1352 * * for i in range(offset): * mslice.shape[i] = 1 # <<<<<<<<<<<<<< * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 */ (__pyx_v_mslice->shape[__pyx_v_i]) = 1; /* "View.MemoryView":1353 * for i in range(offset): * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< * mslice.suboffsets[i] = -1 * */ (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); /* "View.MemoryView":1354 * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * */ (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; } /* "View.MemoryView":1340 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ /* function exit code */ } /* "View.MemoryView":1362 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< * int ndim, bint inc) nogil: * */ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { int __pyx_t_1; /* "View.MemoryView":1366 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ __pyx_t_1 = (__pyx_v_dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":1367 * * if dtype_is_object: * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< * dst.strides, ndim, inc) * */ __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); /* "View.MemoryView":1366 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ } /* "View.MemoryView":1362 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< * int ndim, bint inc) nogil: * */ /* function exit code */ } /* "View.MemoryView":1371 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { __Pyx_RefNannyDeclarations #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); /* "View.MemoryView":1374 * Py_ssize_t *strides, int ndim, * bint inc) with gil: * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_refcount_objects_in_slice') */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); /* "View.MemoryView":1371 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ /* function exit code */ __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } /* "View.MemoryView":1377 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, bint inc): * cdef Py_ssize_t i */ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; int __pyx_t_4; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); /* "View.MemoryView":1381 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< * if ndim == 1: * if inc: */ __pyx_t_1 = (__pyx_v_shape[0]); __pyx_t_2 = __pyx_t_1; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1382 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ __pyx_t_4 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_4) { /* "View.MemoryView":1383 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ __pyx_t_4 = (__pyx_v_inc != 0); if (__pyx_t_4) { /* "View.MemoryView":1384 * if ndim == 1: * if inc: * Py_INCREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * Py_DECREF((<PyObject **> data)[0]) */ Py_INCREF((((PyObject **)__pyx_v_data)[0])); /* "View.MemoryView":1383 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ goto __pyx_L6; } /* "View.MemoryView":1386 * Py_INCREF((<PyObject **> data)[0]) * else: * Py_DECREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, */ /*else*/ { Py_DECREF((((PyObject **)__pyx_v_data)[0])); } __pyx_L6:; /* "View.MemoryView":1382 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ goto __pyx_L5; } /* "View.MemoryView":1388 * Py_DECREF((<PyObject **> data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, inc) * */ /*else*/ { /* "View.MemoryView":1389 * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, * ndim - 1, inc) # <<<<<<<<<<<<<< * * data += strides[0] */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); } __pyx_L5:; /* "View.MemoryView":1391 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } /* "View.MemoryView":1377 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, bint inc): * cdef Py_ssize_t i */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":1397 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< * size_t itemsize, void *item, * bint dtype_is_object) nogil: */ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { /* "View.MemoryView":1400 * size_t itemsize, void *item, * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1401 * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) */ __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); /* "View.MemoryView":1403 * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * * */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1397 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< * size_t itemsize, void *item, * bint dtype_is_object) nogil: */ /* function exit code */ } /* "View.MemoryView":1407 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_stride; Py_ssize_t __pyx_v_extent; int __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; /* "View.MemoryView":1411 * size_t itemsize, void *item) nogil: * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t extent = shape[0] * */ __pyx_v_stride = (__pyx_v_strides[0]); /* "View.MemoryView":1412 * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< * * if ndim == 1: */ __pyx_v_extent = (__pyx_v_shape[0]); /* "View.MemoryView":1414 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":1415 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< * memcpy(data, item, itemsize) * data += stride */ __pyx_t_2 = __pyx_v_extent; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1416 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< * data += stride * else: */ (void)(memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize)); /* "View.MemoryView":1417 * for i in range(extent): * memcpy(data, item, itemsize) * data += stride # <<<<<<<<<<<<<< * else: * for i in range(extent): */ __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } /* "View.MemoryView":1414 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ goto __pyx_L3; } /* "View.MemoryView":1419 * data += stride * else: * for i in range(extent): # <<<<<<<<<<<<<< * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) */ /*else*/ { __pyx_t_2 = __pyx_v_extent; __pyx_t_3 = __pyx_t_2; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "View.MemoryView":1420 * else: * for i in range(extent): * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, itemsize, item) * data += stride */ __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); /* "View.MemoryView":1422 * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) * data += stride # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } } __pyx_L3:; /* "View.MemoryView":1407 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ /* function exit code */ } /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ /* Python wrapper */ static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v___pyx_type = 0; long __pyx_v___pyx_checksum; PyObject *__pyx_v___pyx_state = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(1, 1, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(1, 1, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(1, 1, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } __pyx_v___pyx_type = values[0]; __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 1, __pyx_L3_error) __pyx_v___pyx_state = values[2]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 1, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_v___pyx_PickleError = 0; PyObject *__pyx_v___pyx_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); /* "(tree fragment)":4 * cdef object __pyx_PickleError * cdef object __pyx_result * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) */ __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); if (__pyx_t_1) { /* "(tree fragment)":5 * cdef object __pyx_result * if __pyx_checksum != 0xb068931: * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) */ __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_n_s_PickleError); __Pyx_GIVEREF(__pyx_n_s_PickleError); PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_t_2); __pyx_v___pyx_PickleError = __pyx_t_2; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":6 * if __pyx_checksum != 0xb068931: * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: */ __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_INCREF(__pyx_v___pyx_PickleError); __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 6, __pyx_L1_error) /* "(tree fragment)":4 * cdef object __pyx_PickleError * cdef object __pyx_result * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) */ } /* "(tree fragment)":7 * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v___pyx_result = __pyx_t_3; __pyx_t_3 = 0; /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result */ __pyx_t_1 = (__pyx_v___pyx_state != Py_None); __pyx_t_6 = (__pyx_t_1 != 0); if (__pyx_t_6) { /* "(tree fragment)":9 * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) # <<<<<<<<<<<<<< * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): */ if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) * __pyx_result = Enum.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result */ } /* "(tree fragment)":10 * if __pyx_state is not None: * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result # <<<<<<<<<<<<<< * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v___pyx_result); __pyx_r = __pyx_v___pyx_result; goto __pyx_L0; /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v___pyx_PickleError); __Pyx_XDECREF(__pyx_v___pyx_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; Py_ssize_t __pyx_t_3; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); /* "(tree fragment)":12 * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): * __pyx_result.__dict__.update(__pyx_state[1]) */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(1, 12, __pyx_L1_error) } __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __Pyx_GOTREF(__pyx_v___pyx_result->name); __Pyx_DECREF(__pyx_v___pyx_result->name); __pyx_v___pyx_result->name = __pyx_t_1; __pyx_t_1 = 0; /* "(tree fragment)":13 * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< * __pyx_result.__dict__.update(__pyx_state[1]) */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); __PYX_ERR(1, 13, __pyx_L1_error) } __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(1, 13, __pyx_L1_error) __pyx_t_4 = ((__pyx_t_3 > 1) != 0); if (__pyx_t_4) { } else { __pyx_t_2 = __pyx_t_4; goto __pyx_L4_bool_binop_done; } __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) __pyx_t_5 = (__pyx_t_4 != 0); __pyx_t_2 = __pyx_t_5; __pyx_L4_bool_binop_done:; if (__pyx_t_2) { /* "(tree fragment)":14 * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< */ __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(1, 14, __pyx_L1_error) } __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_8 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); if (likely(__pyx_t_8)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); __Pyx_INCREF(__pyx_t_8); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_7, function); } } __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":13 * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< * __pyx_result.__dict__.update(__pyx_state[1]) */ } /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static struct __pyx_vtabstruct_array __pyx_vtable_array; static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_array_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_array_obj *)o); p->__pyx_vtab = __pyx_vtabptr_array; p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_array(PyObject *o) { struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); __pyx_array___dealloc__(o); __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->mode); Py_CLEAR(p->_format); (*Py_TYPE(o)->tp_free)(o); } static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_array___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { PyObject *v = __Pyx_PyObject_GenericGetAttr(o, n); if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); v = __pyx_array___getattr__(o, n); } return v; } static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); } static PyMethodDef __pyx_methods_array[] = { {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_array[] = { {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_array = { __pyx_array___len__, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ __pyx_sq_item_array, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_array = { __pyx_array___len__, /*mp_length*/ __pyx_array___getitem__, /*mp_subscript*/ __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_array = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif __pyx_array_getbuffer, /*bf_getbuffer*/ 0, /*bf_releasebuffer*/ }; static PyTypeObject __pyx_type___pyx_array = { PyVarObject_HEAD_INIT(0, 0) "monotonic_align.core.array", /*tp_name*/ sizeof(struct __pyx_array_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_array, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ __pyx_tp_getattro_array, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_array, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_array, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_array, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_MemviewEnum_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_MemviewEnum_obj *)o); p->name = Py_None; Py_INCREF(Py_None); return o; } static void __pyx_tp_dealloc_Enum(PyObject *o) { struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); Py_CLEAR(p->name); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { int e; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; if (p->name) { e = (*v)(p->name, a); if (e) return e; } return 0; } static int __pyx_tp_clear_Enum(PyObject *o) { PyObject* tmp; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; tmp = ((PyObject*)p->name); p->name = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); return 0; } static PyMethodDef __pyx_methods_Enum[] = { {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_MemviewEnum = { PyVarObject_HEAD_INIT(0, 0) "monotonic_align.core.Enum", /*tp_name*/ sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_Enum, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif __pyx_MemviewEnum___repr__, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_Enum, /*tp_traverse*/ __pyx_tp_clear_Enum, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_Enum, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ __pyx_MemviewEnum___init__, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_Enum, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_memoryview_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_memoryview_obj *)o); p->__pyx_vtab = __pyx_vtabptr_memoryview; p->obj = Py_None; Py_INCREF(Py_None); p->_size = Py_None; Py_INCREF(Py_None); p->_array_interface = Py_None; Py_INCREF(Py_None); p->view.obj = NULL; if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) goto bad; return o; bad: Py_DECREF(o); o = 0; return NULL; } static void __pyx_tp_dealloc_memoryview(PyObject *o) { struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); __pyx_memoryview___dealloc__(o); __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->obj); Py_CLEAR(p->_size); Py_CLEAR(p->_array_interface); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; if (p->obj) { e = (*v)(p->obj, a); if (e) return e; } if (p->_size) { e = (*v)(p->_size, a); if (e) return e; } if (p->_array_interface) { e = (*v)(p->_array_interface, a); if (e) return e; } if (p->view.obj) { e = (*v)(p->view.obj, a); if (e) return e; } return 0; } static int __pyx_tp_clear_memoryview(PyObject *o) { PyObject* tmp; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; tmp = ((PyObject*)p->obj); p->obj = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_size); p->_size = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_array_interface); p->_array_interface = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); Py_CLEAR(p->view.obj); return 0; } static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_memoryview___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(o); } static PyMethodDef __pyx_methods_memoryview[] = { {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_memoryview[] = { {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_memoryview = { __pyx_memoryview___len__, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ __pyx_sq_item_memoryview, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_memoryview = { __pyx_memoryview___len__, /*mp_length*/ __pyx_memoryview___getitem__, /*mp_subscript*/ __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_memoryview = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif __pyx_memoryview_getbuffer, /*bf_getbuffer*/ 0, /*bf_releasebuffer*/ }; static PyTypeObject __pyx_type___pyx_memoryview = { PyVarObject_HEAD_INIT(0, 0) "monotonic_align.core.memoryview", /*tp_name*/ sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif __pyx_memoryview___repr__, /*tp_repr*/ 0, /*tp_as_number*/ &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ __pyx_memoryview___str__, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_memoryview, /*tp_traverse*/ __pyx_tp_clear_memoryview, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_memoryview, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_memoryview, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_memoryview, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_memoryviewslice_obj *p; PyObject *o = __pyx_tp_new_memoryview(t, a, k); if (unlikely(!o)) return 0; p = ((struct __pyx_memoryviewslice_obj *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; p->from_object = Py_None; Py_INCREF(Py_None); p->from_slice.memview = NULL; return o; } static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; #if CYTHON_USE_TP_FINALIZE if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); __pyx_memoryviewslice___dealloc__(o); __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->from_object); PyObject_GC_Track(o); __pyx_tp_dealloc_memoryview(o); } static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; if (p->from_object) { e = (*v)(p->from_object, a); if (e) return e; } return 0; } static int __pyx_tp_clear__memoryviewslice(PyObject *o) { PyObject* tmp; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; __pyx_tp_clear_memoryview(o); tmp = ((PyObject*)p->from_object); p->from_object = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); __PYX_XDEC_MEMVIEW(&p->from_slice, 1); return 0; } static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); } static PyMethodDef __pyx_methods__memoryviewslice[] = { {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_memoryviewslice = { PyVarObject_HEAD_INIT(0, 0) "monotonic_align.core._memoryviewslice", /*tp_name*/ sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ #if PY_VERSION_HEX < 0x030800b4 0, /*tp_print*/ #endif #if PY_VERSION_HEX >= 0x030800b4 0, /*tp_vectorcall_offset*/ #endif 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #endif #if PY_MAJOR_VERSION >= 3 0, /*tp_as_async*/ #endif #if CYTHON_COMPILING_IN_PYPY __pyx_memoryview___repr__, /*tp_repr*/ #else 0, /*tp_repr*/ #endif 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ #if CYTHON_COMPILING_IN_PYPY __pyx_memoryview___str__, /*tp_str*/ #else 0, /*tp_str*/ #endif 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ "Internal class for passing memoryview slices to Python", /*tp_doc*/ __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ __pyx_tp_clear__memoryviewslice, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods__memoryviewslice, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets__memoryviewslice, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new__memoryviewslice, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif #if PY_VERSION_HEX >= 0x030800b1 0, /*tp_vectorcall*/ #endif #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 0, /*tp_print*/ #endif }; static PyMethodDef __pyx_methods[] = { {"maximum_path_c", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15monotonic_align_4core_1maximum_path_c, METH_VARARGS|METH_KEYWORDS, 0}, {"maximum_path_gradtts_c", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_15monotonic_align_4core_3maximum_path_gradtts_c, METH_VARARGS|METH_KEYWORDS, 0}, {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 #if CYTHON_PEP489_MULTI_PHASE_INIT static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ static int __pyx_pymod_exec_core(PyObject* module); /*proto*/ static PyModuleDef_Slot __pyx_moduledef_slots[] = { {Py_mod_create, (void*)__pyx_pymod_create}, {Py_mod_exec, (void*)__pyx_pymod_exec_core}, {0, NULL} }; #endif static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, "core", 0, /* m_doc */ #if CYTHON_PEP489_MULTI_PHASE_INIT 0, /* m_size */ #else -1, /* m_size */ #endif __pyx_methods /* m_methods */, #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_moduledef_slots, /* m_slots */ #else NULL, /* m_reload */ #endif NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif #ifndef CYTHON_SMALL_CODE #if defined(__clang__) #define CYTHON_SMALL_CODE #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) #define CYTHON_SMALL_CODE __attribute__((cold)) #else #define CYTHON_SMALL_CODE #endif #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_assign_to_read_only_memor, __pyx_k_Cannot_assign_to_read_only_memor, sizeof(__pyx_k_Cannot_assign_to_read_only_memor), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_create_writable_memory_vi, __pyx_k_Cannot_create_writable_memory_vi, sizeof(__pyx_k_Cannot_create_writable_memory_vi), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, {&__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 0, 0, 1, 0}, {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_max_neg_val, __pyx_k_max_neg_val, sizeof(__pyx_k_max_neg_val), 0, 0, 1, 1}, {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, {&__pyx_n_s_paths, __pyx_k_paths, sizeof(__pyx_k_paths), 0, 0, 1, 1}, {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, {&__pyx_n_s_t_xs, __pyx_k_t_xs, sizeof(__pyx_k_t_xs), 0, 0, 1, 1}, {&__pyx_n_s_t_ys, __pyx_k_t_ys, sizeof(__pyx_k_t_ys), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, {&__pyx_n_s_values, __pyx_k_values, sizeof(__pyx_k_values), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 15, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 133, __pyx_L1_error) __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 148, __pyx_L1_error) __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(1, 151, __pyx_L1_error) __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 404, __pyx_L1_error) __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 613, __pyx_L1_error) __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 832, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "View.MemoryView":133 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 133, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "View.MemoryView":136 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if not isinstance(format, bytes): */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 136, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "View.MemoryView":148 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 148, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "View.MemoryView":176 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 176, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "View.MemoryView":192 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 192, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "View.MemoryView":418 * def __setitem__(memoryview self, object index, object value): * if self.view.readonly: * raise TypeError("Cannot assign to read-only memoryview") # <<<<<<<<<<<<<< * * have_slices, index = _unellipsify(index, self.view.ndim) */ __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Cannot_assign_to_read_only_memor); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 418, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); /* "View.MemoryView":495 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 495, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); /* "View.MemoryView":520 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_WRITABLE and self.view.readonly: * raise ValueError("Cannot create writable memory view from read-only memoryview") # <<<<<<<<<<<<<< * * if flags & PyBUF_ND: */ __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Cannot_create_writable_memory_vi); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 520, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__12); __Pyx_GIVEREF(__pyx_tuple__12); /* "View.MemoryView":570 * if self.view.strides == NULL: * * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(1, 570, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); /* "View.MemoryView":577 * def suboffsets(self): * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) */ __pyx_tuple__14 = PyTuple_New(1); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(1, 577, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__14); __Pyx_INCREF(__pyx_int_neg_1); __Pyx_GIVEREF(__pyx_int_neg_1); PyTuple_SET_ITEM(__pyx_tuple__14, 0, __pyx_int_neg_1); __Pyx_GIVEREF(__pyx_tuple__14); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__15); __Pyx_GIVEREF(__pyx_tuple__15); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__16); __Pyx_GIVEREF(__pyx_tuple__16); /* "View.MemoryView":682 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_slice__17 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__17)) __PYX_ERR(1, 682, __pyx_L1_error) __Pyx_GOTREF(__pyx_slice__17); __Pyx_GIVEREF(__pyx_slice__17); /* "View.MemoryView":703 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(1, 703, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__18); __Pyx_GIVEREF(__pyx_tuple__18); /* "(tree fragment)":2 * def __reduce_cython__(self): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") */ __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(1, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__19); __Pyx_GIVEREF(__pyx_tuple__19); /* "(tree fragment)":4 * raise TypeError("no default __reduce__ due to non-trivial __cinit__") * def __setstate_cython__(self, __pyx_state): * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< */ __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(1, 4, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__20); __Pyx_GIVEREF(__pyx_tuple__20); /* "View.MemoryView":286 * return self.name * * cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<< * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") */ __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(1, 286, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__21); __Pyx_GIVEREF(__pyx_tuple__21); /* "View.MemoryView":287 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(1, 287, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__22); __Pyx_GIVEREF(__pyx_tuple__22); /* "View.MemoryView":288 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__23 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(1, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__23); __Pyx_GIVEREF(__pyx_tuple__23); /* "View.MemoryView":291 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(1, 291, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__24); __Pyx_GIVEREF(__pyx_tuple__24); /* "View.MemoryView":292 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(1, 292, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__25); __Pyx_GIVEREF(__pyx_tuple__25); /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ __pyx_tuple__26 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__26)) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__26); __Pyx_GIVEREF(__pyx_tuple__26); __pyx_codeobj__27 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__26, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__27)) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { /* InitThreads.init */ #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ static int __Pyx_modinit_global_init_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); /*--- Global init code ---*/ generic = Py_None; Py_INCREF(Py_None); strided = Py_None; Py_INCREF(Py_None); indirect = Py_None; Py_INCREF(Py_None); contiguous = Py_None; Py_INCREF(Py_None); indirect_contiguous = Py_None; Py_INCREF(Py_None); __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); /*--- Variable export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_export_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); /*--- Function export code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_type_init_code(void) { __Pyx_RefNannyDeclarations int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); /*--- Type init code ---*/ __pyx_vtabptr_array = &__pyx_vtable_array; __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_array.tp_print = 0; #endif if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 105, __pyx_L1_error) __pyx_array_type = &__pyx_type___pyx_array; if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_MemviewEnum.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_MemviewEnum.tp_dictoffset && __pyx_type___pyx_MemviewEnum.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_MemviewEnum.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 279, __pyx_L1_error) __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_memoryview.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryview.tp_dictoffset && __pyx_type___pyx_memoryview.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_memoryview.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 330, __pyx_L1_error) __pyx_memoryview_type = &__pyx_type___pyx_memoryview; __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) #if PY_VERSION_HEX < 0x030800B1 __pyx_type___pyx_memoryviewslice.tp_print = 0; #endif if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type___pyx_memoryviewslice.tp_dictoffset && __pyx_type___pyx_memoryviewslice.tp_getattro == PyObject_GenericGetAttr)) { __pyx_type___pyx_memoryviewslice.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 965, __pyx_L1_error) __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_modinit_type_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); /*--- Type import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_variable_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); /*--- Variable import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } static int __Pyx_modinit_function_import_code(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); /*--- Function import code ---*/ __Pyx_RefNannyFinishContext(); return 0; } #ifndef CYTHON_NO_PYINIT_EXPORT #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #elif PY_MAJOR_VERSION < 3 #ifdef __cplusplus #define __Pyx_PyMODINIT_FUNC extern "C" void #else #define __Pyx_PyMODINIT_FUNC void #endif #else #ifdef __cplusplus #define __Pyx_PyMODINIT_FUNC extern "C" PyObject * #else #define __Pyx_PyMODINIT_FUNC PyObject * #endif #endif #if PY_MAJOR_VERSION < 3 __Pyx_PyMODINIT_FUNC initcore(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC initcore(void) #else __Pyx_PyMODINIT_FUNC PyInit_core(void) CYTHON_SMALL_CODE; /*proto*/ __Pyx_PyMODINIT_FUNC PyInit_core(void) #if CYTHON_PEP489_MULTI_PHASE_INIT { return PyModuleDef_Init(&__pyx_moduledef); } static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { #if PY_VERSION_HEX >= 0x030700A1 static PY_INT64_T main_interpreter_id = -1; PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); if (main_interpreter_id == -1) { main_interpreter_id = current_id; return (unlikely(current_id == -1)) ? -1 : 0; } else if (unlikely(main_interpreter_id != current_id)) #else static PyInterpreterState *main_interpreter = NULL; PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; if (!main_interpreter) { main_interpreter = current_interpreter; } else if (unlikely(main_interpreter != current_interpreter)) #endif { PyErr_SetString( PyExc_ImportError, "Interpreter change detected - this module can only be loaded into one interpreter per process."); return -1; } return 0; } static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { PyObject *value = PyObject_GetAttrString(spec, from_name); int result = 0; if (likely(value)) { if (allow_none || value != Py_None) { result = PyDict_SetItemString(moddict, to_name, value); } Py_DECREF(value); } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { result = -1; } return result; } static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { PyObject *module = NULL, *moddict, *modname; if (__Pyx_check_single_interpreter()) return NULL; if (__pyx_m) return __Pyx_NewRef(__pyx_m); modname = PyObject_GetAttrString(spec, "name"); if (unlikely(!modname)) goto bad; module = PyModule_NewObject(modname); Py_DECREF(modname); if (unlikely(!module)) goto bad; moddict = PyModule_GetDict(module); if (unlikely(!moddict)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; return module; bad: Py_XDECREF(module); return NULL; } static CYTHON_SMALL_CODE int __pyx_pymod_exec_core(PyObject *__pyx_pyinit_module) #endif #endif { PyObject *__pyx_t_1 = NULL; static PyThread_type_lock __pyx_t_2[8]; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT if (__pyx_m) { if (__pyx_m == __pyx_pyinit_module) return 0; PyErr_SetString(PyExc_RuntimeError, "Module 'core' has already been imported. Re-initialisation is not supported."); return -1; } #elif PY_MAJOR_VERSION >= 3 if (__pyx_m) return __Pyx_NewRef(__pyx_m); #endif #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit_core(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pxy_PyFrame_Initialize_Offsets __Pxy_PyFrame_Initialize_Offsets(); #endif __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS PyEval_InitThreads(); #endif /*--- Module creation code ---*/ #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_m = __pyx_pyinit_module; Py_INCREF(__pyx_m); #else #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("core", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) #endif __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_b); __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_cython_runtime); if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_monotonic_align__core) { if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name_2, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "monotonic_align.core")) { if (unlikely(PyDict_SetItemString(modules, "monotonic_align.core", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global type/function init code ---*/ (void)__Pyx_modinit_global_init_code(); (void)__Pyx_modinit_variable_export_code(); (void)__Pyx_modinit_function_export_code(); if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) (void)__Pyx_modinit_type_import_code(); (void)__Pyx_modinit_variable_import_code(); (void)__Pyx_modinit_function_import_code(); /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "monotonic_align/core.pyx":7 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef void maximum_path_each(int[:,::1] path, float[:,::1] value, int t_y, int t_x, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int x * cdef int y */ __pyx_k_ = (-1e9); /* "monotonic_align/core.pyx":75 * @cython.boundscheck(False) * @cython.wraparound(False) * cpdef void maximum_path_gradtts_c(int[:,:,::1] paths, float[:,:,::1] values, int[::1] t_xs, int[::1] t_ys, float max_neg_val=-1e9) nogil: # <<<<<<<<<<<<<< * cdef int b = values.shape[0] * */ __pyx_k__2 = (-1e9); __pyx_k__2 = (-1e9); /* "monotonic_align/core.pyx":1 * cimport cython # <<<<<<<<<<<<<< * from cython.parallel import prange * */ __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":209 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * def __dealloc__(array self): */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 209, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 209, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_array_type); /* "View.MemoryView":286 * return self.name * * cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<< * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 286, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(generic); __Pyx_DECREF_SET(generic, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":287 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 287, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(strided); __Pyx_DECREF_SET(strided, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":288 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 288, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect); __Pyx_DECREF_SET(indirect, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":291 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 291, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(contiguous); __Pyx_DECREF_SET(contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":292 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 292, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_XGOTREF(indirect_contiguous); __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":316 * * DEF THREAD_LOCKS_PREALLOCATED = 8 * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ * PyThread_allocate_lock(), */ __pyx_memoryview_thread_locks_used = 0; /* "View.MemoryView":317 * DEF THREAD_LOCKS_PREALLOCATED = 8 * cdef int __pyx_memoryview_thread_locks_used = 0 * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< * PyThread_allocate_lock(), * PyThread_allocate_lock(), */ __pyx_t_2[0] = PyThread_allocate_lock(); __pyx_t_2[1] = PyThread_allocate_lock(); __pyx_t_2[2] = PyThread_allocate_lock(); __pyx_t_2[3] = PyThread_allocate_lock(); __pyx_t_2[4] = PyThread_allocate_lock(); __pyx_t_2[5] = PyThread_allocate_lock(); __pyx_t_2[6] = PyThread_allocate_lock(); __pyx_t_2[7] = PyThread_allocate_lock(); memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_2, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); /* "View.MemoryView":549 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 549, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 549, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryview_type); /* "View.MemoryView":995 * return self.from_object * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 995, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_1) < 0) __PYX_ERR(1, 995, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; PyType_Modified(__pyx_memoryviewslice_type); /* "(tree fragment)":1 * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< * cdef object __pyx_PickleError * cdef object __pyx_result */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "(tree fragment)":11 * __pyx_unpickle_Enum__set_state(<Enum> __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< * __pyx_result.name = __pyx_state[0] * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init monotonic_align.core", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_CLEAR(__pyx_m); } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init monotonic_align.core"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if CYTHON_PEP489_MULTI_PHASE_INIT return (__pyx_m != NULL) ? 0 : -1; #elif PY_MAJOR_VERSION >= 3 return __pyx_m; #else return; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule(modname); if (!m) goto end; p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* PyObjectGetAttrStr */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* MemviewSliceInit */ static int __Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, int ndim, __Pyx_memviewslice *memviewslice, int memview_is_new_reference) { __Pyx_RefNannyDeclarations int i, retval=-1; Py_buffer *buf = &memview->view; __Pyx_RefNannySetupContext("init_memviewslice", 0); if (unlikely(memviewslice->memview || memviewslice->data)) { PyErr_SetString(PyExc_ValueError, "memviewslice is already initialized!"); goto fail; } if (buf->strides) { for (i = 0; i < ndim; i++) { memviewslice->strides[i] = buf->strides[i]; } } else { Py_ssize_t stride = buf->itemsize; for (i = ndim - 1; i >= 0; i--) { memviewslice->strides[i] = stride; stride *= buf->shape[i]; } } for (i = 0; i < ndim; i++) { memviewslice->shape[i] = buf->shape[i]; if (buf->suboffsets) { memviewslice->suboffsets[i] = buf->suboffsets[i]; } else { memviewslice->suboffsets[i] = -1; } } memviewslice->memview = memview; memviewslice->data = (char *)buf->buf; if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { Py_INCREF(memview); } retval = 0; goto no_fail; fail: memviewslice->memview = 0; memviewslice->data = 0; retval = -1; no_fail: __Pyx_RefNannyFinishContext(); return retval; } #ifndef Py_NO_RETURN #define Py_NO_RETURN #endif static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { va_list vargs; char msg[200]; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, fmt); #else va_start(vargs); #endif vsnprintf(msg, 200, fmt, vargs); va_end(vargs); Py_FatalError(msg); } static CYTHON_INLINE int __pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)++; PyThread_release_lock(lock); return result; } static CYTHON_INLINE int __pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)--; PyThread_release_lock(lock); return result; } static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int first_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (unlikely(!memview || (PyObject *) memview == Py_None)) return; if (unlikely(__pyx_get_slice_count(memview) < 0)) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); first_time = __pyx_add_acquisition_count(memview) == 0; if (unlikely(first_time)) { if (have_gil) { Py_INCREF((PyObject *) memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_INCREF((PyObject *) memview); PyGILState_Release(_gilstate); } } } static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int last_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (unlikely(!memview || (PyObject *) memview == Py_None)) { memslice->memview = NULL; return; } if (unlikely(__pyx_get_slice_count(memview) <= 0)) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); last_time = __pyx_sub_acquisition_count(memview) == 1; memslice->data = NULL; if (unlikely(last_time)) { if (have_gil) { Py_CLEAR(memslice->memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_CLEAR(memslice->memview); PyGILState_Release(_gilstate); } } else { memslice->memview = NULL; } } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* None */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } /* ArgTypeTest */ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } else if (exact) { #if PY_MAJOR_VERSION == 2 if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(__Pyx_TypeCheck(obj, type))) return 1; } PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); return 0; } /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = Py_TYPE(func)->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } if (cause) { PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* PyCFunctionFastCall */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { PyCFunctionObject *func = (PyCFunctionObject*)func_obj; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); int flags = PyCFunction_GET_FLAGS(func); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); assert(nargs >= 0); assert(nargs == 0 || args != NULL); /* _PyCFunction_FastCallDict() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); } else { return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); } } #endif /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; #if PY_MAJOR_VERSION >= 3 PyObject *kwdefs; #endif PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { return NULL; } if ( #if PY_MAJOR_VERSION >= 3 co->co_kwonlyargcount == 0 && #endif likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); #if PY_MAJOR_VERSION >= 3 kwdefs = PyFunction_GET_KW_DEFAULTS(func); #endif if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, (int)nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, args, (int)nargs, k, (int)nk, d, (int)nd, closure); #endif Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif #endif /* PyObjectCall2Args */ static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { PyObject *args, *result = NULL; #if CYTHON_FAST_PYCALL if (PyFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyFunction_FastCall(function, args, 2); } #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(function)) { PyObject *args[2] = {arg1, arg2}; return __Pyx_PyCFunction_FastCall(function, args, 2); } #endif args = PyTuple_New(2); if (unlikely(!args)) goto done; Py_INCREF(arg1); PyTuple_SET_ITEM(args, 0, arg1); Py_INCREF(arg2); PyTuple_SET_ITEM(args, 1, arg2); Py_INCREF(function); result = __Pyx_PyObject_Call(function, args, NULL); Py_DECREF(args); Py_DECREF(function); done: return result; } /* PyObjectCallMethO */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = PyCFunction_GET_FUNCTION(func); self = PyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectCallOneArg */ #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #if CYTHON_FAST_PYCALL if (PyFunction_Check(func)) { return __Pyx_PyFunction_FastCall(func, &arg, 1); } #endif if (likely(PyCFunction_Check(func))) { if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); #if CYTHON_FAST_PYCCALL } else if (__Pyx_PyFastCFunction_Check(func)) { return __Pyx_PyCFunction_FastCall(func, &arg, 1); #endif } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif /* BytesEquals */ static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else if (s1 == s2) { return (equals == Py_EQ); } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { const char *ps1, *ps2; Py_ssize_t length = PyBytes_GET_SIZE(s1); if (length != PyBytes_GET_SIZE(s2)) return (equals == Py_NE); ps1 = PyBytes_AS_STRING(s1); ps2 = PyBytes_AS_STRING(s2); if (ps1[0] != ps2[0]) { return (equals == Py_NE); } else if (length == 1) { return (equals == Py_EQ); } else { int result; #if CYTHON_USE_UNICODE_INTERNALS Py_hash_t hash1, hash2; hash1 = ((PyBytesObject*)s1)->ob_shash; hash2 = ((PyBytesObject*)s2)->ob_shash; if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { return (equals == Py_NE); } #endif result = memcmp(ps1, ps2, (size_t)length); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { return (equals == Py_NE); } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { return (equals == Py_NE); } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } #endif } /* UnicodeEquals */ static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else #if PY_MAJOR_VERSION < 3 PyObject* owned_ref = NULL; #endif int s1_is_unicode, s2_is_unicode; if (s1 == s2) { goto return_eq; } s1_is_unicode = PyUnicode_CheckExact(s1); s2_is_unicode = PyUnicode_CheckExact(s2); #if PY_MAJOR_VERSION < 3 if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { owned_ref = PyUnicode_FromObject(s2); if (unlikely(!owned_ref)) return -1; s2 = owned_ref; s2_is_unicode = 1; } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { owned_ref = PyUnicode_FromObject(s1); if (unlikely(!owned_ref)) return -1; s1 = owned_ref; s1_is_unicode = 1; } else if (((!s2_is_unicode) & (!s1_is_unicode))) { return __Pyx_PyBytes_Equals(s1, s2, equals); } #endif if (s1_is_unicode & s2_is_unicode) { Py_ssize_t length; int kind; void *data1, *data2; if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) return -1; length = __Pyx_PyUnicode_GET_LENGTH(s1); if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { goto return_ne; } #if CYTHON_USE_UNICODE_INTERNALS { Py_hash_t hash1, hash2; #if CYTHON_PEP393_ENABLED hash1 = ((PyASCIIObject*)s1)->hash; hash2 = ((PyASCIIObject*)s2)->hash; #else hash1 = ((PyUnicodeObject*)s1)->hash; hash2 = ((PyUnicodeObject*)s2)->hash; #endif if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { goto return_ne; } } #endif kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ); return_ne: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_NE); #endif } /* None */ static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { Py_ssize_t q = a / b; Py_ssize_t r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } /* GetAttr */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { #if CYTHON_USE_TYPE_SLOTS #if PY_MAJOR_VERSION >= 3 if (likely(PyUnicode_Check(n))) #else if (likely(PyString_Check(n))) #endif return __Pyx_PyObject_GetAttrStr(o, n); #endif return PyObject_GetAttr(o, n); } /* GetItemInt */ static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyList_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS Py_ssize_t wrapped_i = i; if (wraparound & unlikely(i < 0)) { wrapped_i += PyTuple_GET_SIZE(o); } if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (!PyErr_ExceptionMatches(PyExc_OverflowError)) return NULL; PyErr_Clear(); } } return m->sq_item(o, i); } } #else if (is_list || PySequence_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } /* ObjectGetItem */ #if CYTHON_USE_TYPE_SLOTS static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { PyObject *runerr; Py_ssize_t key_value; PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; if (unlikely(!(m && m->sq_item))) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); return NULL; } key_value = __Pyx_PyIndex_AsSsize_t(index); if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); } if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { PyErr_Clear(); PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); } return NULL; } static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; if (likely(m && m->mp_subscript)) { return m->mp_subscript(obj, key); } return __Pyx_PyObject_GetIndex(obj, key); } #endif /* decode_c_string */ static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { Py_ssize_t length; if (unlikely((start < 0) | (stop < 0))) { size_t slen = strlen(cstring); if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { PyErr_SetString(PyExc_OverflowError, "c-string too long to convert to Python"); return NULL; } length = (Py_ssize_t) slen; if (start < 0) { start += length; if (start < 0) start = 0; } if (stop < 0) stop += length; } if (unlikely(stop <= start)) return __Pyx_NewRef(__pyx_empty_unicode); length = stop - start; cstring += start; if (decode_func) { return decode_func(cstring, length, errors); } else { return PyUnicode_Decode(cstring, length, encoding, errors); } } /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1; } return 0; } static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { PyObject *exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; if (unlikely(PyTuple_Check(err))) return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); } #endif /* GetAttr3 */ static PyObject *__Pyx_GetAttr3Default(PyObject *d) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) return NULL; __Pyx_PyErr_Clear(); Py_INCREF(d); return d; } static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { PyObject *r = __Pyx_GetAttr(o, n); return (likely(r)) ? r : __Pyx_GetAttr3Default(d); } /* PyDictVersioning */ #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { PyObject *dict = Py_TYPE(obj)->tp_dict; return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; } static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { PyObject **dictptr = NULL; Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; if (offset) { #if CYTHON_COMPILING_IN_CPYTHON dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); #else dictptr = _PyObject_GetDictPtr(obj); #endif } return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; } static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { PyObject *dict = Py_TYPE(obj)->tp_dict; if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) return 0; return obj_dict_version == __Pyx_get_object_dict_version(obj); } #endif /* GetModuleGlobalName */ #if CYTHON_USE_DICT_VERSIONS static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) #else static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) #endif { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } else if (unlikely(PyErr_Occurred())) { return NULL; } #else result = PyDict_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } #endif #else result = PyObject_GetItem(__pyx_d, name); __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { return __Pyx_NewRef(result); } PyErr_Clear(); #endif return __Pyx_GetBuiltinName(name); } /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(__Pyx_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* GetTopmostException */ #if CYTHON_USE_EXC_INFO_STACK static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate) { _PyErr_StackItem *exc_info = tstate->exc_info; while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && exc_info->previous_item != NULL) { exc_info = exc_info->previous_item; } return exc_info; } #endif /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); *type = exc_info->exc_type; *value = exc_info->exc_value; *tb = exc_info->exc_traceback; #else *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; #endif Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = type; exc_info->exc_value = value; exc_info->exc_traceback = tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) #endif { PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE #if CYTHON_USE_EXC_INFO_STACK { _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = local_type; exc_info->exc_value = local_value; exc_info->exc_traceback = local_tb; } #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } /* SwapException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_USE_EXC_INFO_STACK _PyErr_StackItem *exc_info = tstate->exc_info; tmp_type = exc_info->exc_type; tmp_value = exc_info->exc_value; tmp_tb = exc_info->exc_traceback; exc_info->exc_type = *type; exc_info->exc_value = *value; exc_info->exc_traceback = *tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = *type; tstate->exc_value = *value; tstate->exc_traceback = *tb; #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } #endif /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_MAJOR_VERSION < 3 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_MAJOR_VERSION < 3 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_MAJOR_VERSION < 3 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* FastTypeChecks */ #if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = a->tp_base; if (a == b) return 1; } return b == &PyBaseObject_Type; } static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (a == b) return 1; mro = a->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(a, b); } #if PY_MAJOR_VERSION == 2 static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { PyObject *exception, *value, *tb; int res; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&exception, &value, &tb); res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } if (!res) { res = PyObject_IsSubclass(err, exc_type2); if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } } __Pyx_ErrRestore(exception, value, tb); return res; } #else static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; if (!res) { res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); } return res; } #endif static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; assert(PyExceptionClass_Check(exc_type)); n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { PyObject *t = PyTuple_GET_ITEM(tuple, i); #if PY_MAJOR_VERSION < 3 if (likely(exc_type == t)) return 1; #endif if (likely(PyExceptionClass_Check(t))) { if (__Pyx_inner_PyErr_GivenExceptionMatches2(exc_type, NULL, t)) return 1; } else { } } return 0; } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { if (likely(err == exc_type)) return 1; if (likely(PyExceptionClass_Check(err))) { if (likely(PyExceptionClass_Check(exc_type))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); } else if (likely(PyTuple_Check(exc_type))) { return __Pyx_PyErr_GivenExceptionMatchesTuple(err, exc_type); } else { } } return PyErr_GivenExceptionMatches(err, exc_type); } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { assert(PyExceptionClass_Check(exc_type1)); assert(PyExceptionClass_Check(exc_type2)); if (likely(err == exc_type1 || err == exc_type2)) return 1; if (likely(PyExceptionClass_Check(err))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); } return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); } #endif /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { (void)inplace; (void)zerodivision_check; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = (long)((unsigned long)a + b); if (likely((x^a) >= 0 || (x^b) >= 0)) return PyInt_FromLong(x); return PyLong_Type.tp_as_number->nb_add(op1, op2); } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; #ifdef HAVE_LONG_LONG const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; #endif const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } CYTHON_FALLTHROUGH; default: return PyLong_Type.tp_as_number->nb_add(op1, op2); } } x = a + b; return PyLong_FromLong(x); #ifdef HAVE_LONG_LONG long_long: llx = lla + llb; return PyLong_FromLongLong(llx); #endif } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); double result; PyFPE_START_PROTECT("add", return NULL) result = ((double)a) + (double)b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } #endif /* None */ static CYTHON_INLINE long __Pyx_div_long(long a, long b) { long q = a / b; long r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } /* ImportFrom */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_ImportError, #if PY_MAJOR_VERSION < 3 "cannot import name %.230s", PyString_AS_STRING(name)); #else "cannot import name %S", name); #endif } return value; } /* HasAttr */ static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { PyObject *r; if (unlikely(!__Pyx_PyBaseString_Check(n))) { PyErr_SetString(PyExc_TypeError, "hasattr(): attribute name must be string"); return -1; } r = __Pyx_GetAttr(o, n); if (unlikely(!r)) { PyErr_Clear(); return 0; } else { Py_DECREF(r); return 1; } } /* PyObject_GenericGetAttrNoDict */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { PyErr_Format(PyExc_AttributeError, #if PY_MAJOR_VERSION >= 3 "'%.50s' object has no attribute '%U'", tp->tp_name, attr_name); #else "'%.50s' object has no attribute '%.400s'", tp->tp_name, PyString_AS_STRING(attr_name)); #endif return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { PyObject *descr; PyTypeObject *tp = Py_TYPE(obj); if (unlikely(!PyString_Check(attr_name))) { return PyObject_GenericGetAttr(obj, attr_name); } assert(!tp->tp_dictoffset); descr = _PyType_Lookup(tp, attr_name); if (unlikely(!descr)) { return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); } Py_INCREF(descr); #if PY_MAJOR_VERSION < 3 if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) #endif { descrgetfunc f = Py_TYPE(descr)->tp_descr_get; if (unlikely(f)) { PyObject *res = f(descr, obj, (PyObject *)tp); Py_DECREF(descr); return res; } } return descr; } #endif /* PyObject_GenericGetAttr */ #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { return PyObject_GenericGetAttr(obj, attr_name); } return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); } #endif /* SetVTable */ static int __Pyx_SetVtable(PyObject *dict, void *vtable) { #if PY_VERSION_HEX >= 0x02070000 PyObject *ob = PyCapsule_New(vtable, 0, 0); #else PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); #endif if (!ob) goto bad; if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) goto bad; Py_DECREF(ob); return 0; bad: Py_XDECREF(ob); return -1; } /* PyObjectGetAttrStrNoError */ static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) __Pyx_PyErr_Clear(); } static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { PyObject *result; #if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); } #endif result = __Pyx_PyObject_GetAttrStr(obj, attr_name); if (unlikely(!result)) { __Pyx_PyObject_GetAttrStr_ClearAttributeError(); } return result; } /* SetupReduce */ static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { int ret; PyObject *name_attr; name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); if (likely(name_attr)) { ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); } else { ret = -1; } if (unlikely(ret < 0)) { PyErr_Clear(); ret = 0; } Py_XDECREF(name_attr); return ret; } static int __Pyx_setup_reduce(PyObject* type_obj) { int ret = 0; PyObject *object_reduce = NULL; PyObject *object_reduce_ex = NULL; PyObject *reduce = NULL; PyObject *reduce_ex = NULL; PyObject *reduce_cython = NULL; PyObject *setstate = NULL; PyObject *setstate_cython = NULL; #if CYTHON_USE_PYTYPE_LOOKUP if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; #else if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; #endif #if CYTHON_USE_PYTYPE_LOOKUP object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #else object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; #endif reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; if (reduce_ex == object_reduce_ex) { #if CYTHON_USE_PYTYPE_LOOKUP object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; #else object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; #endif reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); if (likely(reduce_cython)) { ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (reduce == object_reduce || PyErr_Occurred()) { goto __PYX_BAD; } setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); if (!setstate) PyErr_Clear(); if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); if (likely(setstate_cython)) { ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; } else if (!setstate || PyErr_Occurred()) { goto __PYX_BAD; } } PyType_Modified((PyTypeObject*)type_obj); } } goto __PYX_GOOD; __PYX_BAD: if (!PyErr_Occurred()) PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); ret = -1; __PYX_GOOD: #if !CYTHON_USE_PYTYPE_LOOKUP Py_XDECREF(object_reduce); Py_XDECREF(object_reduce_ex); #endif Py_XDECREF(reduce); Py_XDECREF(reduce_ex); Py_XDECREF(reduce_cython); Py_XDECREF(setstate); Py_XDECREF(setstate_cython); return ret; } /* CLineInTraceback */ #ifndef CYTHON_CLINE_IN_TRACEBACK static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { PyObject *use_cline; PyObject *ptype, *pvalue, *ptraceback; #if CYTHON_COMPILING_IN_CPYTHON PyObject **cython_runtime_dict; #endif if (unlikely(!__pyx_cython_runtime)) { return c_line; } __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); #if CYTHON_COMPILING_IN_CPYTHON cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); if (likely(cython_runtime_dict)) { __PYX_PY_DICT_LOOKUP_IF_MODIFIED( use_cline, *cython_runtime_dict, __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) } else #endif { PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); if (use_cline_obj) { use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; Py_DECREF(use_cline_obj); } else { PyErr_Clear(); use_cline = NULL; } } if (!use_cline) { c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); return c_line; } #endif /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; PyThreadState *tstate = __Pyx_PyThreadState_Current; if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } py_code = __pyx_find_code_object(c_line ? -c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); } py_frame = PyFrame_New( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); if (__Pyx_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if ((0)) {} view->obj = NULL; Py_DECREF(obj); } #endif /* MemviewSliceIsContig */ static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim) { int i, index, step, start; Py_ssize_t itemsize = mvs.memview->view.itemsize; if (order == 'F') { step = 1; start = 0; } else { step = -1; start = ndim - 1; } for (i = 0; i < ndim; i++) { index = start + step * i; if (mvs.suboffsets[index] >= 0 || mvs.strides[index] != itemsize) return 0; itemsize *= mvs.shape[index]; } return 1; } /* OverlappingSlices */ static void __pyx_get_array_memory_extents(__Pyx_memviewslice *slice, void **out_start, void **out_end, int ndim, size_t itemsize) { char *start, *end; int i; start = end = slice->data; for (i = 0; i < ndim; i++) { Py_ssize_t stride = slice->strides[i]; Py_ssize_t extent = slice->shape[i]; if (extent == 0) { *out_start = *out_end = start; return; } else { if (stride > 0) end += stride * (extent - 1); else start += stride * (extent - 1); } } *out_start = start; *out_end = end + itemsize; } static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize) { void *start1, *end1, *start2, *end2; __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); return (start1 < end2) && (start2 < end1); } /* Capsule */ static CYTHON_INLINE PyObject * __pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) { PyObject *cobj; #if PY_VERSION_HEX >= 0x02070000 cobj = PyCapsule_New(p, sig, NULL); #else cobj = PyCObject_FromVoidPtr(p, NULL); #endif return cobj; } /* IsLittleEndian */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) { union { uint32_t u32; uint8_t u8[4]; } S; S.u32 = 0x01020304; return S.u8[0] == 4; } /* BufferFormatCheck */ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t <= '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case '?': return "'bool'"; case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number, ndim; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ndim = ctx->head->field->type->ndim; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } CYTHON_FALLTHROUGH; case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if ((ctx->enc_type == *ts) && (got_Z == ctx->is_complex) && (ctx->enc_packmode == ctx->new_packmode) && (!ctx->is_valid_array)) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } CYTHON_FALLTHROUGH; case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } /* TypeInfoCompare */ static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) { int i; if (!a || !b) return 0; if (a == b) return 1; if (a->size != b->size || a->typegroup != b->typegroup || a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { if (a->typegroup == 'H' || b->typegroup == 'H') { return a->size == b->size; } else { return 0; } } if (a->ndim) { for (i = 0; i < a->ndim; i++) if (a->arraysize[i] != b->arraysize[i]) return 0; } if (a->typegroup == 'S') { if (a->flags != b->flags) return 0; if (a->fields || b->fields) { if (!(a->fields && b->fields)) return 0; for (i = 0; a->fields[i].type && b->fields[i].type; i++) { __Pyx_StructField *field_a = a->fields + i; __Pyx_StructField *field_b = b->fields + i; if (field_a->offset != field_b->offset || !__pyx_typeinfo_cmp(field_a->type, field_b->type)) return 0; } return !a->fields[i].type && !b->fields[i].type; } } return 1; } /* MemviewSliceValidateAndInit */ static int __pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) { if (buf->shape[dim] <= 1) return 1; if (buf->strides) { if (spec & __Pyx_MEMVIEW_CONTIG) { if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { if (unlikely(buf->strides[dim] != sizeof(void *))) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly contiguous " "in dimension %d.", dim); goto fail; } } else if (unlikely(buf->strides[dim] != buf->itemsize)) { PyErr_SetString(PyExc_ValueError, "Buffer and memoryview are not contiguous " "in the same dimension."); goto fail; } } if (spec & __Pyx_MEMVIEW_FOLLOW) { Py_ssize_t stride = buf->strides[dim]; if (stride < 0) stride = -stride; if (unlikely(stride < buf->itemsize)) { PyErr_SetString(PyExc_ValueError, "Buffer and memoryview are not contiguous " "in the same dimension."); goto fail; } } } else { if (unlikely(spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1)) { PyErr_Format(PyExc_ValueError, "C-contiguous buffer is not contiguous in " "dimension %d", dim); goto fail; } else if (unlikely(spec & (__Pyx_MEMVIEW_PTR))) { PyErr_Format(PyExc_ValueError, "C-contiguous buffer is not indirect in " "dimension %d", dim); goto fail; } else if (unlikely(buf->suboffsets)) { PyErr_SetString(PyExc_ValueError, "Buffer exposes suboffsets but no strides"); goto fail; } } return 1; fail: return 0; } static int __pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) { if (spec & __Pyx_MEMVIEW_DIRECT) { if (unlikely(buf->suboffsets && buf->suboffsets[dim] >= 0)) { PyErr_Format(PyExc_ValueError, "Buffer not compatible with direct access " "in dimension %d.", dim); goto fail; } } if (spec & __Pyx_MEMVIEW_PTR) { if (unlikely(!buf->suboffsets || (buf->suboffsets[dim] < 0))) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly accessible " "in dimension %d.", dim); goto fail; } } return 1; fail: return 0; } static int __pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) { int i; if (c_or_f_flag & __Pyx_IS_F_CONTIG) { Py_ssize_t stride = 1; for (i = 0; i < ndim; i++) { if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { PyErr_SetString(PyExc_ValueError, "Buffer not fortran contiguous."); goto fail; } stride = stride * buf->shape[i]; } } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { Py_ssize_t stride = 1; for (i = ndim - 1; i >- 1; i--) { if (unlikely(stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1)) { PyErr_SetString(PyExc_ValueError, "Buffer not C contiguous."); goto fail; } stride = stride * buf->shape[i]; } } return 1; fail: return 0; } static int __Pyx_ValidateAndInit_memviewslice( int *axes_specs, int c_or_f_flag, int buf_flags, int ndim, __Pyx_TypeInfo *dtype, __Pyx_BufFmt_StackElem stack[], __Pyx_memviewslice *memviewslice, PyObject *original_obj) { struct __pyx_memoryview_obj *memview, *new_memview; __Pyx_RefNannyDeclarations Py_buffer *buf; int i, spec = 0, retval = -1; __Pyx_BufFmt_Context ctx; int from_memoryview = __pyx_memoryview_check(original_obj); __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) original_obj)->typeinfo)) { memview = (struct __pyx_memoryview_obj *) original_obj; new_memview = NULL; } else { memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( original_obj, buf_flags, 0, dtype); new_memview = memview; if (unlikely(!memview)) goto fail; } buf = &memview->view; if (unlikely(buf->ndim != ndim)) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", ndim, buf->ndim); goto fail; } if (new_memview) { __Pyx_BufFmt_Init(&ctx, stack, dtype); if (unlikely(!__Pyx_BufFmt_CheckString(&ctx, buf->format))) goto fail; } if (unlikely((unsigned) buf->itemsize != dtype->size)) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->len > 0) { for (i = 0; i < ndim; i++) { spec = axes_specs[i]; if (unlikely(!__pyx_check_strides(buf, i, ndim, spec))) goto fail; if (unlikely(!__pyx_check_suboffsets(buf, i, ndim, spec))) goto fail; } if (unlikely(buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag))) goto fail; } if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, new_memview != NULL) == -1)) { goto fail; } retval = 0; goto no_fail; fail: Py_XDECREF(new_memview); retval = -1; no_fail: __Pyx_RefNannyFinishContext(); return retval; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_int(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 3, &__Pyx_TypeInfo_int, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_d_dc_float(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 3, &__Pyx_TypeInfo_float, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_int(PyObject *obj, int writable_flag) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG, (PyBUF_C_CONTIGUOUS | PyBUF_FORMAT) | writable_flag, 1, &__Pyx_TypeInfo_int, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* MemviewSliceCopyTemplate */ static __Pyx_memviewslice __pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, const char *mode, int ndim, size_t sizeof_dtype, int contig_flag, int dtype_is_object) { __Pyx_RefNannyDeclarations int i; __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; struct __pyx_memoryview_obj *from_memview = from_mvs->memview; Py_buffer *buf = &from_memview->view; PyObject *shape_tuple = NULL; PyObject *temp_int = NULL; struct __pyx_array_obj *array_obj = NULL; struct __pyx_memoryview_obj *memview_obj = NULL; __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); for (i = 0; i < ndim; i++) { if (unlikely(from_mvs->suboffsets[i] >= 0)) { PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " "indirect dimensions (axis %d)", i); goto fail; } } shape_tuple = PyTuple_New(ndim); if (unlikely(!shape_tuple)) { goto fail; } __Pyx_GOTREF(shape_tuple); for(i = 0; i < ndim; i++) { temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); if(unlikely(!temp_int)) { goto fail; } else { PyTuple_SET_ITEM(shape_tuple, i, temp_int); temp_int = NULL; } } array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); if (unlikely(!array_obj)) { goto fail; } __Pyx_GOTREF(array_obj); memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( (PyObject *) array_obj, contig_flag, dtype_is_object, from_mvs->memview->typeinfo); if (unlikely(!memview_obj)) goto fail; if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) goto fail; if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, dtype_is_object) < 0)) goto fail; goto no_fail; fail: __Pyx_XDECREF(new_mvs.memview); new_mvs.memview = NULL; new_mvs.data = NULL; no_fail: __Pyx_XDECREF(shape_tuple); __Pyx_XDECREF(temp_int); __Pyx_XDECREF(array_obj); __Pyx_RefNannyFinishContext(); return new_mvs; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const int neg_one = (int) -1, const_zero = (int) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const int neg_one = (int) -1, const_zero = (int) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const long neg_one = (long) -1, const_zero = (long) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const long neg_one = (long) -1, const_zero = (long) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* CIntFromPy */ static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif const char neg_one = (char) -1, const_zero = (char) 0; #ifdef __Pyx_HAS_GCC_DIAGNOSTIC #pragma GCC diagnostic pop #endif const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(char) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (char) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (char) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(char) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (char) 0; case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) case -2: if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 2: if (8 * sizeof(char) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -3: if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 3: if (8 * sizeof(char) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case -4: if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; case 4: if (8 * sizeof(char) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); } } break; } #endif if (sizeof(char) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else char val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (char) -1; } } else { char val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (char) -1; val = __Pyx_PyInt_As_char(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to char"); return (char) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to char"); return (char) -1; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; if (PyObject_Hash(*t->p) == -1) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT #if !CYTHON_PEP393_ENABLED static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; } #else static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(PyUnicode_IS_ASCII(o))) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif } #endif #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { int retval; if (unlikely(!x)) return -1; retval = __Pyx_PyObject_IsTrue(x); Py_DECREF(x); return retval; } static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(result)) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", Py_TYPE(result)->tp_name)) { Py_DECREF(result); return NULL; } return result; } #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", type_name, type_name, Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x) || PyLong_Check(x))) #else if (likely(PyLong_Check(x))) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = m->nb_int(x); } else if (m && m->nb_long) { name = "long"; res = m->nb_long(x); } #else if (likely(m && m->nb_int)) { name = "int"; res = m->nb_int(x); } #endif #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Int(x); } #endif if (likely(res)) { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { #else if (unlikely(!PyLong_CheckExact(res))) { #endif return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
prelu_kernel_arm.c
#include <arm_neon.h> #include <assert.h> #include "prelu_kernel_arm.h" #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) int prelu_kernel_run(float* input, float* output, int dim0, int dim1, int dim2, int dim3, float* slope, int layout, int num_thread) { int channel_size = dim1 * dim2 * dim3; float32x4_t _zero = vdupq_n_f32(0.f); if (layout == 0) { int size = dim2 * dim3; for (int n = 0; n < dim0; n++) { #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < dim1; c++) { float* cur_input = input + n * channel_size + c * size; float* cur_output = output + n * channel_size + c * size; float32x4_t _slope = vdupq_n_f32(slope[c]); for (int k = 0; k < (size & -4); k += 4) { float32x4_t _p = vld1q_f32(cur_input); // ri = ai <= bi ? 1...1:0...0 uint32x4_t _lemask = vcleq_f32(_p, _zero); float32x4_t _ps = vmulq_f32(_p, _slope); // bitwise select _p = vbslq_f32(_lemask, _ps, _p); vst1q_f32(cur_output, _p); cur_input += 4; cur_output += 4; } for (int k = size & ~3; k < size; k++) { *cur_output = MAX(cur_input[0], 0.f) + slope[c] * MIN(cur_input[0], 0.f); cur_input++; cur_output++; } } } } else { return -1; } return 0; }
ActionOP.h
/* * SparseOP.h * * Created on: Jul 20, 2016 * Author: mason */ #ifndef ACTIONOP_H_ #define ACTIONOP_H_ #include "MyLib.h" #include "Alphabet.h" #include "Node.h" #include "Graph.h" #include "SparseParam.h" // for sparse features class ActionParams { public: SparseParam W; PAlphabet elems; int nVSize; int nDim; public: ActionParams() { nVSize = 0; nDim = 0; elems = NULL; } inline void exportAdaParams(ModelUpdate& ada) { ada.addParam(&W); } inline void initialWeights(int nOSize) { if (nVSize == 0) { std::cout << "please check the alphabet" << std::endl; return; } nDim = nOSize; W.initial(nOSize, nVSize); W.val.random(0.01); } //random initialization inline void initial(PAlphabet alpha, int nOSize) { elems = alpha; nVSize =elems->size(); initialWeights(nOSize); } inline int getFeatureId(const string& strFeat) { int idx = elems->from_string(strFeat); return idx; } }; //only implemented sparse linear node. //non-linear transformations are not support, class ActionNode : public Node { public: ActionParams* param; int actid; PNode in; public: ActionNode() : Node() { actid = -1; param = NULL; node_type = "actionnode"; } inline void setParam(ActionParams* paramInit) { param = paramInit; } //can not be dropped since the output is a scalar inline void init(int ndim, dtype dropout) { dim = 1; Node::init(dim, -1); } inline void clearValue() { Node::clearValue(); actid = -1; } public: //notice the output void forward(Graph *cg, const string& ac, PNode x) { actid = param->getFeatureId(ac); in = x; degree = 0; in->addParent(this); cg->addNode(this); } public: inline void compute() { if (param->nDim != in->dim) { std::cout << "warning: action dim not equal ." << std::endl; } val[0] = 0; if (actid >= 0) { for (int idx = 0; idx < in->dim; idx++) { val[0] += in->val[idx] * param->W.val[actid][idx]; } } else { std::cout << "unknown action" << std::endl; } } //no output losses void backward() { if (actid >= 0) { for (int idx = 0; idx < in->dim; idx++) { in->loss[idx] += loss[0] * param->W.val[actid][idx]; param->W.grad[actid][idx] += loss[0] * in->val[idx]; } param->W.indexers[actid] = true; } } public: inline PExecute generate(bool bTrain, dtype cur_drop_factor); // better to rewrite for deep understanding inline bool typeEqual(PNode other) { bool result = Node::typeEqual(other); if (!result) return false; ActionNode* conv_other = (ActionNode*)other; if (param != conv_other->param) { return false; } return true; } }; class ActionExecute :public Execute { public: bool bTrain; public: inline void forward() { int count = batch.size(); //#pragma omp parallel for for (int idx = 0; idx < count; idx++) { batch[idx]->compute(); batch[idx]->forward_drop(bTrain, drop_factor); } } inline void backward() { int count = batch.size(); //#pragma omp parallel for for (int idx = 0; idx < count; idx++) { batch[idx]->backward_drop(); batch[idx]->backward(); } } }; inline PExecute ActionNode::generate(bool bTrain, dtype cur_drop_factor) { ActionExecute* exec = new ActionExecute(); exec->batch.push_back(this); exec->bTrain = bTrain; exec->drop_factor = cur_drop_factor; return exec; } #endif /* ACTIONOP_H_ */
wow_srp_fmt_plug.c
/* * This software was written by Jim Fougeron jfoug AT cox dot net * in 2012. No copyright is claimed, and the software is hereby * placed in the public domain. In case this attempt to disclaim * copyright and place the software in the public domain is deemed * null and void, then the software is Copyright (c) 2012 Jim Fougeron * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. * * * This implements the SRP protocol, with Blizzard's (battlenet) documented * implementation specifics. * * U = username in upper case * P = password in upper case * s = random salt value. * * x = SHA1(s . SHA1(U . ":" . P)); * v = 47^x % 112624315653284427036559548610503669920632123929604336254260115573677366691719 * * v is the 'verifier' value (256 bit value). * * Added OMP. Added 'default' oSSL BigNum exponentiation. * GMP exponentation (faster) is optional, and controlled with HAVE_LIBGMP in autoconfig.h * * NOTE, big fix required. The incoming binary may be 64 bytes OR LESS. It * can also be 64 bytes (or less), and have left padded 0's. We have to adjust * several things to handle this properly. First, valid must handle it. Then * binary and salt both must handle this. Also, crypt must handle this. NOTE, * the string 'could' be an odd length. If so, then only 1 byte of hex is put * into the first binary byte. all of these problems were found once I got * jtrts.pl working with wowsrp. There now are 2 input files for wowsrp. One * bytes of precision, then only 61 bytes will be in the string). The other * file left pads the numbers with 0's to an even 64 bytes long, so all are * 64 bytes. the format MUST handle both, since at this momement, we are not * exactly sure which type will be seen in the wild. NOTE, the byte swapped * method (GMP) within is no longer valid, and was removed. * NOTE, we need to add split() to canonize this format (remove LPad 0's) */ #if FMT_EXTERNS_H extern struct fmt_main fmt_blizzard; #elif FMT_REGISTERS_H john_register_one(&fmt_blizzard); #else #if AC_BUILT /* we need to know if HAVE_LIBGMP is defined */ #include "autoconfig.h" #endif #include <string.h> #include "sha.h" #include "sha2.h" #include "arch.h" #include "params.h" #include "common.h" #include "formats.h" #include "unicode.h" /* For encoding-aware uppercasing */ #ifdef HAVE_LIBGMP #if HAVE_GMP_GMP_H #include <gmp/gmp.h> #else #include <gmp.h> #endif #define EXP_STR " GMP-exp" #else #include <openssl/bn.h> #define EXP_STR " oSSL-exp" #endif #include "johnswap.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 64 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "WoWSRP" #define FORMAT_NAME "Battlenet" #define ALGORITHM_NAME "SHA1 32/" ARCH_BITS_STR EXP_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define WOWSIG "$WoWSRP$" #define WOWSIGLEN (sizeof(WOWSIG)-1) // min plaintext len is 8 PW's are only alpha-num uppercase #define PLAINTEXT_LENGTH 16 #define CIPHERTEXT_LENGTH 64 #define BINARY_SIZE 4 #define BINARY_ALIGN 4 #define FULL_BINARY_SIZE 32 #define SALT_SIZE (64+3) #define SALT_ALIGN 1 #define USERNAMELEN 32 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 4 // salt is in hex (salt and salt2) static struct fmt_tests tests[] = { {WOWSIG"6D00CD214C8473C7F4E9DC77AE8FC6B3944298C48C7454E6BB8296952DCFE78D$73616C74", "PASSWORD", {"SOLAR"}}, {WOWSIG"A35DCC134159A34F1D411DA7F38AB064B617D5DBDD9258FE2F23D5AB1CF3F685$73616C7432", "PASSWORD2", {"DIZ"}}, {WOWSIG"A35DCC134159A34F1D411DA7F38AB064B617D5DBDD9258FE2F23D5AB1CF3F685$73616C7432*DIZ", "PASSWORD2"}, // this one has a leading 0 {"$WoWSRP$01C7F618E4589F3229D764580FDBF0D579D7CB1C071F11C856BDDA9E41946530$36354172646F744A366A7A58386D4D6E*JOHN", "PASSWORD"}, // same hash, but without 0 (only 63 byte hash). {"$WoWSRP$1C7F618E4589F3229D764580FDBF0D579D7CB1C071F11C856BDDA9E41946530$36354172646F744A366A7A58386D4D6E*JOHN", "PASSWORD"}, {NULL} }; #ifdef HAVE_LIBGMP typedef struct t_SRP_CTX { mpz_t z_mod, z_base, z_exp, z_rop; } SRP_CTX; #else typedef struct t_SRP_CTX { BIGNUM *z_mod, *z_base, *z_exp, *z_rop; BN_CTX *BN_ctx; }SRP_CTX; #endif static SRP_CTX *pSRP_CTX; static unsigned char saved_salt[SALT_SIZE]; static unsigned char user_id[USERNAMELEN]; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[8]; static int max_keys_per_crypt; static void init(struct fmt_main *self) { int i; #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)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); pSRP_CTX = mem_calloc(self->params.max_keys_per_crypt, sizeof(*pSRP_CTX)); max_keys_per_crypt = self->params.max_keys_per_crypt; for (i = 0; i < max_keys_per_crypt; ++i) { #ifdef HAVE_LIBGMP mpz_init_set_str(pSRP_CTX[i].z_mod, "112624315653284427036559548610503669920632123929604336254260115573677366691719", 10); mpz_init_set_str(pSRP_CTX[i].z_base, "47", 10); mpz_init_set_str(pSRP_CTX[i].z_exp, "1", 10); mpz_init(pSRP_CTX[i].z_rop); // Now, properly initialized mpz_exp, so it is 'large enough' to hold any SHA1 value // we need to put into it. Then we simply need to copy in the data, and possibly set // the limb count size. mpz_mul_2exp(pSRP_CTX[i].z_exp, pSRP_CTX[i].z_exp, 159); #else pSRP_CTX[i].z_mod=BN_new(); BN_dec2bn(&pSRP_CTX[i].z_mod, "112624315653284427036559548610503669920632123929604336254260115573677366691719"); pSRP_CTX[i].z_base=BN_new(); BN_set_word(pSRP_CTX[i].z_base, 47); pSRP_CTX[i].z_exp=BN_new(); pSRP_CTX[i].z_rop=BN_new(); pSRP_CTX[i].BN_ctx = BN_CTX_new(); #endif } } static void done(void) { int i; for (i = 0; i < max_keys_per_crypt; ++i) { #ifdef HAVE_LIBGMP mpz_clear(pSRP_CTX[i].z_mod); mpz_clear(pSRP_CTX[i].z_base); mpz_clear(pSRP_CTX[i].z_exp); mpz_clear(pSRP_CTX[i].z_rop); #else BN_clear_free(pSRP_CTX[i].z_mod); BN_clear_free(pSRP_CTX[i].z_base); BN_clear_free(pSRP_CTX[i].z_exp); BN_clear_free(pSRP_CTX[i].z_rop); BN_CTX_free(pSRP_CTX[i].BN_ctx); #endif } MEM_FREE(pSRP_CTX); MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q; if (strncmp(ciphertext, WOWSIG, WOWSIGLEN)) return 0; q = p = &ciphertext[WOWSIGLEN]; while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; if (q-p > CIPHERTEXT_LENGTH) return 0; if (*q != '$') return 0; ++q; p = strchr(q, '*'); if (!p) return 0; if (((p - q) & 1)) return 0; if (p - q >= 2 * SALT_SIZE) return 0; while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; if (q != p) return 0; if (strlen(&p[1]) > USERNAMELEN) return 0; return 1; } /* * Copy as much as ct2_size to ct2 to avoid buffer overflow */ static void StripZeros(const char *ct, char *ct2, const int ct2_size) { int i; for (i = 0; i < WOWSIGLEN && i < (ct2_size - 1); ++i) *ct2++ = *ct++; while (*ct == '0') ++ct; while (*ct && i < (ct2_size - 1)) { *ct2++ = *ct++; i++; } *ct2 = 0; } static char *prepare(char *split_fields[10], struct fmt_main *pFmt) { // if user name not there, then add it static char ct[128+32+1]; char *cp; if (!split_fields[1][0] || strncmp(split_fields[1], WOWSIG, WOWSIGLEN)) return split_fields[1]; cp = strchr(split_fields[1], '*'); if (cp) { if (split_fields[1][WOWSIGLEN] == '0') { StripZeros(split_fields[1], ct, sizeof(ct)); return ct; } return split_fields[1]; } if (strnlen(split_fields[1], 129) <= 128) { strnzcpy(ct, split_fields[1], 128); cp = &ct[strlen(ct)]; *cp++ = '*'; strnzcpy(cp, split_fields[0], USERNAMELEN); // upcase user name enc_strupper(cp); // Ok, if there are leading 0's for that binary resultant value, then remove them. if (ct[WOWSIGLEN] == '0') { char ct2[128+32+1]; StripZeros(ct, ct2, sizeof(ct2)); strcpy(ct, ct2); } return ct; } return split_fields[1]; } static char *split(char *ciphertext, int index, struct fmt_main *pFmt) { static char ct[128+32+1]; char *cp; strnzcpy(ct, ciphertext, 128+32+1); cp = strchr(ct, '*'); if (cp) *cp = 0; strupr(&ct[WOWSIGLEN]); if (cp) *cp = '*'; if (ct[WOWSIGLEN] == '0') { char ct2[128+32+1]; StripZeros(ct, ct2, sizeof(ct2)); strcpy(ct, ct2); } return ct; } static void *get_binary(char *ciphertext) { static union { unsigned char b[FULL_BINARY_SIZE]; uint32_t dummy[1]; } out; char *p, *q; int i; p = &ciphertext[WOWSIGLEN]; q = strchr(p, '$'); memset(out.b, 0, sizeof(out.b)); while (*p == '0') ++p; if ((q-p)&1) { out.b[0] = atoi16[ARCH_INDEX(*p)]; ++p; } else { out.b[0] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } for (i = 1; i < FULL_BINARY_SIZE; i++) { out.b[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; if (p >= q) break; } //dump_stuff_msg("binary", out.b, 32); return out.b; } static void *get_salt(char *ciphertext) { static union { unsigned char b[SALT_SIZE]; uint32_t dummy; } out; char *p; int length=0; memset(out.b, 0, SALT_SIZE); p = strchr(&ciphertext[WOWSIGLEN], '$') + 1; // We need to know if this is odd length or not. while (atoi16[ARCH_INDEX(*p++)] != 0x7f) length++; p = strchr(&ciphertext[WOWSIGLEN], '$') + 1; // handle odd length hex (yes there can be odd length in these SRP files). if ((length&1)&&atoi16[ARCH_INDEX(*p)] != 0x7f) { length=0; out.b[++length] = atoi16[ARCH_INDEX(*p)]; ++p; } else length = 0; while (atoi16[ARCH_INDEX(*p)] != 0x7f && atoi16[ARCH_INDEX(p[1])] != 0x7f) { out.b[++length] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } out.b[0] = length; if (*p) { ++p; memcpy(out.b + length+1, p, strlen(p)+1); } return out.b; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static int salt_hash(void *salt) { unsigned int hash = 0; char *p = (char *)salt; while (*p) { hash <<= 1; hash += (unsigned char)*p++; if (hash >> SALT_HASH_LOG) { hash ^= hash >> SALT_HASH_LOG; hash &= (SALT_HASH_SIZE - 1); } } hash ^= hash >> SALT_HASH_LOG; hash &= (SALT_HASH_SIZE - 1); return hash; } static void set_salt(void *salt) { unsigned char *cp = (unsigned char*)salt; memcpy(saved_salt, &cp[1], *cp); saved_salt[*cp] = 0; strcpy((char*)user_id, (char*)&cp[*cp+1]); } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, PLAINTEXT_LENGTH+1); enc_strupper(saved_key[index]); } static char *get_key(int index) { return saved_key[index]; } // x = SHA1(s, H(U, ":", P)); // v = 47^x % 112624315653284427036559548610503669920632123929604336254260115573677366691719 static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int j; #ifdef _OPENMP #pragma omp parallel for #endif for (j = 0; j < count; ++j) { SHA_CTX ctx; unsigned char Tmp[20]; memset(crypt_out[j], 0, sizeof(crypt_out[j])); SHA1_Init(&ctx); SHA1_Update(&ctx, user_id, strlen((char*)user_id)); SHA1_Update(&ctx, ":", 1); SHA1_Update(&ctx, saved_key[j], strlen(saved_key[j])); SHA1_Final(Tmp, &ctx); SHA1_Init(&ctx); SHA1_Update(&ctx, saved_salt, strlen((char*)saved_salt)); SHA1_Update(&ctx, Tmp, 20); SHA1_Final(Tmp, &ctx); // Ok, now Tmp is v //if (!strcmp(saved_key[j], "ENTERNOW__1") && !strcmp((char*)user_id, "DIP")) { // printf ("salt=%s user=%s pass=%s, ", (char*)saved_salt, (char*)user_id, saved_key[j]); // dump_stuff_msg("sha$h ", Tmp, 20); //} #ifdef HAVE_LIBGMP { unsigned char HashStr[80], *p; int i, todo; p = HashStr; for (i = 0; i < 20; ++i) { *p++ = itoa16[Tmp[i]>>4]; *p++ = itoa16[Tmp[i]&0xF]; } *p = 0; mpz_set_str(pSRP_CTX[j].z_exp, (char*)HashStr, 16); mpz_powm (pSRP_CTX[j].z_rop, pSRP_CTX[j].z_base, pSRP_CTX[j].z_exp, pSRP_CTX[j].z_mod ); mpz_get_str ((char*)HashStr, 16, pSRP_CTX[j].z_rop); p = HashStr; todo = strlen((char*)p); if (todo&1) { ((unsigned char*)(crypt_out[j]))[0] = atoi16[ARCH_INDEX(*p)]; ++p; --todo; } else { ((unsigned char*)(crypt_out[j]))[0] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; todo -= 2; } todo >>= 1; for (i = 1; i <= todo; i++) { ((unsigned char*)(crypt_out[j]))[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } //if (!strcmp(saved_key[j], "ENTERNOW__1") && !strcmp((char*)user_id, "DIP")) { // dump_stuff_msg("crypt ", crypt_out[j], 32); //} } #else // using oSSL's BN to do expmod. pSRP_CTX[j].z_exp = BN_bin2bn(Tmp,20,pSRP_CTX[j].z_exp); BN_mod_exp(pSRP_CTX[j].z_rop, pSRP_CTX[j].z_base, pSRP_CTX[j].z_exp, pSRP_CTX[j].z_mod, pSRP_CTX[j].BN_ctx); BN_bn2bin(pSRP_CTX[j].z_rop, (unsigned char*)(crypt_out[j])); //if (!strcmp(saved_key[j], "ENTERNOW__1") && !strcmp((char*)user_id, "DIP")) { // dump_stuff_msg("crypt ", crypt_out[j], 32); //} #endif } return count; } static int cmp_all(void *binary, int count) { int i; for (i = 0; i < count; ++i) { if (*((uint32_t*)binary) == *((uint32_t*)(crypt_out[i]))) return 1; } return 0; } static int cmp_one(void *binary, int index) { return *((uint32_t*)binary) == *((uint32_t*)(crypt_out[index])); } static int cmp_exact(char *source, int index) { return !memcmp(get_binary(source), crypt_out[index], BINARY_SIZE); } struct fmt_main fmt_blizzard = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 8, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, { NULL }, { WOWSIG }, tests }, { init, done, fmt_default_reset, prepare, valid, split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
omp2.c
// note not doing O0 below as to ensure we get tbaa // TODO: %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 -disable-llvm-optzns %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out // TODO: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // note not doing O0 below as to ensure we get tbaa // TODO: %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 -Xclang -disable-llvm-optzns %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out // TODO: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi #include <stdio.h> #include <math.h> #include <assert.h> #include "test_utils.h" double __enzyme_autodiff(void*, ...); /* void omp(float& a, int N) { #define N 20 #pragma omp parallel for for (int i=0; i<N; i++) { //a[i] *= a[i]; (&a)[i] *= (&a)[i]; } #undef N (&a)[0] = 0; } */ void omp(float* a, int N, int M) { #pragma omp parallel for #pragma nounroll for (unsigned int i=M; i<N; i++) { //a[i] *= a[i]; a[i] *= a[i]; } a[0] = 0; } int main(int argc, char** argv) { int N = 20; int M = 10; float a[N]; for(int i=0; i<N; i++) { a[i] = i+1; } float d_a[N]; for(int i=0; i<N; i++) d_a[i] = 1.0f; //omp(*a, N); printf("ran omp\n"); __enzyme_autodiff((void*)omp, a, d_a, N, M); for(int i=0; i<N; i++) { printf("a[%d]=%f d_a[%d]=%f\n", i, a[i], i, d_a[i]); } //APPROX_EQ(da, 17711.0*2, 1e-10); //APPROX_EQ(db, 17711.0*2, 1e-10); //printf("hello! %f, res2 %f, da: %f, db: %f\n", ret, ret, da,db); APPROX_EQ(d_a[0], 0.0f, 1e-10); for(int i=1; i<N; i++) { if (i < M) { APPROX_EQ(d_a[i], 1.0f, 1e-10); } else { APPROX_EQ(d_a[i], 2.0f*(i+1), 1e-10); } } return 0; }
psd.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/policy.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[257], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(Image *image) { switch (image->compose) { case ColorBurnCompositeOp: return(image->endian == LSBEndian ? "vidi" : "idiv"); case ColorDodgeCompositeOp: return(image->endian == LSBEndian ? " vid" : "div "); case ColorizeCompositeOp: return(image->endian == LSBEndian ? "rloc" : "colr"); case DarkenCompositeOp: return(image->endian == LSBEndian ? "krad" : "dark"); case DifferenceCompositeOp: return(image->endian == LSBEndian ? "ffid" : "diff"); case DissolveCompositeOp: return(image->endian == LSBEndian ? "ssid" : "diss"); case ExclusionCompositeOp: return(image->endian == LSBEndian ? "dums" : "smud"); case HardLightCompositeOp: return(image->endian == LSBEndian ? "tiLh" : "hLit"); case HardMixCompositeOp: return(image->endian == LSBEndian ? "xiMh" : "hMix"); case HueCompositeOp: return(image->endian == LSBEndian ? " euh" : "hue "); case LightenCompositeOp: return(image->endian == LSBEndian ? "etil" : "lite"); case LinearBurnCompositeOp: return(image->endian == LSBEndian ? "nrbl" : "lbrn"); case LinearDodgeCompositeOp: return(image->endian == LSBEndian ? "gddl" : "lddg"); case LinearLightCompositeOp: return(image->endian == LSBEndian ? "tiLl" : "lLit"); case LuminizeCompositeOp: return(image->endian == LSBEndian ? " mul" : "lum "); case MultiplyCompositeOp: return(image->endian == LSBEndian ? " lum" : "mul "); case OverlayCompositeOp: return(image->endian == LSBEndian ? "revo" : "over"); case PinLightCompositeOp: return(image->endian == LSBEndian ? "tiLp" : "pLit"); case SaturateCompositeOp: return(image->endian == LSBEndian ? " tas" : "sat "); case ScreenCompositeOp: return(image->endian == LSBEndian ? "nrcs" : "scrn"); case SoftLightCompositeOp: return(image->endian == LSBEndian ? "tiLs" : "sLit"); case VividLightCompositeOp: return(image->endian == LSBEndian ? "tiLv" : "vLit"); case OverCompositeOp: default: return(image->endian == LSBEndian ? "mron" : "norm"); } } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if ((image->matte == MagickFalse) || (image->colorspace != sRGBColorspace)) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(option) == MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); if (image->matte != MagickTrue) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->matte == MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,0,0,MagickTrue,exception); if (complete_mask == (Image *) NULL) return(MagickFalse); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=(MagickRealType) background; (void) SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=(MagickRealType) GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=(char) layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(const Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); } if (image->depth > 16) return(4); if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static StringInfo *ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; ssize_t offset; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return((StringInfo *) NULL); profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); SetStringInfoName(profile,"8bim"); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) break; p=PushLongPixel(MSBEndian,p,&count); offset=(ssize_t) count; if (((p+offset) < blocks) || ((p+offset) > (blocks+length))) break; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ if (offset < 16) break; p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((offset > 4) && (*(p+4) == 0)) *has_merged_image=MagickFalse; p+=offset; break; } default: { p+=offset; break; } } if ((offset & 0x01) != 0) p++; } return(profile); } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline ssize_t ReadPSDString(Image *image,char *p,const size_t length) { ssize_t count; count=ReadBlob(image,length,(unsigned char *) p); if ((count == (ssize_t) length) && (image->endian != MSBEndian)) { char *q; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } return(count); } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,PixelPacket *q, IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { PixelPacket *color; IndexPacket index; index=(IndexPacket) pixel; if (packet_size == 1) index=(IndexPacket) ScaleQuantumToChar(index); index=ConstrainColormapIndex(image,(ssize_t) index); if (type == 0) SetPixelIndex(indexes+x,index); if ((type == 0) && (channels > 1)) return; color=image->colormap+(ssize_t) GetPixelIndex(indexes+x); if (type != 0) SetPixelAlpha(color,pixel); SetPixelRGBO(q,color); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if ((channels < 3) || (type == -2)) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case -3: case 1: { SetPixelGreen(q,pixel); break; } case -4: case 2: { SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const ssize_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else if (packet_size == 2) { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } else { MagickFloatType nibble; p=PushFloatPixel(MSBEndian,p,&nibble); pixel=ClampToQuantum((MagickRealType)QuantumRange*nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,indexes,x); q++; } else { ssize_t bit, number_bits; number_bits=(ssize_t) image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t row_size; ssize_t count, y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(pixels,0,row_size*sizeof(*pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != (ssize_t) row_size) { status=MagickFalse; break; } status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > (row_size+2048)) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); if ((MagickSizeType) compact_size > GetBlobSize(image)) ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } if (ret == Z_STREAM_END) break; } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { (void) SeekBlob(image,(MagickOffsetType) layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { (void) ResetImagePixels(mask,exception); mask->matte=MagickFalse; channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, (ssize_t) layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, (ssize_t) layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, (ssize_t) layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } (void) SeekBlob(image,offset+layer_info->channel_info[channel].size-2, SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) (void) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (layer_info->mask.image != (Image *) NULL) layer_info->mask.image=DestroyImage(layer_info->mask.image); layer_info->mask.image=mask; } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) (void) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) (void) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); if ((compression == ZipWithPrediction) && (image->depth == 32)) { (void) ThrowMagickException(exception,GetMagickModule(), TypeError,"CompressionNotSupported","ZipWithPrediction(32 bit)"); return(MagickFalse); } layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info, (size_t) j,compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info, LayerInfo *layer_info) { int channel_type; register ssize_t i; if (layer_info->channels < psd_info->min_channels) return(MagickFalse); channel_type=RedChannel; if (psd_info->min_channels >= 3) channel_type|=(GreenChannel | BlueChannel); if (psd_info->min_channels >= 4) channel_type|=BlackChannel; for (i=0; i < (ssize_t) layer_info->channels; i++) { short type; type=layer_info->channel_info[i].type; if ((i == 0) && (psd_info->mode == IndexedMode) && (type != 0)) return(MagickFalse); if (type == -1) { channel_type|=AlphaChannel; continue; } if (type < -1) continue; if (type == 0) channel_type&=~RedChannel; else if (type == 1) channel_type&=~GreenChannel; else if (type == 2) channel_type&=~BlueChannel; else if (type == 3) channel_type&=~BlackChannel; } if (channel_type == 0) return(MagickTrue); if ((channel_type == AlphaChannel) && (layer_info->channels >= psd_info->min_channels + 1)) return(MagickTrue); return(MagickFalse); } static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image) { /* The number of layers cannot be used to determine if the merged image contains an alpha channel. So we enable it when we think we should. */ if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 1)) || ((psd_info->mode == RGBMode) && (psd_info->channels > 3)) || ((psd_info->mode == CMYKMode) && (psd_info->channels > 4))) image->matte=MagickTrue; } static MagickSizeType GetLayerInfoSize(const PSDInfo *psd_info,Image *image) { char type[4]; MagickSizeType size; ssize_t count; size=GetPSDSize(psd_info,image); if (size != 0) return(size); (void) ReadBlobLong(image); count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) return(0); count=ReadPSDString(image,type,4); if ((count == 4) && ((LocaleNCompare(type,"Mt16",4) == 0) || (LocaleNCompare(type,"Mt32",4) == 0) || (LocaleNCompare(type,"Mtrn",4) == 0))) { size=GetPSDSize(psd_info,image); if (size != 0) return(0); image->matte=MagickTrue; count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) return(0); count=ReadPSDString(image,type,4); } if ((count == 4) && ((LocaleNCompare(type,"Lr16",4) == 0) || (LocaleNCompare(type,"Lr32",4) == 0))) size=GetPSDSize(psd_info,image); return(size); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetLayerInfoSize(psd_info,image); status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(ssize_t) ReadBlobSignedShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->matte=MagickTrue; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t top, left, bottom, right; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); top=(ssize_t) ReadBlobSignedLong(image); left=(ssize_t) ReadBlobSignedLong(image); bottom=(ssize_t) ReadBlobSignedLong(image); right=(ssize_t) ReadBlobSignedLong(image); if ((right < left) || (bottom < top)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].page.y=top; layer_info[i].page.x=left; layer_info[i].page.width=(size_t) (right-left); layer_info[i].page.height=(size_t) (bottom-top); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); if ((layer_info[i].channel_info[j].type < -4) || (layer_info[i].channel_info[j].type > 4)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"NoSuchImageChannel", image->filename); } layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadPSDString(image,layer_info[i].blendkey,4); if (count != 4) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) ( ReadBlobSignedLong(image)-layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) ( ReadBlobSignedLong(image)-layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < (ssize_t) layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, (MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickFalse); return(ReadPSDLayersInternal(image,image_info,psd_info,skip_layers, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image* image,const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { ssize_t type; type=i; if ((type == 1) && (psd_info->channels == 2)) type=-1; if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,type,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; size_t image_list_length; ssize_t count; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count != 4) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels < 1) ThrowReaderException(CorruptImageError,"MissingImageChannel"); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16) && (psd_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } status=ResetImagePixels(image,exception); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } psd_info.min_channels=3; if (psd_info.mode == LabMode) (void) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { psd_info.min_channels=4; (void) SetImageColorspace(image,CMYKColorspace); } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { if (psd_info.depth != 32) { status=AcquireImageColormap(image,MagickMin((size_t) (psd_info.depth < 16 ? 256 : 65536), MaxColormapSize)); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); } psd_info.min_channels=1; (void) SetImageColorspace(image,GRAYColorspace); } if (psd_info.channels < psd_info.min_channels) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if ((psd_info.mode == IndexedMode) && (length < 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32)) { /* Duotone image data; the format of this data is undocumented. */ (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=(size_t) length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; profile=(StringInfo *) NULL; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } profile=ParseImageResourceBlocks(image,blocks,(size_t) length, &has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ (void) SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (EOFBlob(image) != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (image_info->ping != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); image_list_length=GetImageListLength(image); if (has_merged_image != MagickFalse || image_list_length == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (image_list_length == 1) && (length != 0)) { (void) SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } image_list_length=GetImageListLength(image); } if (has_merged_image == MagickFalse) { Image *merged; if (image_list_length == 1) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } image->background_color.opacity=TransparentOpacity; (void) SetImageBackgroundColor(image); merged=MergeImageLayers(image,FlattenLayer,exception); if (merged == (Image *) NULL) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } ReplaceImageInList(&image,merged); } if (profile != (StringInfo *) NULL) { Image *next; next=image; while (next != (Image *) NULL) { (void) SetImageProfile(next,GetStringInfoName(profile),profile); next=next->next; } profile=DestroyStringInfo(profile); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->magick_module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->magick_module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned int) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=WriteBlobMSBLong(image,(unsigned int) size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { ssize_t i, offset, y; if (next_image->compression == RLECompression) { offset=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) offset+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) offset=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else offset=WriteBlobMSBShort(image,Raw); return((size_t) offset); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory( MagickMinBufferExtent,sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) MagickMinBufferExtent; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) MagickMinBufferExtent-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, length, offset_length; ssize_t count; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if ((next_image->storage_class != PseudoClass) || (IsGrayImage(next_image,&next_image->exception) != MagickFalse)) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 : 3); if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,(ssize_t) channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if ((next_image->storage_class == PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { ssize_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return((size_t) count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) memmove(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) && ((ssize_t) length-(cnt+12)-(q-datum)) > 0) { (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) memmove(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); (void) SetImageProfile(image,"psd:additional-info",info); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { char layer_name[MaxTextExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,&image->exception) != MagickFalse)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } base_image=GetNextImageInList(image); if (base_image == (Image *)NULL) base_image=image; size=0; size_offset=TellBlob(image); (void) SetPSDSize(&psd_info,image,0); (void) SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->matte != MagickFalse) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0); } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1; if ((next_image->storage_class != PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 : 3); total_channels=channels; if (next_image->matte != MagickFalse) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->matte != MagickFalse) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue, &image->exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,(unsigned char) (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image); property=(const char *) GetImageProperty(next_image,"label"); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,&image->exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->page.y); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->page.x); size+=WriteBlobMSBSignedLong(image,(const signed int) (mask->rows+ mask->page.y)); size+=WriteBlobMSBSignedLong(image,(const signed int) (mask->columns+ mask->page.x)); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,(unsigned char) ( mask->compose == NoCompositeOp ? 2 : 0)); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info),GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=(size_t) WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) (void) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 12),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image_info->compression != UndefinedCompression) image->compression=image_info->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0, MagickFalse) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
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] = 4; tile_size[1] = 4; tile_size[2] = 16; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=2*Nt-2;t1++) { lbp=ceild(t1+2,2); ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-4,8),ceild(4*t2-Nz-3,16));t3<=min(min(floord(4*Nt+Ny-9,16),floord(2*t1+Ny-3,16)),floord(4*t2+Ny-9,16));t3++) { for (t4=max(max(ceild(t1-252,256),ceild(4*t2-Nz-499,512)),ceild(16*t3-Ny-499,512));t4<=min(min(min(floord(4*Nt+Nx-9,512),floord(2*t1+Nx-3,512)),floord(4*t2+Nx-9,512)),floord(16*t3+Nx+3,512));t4++) { for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(16*t3-Ny+5,4)),ceild(512*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) { for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(16*t3,4*t5+4);t7<=min(16*t3+15,4*t5+Ny-5);t7++) { lbv=max(512*t4,4*t5+4); ubv=min(512*t4+511,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_unaryop__ainv_fp64_int8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_fp64_int8 // op(A') function: GB_tran__ainv_fp64_int8 // C type: double // A type: int8_t // cast: double cij = (double) aij // unaryop: cij = -aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ double // 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_CASTING(z, aij) \ double z = (double) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_FP64 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_fp64_int8 ( double *Cx, // Cx and Ax may be aliased int8_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_fp64_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
pi.c
#include <stdio.h> long long num_passos = 1000000000; double passo; int main(){ int i; double x, pi, soma=0.0; passo = 1.0/(double)num_passos; #pragma omp target map(tofrom:soma) #pragma omp teams distribute parallel for simd private(x) reduction(+:soma) for(i=0; i < num_passos; i++){ x = (i + 0.5)*passo; soma = soma + 4.0/(1.0 + x*x); } pi = soma*passo; printf("O valor de PI é: %f\n", pi); return 0; }
wino_conv_kernel_mips.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: qtang@openailab.com */ #include <stdint.h> #include <stdlib.h> #include <math.h> #include "wino_conv_kernel_mips.h" #define TILE 4 #define ELEM_SIZE ((TILE + 2) * (TILE + 2)) #define WINO_MAX(a, b) ((a) > (b) ? (a) : (b)) #define WINO_MIN(a, b) ((a) < (b) ? (a) : (b)) static void relu(float* data, int size, int activation) { for (int i = 0; i < size; i++) { data[i] = WINO_MAX(data[i], ( float )0); if (activation > 0) { data[i] = WINO_MIN(data[i], ( float )activation); } } } static int get_private_mem_size(struct tensor* filter, struct conv_param* param) { int output_c = filter->dims[0]; int input_c = filter->dims[1]; int trans_ker_size = output_c * input_c * ELEM_SIZE * sizeof(float); return trans_ker_size + 128; // caution } static void pad_0_align_2D(float* dst, float* src, int m, int n, int m_align, int n_align, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, m * n * sizeof(float)); return; } for (i = 0; i < m; ++i) { memcpy(dst + (i + pad_h) * n_align + pad_w, src + i * n, n * sizeof(float)); } } // pad 0 in right and down side on 3D static void pad_0_align_3D(float* dst, float* src, int m, int n, int m_align, int n_align, int c, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, c * m * n * sizeof(float)); return; } for (i = 0; i < c; ++i) { pad_0_align_2D(dst + i * m_align * n_align, src + i * m * n, m, n, m_align, n_align, pad_h, pad_w); } } static void delete_0_2D(float* dst, float* src, int m_align, int n_align, int m, int n, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, m * n * sizeof(float)); return; } for (i = 0; i < m; ++i) { memcpy(dst + i * n, src + (i + pad_h) * n_align + pad_w, n * sizeof(float)); } } // pad 0 in right and down side on 3D static void delete_0_3D(float* dst, float* src, int m_align, int n_align, int m, int n, int c, int pad_h, int pad_w) { int i; if (n >= n_align && m >= m_align) { memcpy(dst, src, c * m * n * sizeof(float)); return; } for (i = 0; i < c; ++i) { delete_0_2D(dst + i * m * n, src + i * m_align * n_align, m_align, n_align, m, n, pad_h, pad_w); } } void conv3x3s1_winograd43_sse(float* bottom_blob, float* top_blob, float* kernel_tm_test, float* dot_block, float* transform_input, float* output_bordered, float* _bias, int w, int h, int inch, int outw, int outh, int outch, int num_thread) { size_t elemsize = sizeof(float); const float* bias = _bias; // pad to 4n+2, winograd F(4,3) float* bottom_blob_bordered = bottom_blob; int outw_align = (outw + 3) / 4 * 4; int outh_align = (outh + 3) / 4 * 4; w = outw_align + 2; h = outh_align + 2; // BEGIN transform input float* bottom_blob_tm = NULL; { int w_tm = outw_align / 4 * 6; int h_tm = outh_align / 4 * 6; int nColBlocks = h_tm / 6; // may be the block num in Feathercnn int nRowBlocks = w_tm / 6; const int tiles = nColBlocks * nRowBlocks; const int tiles_n = 4 * inch * tiles; bottom_blob_tm = transform_input; // BT // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r03 + r04 // 2 = 4 * (r01 - r02) - r03 + r04 // 3 = -2 * r01 - r02 + 2 * r03 + r04 // 4 = 2 * r01 - r02 - 2 * r03 + r04 // 5 = 4 * r01 - 5 * r03 + r05 // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r03 + r04 // 2 = 4 * (r01 - r02) - r03 + r04 // 3 = -2 * r01 - r02 + 2 * r03 + r04 // 4 = 2 * r01 - r02 - 2 * r03 + r04 // 5 = 4 * r01 - 5 * r03 + r05 #pragma omp parallel for num_threads(num_thread) for (int q = 0; q < inch; q++) { const float* img = bottom_blob_bordered + q * w * h; for (int j = 0; j < nColBlocks; j++) { const float* r0 = img + w * j * 4; const float* r1 = r0 + w; const float* r2 = r1 + w; const float* r3 = r2 + w; const float* r4 = r3 + w; const float* r5 = r4 + w; for (int i = 0; i < nRowBlocks; i++) { float* out_tm0 = bottom_blob_tm + 4 * inch * (j * nRowBlocks + i) + 4 * q; float* out_tm1 = out_tm0 + tiles_n; float* out_tm2 = out_tm0 + 2 * tiles_n; float* out_tm3 = out_tm0 + 3 * tiles_n; float* out_tm4 = out_tm0 + 4 * tiles_n; float* out_tm5 = out_tm0 + 5 * tiles_n; float* out_tm6 = out_tm0 + 6 * tiles_n; float* out_tm7 = out_tm0 + 7 * tiles_n; float* out_tm8 = out_tm0 + 8 * tiles_n; float d0[6], d1[6], d2[6], d3[6], d4[6], d5[6]; float w0[6], w1[6], w2[6], w3[6], w4[6], w5[6]; float t0[6], t1[6], t2[6], t3[6], t4[6], t5[6]; // load for (int n = 0; n < 6; n++) { d0[n] = r0[n]; d1[n] = r1[n]; d2[n] = r2[n]; d3[n] = r3[n]; d4[n] = r4[n]; d5[n] = r5[n]; } // w = B_t * d for (int n = 0; n < 6; n++) { w0[n] = 4 * d0[n] - 5 * d2[n] + d4[n]; w1[n] = -4 * d1[n] - 4 * d2[n] + d3[n] + d4[n]; w2[n] = 4 * d1[n] - 4 * d2[n] - d3[n] + d4[n]; w3[n] = -2 * d1[n] - d2[n] + 2 * d3[n] + d4[n]; w4[n] = 2 * d1[n] - d2[n] - 2 * d3[n] + d4[n]; w5[n] = 4 * d1[n] - 5 * d3[n] + d5[n]; } // transpose d to d_t { t0[0] = w0[0]; t1[0] = w0[1]; t2[0] = w0[2]; t3[0] = w0[3]; t4[0] = w0[4]; t5[0] = w0[5]; t0[1] = w1[0]; t1[1] = w1[1]; t2[1] = w1[2]; t3[1] = w1[3]; t4[1] = w1[4]; t5[1] = w1[5]; t0[2] = w2[0]; t1[2] = w2[1]; t2[2] = w2[2]; t3[2] = w2[3]; t4[2] = w2[4]; t5[2] = w2[5]; t0[3] = w3[0]; t1[3] = w3[1]; t2[3] = w3[2]; t3[3] = w3[3]; t4[3] = w3[4]; t5[3] = w3[5]; t0[4] = w4[0]; t1[4] = w4[1]; t2[4] = w4[2]; t3[4] = w4[3]; t4[4] = w4[4]; t5[4] = w4[5]; t0[5] = w5[0]; t1[5] = w5[1]; t2[5] = w5[2]; t3[5] = w5[3]; t4[5] = w5[4]; t5[5] = w5[5]; } // d = B_t * d_t for (int n = 0; n < 6; n++) { d0[n] = 4 * t0[n] - 5 * t2[n] + t4[n]; d1[n] = -4 * t1[n] - 4 * t2[n] + t3[n] + t4[n]; d2[n] = 4 * t1[n] - 4 * t2[n] - t3[n] + t4[n]; d3[n] = -2 * t1[n] - t2[n] + 2 * t3[n] + t4[n]; d4[n] = 2 * t1[n] - t2[n] - 2 * t3[n] + t4[n]; d5[n] = 4 * t1[n] - 5 * t3[n] + t5[n]; } // save to out_tm { out_tm0[0] = d0[0]; out_tm0[1] = d0[1]; out_tm0[2] = d0[2]; out_tm0[3] = d0[3]; out_tm1[0] = d0[4]; out_tm1[1] = d0[5]; out_tm1[2] = d1[0]; out_tm1[3] = d1[1]; out_tm2[0] = d1[2]; out_tm2[1] = d1[3]; out_tm2[2] = d1[4]; out_tm2[3] = d1[5]; out_tm3[0] = d2[0]; out_tm3[1] = d2[1]; out_tm3[2] = d2[2]; out_tm3[3] = d2[3]; out_tm4[0] = d2[4]; out_tm4[1] = d2[5]; out_tm4[2] = d3[0]; out_tm4[3] = d3[1]; out_tm5[0] = d3[2]; out_tm5[1] = d3[3]; out_tm5[2] = d3[4]; out_tm5[3] = d3[5]; out_tm6[0] = d4[0]; out_tm6[1] = d4[1]; out_tm6[2] = d4[2]; out_tm6[3] = d4[3]; out_tm7[0] = d4[4]; out_tm7[1] = d4[5]; out_tm7[2] = d5[0]; out_tm7[3] = d5[1]; out_tm8[0] = d5[2]; out_tm8[1] = d5[3]; out_tm8[2] = d5[4]; out_tm8[3] = d5[5]; } r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; } } } } // BEGIN dot float* top_blob_tm = NULL; { int w_tm = outw_align / 4 * 6; int h_tm = outh_align / 4 * 6; int nColBlocks = h_tm / 6; // may be the block num in Feathercnn int nRowBlocks = w_tm / 6; const int tiles = nColBlocks * nRowBlocks; const int tiles_n = 36 * tiles; top_blob_tm = dot_block; #pragma omp parallel for num_threads(num_thread) for (int r = 0; r < 9; r++) { int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; for (int pp = 0; pp < nn_outch; pp++) { int p = pp << 3; float* output0_tm = top_blob_tm + tiles_n * p; float* output1_tm = top_blob_tm + tiles_n * (p + 1); float* output2_tm = top_blob_tm + tiles_n * (p + 2); float* output3_tm = top_blob_tm + tiles_n * (p + 3); float* output4_tm = top_blob_tm + tiles_n * (p + 4); float* output5_tm = top_blob_tm + tiles_n * (p + 5); float* output6_tm = top_blob_tm + tiles_n * (p + 6); float* output7_tm = top_blob_tm + tiles_n * (p + 7); output0_tm = output0_tm + r * 4; output1_tm = output1_tm + r * 4; output2_tm = output2_tm + r * 4; output3_tm = output3_tm + r * 4; output4_tm = output4_tm + r * 4; output5_tm = output5_tm + r * 4; output6_tm = output6_tm + r * 4; output7_tm = output7_tm + r * 4; for (int i = 0; i < tiles; i++) { const float* kptr = kernel_tm_test + 4 * r * inch * outch + p / 8 * inch * 32; const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i); #if __mips_msa v4f32 _sum0 = {0.f}; v4f32 _sum1 = {0.f}; v4f32 _sum2 = {0.f}; v4f32 _sum3 = {0.f}; v4f32 _sum4 = {0.f}; v4f32 _sum5 = {0.f}; v4f32 _sum6 = {0.f}; v4f32 _sum7 = {0.f}; int q = 0; for (; q + 3 < inch; q = q + 4) { v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 8, 0); v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 12, 0); v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0); v4f32 _k1 = (v4f32)__msa_ld_w(kptr + 4, 0); v4f32 _k2 = (v4f32)__msa_ld_w(kptr + 8, 0); v4f32 _k3 = (v4f32)__msa_ld_w(kptr + 12, 0); v4f32 _k4 = (v4f32)__msa_ld_w(kptr + 16, 0); v4f32 _k5 = (v4f32)__msa_ld_w(kptr + 20, 0); v4f32 _k6 = (v4f32)__msa_ld_w(kptr + 24, 0); v4f32 _k7 = (v4f32)__msa_ld_w(kptr + 28, 0); _sum0 = __msa_fadd_w(_sum0, __msa_fmul_w(_r0, _k0)); _sum1 = __msa_fadd_w(_sum1, __msa_fmul_w(_r0, _k1)); _sum2 = __msa_fadd_w(_sum2, __msa_fmul_w(_r0, _k2)); _sum3 = __msa_fadd_w(_sum3, __msa_fmul_w(_r0, _k3)); _sum4 = __msa_fadd_w(_sum4, __msa_fmul_w(_r0, _k4)); _sum5 = __msa_fadd_w(_sum5, __msa_fmul_w(_r0, _k5)); _sum6 = __msa_fadd_w(_sum6, __msa_fmul_w(_r0, _k6)); _sum7 = __msa_fadd_w(_sum7, __msa_fmul_w(_r0, _k7)); kptr += 32; _k0 = (v4f32)__msa_ld_w(kptr, 0); _k1 = (v4f32)__msa_ld_w(kptr + 4, 0); _k2 = (v4f32)__msa_ld_w(kptr + 8, 0); _k3 = (v4f32)__msa_ld_w(kptr + 12, 0); _k4 = (v4f32)__msa_ld_w(kptr + 16, 0); _k5 = (v4f32)__msa_ld_w(kptr + 20, 0); _k6 = (v4f32)__msa_ld_w(kptr + 24, 0); _k7 = (v4f32)__msa_ld_w(kptr + 28, 0); _sum0 = __msa_fadd_w(_sum0, __msa_fmul_w(_r1, _k0)); _sum1 = __msa_fadd_w(_sum1, __msa_fmul_w(_r1, _k1)); _sum2 = __msa_fadd_w(_sum2, __msa_fmul_w(_r1, _k2)); _sum3 = __msa_fadd_w(_sum3, __msa_fmul_w(_r1, _k3)); _sum4 = __msa_fadd_w(_sum4, __msa_fmul_w(_r1, _k4)); _sum5 = __msa_fadd_w(_sum5, __msa_fmul_w(_r1, _k5)); _sum6 = __msa_fadd_w(_sum6, __msa_fmul_w(_r1, _k6)); _sum7 = __msa_fadd_w(_sum7, __msa_fmul_w(_r1, _k7)); kptr += 32; _k0 = (v4f32)__msa_ld_w(kptr, 0); _k1 = (v4f32)__msa_ld_w(kptr + 4, 0); _k2 = (v4f32)__msa_ld_w(kptr + 8, 0); _k3 = (v4f32)__msa_ld_w(kptr + 12, 0); _k4 = (v4f32)__msa_ld_w(kptr + 16, 0); _k5 = (v4f32)__msa_ld_w(kptr + 20, 0); _k6 = (v4f32)__msa_ld_w(kptr + 24, 0); _k7 = (v4f32)__msa_ld_w(kptr + 28, 0); _sum0 = __msa_fadd_w(_sum0, __msa_fmul_w(_r2, _k0)); _sum1 = __msa_fadd_w(_sum1, __msa_fmul_w(_r2, _k1)); _sum2 = __msa_fadd_w(_sum2, __msa_fmul_w(_r2, _k2)); _sum3 = __msa_fadd_w(_sum3, __msa_fmul_w(_r2, _k3)); _sum4 = __msa_fadd_w(_sum4, __msa_fmul_w(_r2, _k4)); _sum5 = __msa_fadd_w(_sum5, __msa_fmul_w(_r2, _k5)); _sum6 = __msa_fadd_w(_sum6, __msa_fmul_w(_r2, _k6)); _sum7 = __msa_fadd_w(_sum7, __msa_fmul_w(_r2, _k7)); kptr += 32; _k0 = (v4f32)__msa_ld_w(kptr, 0); _k1 = (v4f32)__msa_ld_w(kptr + 4, 0); _k2 = (v4f32)__msa_ld_w(kptr + 8, 0); _k3 = (v4f32)__msa_ld_w(kptr + 12, 0); _k4 = (v4f32)__msa_ld_w(kptr + 16, 0); _k5 = (v4f32)__msa_ld_w(kptr + 20, 0); _k6 = (v4f32)__msa_ld_w(kptr + 24, 0); _k7 = (v4f32)__msa_ld_w(kptr + 28, 0); _sum0 = __msa_fadd_w(_sum0, __msa_fmul_w(_r3, _k0)); _sum1 = __msa_fadd_w(_sum1, __msa_fmul_w(_r3, _k1)); _sum2 = __msa_fadd_w(_sum2, __msa_fmul_w(_r3, _k2)); _sum3 = __msa_fadd_w(_sum3, __msa_fmul_w(_r3, _k3)); _sum4 = __msa_fadd_w(_sum4, __msa_fmul_w(_r3, _k4)); _sum5 = __msa_fadd_w(_sum5, __msa_fmul_w(_r3, _k5)); _sum6 = __msa_fadd_w(_sum6, __msa_fmul_w(_r3, _k6)); _sum7 = __msa_fadd_w(_sum7, __msa_fmul_w(_r3, _k7)); kptr += 32; r0 += 16; } for (; q < inch; q++) { v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0); v4f32 _k1 = (v4f32)__msa_ld_w(kptr + 4, 0); v4f32 _k2 = (v4f32)__msa_ld_w(kptr + 8, 0); v4f32 _k3 = (v4f32)__msa_ld_w(kptr + 12, 0); v4f32 _k4 = (v4f32)__msa_ld_w(kptr + 16, 0); v4f32 _k5 = (v4f32)__msa_ld_w(kptr + 20, 0); v4f32 _k6 = (v4f32)__msa_ld_w(kptr + 24, 0); v4f32 _k7 = (v4f32)__msa_ld_w(kptr + 28, 0); _sum0 = __msa_fadd_w(_sum0, __msa_fmul_w(_r0, _k0)); _sum1 = __msa_fadd_w(_sum1, __msa_fmul_w(_r0, _k1)); _sum2 = __msa_fadd_w(_sum2, __msa_fmul_w(_r0, _k2)); _sum3 = __msa_fadd_w(_sum3, __msa_fmul_w(_r0, _k3)); _sum4 = __msa_fadd_w(_sum4, __msa_fmul_w(_r0, _k4)); _sum5 = __msa_fadd_w(_sum5, __msa_fmul_w(_r0, _k5)); _sum6 = __msa_fadd_w(_sum6, __msa_fmul_w(_r0, _k6)); _sum7 = __msa_fadd_w(_sum7, __msa_fmul_w(_r0, _k7)); kptr += 32; r0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output1_tm, 0); __msa_st_w((v4i32)_sum2, output2_tm, 0); __msa_st_w((v4i32)_sum3, output3_tm, 0); __msa_st_w((v4i32)_sum4, output4_tm, 0); __msa_st_w((v4i32)_sum5, output5_tm, 0); __msa_st_w((v4i32)_sum6, output6_tm, 0); __msa_st_w((v4i32)_sum7, output7_tm, 0); #else float sum0[4] = {0}; float sum1[4] = {0}; float sum2[4] = {0}; float sum3[4] = {0}; float sum4[4] = {0}; float sum5[4] = {0}; float sum6[4] = {0}; float sum7[4] = {0}; for (int q = 0; q < inch; q++) { for (int n = 0; n < 4; n++) { sum0[n] += r0[n] * kptr[n]; sum1[n] += r0[n] * kptr[n + 4]; sum2[n] += r0[n] * kptr[n + 8]; sum3[n] += r0[n] * kptr[n + 12]; sum4[n] += r0[n] * kptr[n + 16]; sum5[n] += r0[n] * kptr[n + 20]; sum6[n] += r0[n] * kptr[n + 24]; sum7[n] += r0[n] * kptr[n + 28]; } kptr += 32; r0 += 4; } for (int n = 0; n < 4; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; output4_tm[n] = sum4[n]; output5_tm[n] = sum5[n]; output6_tm[n] = sum6[n]; output7_tm[n] = sum7[n]; } #endif // __mips_msa output0_tm += 36; output1_tm += 36; output2_tm += 36; output3_tm += 36; output4_tm += 36; output5_tm += 36; output6_tm += 36; output7_tm += 36; } } nn_outch = (outch - remain_outch_start) >> 2; for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* output0_tm = top_blob_tm + tiles_n * p; float* output1_tm = top_blob_tm + tiles_n * (p + 1); float* output2_tm = top_blob_tm + tiles_n * (p + 2); float* output3_tm = top_blob_tm + tiles_n * (p + 3); output0_tm = output0_tm + r * 4; output1_tm = output1_tm + r * 4; output2_tm = output2_tm + r * 4; output3_tm = output3_tm + r * 4; for (int i = 0; i < tiles; i++) { const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4) * inch * 32; const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i); #if __mips_msa v4f32 _sum0 = {0.f}; v4f32 _sum1 = {0.f}; v4f32 _sum2 = {0.f}; v4f32 _sum3 = {0.f}; for (int q = 0; q < inch; q++) { v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0); v4f32 _k1 = (v4f32)__msa_ld_w(kptr + 4, 0); v4f32 _k2 = (v4f32)__msa_ld_w(kptr + 8, 0); v4f32 _k3 = (v4f32)__msa_ld_w(kptr + 12, 0); _sum0 = __msa_fadd_w(_sum0, __msa_fmul_w(_r0, _k0)); _sum1 = __msa_fadd_w(_sum1, __msa_fmul_w(_r0, _k1)); _sum2 = __msa_fadd_w(_sum2, __msa_fmul_w(_r0, _k2)); _sum3 = __msa_fadd_w(_sum3, __msa_fmul_w(_r0, _k3)); kptr += 16; r0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output1_tm, 0); __msa_st_w((v4i32)_sum2, output2_tm, 0); __msa_st_w((v4i32)_sum3, output3_tm, 0); #else float sum0[4] = {0}; float sum1[4] = {0}; float sum2[4] = {0}; float sum3[4] = {0}; for (int q = 0; q < inch; q++) { for (int n = 0; n < 4; n++) { sum0[n] += r0[n] * kptr[n]; sum1[n] += r0[n] * kptr[n + 4]; sum2[n] += r0[n] * kptr[n + 8]; sum3[n] += r0[n] * kptr[n + 12]; } kptr += 16; r0 += 4; } for (int n = 0; n < 4; n++) { output0_tm[n] = sum0[n]; output1_tm[n] = sum1[n]; output2_tm[n] = sum2[n]; output3_tm[n] = sum3[n]; } #endif // __mips_msa output0_tm += 36; output1_tm += 36; output2_tm += 36; output3_tm += 36; } } remain_outch_start += nn_outch << 2; for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm + 36 * tiles * p; output0_tm = output0_tm + r * 4; for (int i = 0; i < tiles; i++) { const float* kptr = kernel_tm_test + 4 * r * inch * outch + (p / 8 + (p % 8) / 4 + p % 4) * inch * 32; const float* r0 = bottom_blob_tm + 4 * inch * (tiles * r + i); #if __mips_msa v4f32 _sum0 = {0.f}; for (int q = 0; q < inch; q++) { v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _k0 = (v4f32)__msa_ld_w(kptr, 0); _sum0 = __msa_fadd_w(_sum0, __msa_fmul_w(_r0, _k0)); kptr += 16; r0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); #else float sum0[4] = {0}; for (int q = 0; q < inch; q++) { for (int n = 0; n < 4; n++) { sum0[n] += ( int )r0[n] * kptr[n]; } kptr += 4; r0 += 4; } for (int n = 0; n < 4; n++) { output0_tm[n] = sum0[n]; } #endif // __mips_msa output0_tm += 36; } } } } // END dot // BEGIN transform output float* top_blob_bordered = NULL; if (outw_align == outw && outh_align == outh) { top_blob_bordered = top_blob; } else { top_blob_bordered = output_bordered; } { // AT // const float itm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + r01 + r02 + r03 + r04 // 1 = r01 - r02 + 2 * (r03 - r04) // 2 = r01 + r02 + 4 * (r03 + r04) // 3 = r01 - r02 + 8 * (r03 - r04) + r05 int w_tm = outw_align / 4 * 6; int h_tm = outh_align / 4 * 6; int nColBlocks = h_tm / 6; // may be the block num in Feathercnn int nRowBlocks = w_tm / 6; const int tiles = nColBlocks * nRowBlocks; #pragma omp parallel for num_threads(num_thread) for (int p = 0; p < outch; p++) { float* out_tile = top_blob_tm + 36 * tiles * p; float* outRow0 = top_blob_bordered + outw_align * outh_align * p; float* outRow1 = outRow0 + outw_align; float* outRow2 = outRow0 + outw_align * 2; float* outRow3 = outRow0 + outw_align * 3; const float bias0 = bias ? bias[p] : 0.f; for (int j = 0; j < nColBlocks; j++) { for (int i = 0; i < nRowBlocks; i++) { // TODO AVX2 float s0[6], s1[6], s2[6], s3[6], s4[6], s5[6]; float w0[6], w1[6], w2[6], w3[6]; float d0[4], d1[4], d2[4], d3[4], d4[4], d5[4]; float o0[4], o1[4], o2[4], o3[4]; // load for (int n = 0; n < 6; n++) { s0[n] = out_tile[n]; s1[n] = out_tile[n + 6]; s2[n] = out_tile[n + 12]; s3[n] = out_tile[n + 18]; s4[n] = out_tile[n + 24]; s5[n] = out_tile[n + 30]; } // w = A_T * W for (int n = 0; n < 6; n++) { w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n]; w1[n] = s1[n] - s2[n] + 2 * s3[n] - 2 * s4[n]; w2[n] = s1[n] + s2[n] + 4 * s3[n] + 4 * s4[n]; w3[n] = s1[n] - s2[n] + 8 * s3[n] - 8 * s4[n] + s5[n]; } // transpose w to w_t { d0[0] = w0[0]; d0[1] = w1[0]; d0[2] = w2[0]; d0[3] = w3[0]; d1[0] = w0[1]; d1[1] = w1[1]; d1[2] = w2[1]; d1[3] = w3[1]; d2[0] = w0[2]; d2[1] = w1[2]; d2[2] = w2[2]; d2[3] = w3[2]; d3[0] = w0[3]; d3[1] = w1[3]; d3[2] = w2[3]; d3[3] = w3[3]; d4[0] = w0[4]; d4[1] = w1[4]; d4[2] = w2[4]; d4[3] = w3[4]; d5[0] = w0[5]; d5[1] = w1[5]; d5[2] = w2[5]; d5[3] = w3[5]; } // Y = A_T * w_t for (int n = 0; n < 4; n++) { o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n]; o1[n] = d1[n] - d2[n] + 2 * d3[n] - 2 * d4[n]; o2[n] = d1[n] + d2[n] + 4 * d3[n] + 4 * d4[n]; o3[n] = d1[n] - d2[n] + 8 * d3[n] - 8 * d4[n] + d5[n]; } // save to top blob tm for (int n = 0; n < 4; n++) { outRow0[n] = o0[n] + bias0; outRow1[n] = o1[n] + bias0; outRow2[n] = o2[n] + bias0; outRow3[n] = o3[n] + bias0; } out_tile += 36; outRow0 += 4; outRow1 += 4; outRow2 += 4; outRow3 += 4; } outRow0 += outw_align * 3; outRow1 += outw_align * 3; outRow2 += outw_align * 3; outRow3 += outw_align * 3; } } } // END transform output if (outw_align != outw || outh_align != outw) { delete_0_3D(top_blob, top_blob_bordered, outh_align, outw_align, outh, outw, outch, 0, 0); } } void conv3x3s1_winograd43_transform_kernel_sse(const float* kernel, float* kernel_wino, int inch, int outch) { float* kernel_tm = ( float* )sys_malloc(6 * 6 * inch * outch * sizeof(float)); // G const float ktm[6][3] = { {1.0f / 4, 0.0f, 0.0f}, {-1.0f / 6, -1.0f / 6, -1.0f / 6}, {-1.0f / 6, 1.0f / 6, -1.0f / 6}, {1.0f / 24, 1.0f / 12, 1.0f / 6}, {1.0f / 24, -1.0f / 12, 1.0f / 6}, {0.0f, 0.0f, 1.0f}}; #pragma omp parallel for for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm + p * inch * 36 + q * 36; // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[6][3] = {0}; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } float* kernel_tm_test = kernel_wino; for (int r = 0; r < 9; r++) { int p = 0; for (; p + 7 < outch; p += 8) { const float* kernel0 = ( const float* )kernel_tm + p * inch * 36; const float* kernel1 = ( const float* )kernel_tm + (p + 1) * inch * 36; const float* kernel2 = ( const float* )kernel_tm + (p + 2) * inch * 36; const float* kernel3 = ( const float* )kernel_tm + (p + 3) * inch * 36; const float* kernel4 = ( const float* )kernel_tm + (p + 4) * inch * 36; const float* kernel5 = ( const float* )kernel_tm + (p + 5) * inch * 36; const float* kernel6 = ( const float* )kernel_tm + (p + 6) * inch * 36; const float* kernel7 = ( const float* )kernel_tm + (p + 7) * inch * 36; float* ktmp = kernel_tm_test + p / 8 * inch * 32; for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[r * 4 + 0]; ktmp[1] = kernel0[r * 4 + 1]; ktmp[2] = kernel0[r * 4 + 2]; ktmp[3] = kernel0[r * 4 + 3]; ktmp[4] = kernel1[r * 4 + 0]; ktmp[5] = kernel1[r * 4 + 1]; ktmp[6] = kernel1[r * 4 + 2]; ktmp[7] = kernel1[r * 4 + 3]; ktmp[8] = kernel2[r * 4 + 0]; ktmp[9] = kernel2[r * 4 + 1]; ktmp[10] = kernel2[r * 4 + 2]; ktmp[11] = kernel2[r * 4 + 3]; ktmp[12] = kernel3[r * 4 + 0]; ktmp[13] = kernel3[r * 4 + 1]; ktmp[14] = kernel3[r * 4 + 2]; ktmp[15] = kernel3[r * 4 + 3]; ktmp[16] = kernel4[r * 4 + 0]; ktmp[17] = kernel4[r * 4 + 1]; ktmp[18] = kernel4[r * 4 + 2]; ktmp[19] = kernel4[r * 4 + 3]; ktmp[20] = kernel5[r * 4 + 0]; ktmp[21] = kernel5[r * 4 + 1]; ktmp[22] = kernel5[r * 4 + 2]; ktmp[23] = kernel5[r * 4 + 3]; ktmp[24] = kernel6[r * 4 + 0]; ktmp[25] = kernel6[r * 4 + 1]; ktmp[26] = kernel6[r * 4 + 2]; ktmp[27] = kernel6[r * 4 + 3]; ktmp[28] = kernel7[r * 4 + 0]; ktmp[29] = kernel7[r * 4 + 1]; ktmp[30] = kernel7[r * 4 + 2]; ktmp[31] = kernel7[r * 4 + 3]; ktmp += 32; kernel0 += 36; kernel1 += 36; kernel2 += 36; kernel3 += 36; kernel4 += 36; kernel5 += 36; kernel6 += 36; kernel7 += 36; } } for (; p + 3 < outch; p += 4) { const float* kernel0 = ( const float* )kernel_tm + p * inch * 36; const float* kernel1 = ( const float* )kernel_tm + (p + 1) * inch * 36; const float* kernel2 = ( const float* )kernel_tm + (p + 2) * inch * 36; const float* kernel3 = ( const float* )kernel_tm + (p + 3) * inch * 36; float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4) * inch * 32; for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[r * 4 + 0]; ktmp[1] = kernel0[r * 4 + 1]; ktmp[2] = kernel0[r * 4 + 2]; ktmp[3] = kernel0[r * 4 + 3]; ktmp[4] = kernel1[r * 4 + 0]; ktmp[5] = kernel1[r * 4 + 1]; ktmp[6] = kernel1[r * 4 + 2]; ktmp[7] = kernel1[r * 4 + 3]; ktmp[8] = kernel2[r * 4 + 0]; ktmp[9] = kernel2[r * 4 + 1]; ktmp[10] = kernel2[r * 4 + 2]; ktmp[11] = kernel2[r * 4 + 3]; ktmp[12] = kernel3[r * 4 + 0]; ktmp[13] = kernel3[r * 4 + 1]; ktmp[14] = kernel3[r * 4 + 2]; ktmp[15] = kernel3[r * 4 + 3]; ktmp += 16; kernel0 += 36; kernel1 += 36; kernel2 += 36; kernel3 += 36; } } for (; p < outch; p++) { const float* kernel0 = ( const float* )kernel_tm + p * inch * 36; float* ktmp = kernel_tm_test + (p / 8 + (p % 8) / 4 + p % 4) * inch * 32; for (int q = 0; q < inch; q++) { ktmp[0] = kernel0[r * 4 + 0]; ktmp[1] = kernel0[r * 4 + 1]; ktmp[2] = kernel0[r * 4 + 2]; ktmp[3] = kernel0[r * 4 + 3]; ktmp += 4; kernel0 += 36; } } kernel_tm_test += 4 * inch * outch; } free(kernel_tm); } int wino_conv_hcl_prerun(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param) { int batch = input_tensor->dims[0]; int input_c = input_tensor->dims[1]; int input_h = input_tensor->dims[2]; int input_w = input_tensor->dims[3]; int output_c = output_tensor->dims[1]; int output_h = output_tensor->dims[2]; int output_w = output_tensor->dims[3]; int pad_h = param->pad_h0; int pad_w = param->pad_w0; float* kernel = ( float* )filter_tensor->data; if (!priv_info->external_interleave_mem) { int mem_size = get_private_mem_size(filter_tensor, param); void* mem = sys_malloc(mem_size); priv_info->interleave_buffer = mem; priv_info->interleave_buffer_size = mem_size; } int block_h = (output_h + TILE - 1) / TILE; int block_w = (output_w + TILE - 1) / TILE; int block = block_h * block_w; int padded_inh = TILE * block_h + 2 * pad_h; int padded_inw = TILE * block_w + 2 * pad_w; int pad_inhw = padded_inh * padded_inw; int outw = block_w * TILE; int outh = block_h * TILE; priv_info->input_pad = ( float* )sys_malloc(batch * input_c * pad_inhw * sizeof(float)); memset(priv_info->input_pad, 0, batch * input_c * pad_inhw * sizeof(float)); priv_info->dot_block = ( float* )sys_malloc(ELEM_SIZE * block * output_c * sizeof(float)); priv_info->transform_input = ( float* )sys_malloc(ELEM_SIZE * block * input_c * sizeof(float)); priv_info->output_bordered = NULL; if (outw != output_w || outh != output_h) { priv_info->output_bordered = ( float* )sys_malloc(outw * outh * output_c * sizeof(float)); } conv3x3s1_winograd43_transform_kernel_sse(kernel, ( float* )priv_info->interleave_buffer, input_c, output_c); return 0; } int wino_conv_hcl_postrun(struct conv_priv_info* priv_info) { if (!priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = NULL; } if (priv_info->input_pad) { sys_free(priv_info->input_pad); priv_info->input_pad = NULL; } if (priv_info->dot_block) { sys_free(priv_info->dot_block); priv_info->dot_block = NULL; } if (priv_info->transform_input) { sys_free(priv_info->transform_input); priv_info->transform_input = NULL; } if (priv_info->output_bordered) { sys_free(priv_info->output_bordered); priv_info->output_bordered = NULL; } return 0; } int wino_conv_hcl_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param, int num_thread, int cpu_affinity) { /* param */ // TLOG_ERR("wino run\n"); int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int pad_h0 = param->pad_h0; int pad_w0 = param->pad_w0; int act_type = param->activation; int group = param->group; int batch = input_tensor->dims[0]; int in_c = input_tensor->dims[1]; int in_c_g = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int input_size = in_c * in_h * in_w; int input_size_g = in_c_g * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int out_c = output_tensor->dims[1]; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; int out_hw = out_h * out_w; int output_size = out_c * out_h * out_w; int out_c_align = ((out_c + 3) & -4); /* wino param */ int block_h = (out_h + TILE - 1) / TILE; int block_w = (out_w + TILE - 1) / TILE; int block_hw = block_h * block_w; int padded_in_h = block_h * TILE + 2 * pad_h0; int padded_in_w = block_w * TILE + 2 * pad_h0; int padded_in_hw = padded_in_h * padded_in_w; /* buffer addr */ float* input = ( float* )input_tensor->data; float* output = ( float* )output_tensor->data; float* biases = NULL; if (bias_tensor != NULL) biases = ( float* )bias_tensor->data; pad_0_align_3D(priv_info->input_pad, input, in_h, in_w, padded_in_h, padded_in_w, in_c, pad_h0, pad_w0); for (int i = 0; i < batch; i++) { for (int g = 0; g < group; g++) { conv3x3s1_winograd43_sse(priv_info->input_pad + i * input_size + g * input_size_g, output, priv_info->interleave_buffer, priv_info->dot_block, priv_info->transform_input, priv_info->output_bordered, biases, padded_in_w, padded_in_h, in_c, out_w, out_h, out_c, num_thread); } } if (act_type >= 0) { relu(output, batch * output_size, act_type); } return 0; }
omp-loop-invert.c
/***************************************************************************** Example : omp-loop-invert.c Objective : Write an OpenMP Program to demonstrate Performance improvement by doing the loop inverting. Input : a) Number of threads b) Size of matrices (numofrows and noofcols ) Output : Time taken for the computation. Created : Aug 2011. Author : RarchK *********************************************************************************/ #include <stdio.h> #include <sys/time.h> #include <omp.h> #include<math.h> #include <stdlib.h> /* Main Program */ main(int argc,char **argv) { int i,j,Noofthreads,Matsize; float **Matrix; struct timeval TimeValue_Start, TimeValue_Start1; struct timezone TimeZone_Start, TimeZone_Start1; struct timeval TimeValue_Final, TimeValue_Final1; struct timezone TimeZone_Final, TimeZone_Final1; long time_start, time_end; double time_overhead1,time_overhead2; printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Email : RarchK"); printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Objective : OpenMP Program to demonstrate Performance improvement "); printf("\n\t\t by doing the loop inverting. ."); printf("\n\t\t..........................................................................\n"); /*i Checking for command line arguments */ if( argc != 3 ){ printf("\t\t Very Few Arguments\n "); printf("\t\t Syntax : exec <Threads> <matrix-size>\n"); exit(-1); } Noofthreads=atoi(argv[1]); Matsize=atoi(argv[2]); if ((Noofthreads!=1) && (Noofthreads!=2) && (Noofthreads!=4) && (Noofthreads!=8) && (Noofthreads!= 16) ) { printf("\n Number of threads should be 1,2,4,8 or 16 for the execution of program. \n\n"); exit(-1); } /* printf("\n\t\t Enter the size of the Matrix \n"); scanf("%d",&Matsize);*/ printf("\n\t\t Threads : %d",Noofthreads); printf("\n\t\t Matrix Size : %d",Matsize); /* Read the input */ Matrix = (float **)malloc( Matsize *sizeof(float *)); for(i=0 ; i<Matsize ; i++) { Matrix[i] = (float *)malloc(Matsize * sizeof(float)); for(j=0; j<Matsize; j++) { Matrix[i][j] = cos(i*1.0) ; } } /* ....................................................................................... This section parallelizes the sequential for loop into Parallel for loop. Because of the data dependency between the two rows, the two rows cannot be updated simultaneously. That is the loop index j can be parallelized but index i cannot. If the Parallel for inserted before the inner loop, the resulting Parallel program execute correctly, but it may not exhibits good performance. (Matsize-1) fork/join steps required. ........................................................................................*/ gettimeofday(&TimeValue_Start, &TimeZone_Start); omp_set_num_threads(Noofthreads); for(i = 1; i < Matsize ; i++){ #pragma omp parallel for for(j = 1 ;j < Matsize;j++) { Matrix[i][j] =2 * Matrix[i-1][j]; } } gettimeofday(&TimeValue_Final, &TimeZone_Final); time_start = TimeValue_Start.tv_sec * 1000000 + TimeValue_Start.tv_usec; time_end = TimeValue_Final.tv_sec * 1000000 + TimeValue_Final.tv_usec; time_overhead1 = (time_end - time_start)/1000000.0; /* ....................................................................................... This section parallelizes the sequential for loop into Parallel for loop. Because of the data dependency between the two rows the two rows cannot be updated simultaniously. That means the loop index j can be parallelized but i cannot. if the loop is invert and then apply parallel for before the outer loop. only single fork/join step required. ........................................................................................*/ time_start=0; time_end=0; gettimeofday(&TimeValue_Start1, &TimeZone_Start1); #pragma omp parallel for private(i) for(j = 1 ;j < Matsize;j++) { for(i = 1; i < Matsize ; i++){ Matrix[i][j] =2 * Matrix[i-1][j]; } } gettimeofday(&TimeValue_Final1, &TimeZone_Final1); time_start = TimeValue_Start1.tv_sec * 1000000 + TimeValue_Start1.tv_usec; time_end = TimeValue_Final1.tv_sec * 1000000 + TimeValue_Final1.tv_usec; time_overhead2 = (time_end - time_start)/1000000.0; printf("\n\n\t\t Time Taken in Seconds (By Parallel Computation ) :%lf ", time_overhead1); printf("\n\t\t Time Taken in Seconds (By Inverting loop Computation ) :%lf \n ", time_overhead2); printf("\n\t\t..........................................................................\n"); }
recursive.h
#pragma once #include <algorithm> #include <cinttypes> #include <iostream> #include <vector> #include <random> #include <gms/common/format.h> #include "output.h" /** * Parallel set-based implementation of the k-clique-star algorithm [1]. * * [1]: https://doi.org/10.1007/978-3-030-01768-2_13 */ namespace GMS::KCliqueStar::Par { template<class SGraph, OutputMode TOutputMode> void CliqueStar(const SGraph &g, int32_t k, Seq::Output<typename SGraph::Set, TOutputMode> &output) { assert(k > 0); size_t num_nodes = g.num_nodes(); ListOutputPar<typename SGraph::Set, TOutputMode, 2> output_par; auto output_writer = output_par.writer(); #pragma omp parallel for schedule(dynamic, 64) firstprivate(output_writer) for (NodeId u = 0; u < num_nodes; ++u) { RoaringSet curClique(u); Seq::RecursiveStepCliqueStar(g, k - 1, curClique, g.out_neigh(u), output_writer); } output = std::move(output_par.collect()); std::cout << "total " << k << "-cliques: " << output.size() << std::endl; } template <class SGraph> auto CliqueStarList(const SGraph &g, int32_t k) { Seq::Output<typename SGraph::Set, OutputMode::List> output; Par::CliqueStar<SGraph>(g, k, output); //return Seq::remove_redundancy(output); return output; } }
Example_array_sections.1.c
/* * @@name: array_sections.1c * @@type: C * @@compilable: no * @@linkable: no * @@expect: failure * @@version: omp_4.0 */ void foo () { int A[30]; #pragma omp target data map( A[0:4] ) { /* Cannot map distinct parts of the same array */ #pragma omp target map( A[7:20] ) { A[2] = 0; } } }
gm_bfs_template.h
#ifndef GM_BFS_TEMPLATE_H #define GM_BFS_TEMPLATE_H #include <omp.h> #include <string.h> #include <map> #include <set> #include "gm_graph.h" #include "gm_atomic_wrapper.h" #include "gm_bitmap.h" // todo: consideration for non small-world graph template<typename level_t, bool use_multithread, bool has_navigator, bool use_reverse_edge, bool save_child> class gm_bfs_template { public: gm_bfs_template(gm_graph& _G) : G(_G) { visited_bitmap = NULL; // bitmap visited_level = NULL; //global_curr_level = NULL; //global_next_level = NULL; //global_queue = NULL; thread_local_next_level = NULL; down_edge_array = NULL; down_edge_set = NULL; if (save_child) { down_edge_set = new std::set<edge_t>(); } } virtual ~gm_bfs_template() { delete visited_bitmap; delete visited_level; //delete [] global_queue; delete [] thread_local_next_level; delete down_edge_set; delete down_edge_array; } void prepare(node_t root_node, int max_num_thread) { int num_thread; if (use_multithread) { num_thread = max_num_thread; } else { num_thread = 1; } is_finished = false; curr_level = 0; root = root_node; state = ST_SMALL; assert(root != gm_graph::NIL_NODE); //global_queue = new node_t[G.num_nodes()]; //global_curr_level = global_queue; //global_next_level = NULL; // create local queues thread_local_next_level = new std::vector<node_t>[num_thread]; for (int i = 0; i < num_thread; i++) thread_local_next_level[i].reserve(THRESHOLD2); } void do_bfs_forward() { //--------------------------------- // prepare root node //--------------------------------- curr_level = 0; curr_count = 0; next_count = 0; small_visited[root] = curr_level; curr_count++; global_vector.push_back(root); global_curr_level_begin = 0; global_next_level_begin = curr_count; level_count.push_back(curr_count); level_queue_begin.push_back(global_curr_level_begin); bool is_done = false; while (!is_done) { switch (state) { case ST_SMALL: { for (node_t i = 0; i < curr_count; i++) { node_t t = global_vector[global_curr_level_begin + i]; iterate_neighbor_small(t); visit_fw(t); // visit after iteration. in that way, one can check down-neighbors quite easily } break; } case ST_QUE: { if (use_multithread) // do it in parallel { #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp for nowait for (node_t i = 0; i < curr_count; i++) { //node_t t = global_curr_level[i]; node_t t = global_vector[global_curr_level_begin + i]; iterate_neighbor_que(t, tid); visit_fw(t); } finish_thread_que(tid); } } else { // do it in sequential int tid = 0; for (node_t i = 0; i < curr_count; i++) { //node_t t = global_curr_level[i]; node_t t = global_vector[global_curr_level_begin + i]; iterate_neighbor_que(t, tid); visit_fw(t); } finish_thread_que(tid); } break; } case ST_Q2R: { if (use_multithread) { // do it in parallel #pragma omp parallel { node_t local_cnt = 0; #pragma omp for nowait for (node_t i = 0; i < curr_count; i++) { //node_t t = global_curr_level[i]; node_t t = global_vector[global_curr_level_begin + i]; iterate_neighbor_rd(t, local_cnt); visit_fw(t); } finish_thread_rd(local_cnt); } } else { // do it sequentially node_t local_cnt = 0; for (node_t i = 0; i < curr_count; i++) { //node_t t = global_curr_level[i]; node_t t = global_vector[global_curr_level_begin + i]; iterate_neighbor_rd(t, local_cnt); visit_fw(t); } finish_thread_rd(local_cnt); } break; } case ST_RD: { if (use_multithread) { // do it in parallel #pragma omp parallel { node_t local_cnt = 0; #pragma omp for nowait schedule(dynamic,128) for (node_t t = 0; t < G.num_nodes(); t++) { if (visited_level[t] == curr_level) { iterate_neighbor_rd(t, local_cnt); visit_fw(t); } } finish_thread_rd(local_cnt); } } else { // do it in sequential node_t local_cnt = 0; for (node_t t = 0; t < G.num_nodes(); t++) { if (visited_level[t] == curr_level) { iterate_neighbor_rd(t, local_cnt); visit_fw(t); } } finish_thread_rd(local_cnt); } break; } case ST_R2Q: { if (use_multithread) { // do it in parallel #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp for nowait schedule(dynamic,128) for (node_t t = 0; t < G.num_nodes(); t++) { if (visited_level[t] == curr_level) { iterate_neighbor_que(t, tid); visit_fw(t); } } finish_thread_que(tid); } } else { int tid = 0; for (node_t t = 0; t < G.num_nodes(); t++) { if (visited_level[t] == curr_level) { iterate_neighbor_que(t, tid); visit_fw(t); } } finish_thread_que(tid); } break; } } // end of switch do_end_of_level_fw(); is_done = get_next_state(); } // end of while } void do_bfs_reverse() { // This function should be called only after do_bfs_foward has finished. // assumption: small-world graph level_t& level = curr_level; while (true) { node_t count = level_count[level]; //node_t* queue_ptr = level_start_ptr[level]; node_t* queue_ptr; node_t begin_idx = level_queue_begin[level]; if (begin_idx == -1) { queue_ptr = NULL; } else { queue_ptr = & (global_vector[begin_idx]); } if (queue_ptr == NULL) { #pragma omp parallel if (use_multithread) { #pragma omp for nowait schedule(dynamic,128) for (node_t i = 0; i < G.num_nodes(); i++) { if (visited_level[i] != curr_level) continue; visit_rv(i); } } } else { #pragma omp parallel if (use_multithread) { #pragma omp for nowait for (node_t i = 0; i < count; i++) { node_t u = queue_ptr[i]; visit_rv(u); } } } do_end_of_level_rv(); if (level == 0) break; level--; } } bool is_down_edge(edge_t idx) { if (state == ST_SMALL) return (down_edge_set->find(idx) != down_edge_set->end()); else return down_edge_array[idx]; } protected: virtual void visit_fw(node_t t)=0; virtual void visit_rv(node_t t)=0; virtual bool check_navigator(node_t t, edge_t nx)=0; virtual void do_end_of_level_fw() { } virtual void do_end_of_level_rv() { } node_t get_root() { return root; } level_t get_level(node_t t) { // GCC expansion if (__builtin_expect((state == ST_SMALL), 0)) { if (small_visited.find(t) == small_visited.end()) return __INVALID_LEVEL; else return small_visited[t]; } else { return visited_level[t]; } } level_t get_curr_level() { return curr_level; } private: bool get_next_state() { const char* state_name[5] = {"SMALL","QUEUE","Q2R","RD","R2Q"}; if (next_count == 0) return true; // BFS is finished int next_state = state; switch (state) { case ST_SMALL: if (next_count >= THRESHOLD1) { prepare_que(); next_state = ST_QUE; } break; case ST_QUE: if ((next_count >= THRESHOLD2) && (next_count >= curr_count*5)) { prepare_read(); next_state = ST_Q2R; } break; case ST_Q2R: next_state = ST_RD; break; case ST_RD: if (next_count <= (2 * curr_count)) { next_state = ST_R2Q; } break; case ST_R2Q: next_state = ST_QUE; break; } finish_level(state); state = next_state; return false; } void finish_level(int state) { if ((state == ST_RD) || (state == ST_Q2R)) { // output queue is not valid } else { // move output queue //node_t* temp = &(global_next_level[next_count]); //global_curr_level = global_next_level; //global_next_level = temp; global_curr_level_begin = global_next_level_begin; global_next_level_begin = global_next_level_begin + next_count; } curr_count = next_count; next_count = 0; curr_level++; // save 'new current' level status level_count.push_back(curr_count); if ((state == ST_RD) || (state == ST_Q2R)) { //level_start_ptr.push_back(NULL); level_queue_begin.push_back(-1); } else { //level_start_ptr.push_back(global_curr_level); level_queue_begin.push_back(global_curr_level_begin); } } void get_range(edge_t& begin, edge_t& end, node_t t) { if (use_reverse_edge) { begin = G.r_begin[t]; end = G.r_begin[t + 1]; } else { begin = G.begin[t]; end = G.begin[t + 1]; } } node_t get_node(edge_t& n) { if (use_reverse_edge) { return G.r_node_idx[n]; } else { return G.node_idx[n]; } } void iterate_neighbor_small(node_t t) { edge_t begin; edge_t end; get_range(begin, end, t); for (edge_t nx = begin; nx < end; nx++) { node_t u = get_node(nx); // check visited if (small_visited.find(u) == small_visited.end()) { if (has_navigator) { if (check_navigator(u, nx) == false) continue; } if (save_child) { save_down_edge_small(nx); } small_visited[u] = curr_level + 1; //global_next_level[next_count++] = u; global_vector.push_back(u); next_count++; } else if (save_child) { if (has_navigator) { if (check_navigator(u, nx) == false) continue; } if (small_visited[u] == (curr_level+1)){ save_down_edge_small(nx); } } } } // should be used only when save_child is enabled void save_down_edge_small(edge_t idx) { down_edge_set->insert(idx); } void save_down_edge_large(edge_t idx) { down_edge_array[idx] = 1; } void prepare_que() { global_vector.reserve(G.num_nodes()); // create bitmap and edges visited_bitmap = new unsigned char[(G.num_nodes() + 7) / 8]; visited_level = new level_t[G.num_nodes()]; if (save_child) { down_edge_array = new unsigned char[G.num_edges()]; } if (use_multithread) { #pragma omp parallel { #pragma omp for nowait for (node_t i = 0; i < (G.num_nodes() + 7) / 8; i++) visited_bitmap[i] = 0; #pragma omp for nowait for (node_t i = 0; i < G.num_nodes(); i++) visited_level[i] = __INVALID_LEVEL; if (save_child) { #pragma omp for nowait for (edge_t i = 0; i < G.num_edges(); i++) down_edge_array[i] = 0; } } } else { for (node_t i = 0; i < (G.num_nodes() + 7) / 8; i++) visited_bitmap[i] = 0; for (node_t i = 0; i < G.num_nodes(); i++) visited_level[i] = __INVALID_LEVEL; if (save_child) { for (edge_t i = 0; i < G.num_edges(); i++) down_edge_array[i] = 0; } } typename std::map<node_t, level_t>::iterator II; for (II = small_visited.begin(); II != small_visited.end(); II++) { node_t u = II->first; level_t lev = II->second; _gm_set_bit(visited_bitmap, u); visited_level[u] = lev; } if (save_child) { typename std::set<edge_t>::iterator J; for (J = down_edge_set->begin(); J != down_edge_set->end(); J++) { down_edge_array[*J] = 1; } } } void iterate_neighbor_que(node_t t, int tid) { edge_t begin; edge_t end; get_range(begin, end, t); for (edge_t nx = begin; nx < end; nx++) { node_t u = get_node(nx); // check visited bitmap // test & test& set if (_gm_get_bit(visited_bitmap, u) == 0) { if (has_navigator) { if (check_navigator(u, nx) == false) continue; } bool re_check_result; if (use_multithread) { re_check_result = _gm_set_bit_atomic(visited_bitmap, u); } else { re_check_result = true; _gm_set_bit(visited_bitmap, u); } if (save_child) { save_down_edge_large(nx); } if (re_check_result) { // add to local q thread_local_next_level[tid].push_back(u); visited_level[u] = (curr_level + 1); } } else if (save_child) { if (has_navigator) { if (check_navigator(u, nx) == false) continue; } if (visited_level[u] == (curr_level +1)) { save_down_edge_large(nx); } } } } void finish_thread_que(int tid) { node_t local_cnt = thread_local_next_level[tid].size(); //copy curr_cnt to next_cnt if (local_cnt > 0) { node_t old_idx = _gm_atomic_fetch_and_add_node(&next_count, local_cnt); // copy to global vector memcpy(&(global_vector[global_next_level_begin + old_idx]), &(thread_local_next_level[tid][0]), local_cnt * sizeof(node_t)); } thread_local_next_level[tid].clear(); } void prepare_read() { // nothing to do } void iterate_neighbor_rd(node_t t, node_t& local_cnt) { edge_t begin; edge_t end; get_range(begin, end, t); for (edge_t nx = begin; nx < end; nx++) { node_t u = get_node(nx); // check visited bitmap // test & test& set if (_gm_get_bit(visited_bitmap, u) == 0) { if (has_navigator) { if (check_navigator(u, nx) == false) continue; } bool re_check_result; if (use_multithread) { re_check_result = _gm_set_bit_atomic(visited_bitmap, u); } else { re_check_result = true; _gm_set_bit(visited_bitmap, u); } if (save_child) { save_down_edge_large(nx); } if (re_check_result) { // add to local q visited_level[u] = curr_level + 1; local_cnt++; } } else if (save_child) { if (has_navigator) { if (check_navigator(u, nx) == false) continue; } if (visited_level[u] == (curr_level +1)) { save_down_edge_large(nx); } } } } void finish_thread_rd(node_t local_cnt) { _gm_atomic_fetch_and_add_node(&next_count, local_cnt); } //----------------------------------------------------- //----------------------------------------------------- static const int ST_SMALL = 0; static const int ST_QUE = 1; static const int ST_Q2R = 2; static const int ST_RD = 3; static const int ST_R2Q = 4; static const int THRESHOLD1 = 128; // single threaded static const int THRESHOLD2 = 1024; // move to RD-based // not -1. //(why? because curr_level-1 might be -1, when curr_level = 0) static const level_t __INVALID_LEVEL = -2; int state; unsigned char* visited_bitmap; // bitmap level_t* visited_level; // assumption: small_world graph bool is_finished; level_t curr_level; node_t root; gm_graph& G; node_t curr_count; node_t next_count; std::map<node_t, level_t> small_visited; std::set<edge_t>* down_edge_set; unsigned char* down_edge_array; //node_t* global_next_level; //node_t* global_curr_level; //node_t* global_queue; std::vector<node_t> global_vector; node_t global_curr_level_begin; node_t global_next_level_begin; //std::vector<node_t*> level_start_ptr; std::vector<node_t> level_queue_begin; std::vector<node_t> level_count; std::vector<node_t>* thread_local_next_level; }; #endif
dynprog.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 int, default size is 50. */ #include "dynprog.h" /* Array initialization. */ static void init_array(int length, DATA_TYPE POLYBENCH_2D(c,LENGTH,LENGTH,length,length), DATA_TYPE POLYBENCH_2D(W,LENGTH,LENGTH,length,length)) { int i, j; for (i = 0; i < length; i++) for (j = 0; j < length; j++) { c[i][j] = i*j % 2; W[i][j] = ((DATA_TYPE) i-j) / length; } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(DATA_TYPE out) { fprintf (stderr, DATA_PRINTF_MODIFIER, out); fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_dynprog(int tsteps, int length, DATA_TYPE POLYBENCH_2D(c,LENGTH,LENGTH,length,length), DATA_TYPE POLYBENCH_2D(W,LENGTH,LENGTH,length,length), DATA_TYPE POLYBENCH_3D(sum_c,LENGTH,LENGTH,LENGTH,length,length,length), DATA_TYPE *out) { int iter, i, j, k; DATA_TYPE out_l = 0; #pragma scop #pragma omp parallel { #pragma omp master { for (iter = 0; iter < _PB_TSTEPS; iter++) { #pragma omp for private (j) for (i = 0; i <= _PB_LENGTH - 1; i++) for (j = 0; j <= _PB_LENGTH - 1; j++) c[i][j] = 0; #pragma omp for private (j, k) for (i = 0; i <= _PB_LENGTH - 2; i++) { for (j = i + 1; j <= _PB_LENGTH - 1; j++) { sum_c[i][j][i] = 0; for (k = i + 1; k <= j-1; k++) sum_c[i][j][k] = sum_c[i][j][k - 1] + c[i][k] + c[k][j]; c[i][j] = sum_c[i][j][j-1] + W[i][j]; } } out_l += c[0][_PB_LENGTH - 1]; } } } #pragma endscop *out = out_l; } int main(int argc, char** argv) { /* Retrieve problem size. */ int length = LENGTH; int tsteps = TSTEPS; /* Variable declaration/allocation. */ DATA_TYPE out; POLYBENCH_3D_ARRAY_DECL(sum_c,DATA_TYPE,LENGTH,LENGTH,LENGTH,length,length,length); POLYBENCH_2D_ARRAY_DECL(c,DATA_TYPE,LENGTH,LENGTH,length,length); POLYBENCH_2D_ARRAY_DECL(W,DATA_TYPE,LENGTH,LENGTH,length,length); /* Initialize array(s). */ init_array (length, POLYBENCH_ARRAY(c), POLYBENCH_ARRAY(W)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_dynprog (tsteps, length, POLYBENCH_ARRAY(c), POLYBENCH_ARRAY(W), POLYBENCH_ARRAY(sum_c), &out); /* 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(out)); /* Be clean. */ POLYBENCH_FREE_ARRAY(sum_c); POLYBENCH_FREE_ARRAY(c); POLYBENCH_FREE_ARRAY(W); return 0; }
c-typeck.c
/* Build expressions with type checking for C compiler. Copyright (C) 1987-2015 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ /* This file is part of the C front end. It contains routines to build C expressions given their operands, including computing the types of the result, C-specific error checks, and some optimization. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "hash-set.h" #include "vec.h" #include "symtab.h" #include "input.h" #include "alias.h" #include "double-int.h" #include "machmode.h" #include "inchash.h" #include "real.h" #include "fixed-value.h" #include "tree.h" #include "fold-const.h" #include "stor-layout.h" #include "trans-mem.h" #include "varasm.h" #include "stmt.h" #include "langhooks.h" #include "c-tree.h" #include "c-lang.h" #include "flags.h" #include "intl.h" #include "target.h" #include "tree-iterator.h" #include "bitmap.h" #include "predict.h" #include "vec.h" #include "hashtab.h" #include "hash-set.h" #include "machmode.h" #include "hard-reg-set.h" #include "input.h" #include "function.h" #include "gimple-expr.h" #include "gimplify.h" #include "tree-inline.h" #include "omp-low.h" #include "c-family/c-objc.h" #include "c-family/c-common.h" #include "c-family/c-ubsan.h" #include "cilk.h" #include "wide-int.h" #include "gomp-constants.h" /* Possible cases of implicit bad conversions. Used to select diagnostic messages in convert_for_assignment. */ enum impl_conv { ic_argpass, ic_assign, ic_init, ic_return }; /* The level of nesting inside "__alignof__". */ int in_alignof; /* The level of nesting inside "sizeof". */ int in_sizeof; /* The level of nesting inside "typeof". */ int in_typeof; /* The argument of last parsed sizeof expression, only to be tested if expr.original_code == SIZEOF_EXPR. */ tree c_last_sizeof_arg; /* Nonzero if we might need to print a "missing braces around initializer" message within this initializer. */ static int found_missing_braces; static int require_constant_value; static int require_constant_elements; static bool null_pointer_constant_p (const_tree); static tree qualify_type (tree, tree); static int tagged_types_tu_compatible_p (const_tree, const_tree, bool *, bool *); static int comp_target_types (location_t, tree, tree); static int function_types_compatible_p (const_tree, const_tree, bool *, bool *); static int type_lists_compatible_p (const_tree, const_tree, bool *, bool *); static tree lookup_field (tree, tree); static int convert_arguments (location_t, vec<location_t>, tree, vec<tree, va_gc> *, vec<tree, va_gc> *, tree, tree); static tree pointer_diff (location_t, tree, tree); static tree convert_for_assignment (location_t, location_t, tree, tree, tree, enum impl_conv, bool, tree, tree, int); static tree valid_compound_expr_initializer (tree, tree); static void push_string (const char *); static void push_member_name (tree); static int spelling_length (void); static char *print_spelling (char *); static void warning_init (location_t, int, const char *); static tree digest_init (location_t, tree, tree, tree, bool, bool, int); static void output_init_element (location_t, tree, tree, bool, tree, tree, int, bool, struct obstack *); static void output_pending_init_elements (int, struct obstack *); static int set_designator (location_t, int, struct obstack *); static void push_range_stack (tree, struct obstack *); static void add_pending_init (location_t, tree, tree, tree, bool, struct obstack *); static void set_nonincremental_init (struct obstack *); static void set_nonincremental_init_from_string (tree, struct obstack *); static tree find_init_member (tree, struct obstack *); static void readonly_warning (tree, enum lvalue_use); static int lvalue_or_else (location_t, const_tree, enum lvalue_use); static void record_maybe_used_decl (tree); static int comptypes_internal (const_tree, const_tree, bool *, bool *); /* Return true if EXP is a null pointer constant, false otherwise. */ static bool null_pointer_constant_p (const_tree expr) { /* This should really operate on c_expr structures, but they aren't yet available everywhere required. */ tree type = TREE_TYPE (expr); return (TREE_CODE (expr) == INTEGER_CST && !TREE_OVERFLOW (expr) && integer_zerop (expr) && (INTEGRAL_TYPE_P (type) || (TREE_CODE (type) == POINTER_TYPE && VOID_TYPE_P (TREE_TYPE (type)) && TYPE_QUALS (TREE_TYPE (type)) == TYPE_UNQUALIFIED))); } /* EXPR may appear in an unevaluated part of an integer constant expression, but not in an evaluated part. Wrap it in a C_MAYBE_CONST_EXPR, or mark it with TREE_OVERFLOW if it is just an INTEGER_CST and we cannot create a C_MAYBE_CONST_EXPR. */ static tree note_integer_operands (tree expr) { tree ret; if (TREE_CODE (expr) == INTEGER_CST && in_late_binary_op) { ret = copy_node (expr); TREE_OVERFLOW (ret) = 1; } else { ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL_TREE, expr); C_MAYBE_CONST_EXPR_INT_OPERANDS (ret) = 1; } return ret; } /* Having checked whether EXPR may appear in an unevaluated part of an integer constant expression and found that it may, remove any C_MAYBE_CONST_EXPR noting this fact and return the resulting expression. */ static inline tree remove_c_maybe_const_expr (tree expr) { if (TREE_CODE (expr) == C_MAYBE_CONST_EXPR) return C_MAYBE_CONST_EXPR_EXPR (expr); else return expr; } /* This is a cache to hold if two types are compatible or not. */ struct tagged_tu_seen_cache { const struct tagged_tu_seen_cache * next; const_tree t1; const_tree t2; /* The return value of tagged_types_tu_compatible_p if we had seen these two types already. */ int val; }; static const struct tagged_tu_seen_cache * tagged_tu_seen_base; static void free_all_tagged_tu_seen_up_to (const struct tagged_tu_seen_cache *); /* Do `exp = require_complete_type (exp);' to make sure exp does not have an incomplete type. (That includes void types.) */ tree require_complete_type (tree value) { tree type = TREE_TYPE (value); if (error_operand_p (value)) return error_mark_node; /* First, detect a valid value with a complete type. */ if (COMPLETE_TYPE_P (type)) return value; c_incomplete_type_error (value, type); return error_mark_node; } /* Print an error message for invalid use of an incomplete type. VALUE is the expression that was used (or 0 if that isn't known) and TYPE is the type that was invalid. */ void c_incomplete_type_error (const_tree value, const_tree type) { const char *type_code_string; /* Avoid duplicate error message. */ if (TREE_CODE (type) == ERROR_MARK) return; if (value != 0 && (TREE_CODE (value) == VAR_DECL || TREE_CODE (value) == PARM_DECL)) error ("%qD has an incomplete type", value); else { retry: /* We must print an error message. Be clever about what it says. */ switch (TREE_CODE (type)) { case RECORD_TYPE: type_code_string = "struct"; break; case UNION_TYPE: type_code_string = "union"; break; case ENUMERAL_TYPE: type_code_string = "enum"; break; case VOID_TYPE: error ("invalid use of void expression"); return; case ARRAY_TYPE: if (TYPE_DOMAIN (type)) { if (TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL) { error ("invalid use of flexible array member"); return; } type = TREE_TYPE (type); goto retry; } error ("invalid use of array with unspecified bounds"); return; default: gcc_unreachable (); } if (TREE_CODE (TYPE_NAME (type)) == IDENTIFIER_NODE) error ("invalid use of undefined type %<%s %E%>", type_code_string, TYPE_NAME (type)); else /* If this type has a typedef-name, the TYPE_NAME is a TYPE_DECL. */ error ("invalid use of incomplete typedef %qD", TYPE_NAME (type)); } } /* Given a type, apply default promotions wrt unnamed function arguments and return the new type. */ tree c_type_promotes_to (tree type) { tree ret = NULL_TREE; if (TYPE_MAIN_VARIANT (type) == float_type_node) ret = double_type_node; else if (c_promoting_integer_type_p (type)) { /* Preserve unsignedness if not really getting any wider. */ if (TYPE_UNSIGNED (type) && (TYPE_PRECISION (type) == TYPE_PRECISION (integer_type_node))) ret = unsigned_type_node; else ret = integer_type_node; } if (ret != NULL_TREE) return (TYPE_ATOMIC (type) ? c_build_qualified_type (ret, TYPE_QUAL_ATOMIC) : ret); return type; } /* Return true if between two named address spaces, whether there is a superset named address space that encompasses both address spaces. If there is a superset, return which address space is the superset. */ static bool addr_space_superset (addr_space_t as1, addr_space_t as2, addr_space_t *common) { if (as1 == as2) { *common = as1; return true; } else if (targetm.addr_space.subset_p (as1, as2)) { *common = as2; return true; } else if (targetm.addr_space.subset_p (as2, as1)) { *common = as1; return true; } else return false; } /* Return a variant of TYPE which has all the type qualifiers of LIKE as well as those of TYPE. */ static tree qualify_type (tree type, tree like) { addr_space_t as_type = TYPE_ADDR_SPACE (type); addr_space_t as_like = TYPE_ADDR_SPACE (like); addr_space_t as_common; /* If the two named address spaces are different, determine the common superset address space. If there isn't one, raise an error. */ if (!addr_space_superset (as_type, as_like, &as_common)) { as_common = as_type; error ("%qT and %qT are in disjoint named address spaces", type, like); } return c_build_qualified_type (type, TYPE_QUALS_NO_ADDR_SPACE (type) | TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (like) | ENCODE_QUAL_ADDR_SPACE (as_common)); } /* Return true iff the given tree T is a variable length array. */ bool c_vla_type_p (const_tree t) { if (TREE_CODE (t) == ARRAY_TYPE && C_TYPE_VARIABLE_SIZE (t)) return true; return false; } /* Return the composite type of two compatible types. We assume that comptypes has already been done and returned nonzero; if that isn't so, this may crash. In particular, we assume that qualifiers match. */ tree composite_type (tree t1, tree t2) { enum tree_code code1; enum tree_code code2; tree attributes; /* Save time if the two types are the same. */ if (t1 == t2) return t1; /* If one type is nonsense, use the other. */ if (t1 == error_mark_node) return t2; if (t2 == error_mark_node) return t1; code1 = TREE_CODE (t1); code2 = TREE_CODE (t2); /* Merge the attributes. */ attributes = targetm.merge_type_attributes (t1, t2); /* If one is an enumerated type and the other is the compatible integer type, the composite type might be either of the two (DR#013 question 3). For consistency, use the enumerated type as the composite type. */ if (code1 == ENUMERAL_TYPE && code2 == INTEGER_TYPE) return t1; if (code2 == ENUMERAL_TYPE && code1 == INTEGER_TYPE) return t2; gcc_assert (code1 == code2); switch (code1) { case POINTER_TYPE: /* For two pointers, do this recursively on the target type. */ { tree pointed_to_1 = TREE_TYPE (t1); tree pointed_to_2 = TREE_TYPE (t2); tree target = composite_type (pointed_to_1, pointed_to_2); t1 = build_pointer_type_for_mode (target, TYPE_MODE (t1), false); t1 = build_type_attribute_variant (t1, attributes); return qualify_type (t1, t2); } case ARRAY_TYPE: { tree elt = composite_type (TREE_TYPE (t1), TREE_TYPE (t2)); int quals; tree unqual_elt; tree d1 = TYPE_DOMAIN (t1); tree d2 = TYPE_DOMAIN (t2); bool d1_variable, d2_variable; bool d1_zero, d2_zero; bool t1_complete, t2_complete; /* We should not have any type quals on arrays at all. */ gcc_assert (!TYPE_QUALS_NO_ADDR_SPACE (t1) && !TYPE_QUALS_NO_ADDR_SPACE (t2)); t1_complete = COMPLETE_TYPE_P (t1); t2_complete = COMPLETE_TYPE_P (t2); d1_zero = d1 == 0 || !TYPE_MAX_VALUE (d1); d2_zero = d2 == 0 || !TYPE_MAX_VALUE (d2); d1_variable = (!d1_zero && (TREE_CODE (TYPE_MIN_VALUE (d1)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d1)) != INTEGER_CST)); d2_variable = (!d2_zero && (TREE_CODE (TYPE_MIN_VALUE (d2)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d2)) != INTEGER_CST)); d1_variable = d1_variable || (d1_zero && c_vla_type_p (t1)); d2_variable = d2_variable || (d2_zero && c_vla_type_p (t2)); /* Save space: see if the result is identical to one of the args. */ if (elt == TREE_TYPE (t1) && TYPE_DOMAIN (t1) && (d2_variable || d2_zero || !d1_variable)) return build_type_attribute_variant (t1, attributes); if (elt == TREE_TYPE (t2) && TYPE_DOMAIN (t2) && (d1_variable || d1_zero || !d2_variable)) return build_type_attribute_variant (t2, attributes); if (elt == TREE_TYPE (t1) && !TYPE_DOMAIN (t2) && !TYPE_DOMAIN (t1)) return build_type_attribute_variant (t1, attributes); if (elt == TREE_TYPE (t2) && !TYPE_DOMAIN (t2) && !TYPE_DOMAIN (t1)) return build_type_attribute_variant (t2, attributes); /* Merge the element types, and have a size if either arg has one. We may have qualifiers on the element types. To set up TYPE_MAIN_VARIANT correctly, we need to form the composite of the unqualified types and add the qualifiers back at the end. */ quals = TYPE_QUALS (strip_array_types (elt)); unqual_elt = c_build_qualified_type (elt, TYPE_UNQUALIFIED); t1 = build_array_type (unqual_elt, TYPE_DOMAIN ((TYPE_DOMAIN (t1) && (d2_variable || d2_zero || !d1_variable)) ? t1 : t2)); /* Ensure a composite type involving a zero-length array type is a zero-length type not an incomplete type. */ if (d1_zero && d2_zero && (t1_complete || t2_complete) && !COMPLETE_TYPE_P (t1)) { TYPE_SIZE (t1) = bitsize_zero_node; TYPE_SIZE_UNIT (t1) = size_zero_node; } t1 = c_build_qualified_type (t1, quals); return build_type_attribute_variant (t1, attributes); } case ENUMERAL_TYPE: case RECORD_TYPE: case UNION_TYPE: if (attributes != NULL) { /* Try harder not to create a new aggregate type. */ if (attribute_list_equal (TYPE_ATTRIBUTES (t1), attributes)) return t1; if (attribute_list_equal (TYPE_ATTRIBUTES (t2), attributes)) return t2; } return build_type_attribute_variant (t1, attributes); case FUNCTION_TYPE: /* Function types: prefer the one that specified arg types. If both do, merge the arg types. Also merge the return types. */ { tree valtype = composite_type (TREE_TYPE (t1), TREE_TYPE (t2)); tree p1 = TYPE_ARG_TYPES (t1); tree p2 = TYPE_ARG_TYPES (t2); int len; tree newargs, n; int i; /* Save space: see if the result is identical to one of the args. */ if (valtype == TREE_TYPE (t1) && !TYPE_ARG_TYPES (t2)) return build_type_attribute_variant (t1, attributes); if (valtype == TREE_TYPE (t2) && !TYPE_ARG_TYPES (t1)) return build_type_attribute_variant (t2, attributes); /* Simple way if one arg fails to specify argument types. */ if (TYPE_ARG_TYPES (t1) == 0) { t1 = build_function_type (valtype, TYPE_ARG_TYPES (t2)); t1 = build_type_attribute_variant (t1, attributes); return qualify_type (t1, t2); } if (TYPE_ARG_TYPES (t2) == 0) { t1 = build_function_type (valtype, TYPE_ARG_TYPES (t1)); t1 = build_type_attribute_variant (t1, attributes); return qualify_type (t1, t2); } /* If both args specify argument types, we must merge the two lists, argument by argument. */ len = list_length (p1); newargs = 0; for (i = 0; i < len; i++) newargs = tree_cons (NULL_TREE, NULL_TREE, newargs); n = newargs; for (; p1; p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2), n = TREE_CHAIN (n)) { /* A null type means arg type is not specified. Take whatever the other function type has. */ if (TREE_VALUE (p1) == 0) { TREE_VALUE (n) = TREE_VALUE (p2); goto parm_done; } if (TREE_VALUE (p2) == 0) { TREE_VALUE (n) = TREE_VALUE (p1); goto parm_done; } /* Given wait (union {union wait *u; int *i} *) and wait (union wait *), prefer union wait * as type of parm. */ if (TREE_CODE (TREE_VALUE (p1)) == UNION_TYPE && TREE_VALUE (p1) != TREE_VALUE (p2)) { tree memb; tree mv2 = TREE_VALUE (p2); if (mv2 && mv2 != error_mark_node && TREE_CODE (mv2) != ARRAY_TYPE) mv2 = TYPE_MAIN_VARIANT (mv2); for (memb = TYPE_FIELDS (TREE_VALUE (p1)); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = TYPE_MAIN_VARIANT (mv3); if (comptypes (mv3, mv2)) { TREE_VALUE (n) = composite_type (TREE_TYPE (memb), TREE_VALUE (p2)); pedwarn (input_location, OPT_Wpedantic, "function types not truly compatible in ISO C"); goto parm_done; } } } if (TREE_CODE (TREE_VALUE (p2)) == UNION_TYPE && TREE_VALUE (p2) != TREE_VALUE (p1)) { tree memb; tree mv1 = TREE_VALUE (p1); if (mv1 && mv1 != error_mark_node && TREE_CODE (mv1) != ARRAY_TYPE) mv1 = TYPE_MAIN_VARIANT (mv1); for (memb = TYPE_FIELDS (TREE_VALUE (p2)); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = TYPE_MAIN_VARIANT (mv3); if (comptypes (mv3, mv1)) { TREE_VALUE (n) = composite_type (TREE_TYPE (memb), TREE_VALUE (p1)); pedwarn (input_location, OPT_Wpedantic, "function types not truly compatible in ISO C"); goto parm_done; } } } TREE_VALUE (n) = composite_type (TREE_VALUE (p1), TREE_VALUE (p2)); parm_done: ; } t1 = build_function_type (valtype, newargs); t1 = qualify_type (t1, t2); /* ... falls through ... */ } default: return build_type_attribute_variant (t1, attributes); } } /* Return the type of a conditional expression between pointers to possibly differently qualified versions of compatible types. We assume that comp_target_types has already been done and returned nonzero; if that isn't so, this may crash. */ static tree common_pointer_type (tree t1, tree t2) { tree attributes; tree pointed_to_1, mv1; tree pointed_to_2, mv2; tree target; unsigned target_quals; addr_space_t as1, as2, as_common; int quals1, quals2; /* Save time if the two types are the same. */ if (t1 == t2) return t1; /* If one type is nonsense, use the other. */ if (t1 == error_mark_node) return t2; if (t2 == error_mark_node) return t1; gcc_assert (TREE_CODE (t1) == POINTER_TYPE && TREE_CODE (t2) == POINTER_TYPE); /* Merge the attributes. */ attributes = targetm.merge_type_attributes (t1, t2); /* Find the composite type of the target types, and combine the qualifiers of the two types' targets. Do not lose qualifiers on array element types by taking the TYPE_MAIN_VARIANT. */ mv1 = pointed_to_1 = TREE_TYPE (t1); mv2 = pointed_to_2 = TREE_TYPE (t2); if (TREE_CODE (mv1) != ARRAY_TYPE) mv1 = TYPE_MAIN_VARIANT (pointed_to_1); if (TREE_CODE (mv2) != ARRAY_TYPE) mv2 = TYPE_MAIN_VARIANT (pointed_to_2); target = composite_type (mv1, mv2); /* Strip array types to get correct qualifier for pointers to arrays */ quals1 = TYPE_QUALS_NO_ADDR_SPACE (strip_array_types (pointed_to_1)); quals2 = TYPE_QUALS_NO_ADDR_SPACE (strip_array_types (pointed_to_2)); /* For function types do not merge const qualifiers, but drop them if used inconsistently. The middle-end uses these to mark const and noreturn functions. */ if (TREE_CODE (pointed_to_1) == FUNCTION_TYPE) target_quals = (quals1 & quals2); else target_quals = (quals1 | quals2); /* If the two named address spaces are different, determine the common superset address space. This is guaranteed to exist due to the assumption that comp_target_type returned non-zero. */ as1 = TYPE_ADDR_SPACE (pointed_to_1); as2 = TYPE_ADDR_SPACE (pointed_to_2); if (!addr_space_superset (as1, as2, &as_common)) gcc_unreachable (); target_quals |= ENCODE_QUAL_ADDR_SPACE (as_common); t1 = build_pointer_type (c_build_qualified_type (target, target_quals)); return build_type_attribute_variant (t1, attributes); } /* Return the common type for two arithmetic types under the usual arithmetic conversions. The default conversions have already been applied, and enumerated types converted to their compatible integer types. The resulting type is unqualified and has no attributes. This is the type for the result of most arithmetic operations if the operands have the given two types. */ static tree c_common_type (tree t1, tree t2) { enum tree_code code1; enum tree_code code2; /* If one type is nonsense, use the other. */ if (t1 == error_mark_node) return t2; if (t2 == error_mark_node) return t1; if (TYPE_QUALS (t1) != TYPE_UNQUALIFIED) t1 = TYPE_MAIN_VARIANT (t1); if (TYPE_QUALS (t2) != TYPE_UNQUALIFIED) t2 = TYPE_MAIN_VARIANT (t2); if (TYPE_ATTRIBUTES (t1) != NULL_TREE) t1 = build_type_attribute_variant (t1, NULL_TREE); if (TYPE_ATTRIBUTES (t2) != NULL_TREE) t2 = build_type_attribute_variant (t2, NULL_TREE); /* Save time if the two types are the same. */ if (t1 == t2) return t1; code1 = TREE_CODE (t1); code2 = TREE_CODE (t2); gcc_assert (code1 == VECTOR_TYPE || code1 == COMPLEX_TYPE || code1 == FIXED_POINT_TYPE || code1 == REAL_TYPE || code1 == INTEGER_TYPE); gcc_assert (code2 == VECTOR_TYPE || code2 == COMPLEX_TYPE || code2 == FIXED_POINT_TYPE || code2 == REAL_TYPE || code2 == INTEGER_TYPE); /* When one operand is a decimal float type, the other operand cannot be a generic float type or a complex type. We also disallow vector types here. */ if ((DECIMAL_FLOAT_TYPE_P (t1) || DECIMAL_FLOAT_TYPE_P (t2)) && !(DECIMAL_FLOAT_TYPE_P (t1) && DECIMAL_FLOAT_TYPE_P (t2))) { if (code1 == VECTOR_TYPE || code2 == VECTOR_TYPE) { error ("can%'t mix operands of decimal float and vector types"); return error_mark_node; } if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE) { error ("can%'t mix operands of decimal float and complex types"); return error_mark_node; } if (code1 == REAL_TYPE && code2 == REAL_TYPE) { error ("can%'t mix operands of decimal float and other float types"); return error_mark_node; } } /* If one type is a vector type, return that type. (How the usual arithmetic conversions apply to the vector types extension is not precisely specified.) */ if (code1 == VECTOR_TYPE) return t1; if (code2 == VECTOR_TYPE) return t2; /* If one type is complex, form the common type of the non-complex components, then make that complex. Use T1 or T2 if it is the required type. */ if (code1 == COMPLEX_TYPE || code2 == COMPLEX_TYPE) { tree subtype1 = code1 == COMPLEX_TYPE ? TREE_TYPE (t1) : t1; tree subtype2 = code2 == COMPLEX_TYPE ? TREE_TYPE (t2) : t2; tree subtype = c_common_type (subtype1, subtype2); if (code1 == COMPLEX_TYPE && TREE_TYPE (t1) == subtype) return t1; else if (code2 == COMPLEX_TYPE && TREE_TYPE (t2) == subtype) return t2; else return build_complex_type (subtype); } /* If only one is real, use it as the result. */ if (code1 == REAL_TYPE && code2 != REAL_TYPE) return t1; if (code2 == REAL_TYPE && code1 != REAL_TYPE) return t2; /* If both are real and either are decimal floating point types, use the decimal floating point type with the greater precision. */ if (code1 == REAL_TYPE && code2 == REAL_TYPE) { if (TYPE_MAIN_VARIANT (t1) == dfloat128_type_node || TYPE_MAIN_VARIANT (t2) == dfloat128_type_node) return dfloat128_type_node; else if (TYPE_MAIN_VARIANT (t1) == dfloat64_type_node || TYPE_MAIN_VARIANT (t2) == dfloat64_type_node) return dfloat64_type_node; else if (TYPE_MAIN_VARIANT (t1) == dfloat32_type_node || TYPE_MAIN_VARIANT (t2) == dfloat32_type_node) return dfloat32_type_node; } /* Deal with fixed-point types. */ if (code1 == FIXED_POINT_TYPE || code2 == FIXED_POINT_TYPE) { unsigned int unsignedp = 0, satp = 0; machine_mode m1, m2; unsigned int fbit1, ibit1, fbit2, ibit2, max_fbit, max_ibit; m1 = TYPE_MODE (t1); m2 = TYPE_MODE (t2); /* If one input type is saturating, the result type is saturating. */ if (TYPE_SATURATING (t1) || TYPE_SATURATING (t2)) satp = 1; /* If both fixed-point types are unsigned, the result type is unsigned. When mixing fixed-point and integer types, follow the sign of the fixed-point type. Otherwise, the result type is signed. */ if ((TYPE_UNSIGNED (t1) && TYPE_UNSIGNED (t2) && code1 == FIXED_POINT_TYPE && code2 == FIXED_POINT_TYPE) || (code1 == FIXED_POINT_TYPE && code2 != FIXED_POINT_TYPE && TYPE_UNSIGNED (t1)) || (code1 != FIXED_POINT_TYPE && code2 == FIXED_POINT_TYPE && TYPE_UNSIGNED (t2))) unsignedp = 1; /* The result type is signed. */ if (unsignedp == 0) { /* If the input type is unsigned, we need to convert to the signed type. */ if (code1 == FIXED_POINT_TYPE && TYPE_UNSIGNED (t1)) { enum mode_class mclass = (enum mode_class) 0; if (GET_MODE_CLASS (m1) == MODE_UFRACT) mclass = MODE_FRACT; else if (GET_MODE_CLASS (m1) == MODE_UACCUM) mclass = MODE_ACCUM; else gcc_unreachable (); m1 = mode_for_size (GET_MODE_PRECISION (m1), mclass, 0); } if (code2 == FIXED_POINT_TYPE && TYPE_UNSIGNED (t2)) { enum mode_class mclass = (enum mode_class) 0; if (GET_MODE_CLASS (m2) == MODE_UFRACT) mclass = MODE_FRACT; else if (GET_MODE_CLASS (m2) == MODE_UACCUM) mclass = MODE_ACCUM; else gcc_unreachable (); m2 = mode_for_size (GET_MODE_PRECISION (m2), mclass, 0); } } if (code1 == FIXED_POINT_TYPE) { fbit1 = GET_MODE_FBIT (m1); ibit1 = GET_MODE_IBIT (m1); } else { fbit1 = 0; /* Signed integers need to subtract one sign bit. */ ibit1 = TYPE_PRECISION (t1) - (!TYPE_UNSIGNED (t1)); } if (code2 == FIXED_POINT_TYPE) { fbit2 = GET_MODE_FBIT (m2); ibit2 = GET_MODE_IBIT (m2); } else { fbit2 = 0; /* Signed integers need to subtract one sign bit. */ ibit2 = TYPE_PRECISION (t2) - (!TYPE_UNSIGNED (t2)); } max_ibit = ibit1 >= ibit2 ? ibit1 : ibit2; max_fbit = fbit1 >= fbit2 ? fbit1 : fbit2; return c_common_fixed_point_type_for_size (max_ibit, max_fbit, unsignedp, satp); } /* Both real or both integers; use the one with greater precision. */ if (TYPE_PRECISION (t1) > TYPE_PRECISION (t2)) return t1; else if (TYPE_PRECISION (t2) > TYPE_PRECISION (t1)) return t2; /* Same precision. Prefer long longs to longs to ints when the same precision, following the C99 rules on integer type rank (which are equivalent to the C90 rules for C90 types). */ if (TYPE_MAIN_VARIANT (t1) == long_long_unsigned_type_node || TYPE_MAIN_VARIANT (t2) == long_long_unsigned_type_node) return long_long_unsigned_type_node; if (TYPE_MAIN_VARIANT (t1) == long_long_integer_type_node || TYPE_MAIN_VARIANT (t2) == long_long_integer_type_node) { if (TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2)) return long_long_unsigned_type_node; else return long_long_integer_type_node; } if (TYPE_MAIN_VARIANT (t1) == long_unsigned_type_node || TYPE_MAIN_VARIANT (t2) == long_unsigned_type_node) return long_unsigned_type_node; if (TYPE_MAIN_VARIANT (t1) == long_integer_type_node || TYPE_MAIN_VARIANT (t2) == long_integer_type_node) { /* But preserve unsignedness from the other type, since long cannot hold all the values of an unsigned int. */ if (TYPE_UNSIGNED (t1) || TYPE_UNSIGNED (t2)) return long_unsigned_type_node; else return long_integer_type_node; } /* Likewise, prefer long double to double even if same size. */ if (TYPE_MAIN_VARIANT (t1) == long_double_type_node || TYPE_MAIN_VARIANT (t2) == long_double_type_node) return long_double_type_node; /* Likewise, prefer double to float even if same size. We got a couple of embedded targets with 32 bit doubles, and the pdp11 might have 64 bit floats. */ if (TYPE_MAIN_VARIANT (t1) == double_type_node || TYPE_MAIN_VARIANT (t2) == double_type_node) return double_type_node; /* Otherwise prefer the unsigned one. */ if (TYPE_UNSIGNED (t1)) return t1; else return t2; } /* Wrapper around c_common_type that is used by c-common.c and other front end optimizations that remove promotions. ENUMERAL_TYPEs are allowed here and are converted to their compatible integer types. BOOLEAN_TYPEs are allowed here and return either boolean_type_node or preferably a non-Boolean type as the common type. */ tree common_type (tree t1, tree t2) { if (TREE_CODE (t1) == ENUMERAL_TYPE) t1 = c_common_type_for_size (TYPE_PRECISION (t1), 1); if (TREE_CODE (t2) == ENUMERAL_TYPE) t2 = c_common_type_for_size (TYPE_PRECISION (t2), 1); /* If both types are BOOLEAN_TYPE, then return boolean_type_node. */ if (TREE_CODE (t1) == BOOLEAN_TYPE && TREE_CODE (t2) == BOOLEAN_TYPE) return boolean_type_node; /* If either type is BOOLEAN_TYPE, then return the other. */ if (TREE_CODE (t1) == BOOLEAN_TYPE) return t2; if (TREE_CODE (t2) == BOOLEAN_TYPE) return t1; return c_common_type (t1, t2); } /* Return 1 if TYPE1 and TYPE2 are compatible types for assignment or various other operations. Return 2 if they are compatible but a warning may be needed if you use them together. */ int comptypes (tree type1, tree type2) { const struct tagged_tu_seen_cache * tagged_tu_seen_base1 = tagged_tu_seen_base; int val; val = comptypes_internal (type1, type2, NULL, NULL); free_all_tagged_tu_seen_up_to (tagged_tu_seen_base1); return val; } /* Like comptypes, but if it returns non-zero because enum and int are compatible, it sets *ENUM_AND_INT_P to true. */ static int comptypes_check_enum_int (tree type1, tree type2, bool *enum_and_int_p) { const struct tagged_tu_seen_cache * tagged_tu_seen_base1 = tagged_tu_seen_base; int val; val = comptypes_internal (type1, type2, enum_and_int_p, NULL); free_all_tagged_tu_seen_up_to (tagged_tu_seen_base1); return val; } /* Like comptypes, but if it returns nonzero for different types, it sets *DIFFERENT_TYPES_P to true. */ int comptypes_check_different_types (tree type1, tree type2, bool *different_types_p) { const struct tagged_tu_seen_cache * tagged_tu_seen_base1 = tagged_tu_seen_base; int val; val = comptypes_internal (type1, type2, NULL, different_types_p); free_all_tagged_tu_seen_up_to (tagged_tu_seen_base1); return val; } /* Return 1 if TYPE1 and TYPE2 are compatible types for assignment or various other operations. Return 2 if they are compatible but a warning may be needed if you use them together. If ENUM_AND_INT_P is not NULL, and one type is an enum and the other a compatible integer type, then this sets *ENUM_AND_INT_P to true; *ENUM_AND_INT_P is never set to false. If DIFFERENT_TYPES_P is not NULL, and the types are compatible but different enough not to be permitted in C11 typedef redeclarations, then this sets *DIFFERENT_TYPES_P to true; *DIFFERENT_TYPES_P is never set to false, but may or may not be set if the types are incompatible. This differs from comptypes, in that we don't free the seen types. */ static int comptypes_internal (const_tree type1, const_tree type2, bool *enum_and_int_p, bool *different_types_p) { const_tree t1 = type1; const_tree t2 = type2; int attrval, val; /* Suppress errors caused by previously reported errors. */ if (t1 == t2 || !t1 || !t2 || TREE_CODE (t1) == ERROR_MARK || TREE_CODE (t2) == ERROR_MARK) return 1; /* Enumerated types are compatible with integer types, but this is not transitive: two enumerated types in the same translation unit are compatible with each other only if they are the same type. */ if (TREE_CODE (t1) == ENUMERAL_TYPE && TREE_CODE (t2) != ENUMERAL_TYPE) { t1 = c_common_type_for_size (TYPE_PRECISION (t1), TYPE_UNSIGNED (t1)); if (TREE_CODE (t2) != VOID_TYPE) { if (enum_and_int_p != NULL) *enum_and_int_p = true; if (different_types_p != NULL) *different_types_p = true; } } else if (TREE_CODE (t2) == ENUMERAL_TYPE && TREE_CODE (t1) != ENUMERAL_TYPE) { t2 = c_common_type_for_size (TYPE_PRECISION (t2), TYPE_UNSIGNED (t2)); if (TREE_CODE (t1) != VOID_TYPE) { if (enum_and_int_p != NULL) *enum_and_int_p = true; if (different_types_p != NULL) *different_types_p = true; } } if (t1 == t2) return 1; /* Different classes of types can't be compatible. */ if (TREE_CODE (t1) != TREE_CODE (t2)) return 0; /* Qualifiers must match. C99 6.7.3p9 */ if (TYPE_QUALS (t1) != TYPE_QUALS (t2)) return 0; /* Allow for two different type nodes which have essentially the same definition. Note that we already checked for equality of the type qualifiers (just above). */ if (TREE_CODE (t1) != ARRAY_TYPE && TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2)) return 1; /* 1 if no need for warning yet, 2 if warning cause has been seen. */ if (!(attrval = comp_type_attributes (t1, t2))) return 0; /* 1 if no need for warning yet, 2 if warning cause has been seen. */ val = 0; switch (TREE_CODE (t1)) { case POINTER_TYPE: /* Do not remove mode or aliasing information. */ if (TYPE_MODE (t1) != TYPE_MODE (t2) || TYPE_REF_CAN_ALIAS_ALL (t1) != TYPE_REF_CAN_ALIAS_ALL (t2)) break; val = (TREE_TYPE (t1) == TREE_TYPE (t2) ? 1 : comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2), enum_and_int_p, different_types_p)); break; case FUNCTION_TYPE: val = function_types_compatible_p (t1, t2, enum_and_int_p, different_types_p); break; case ARRAY_TYPE: { tree d1 = TYPE_DOMAIN (t1); tree d2 = TYPE_DOMAIN (t2); bool d1_variable, d2_variable; bool d1_zero, d2_zero; val = 1; /* Target types must match incl. qualifiers. */ if (TREE_TYPE (t1) != TREE_TYPE (t2) && 0 == (val = comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2), enum_and_int_p, different_types_p))) return 0; if (different_types_p != NULL && (d1 == 0) != (d2 == 0)) *different_types_p = true; /* Sizes must match unless one is missing or variable. */ if (d1 == 0 || d2 == 0 || d1 == d2) break; d1_zero = !TYPE_MAX_VALUE (d1); d2_zero = !TYPE_MAX_VALUE (d2); d1_variable = (!d1_zero && (TREE_CODE (TYPE_MIN_VALUE (d1)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d1)) != INTEGER_CST)); d2_variable = (!d2_zero && (TREE_CODE (TYPE_MIN_VALUE (d2)) != INTEGER_CST || TREE_CODE (TYPE_MAX_VALUE (d2)) != INTEGER_CST)); d1_variable = d1_variable || (d1_zero && c_vla_type_p (t1)); d2_variable = d2_variable || (d2_zero && c_vla_type_p (t2)); if (different_types_p != NULL && d1_variable != d2_variable) *different_types_p = true; if (d1_variable || d2_variable) break; if (d1_zero && d2_zero) break; if (d1_zero || d2_zero || !tree_int_cst_equal (TYPE_MIN_VALUE (d1), TYPE_MIN_VALUE (d2)) || !tree_int_cst_equal (TYPE_MAX_VALUE (d1), TYPE_MAX_VALUE (d2))) val = 0; break; } case ENUMERAL_TYPE: case RECORD_TYPE: case UNION_TYPE: if (val != 1 && !same_translation_unit_p (t1, t2)) { tree a1 = TYPE_ATTRIBUTES (t1); tree a2 = TYPE_ATTRIBUTES (t2); if (! attribute_list_contained (a1, a2) && ! attribute_list_contained (a2, a1)) break; if (attrval != 2) return tagged_types_tu_compatible_p (t1, t2, enum_and_int_p, different_types_p); val = tagged_types_tu_compatible_p (t1, t2, enum_and_int_p, different_types_p); } break; case VECTOR_TYPE: val = (TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2) && comptypes_internal (TREE_TYPE (t1), TREE_TYPE (t2), enum_and_int_p, different_types_p)); break; default: break; } return attrval == 2 && val == 1 ? 2 : val; } /* Return 1 if TTL and TTR are pointers to types that are equivalent, ignoring their qualifiers, except for named address spaces. If the pointers point to different named addresses, then we must determine if one address space is a subset of the other. */ static int comp_target_types (location_t location, tree ttl, tree ttr) { int val; int val_ped; tree mvl = TREE_TYPE (ttl); tree mvr = TREE_TYPE (ttr); addr_space_t asl = TYPE_ADDR_SPACE (mvl); addr_space_t asr = TYPE_ADDR_SPACE (mvr); addr_space_t as_common; bool enum_and_int_p; /* Fail if pointers point to incompatible address spaces. */ if (!addr_space_superset (asl, asr, &as_common)) return 0; /* For pedantic record result of comptypes on arrays before losing qualifiers on the element type below. */ val_ped = 1; if (TREE_CODE (mvl) == ARRAY_TYPE && TREE_CODE (mvr) == ARRAY_TYPE) val_ped = comptypes (mvl, mvr); /* Qualifiers on element types of array types that are pointer targets are lost by taking their TYPE_MAIN_VARIANT. */ mvl = (TYPE_ATOMIC (strip_array_types (mvl)) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvl), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvl)); mvr = (TYPE_ATOMIC (strip_array_types (mvr)) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvr), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvr)); enum_and_int_p = false; val = comptypes_check_enum_int (mvl, mvr, &enum_and_int_p); if (val == 1 && val_ped != 1) pedwarn (location, OPT_Wpedantic, "pointers to arrays with different qualifiers " "are incompatible in ISO C"); if (val == 2) pedwarn (location, OPT_Wpedantic, "types are not quite compatible"); if (val == 1 && enum_and_int_p && warn_cxx_compat) warning_at (location, OPT_Wc___compat, "pointer target types incompatible in C++"); return val; } /* Subroutines of `comptypes'. */ /* Determine whether two trees derive from the same translation unit. If the CONTEXT chain ends in a null, that tree's context is still being parsed, so if two trees have context chains ending in null, they're in the same translation unit. */ int same_translation_unit_p (const_tree t1, const_tree t2) { while (t1 && TREE_CODE (t1) != TRANSLATION_UNIT_DECL) switch (TREE_CODE_CLASS (TREE_CODE (t1))) { case tcc_declaration: t1 = DECL_CONTEXT (t1); break; case tcc_type: t1 = TYPE_CONTEXT (t1); break; case tcc_exceptional: t1 = BLOCK_SUPERCONTEXT (t1); break; /* assume block */ default: gcc_unreachable (); } while (t2 && TREE_CODE (t2) != TRANSLATION_UNIT_DECL) switch (TREE_CODE_CLASS (TREE_CODE (t2))) { case tcc_declaration: t2 = DECL_CONTEXT (t2); break; case tcc_type: t2 = TYPE_CONTEXT (t2); break; case tcc_exceptional: t2 = BLOCK_SUPERCONTEXT (t2); break; /* assume block */ default: gcc_unreachable (); } return t1 == t2; } /* Allocate the seen two types, assuming that they are compatible. */ static struct tagged_tu_seen_cache * alloc_tagged_tu_seen_cache (const_tree t1, const_tree t2) { struct tagged_tu_seen_cache *tu = XNEW (struct tagged_tu_seen_cache); tu->next = tagged_tu_seen_base; tu->t1 = t1; tu->t2 = t2; tagged_tu_seen_base = tu; /* The C standard says that two structures in different translation units are compatible with each other only if the types of their fields are compatible (among other things). We assume that they are compatible until proven otherwise when building the cache. An example where this can occur is: struct a { struct a *next; }; If we are comparing this against a similar struct in another TU, and did not assume they were compatible, we end up with an infinite loop. */ tu->val = 1; return tu; } /* Free the seen types until we get to TU_TIL. */ static void free_all_tagged_tu_seen_up_to (const struct tagged_tu_seen_cache *tu_til) { const struct tagged_tu_seen_cache *tu = tagged_tu_seen_base; while (tu != tu_til) { const struct tagged_tu_seen_cache *const tu1 = (const struct tagged_tu_seen_cache *) tu; tu = tu1->next; free (CONST_CAST (struct tagged_tu_seen_cache *, tu1)); } tagged_tu_seen_base = tu_til; } /* Return 1 if two 'struct', 'union', or 'enum' types T1 and T2 are compatible. If the two types are not the same (which has been checked earlier), this can only happen when multiple translation units are being compiled. See C99 6.2.7 paragraph 1 for the exact rules. ENUM_AND_INT_P and DIFFERENT_TYPES_P are as in comptypes_internal. */ static int tagged_types_tu_compatible_p (const_tree t1, const_tree t2, bool *enum_and_int_p, bool *different_types_p) { tree s1, s2; bool needs_warning = false; /* We have to verify that the tags of the types are the same. This is harder than it looks because this may be a typedef, so we have to go look at the original type. It may even be a typedef of a typedef... In the case of compiler-created builtin structs the TYPE_DECL may be a dummy, with no DECL_ORIGINAL_TYPE. Don't fault. */ while (TYPE_NAME (t1) && TREE_CODE (TYPE_NAME (t1)) == TYPE_DECL && DECL_ORIGINAL_TYPE (TYPE_NAME (t1))) t1 = DECL_ORIGINAL_TYPE (TYPE_NAME (t1)); while (TYPE_NAME (t2) && TREE_CODE (TYPE_NAME (t2)) == TYPE_DECL && DECL_ORIGINAL_TYPE (TYPE_NAME (t2))) t2 = DECL_ORIGINAL_TYPE (TYPE_NAME (t2)); /* C90 didn't have the requirement that the two tags be the same. */ if (flag_isoc99 && TYPE_NAME (t1) != TYPE_NAME (t2)) return 0; /* C90 didn't say what happened if one or both of the types were incomplete; we choose to follow C99 rules here, which is that they are compatible. */ if (TYPE_SIZE (t1) == NULL || TYPE_SIZE (t2) == NULL) return 1; { const struct tagged_tu_seen_cache * tts_i; for (tts_i = tagged_tu_seen_base; tts_i != NULL; tts_i = tts_i->next) if (tts_i->t1 == t1 && tts_i->t2 == t2) return tts_i->val; } switch (TREE_CODE (t1)) { case ENUMERAL_TYPE: { struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2); /* Speed up the case where the type values are in the same order. */ tree tv1 = TYPE_VALUES (t1); tree tv2 = TYPE_VALUES (t2); if (tv1 == tv2) { return 1; } for (;tv1 && tv2; tv1 = TREE_CHAIN (tv1), tv2 = TREE_CHAIN (tv2)) { if (TREE_PURPOSE (tv1) != TREE_PURPOSE (tv2)) break; if (simple_cst_equal (TREE_VALUE (tv1), TREE_VALUE (tv2)) != 1) { tu->val = 0; return 0; } } if (tv1 == NULL_TREE && tv2 == NULL_TREE) { return 1; } if (tv1 == NULL_TREE || tv2 == NULL_TREE) { tu->val = 0; return 0; } if (list_length (TYPE_VALUES (t1)) != list_length (TYPE_VALUES (t2))) { tu->val = 0; return 0; } for (s1 = TYPE_VALUES (t1); s1; s1 = TREE_CHAIN (s1)) { s2 = purpose_member (TREE_PURPOSE (s1), TYPE_VALUES (t2)); if (s2 == NULL || simple_cst_equal (TREE_VALUE (s1), TREE_VALUE (s2)) != 1) { tu->val = 0; return 0; } } return 1; } case UNION_TYPE: { struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2); if (list_length (TYPE_FIELDS (t1)) != list_length (TYPE_FIELDS (t2))) { tu->val = 0; return 0; } /* Speed up the common case where the fields are in the same order. */ for (s1 = TYPE_FIELDS (t1), s2 = TYPE_FIELDS (t2); s1 && s2; s1 = DECL_CHAIN (s1), s2 = DECL_CHAIN (s2)) { int result; if (DECL_NAME (s1) != DECL_NAME (s2)) break; result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2), enum_and_int_p, different_types_p); if (result != 1 && !DECL_NAME (s1)) break; if (result == 0) { tu->val = 0; return 0; } if (result == 2) needs_warning = true; if (TREE_CODE (s1) == FIELD_DECL && simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1), DECL_FIELD_BIT_OFFSET (s2)) != 1) { tu->val = 0; return 0; } } if (!s1 && !s2) { tu->val = needs_warning ? 2 : 1; return tu->val; } for (s1 = TYPE_FIELDS (t1); s1; s1 = DECL_CHAIN (s1)) { bool ok = false; for (s2 = TYPE_FIELDS (t2); s2; s2 = DECL_CHAIN (s2)) if (DECL_NAME (s1) == DECL_NAME (s2)) { int result; result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2), enum_and_int_p, different_types_p); if (result != 1 && !DECL_NAME (s1)) continue; if (result == 0) { tu->val = 0; return 0; } if (result == 2) needs_warning = true; if (TREE_CODE (s1) == FIELD_DECL && simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1), DECL_FIELD_BIT_OFFSET (s2)) != 1) break; ok = true; break; } if (!ok) { tu->val = 0; return 0; } } tu->val = needs_warning ? 2 : 10; return tu->val; } case RECORD_TYPE: { struct tagged_tu_seen_cache *tu = alloc_tagged_tu_seen_cache (t1, t2); for (s1 = TYPE_FIELDS (t1), s2 = TYPE_FIELDS (t2); s1 && s2; s1 = DECL_CHAIN (s1), s2 = DECL_CHAIN (s2)) { int result; if (TREE_CODE (s1) != TREE_CODE (s2) || DECL_NAME (s1) != DECL_NAME (s2)) break; result = comptypes_internal (TREE_TYPE (s1), TREE_TYPE (s2), enum_and_int_p, different_types_p); if (result == 0) break; if (result == 2) needs_warning = true; if (TREE_CODE (s1) == FIELD_DECL && simple_cst_equal (DECL_FIELD_BIT_OFFSET (s1), DECL_FIELD_BIT_OFFSET (s2)) != 1) break; } if (s1 && s2) tu->val = 0; else tu->val = needs_warning ? 2 : 1; return tu->val; } default: gcc_unreachable (); } } /* Return 1 if two function types F1 and F2 are compatible. If either type specifies no argument types, the other must specify a fixed number of self-promoting arg types. Otherwise, if one type specifies only the number of arguments, the other must specify that number of self-promoting arg types. Otherwise, the argument types must match. ENUM_AND_INT_P and DIFFERENT_TYPES_P are as in comptypes_internal. */ static int function_types_compatible_p (const_tree f1, const_tree f2, bool *enum_and_int_p, bool *different_types_p) { tree args1, args2; /* 1 if no need for warning yet, 2 if warning cause has been seen. */ int val = 1; int val1; tree ret1, ret2; ret1 = TREE_TYPE (f1); ret2 = TREE_TYPE (f2); /* 'volatile' qualifiers on a function's return type used to mean the function is noreturn. */ if (TYPE_VOLATILE (ret1) != TYPE_VOLATILE (ret2)) pedwarn (input_location, 0, "function return types not compatible due to %<volatile%>"); if (TYPE_VOLATILE (ret1)) ret1 = build_qualified_type (TYPE_MAIN_VARIANT (ret1), TYPE_QUALS (ret1) & ~TYPE_QUAL_VOLATILE); if (TYPE_VOLATILE (ret2)) ret2 = build_qualified_type (TYPE_MAIN_VARIANT (ret2), TYPE_QUALS (ret2) & ~TYPE_QUAL_VOLATILE); val = comptypes_internal (ret1, ret2, enum_and_int_p, different_types_p); if (val == 0) return 0; args1 = TYPE_ARG_TYPES (f1); args2 = TYPE_ARG_TYPES (f2); if (different_types_p != NULL && (args1 == 0) != (args2 == 0)) *different_types_p = true; /* An unspecified parmlist matches any specified parmlist whose argument types don't need default promotions. */ if (args1 == 0) { if (!self_promoting_args_p (args2)) return 0; /* If one of these types comes from a non-prototype fn definition, compare that with the other type's arglist. If they don't match, ask for a warning (but no error). */ if (TYPE_ACTUAL_ARG_TYPES (f1) && 1 != type_lists_compatible_p (args2, TYPE_ACTUAL_ARG_TYPES (f1), enum_and_int_p, different_types_p)) val = 2; return val; } if (args2 == 0) { if (!self_promoting_args_p (args1)) return 0; if (TYPE_ACTUAL_ARG_TYPES (f2) && 1 != type_lists_compatible_p (args1, TYPE_ACTUAL_ARG_TYPES (f2), enum_and_int_p, different_types_p)) val = 2; return val; } /* Both types have argument lists: compare them and propagate results. */ val1 = type_lists_compatible_p (args1, args2, enum_and_int_p, different_types_p); return val1 != 1 ? val1 : val; } /* Check two lists of types for compatibility, returning 0 for incompatible, 1 for compatible, or 2 for compatible with warning. ENUM_AND_INT_P and DIFFERENT_TYPES_P are as in comptypes_internal. */ static int type_lists_compatible_p (const_tree args1, const_tree args2, bool *enum_and_int_p, bool *different_types_p) { /* 1 if no need for warning yet, 2 if warning cause has been seen. */ int val = 1; int newval = 0; while (1) { tree a1, mv1, a2, mv2; if (args1 == 0 && args2 == 0) return val; /* If one list is shorter than the other, they fail to match. */ if (args1 == 0 || args2 == 0) return 0; mv1 = a1 = TREE_VALUE (args1); mv2 = a2 = TREE_VALUE (args2); if (mv1 && mv1 != error_mark_node && TREE_CODE (mv1) != ARRAY_TYPE) mv1 = (TYPE_ATOMIC (mv1) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv1), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv1)); if (mv2 && mv2 != error_mark_node && TREE_CODE (mv2) != ARRAY_TYPE) mv2 = (TYPE_ATOMIC (mv2) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv2), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv2)); /* A null pointer instead of a type means there is supposed to be an argument but nothing is specified about what type it has. So match anything that self-promotes. */ if (different_types_p != NULL && (a1 == 0) != (a2 == 0)) *different_types_p = true; if (a1 == 0) { if (c_type_promotes_to (a2) != a2) return 0; } else if (a2 == 0) { if (c_type_promotes_to (a1) != a1) return 0; } /* If one of the lists has an error marker, ignore this arg. */ else if (TREE_CODE (a1) == ERROR_MARK || TREE_CODE (a2) == ERROR_MARK) ; else if (!(newval = comptypes_internal (mv1, mv2, enum_and_int_p, different_types_p))) { if (different_types_p != NULL) *different_types_p = true; /* Allow wait (union {union wait *u; int *i} *) and wait (union wait *) to be compatible. */ if (TREE_CODE (a1) == UNION_TYPE && (TYPE_NAME (a1) == 0 || TYPE_TRANSPARENT_AGGR (a1)) && TREE_CODE (TYPE_SIZE (a1)) == INTEGER_CST && tree_int_cst_equal (TYPE_SIZE (a1), TYPE_SIZE (a2))) { tree memb; for (memb = TYPE_FIELDS (a1); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = (TYPE_ATOMIC (mv3) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv3), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv3)); if (comptypes_internal (mv3, mv2, enum_and_int_p, different_types_p)) break; } if (memb == 0) return 0; } else if (TREE_CODE (a2) == UNION_TYPE && (TYPE_NAME (a2) == 0 || TYPE_TRANSPARENT_AGGR (a2)) && TREE_CODE (TYPE_SIZE (a2)) == INTEGER_CST && tree_int_cst_equal (TYPE_SIZE (a2), TYPE_SIZE (a1))) { tree memb; for (memb = TYPE_FIELDS (a2); memb; memb = DECL_CHAIN (memb)) { tree mv3 = TREE_TYPE (memb); if (mv3 && mv3 != error_mark_node && TREE_CODE (mv3) != ARRAY_TYPE) mv3 = (TYPE_ATOMIC (mv3) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mv3), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mv3)); if (comptypes_internal (mv3, mv1, enum_and_int_p, different_types_p)) break; } if (memb == 0) return 0; } else return 0; } /* comptypes said ok, but record if it said to warn. */ if (newval > val) val = newval; args1 = TREE_CHAIN (args1); args2 = TREE_CHAIN (args2); } } /* Compute the size to increment a pointer by. When a function type or void type or incomplete type is passed, size_one_node is returned. This function does not emit any diagnostics; the caller is responsible for that. */ static tree c_size_in_bytes (const_tree type) { enum tree_code code = TREE_CODE (type); if (code == FUNCTION_TYPE || code == VOID_TYPE || code == ERROR_MARK || !COMPLETE_TYPE_P (type)) return size_one_node; /* Convert in case a char is more than one unit. */ return size_binop_loc (input_location, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type), size_int (TYPE_PRECISION (char_type_node) / BITS_PER_UNIT)); } /* Return either DECL or its known constant value (if it has one). */ tree decl_constant_value (tree decl) { if (/* Don't change a variable array bound or initial value to a constant in a place where a variable is invalid. Note that DECL_INITIAL isn't valid for a PARM_DECL. */ current_function_decl != 0 && TREE_CODE (decl) != PARM_DECL && !TREE_THIS_VOLATILE (decl) && TREE_READONLY (decl) && DECL_INITIAL (decl) != 0 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK /* This is invalid if initial value is not constant. If it has either a function call, a memory reference, or a variable, then re-evaluating it could give different results. */ && TREE_CONSTANT (DECL_INITIAL (decl)) /* Check for cases where this is sub-optimal, even though valid. */ && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR) return DECL_INITIAL (decl); return decl; } /* Convert the array expression EXP to a pointer. */ static tree array_to_pointer_conversion (location_t loc, tree exp) { tree orig_exp = exp; tree type = TREE_TYPE (exp); tree adr; tree restype = TREE_TYPE (type); tree ptrtype; gcc_assert (TREE_CODE (type) == ARRAY_TYPE); STRIP_TYPE_NOPS (exp); if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp) = 1; ptrtype = build_pointer_type (restype); if (TREE_CODE (exp) == INDIRECT_REF) return convert (ptrtype, TREE_OPERAND (exp, 0)); /* In C++ array compound literals are temporary objects unless they are const or appear in namespace scope, so they are destroyed too soon to use them for much of anything (c++/53220). */ if (warn_cxx_compat && TREE_CODE (exp) == COMPOUND_LITERAL_EXPR) { tree decl = TREE_OPERAND (TREE_OPERAND (exp, 0), 0); if (!TREE_READONLY (decl) && !TREE_STATIC (decl)) warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wc___compat, "converting an array compound literal to a pointer " "is ill-formed in C++"); } adr = build_unary_op (loc, ADDR_EXPR, exp, 1); return convert (ptrtype, adr); } /* Convert the function expression EXP to a pointer. */ static tree function_to_pointer_conversion (location_t loc, tree exp) { tree orig_exp = exp; gcc_assert (TREE_CODE (TREE_TYPE (exp)) == FUNCTION_TYPE); STRIP_TYPE_NOPS (exp); if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp) = 1; return build_unary_op (loc, ADDR_EXPR, exp, 0); } /* Mark EXP as read, not just set, for set but not used -Wunused warning purposes. */ void mark_exp_read (tree exp) { switch (TREE_CODE (exp)) { case VAR_DECL: case PARM_DECL: DECL_READ_P (exp) = 1; break; case ARRAY_REF: case COMPONENT_REF: case MODIFY_EXPR: case REALPART_EXPR: case IMAGPART_EXPR: CASE_CONVERT: case ADDR_EXPR: mark_exp_read (TREE_OPERAND (exp, 0)); break; case COMPOUND_EXPR: case C_MAYBE_CONST_EXPR: mark_exp_read (TREE_OPERAND (exp, 1)); break; default: break; } } /* Perform the default conversion of arrays and functions to pointers. Return the result of converting EXP. For any other expression, just return EXP. LOC is the location of the expression. */ struct c_expr default_function_array_conversion (location_t loc, struct c_expr exp) { tree orig_exp = exp.value; tree type = TREE_TYPE (exp.value); enum tree_code code = TREE_CODE (type); switch (code) { case ARRAY_TYPE: { bool not_lvalue = false; bool lvalue_array_p; while ((TREE_CODE (exp.value) == NON_LVALUE_EXPR || CONVERT_EXPR_P (exp.value)) && TREE_TYPE (TREE_OPERAND (exp.value, 0)) == type) { if (TREE_CODE (exp.value) == NON_LVALUE_EXPR) not_lvalue = true; exp.value = TREE_OPERAND (exp.value, 0); } if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp.value) = 1; lvalue_array_p = !not_lvalue && lvalue_p (exp.value); if (!flag_isoc99 && !lvalue_array_p) { /* Before C99, non-lvalue arrays do not decay to pointers. Normally, using such an array would be invalid; but it can be used correctly inside sizeof or as a statement expression. Thus, do not give an error here; an error will result later. */ return exp; } exp.value = array_to_pointer_conversion (loc, exp.value); } break; case FUNCTION_TYPE: exp.value = function_to_pointer_conversion (loc, exp.value); break; default: break; } return exp; } struct c_expr default_function_array_read_conversion (location_t loc, struct c_expr exp) { mark_exp_read (exp.value); return default_function_array_conversion (loc, exp); } /* Return whether EXPR should be treated as an atomic lvalue for the purposes of load and store handling. */ static bool really_atomic_lvalue (tree expr) { if (error_operand_p (expr)) return false; if (!TYPE_ATOMIC (TREE_TYPE (expr))) return false; if (!lvalue_p (expr)) return false; /* Ignore _Atomic on register variables, since their addresses can't be taken so (a) atomicity is irrelevant and (b) the normal atomic sequences wouldn't work. Ignore _Atomic on structures containing bit-fields, since accessing elements of atomic structures or unions is undefined behavior (C11 6.5.2.3#5), but it's unclear if it's undefined at translation time or execution time, and the normal atomic sequences again wouldn't work. */ while (handled_component_p (expr)) { if (TREE_CODE (expr) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1))) return false; expr = TREE_OPERAND (expr, 0); } if (DECL_P (expr) && C_DECL_REGISTER (expr)) return false; return true; } /* Convert expression EXP (location LOC) from lvalue to rvalue, including converting functions and arrays to pointers if CONVERT_P. If READ_P, also mark the expression as having been read. */ struct c_expr convert_lvalue_to_rvalue (location_t loc, struct c_expr exp, bool convert_p, bool read_p) { if (read_p) mark_exp_read (exp.value); if (convert_p) exp = default_function_array_conversion (loc, exp); if (really_atomic_lvalue (exp.value)) { vec<tree, va_gc> *params; tree nonatomic_type, tmp, tmp_addr, fndecl, func_call; tree expr_type = TREE_TYPE (exp.value); tree expr_addr = build_unary_op (loc, ADDR_EXPR, exp.value, 0); tree seq_cst = build_int_cst (integer_type_node, MEMMODEL_SEQ_CST); gcc_assert (TYPE_ATOMIC (expr_type)); /* Expansion of a generic atomic load may require an addition element, so allocate enough to prevent a resize. */ vec_alloc (params, 4); /* Remove the qualifiers for the rest of the expressions and create the VAL temp variable to hold the RHS. */ nonatomic_type = build_qualified_type (expr_type, TYPE_UNQUALIFIED); tmp = create_tmp_var (nonatomic_type); tmp_addr = build_unary_op (loc, ADDR_EXPR, tmp, 0); TREE_ADDRESSABLE (tmp) = 1; TREE_NO_WARNING (tmp) = 1; /* Issue __atomic_load (&expr, &tmp, SEQ_CST); */ fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_LOAD); params->quick_push (expr_addr); params->quick_push (tmp_addr); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); /* EXPR is always read. */ mark_exp_read (exp.value); /* Return tmp which contains the value loaded. */ exp.value = build2 (COMPOUND_EXPR, nonatomic_type, func_call, tmp); } return exp; } /* EXP is an expression of integer type. Apply the integer promotions to it and return the promoted value. */ tree perform_integral_promotions (tree exp) { tree type = TREE_TYPE (exp); enum tree_code code = TREE_CODE (type); gcc_assert (INTEGRAL_TYPE_P (type)); /* Normally convert enums to int, but convert wide enums to something wider. */ if (code == ENUMERAL_TYPE) { type = c_common_type_for_size (MAX (TYPE_PRECISION (type), TYPE_PRECISION (integer_type_node)), ((TYPE_PRECISION (type) >= TYPE_PRECISION (integer_type_node)) && TYPE_UNSIGNED (type))); return convert (type, exp); } /* ??? This should no longer be needed now bit-fields have their proper types. */ if (TREE_CODE (exp) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (exp, 1)) /* If it's thinner than an int, promote it like a c_promoting_integer_type_p, otherwise leave it alone. */ && 0 > compare_tree_int (DECL_SIZE (TREE_OPERAND (exp, 1)), TYPE_PRECISION (integer_type_node))) return convert (integer_type_node, exp); if (c_promoting_integer_type_p (type)) { /* Preserve unsignedness if not really getting any wider. */ if (TYPE_UNSIGNED (type) && TYPE_PRECISION (type) == TYPE_PRECISION (integer_type_node)) return convert (unsigned_type_node, exp); return convert (integer_type_node, exp); } return exp; } /* Perform default promotions for C data used in expressions. Enumeral types or short or char are converted to int. In addition, manifest constants symbols are replaced by their values. */ tree default_conversion (tree exp) { tree orig_exp; tree type = TREE_TYPE (exp); enum tree_code code = TREE_CODE (type); tree promoted_type; mark_exp_read (exp); /* Functions and arrays have been converted during parsing. */ gcc_assert (code != FUNCTION_TYPE); if (code == ARRAY_TYPE) return exp; /* Constants can be used directly unless they're not loadable. */ if (TREE_CODE (exp) == CONST_DECL) exp = DECL_INITIAL (exp); /* Strip no-op conversions. */ orig_exp = exp; STRIP_TYPE_NOPS (exp); if (TREE_NO_WARNING (orig_exp)) TREE_NO_WARNING (exp) = 1; if (code == VOID_TYPE) { error_at (EXPR_LOC_OR_LOC (exp, input_location), "void value not ignored as it ought to be"); return error_mark_node; } exp = require_complete_type (exp); if (exp == error_mark_node) return error_mark_node; promoted_type = targetm.promoted_type (type); if (promoted_type) return convert (promoted_type, exp); if (INTEGRAL_TYPE_P (type)) return perform_integral_promotions (exp); return exp; } /* Look up COMPONENT in a structure or union TYPE. If the component name is not found, returns NULL_TREE. Otherwise, the return value is a TREE_LIST, with each TREE_VALUE a FIELD_DECL stepping down the chain to the component, which is in the last TREE_VALUE of the list. Normally the list is of length one, but if the component is embedded within (nested) anonymous structures or unions, the list steps down the chain to the component. */ static tree lookup_field (tree type, tree component) { tree field; /* If TYPE_LANG_SPECIFIC is set, then it is a sorted array of pointers to the field elements. Use a binary search on this array to quickly find the element. Otherwise, do a linear search. TYPE_LANG_SPECIFIC will always be set for structures which have many elements. */ if (TYPE_LANG_SPECIFIC (type) && TYPE_LANG_SPECIFIC (type)->s) { int bot, top, half; tree *field_array = &TYPE_LANG_SPECIFIC (type)->s->elts[0]; field = TYPE_FIELDS (type); bot = 0; top = TYPE_LANG_SPECIFIC (type)->s->len; while (top - bot > 1) { half = (top - bot + 1) >> 1; field = field_array[bot+half]; if (DECL_NAME (field) == NULL_TREE) { /* Step through all anon unions in linear fashion. */ while (DECL_NAME (field_array[bot]) == NULL_TREE) { field = field_array[bot++]; if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE) { tree anon = lookup_field (TREE_TYPE (field), component); if (anon) return tree_cons (NULL_TREE, field, anon); /* The Plan 9 compiler permits referring directly to an anonymous struct/union field using a typedef name. */ if (flag_plan9_extensions && TYPE_NAME (TREE_TYPE (field)) != NULL_TREE && (TREE_CODE (TYPE_NAME (TREE_TYPE (field))) == TYPE_DECL) && (DECL_NAME (TYPE_NAME (TREE_TYPE (field))) == component)) break; } } /* Entire record is only anon unions. */ if (bot > top) return NULL_TREE; /* Restart the binary search, with new lower bound. */ continue; } if (DECL_NAME (field) == component) break; if (DECL_NAME (field) < component) bot += half; else top = bot + half; } if (DECL_NAME (field_array[bot]) == component) field = field_array[bot]; else if (DECL_NAME (field) != component) return NULL_TREE; } else { for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field)) { if (DECL_NAME (field) == NULL_TREE && (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)) { tree anon = lookup_field (TREE_TYPE (field), component); if (anon) return tree_cons (NULL_TREE, field, anon); /* The Plan 9 compiler permits referring directly to an anonymous struct/union field using a typedef name. */ if (flag_plan9_extensions && TYPE_NAME (TREE_TYPE (field)) != NULL_TREE && TREE_CODE (TYPE_NAME (TREE_TYPE (field))) == TYPE_DECL && (DECL_NAME (TYPE_NAME (TREE_TYPE (field))) == component)) break; } if (DECL_NAME (field) == component) break; } if (field == NULL_TREE) return NULL_TREE; } return tree_cons (NULL_TREE, field, NULL_TREE); } /* Make an expression to refer to the COMPONENT field of structure or union value DATUM. COMPONENT is an IDENTIFIER_NODE. LOC is the location of the COMPONENT_REF. */ tree build_component_ref (location_t loc, tree datum, tree component) { tree type = TREE_TYPE (datum); enum tree_code code = TREE_CODE (type); tree field = NULL; tree ref; bool datum_lvalue = lvalue_p (datum); if (!objc_is_public (datum, component)) return error_mark_node; /* Detect Objective-C property syntax object.property. */ if (c_dialect_objc () && (ref = objc_maybe_build_component_ref (datum, component))) return ref; /* See if there is a field or component with name COMPONENT. */ if (code == RECORD_TYPE || code == UNION_TYPE) { if (!COMPLETE_TYPE_P (type)) { c_incomplete_type_error (NULL_TREE, type); return error_mark_node; } field = lookup_field (type, component); if (!field) { error_at (loc, "%qT has no member named %qE", type, component); return error_mark_node; } /* Chain the COMPONENT_REFs if necessary down to the FIELD. This might be better solved in future the way the C++ front end does it - by giving the anonymous entities each a separate name and type, and then have build_component_ref recursively call itself. We can't do that here. */ do { tree subdatum = TREE_VALUE (field); int quals; tree subtype; bool use_datum_quals; if (TREE_TYPE (subdatum) == error_mark_node) return error_mark_node; /* If this is an rvalue, it does not have qualifiers in C standard terms and we must avoid propagating such qualifiers down to a non-lvalue array that is then converted to a pointer. */ use_datum_quals = (datum_lvalue || TREE_CODE (TREE_TYPE (subdatum)) != ARRAY_TYPE); quals = TYPE_QUALS (strip_array_types (TREE_TYPE (subdatum))); if (use_datum_quals) quals |= TYPE_QUALS (TREE_TYPE (datum)); subtype = c_build_qualified_type (TREE_TYPE (subdatum), quals); ref = build3 (COMPONENT_REF, subtype, datum, subdatum, NULL_TREE); SET_EXPR_LOCATION (ref, loc); if (TREE_READONLY (subdatum) || (use_datum_quals && TREE_READONLY (datum))) TREE_READONLY (ref) = 1; if (TREE_THIS_VOLATILE (subdatum) || (use_datum_quals && TREE_THIS_VOLATILE (datum))) TREE_THIS_VOLATILE (ref) = 1; if (TREE_DEPRECATED (subdatum)) warn_deprecated_use (subdatum, NULL_TREE); datum = ref; field = TREE_CHAIN (field); } while (field); return ref; } else if (code != ERROR_MARK) error_at (loc, "request for member %qE in something not a structure or union", component); return error_mark_node; } /* Given an expression PTR for a pointer, return an expression for the value pointed to. ERRORSTRING is the name of the operator to appear in error messages. LOC is the location to use for the generated tree. */ tree build_indirect_ref (location_t loc, tree ptr, ref_operator errstring) { tree pointer = default_conversion (ptr); tree type = TREE_TYPE (pointer); tree ref; if (TREE_CODE (type) == POINTER_TYPE) { if (CONVERT_EXPR_P (pointer) || TREE_CODE (pointer) == VIEW_CONVERT_EXPR) { /* If a warning is issued, mark it to avoid duplicates from the backend. This only needs to be done at warn_strict_aliasing > 2. */ if (warn_strict_aliasing > 2) if (strict_aliasing_warning (TREE_TYPE (TREE_OPERAND (pointer, 0)), type, TREE_OPERAND (pointer, 0))) TREE_NO_WARNING (pointer) = 1; } if (TREE_CODE (pointer) == ADDR_EXPR && (TREE_TYPE (TREE_OPERAND (pointer, 0)) == TREE_TYPE (type))) { ref = TREE_OPERAND (pointer, 0); protected_set_expr_location (ref, loc); return ref; } else { tree t = TREE_TYPE (type); ref = build1 (INDIRECT_REF, t, pointer); if (!COMPLETE_OR_VOID_TYPE_P (t) && TREE_CODE (t) != ARRAY_TYPE) { if (!C_TYPE_ERROR_REPORTED (TREE_TYPE (ptr))) { error_at (loc, "dereferencing pointer to incomplete type " "%qT", t); C_TYPE_ERROR_REPORTED (TREE_TYPE (ptr)) = 1; } return error_mark_node; } if (VOID_TYPE_P (t) && c_inhibit_evaluation_warnings == 0) warning_at (loc, 0, "dereferencing %<void *%> pointer"); /* We *must* set TREE_READONLY when dereferencing a pointer to const, so that we get the proper error message if the result is used to assign to. Also, &* is supposed to be a no-op. And ANSI C seems to specify that the type of the result should be the const type. */ /* A de-reference of a pointer to const is not a const. It is valid to change it via some other pointer. */ TREE_READONLY (ref) = TYPE_READONLY (t); TREE_SIDE_EFFECTS (ref) = TYPE_VOLATILE (t) || TREE_SIDE_EFFECTS (pointer); TREE_THIS_VOLATILE (ref) = TYPE_VOLATILE (t); protected_set_expr_location (ref, loc); return ref; } } else if (TREE_CODE (pointer) != ERROR_MARK) invalid_indirection_error (loc, type, errstring); return error_mark_node; } /* This handles expressions of the form "a[i]", which denotes an array reference. This is logically equivalent in C to *(a+i), but we may do it differently. If A is a variable or a member, we generate a primitive ARRAY_REF. This avoids forcing the array out of registers, and can work on arrays that are not lvalues (for example, members of structures returned by functions). For vector types, allow vector[i] but not i[vector], and create *(((type*)&vectortype) + i) for the expression. LOC is the location to use for the returned expression. */ tree build_array_ref (location_t loc, tree array, tree index) { tree ret; bool swapped = false; if (TREE_TYPE (array) == error_mark_node || TREE_TYPE (index) == error_mark_node) return error_mark_node; if (flag_cilkplus && contains_array_notation_expr (index)) { size_t rank = 0; if (!find_rank (loc, index, index, true, &rank)) return error_mark_node; if (rank > 1) { error_at (loc, "rank of the array's index is greater than 1"); return error_mark_node; } } if (TREE_CODE (TREE_TYPE (array)) != ARRAY_TYPE && TREE_CODE (TREE_TYPE (array)) != POINTER_TYPE /* Allow vector[index] but not index[vector]. */ && TREE_CODE (TREE_TYPE (array)) != VECTOR_TYPE) { tree temp; if (TREE_CODE (TREE_TYPE (index)) != ARRAY_TYPE && TREE_CODE (TREE_TYPE (index)) != POINTER_TYPE) { error_at (loc, "subscripted value is neither array nor pointer nor vector"); return error_mark_node; } temp = array; array = index; index = temp; swapped = true; } if (!INTEGRAL_TYPE_P (TREE_TYPE (index))) { error_at (loc, "array subscript is not an integer"); return error_mark_node; } if (TREE_CODE (TREE_TYPE (TREE_TYPE (array))) == FUNCTION_TYPE) { error_at (loc, "subscripted value is pointer to function"); return error_mark_node; } /* ??? Existing practice has been to warn only when the char index is syntactically the index, not for char[array]. */ if (!swapped) warn_array_subscript_with_type_char (loc, index); /* Apply default promotions *after* noticing character types. */ index = default_conversion (index); if (index == error_mark_node) return error_mark_node; gcc_assert (TREE_CODE (TREE_TYPE (index)) == INTEGER_TYPE); bool non_lvalue = convert_vector_to_pointer_for_subscript (loc, &array, index); if (TREE_CODE (TREE_TYPE (array)) == ARRAY_TYPE) { tree rval, type; /* An array that is indexed by a non-constant cannot be stored in a register; we must be able to do address arithmetic on its address. Likewise an array of elements of variable size. */ if (TREE_CODE (index) != INTEGER_CST || (COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (array))) && TREE_CODE (TYPE_SIZE (TREE_TYPE (TREE_TYPE (array)))) != INTEGER_CST)) { if (!c_mark_addressable (array)) return error_mark_node; } /* An array that is indexed by a constant value which is not within the array bounds cannot be stored in a register either; because we would get a crash in store_bit_field/extract_bit_field when trying to access a non-existent part of the register. */ if (TREE_CODE (index) == INTEGER_CST && TYPE_DOMAIN (TREE_TYPE (array)) && !int_fits_type_p (index, TYPE_DOMAIN (TREE_TYPE (array)))) { if (!c_mark_addressable (array)) return error_mark_node; } if (pedantic || warn_c90_c99_compat) { tree foo = array; while (TREE_CODE (foo) == COMPONENT_REF) foo = TREE_OPERAND (foo, 0); if (TREE_CODE (foo) == VAR_DECL && C_DECL_REGISTER (foo)) pedwarn (loc, OPT_Wpedantic, "ISO C forbids subscripting %<register%> array"); else if (!lvalue_p (foo)) pedwarn_c90 (loc, OPT_Wpedantic, "ISO C90 forbids subscripting non-lvalue " "array"); } type = TREE_TYPE (TREE_TYPE (array)); rval = build4 (ARRAY_REF, type, array, index, NULL_TREE, NULL_TREE); /* Array ref is const/volatile if the array elements are or if the array is. */ TREE_READONLY (rval) |= (TYPE_READONLY (TREE_TYPE (TREE_TYPE (array))) | TREE_READONLY (array)); TREE_SIDE_EFFECTS (rval) |= (TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (array))) | TREE_SIDE_EFFECTS (array)); TREE_THIS_VOLATILE (rval) |= (TYPE_VOLATILE (TREE_TYPE (TREE_TYPE (array))) /* This was added by rms on 16 Nov 91. It fixes vol struct foo *a; a->elts[1] in an inline function. Hope it doesn't break something else. */ | TREE_THIS_VOLATILE (array)); ret = require_complete_type (rval); protected_set_expr_location (ret, loc); if (non_lvalue) ret = non_lvalue_loc (loc, ret); return ret; } else { tree ar = default_conversion (array); if (ar == error_mark_node) return ar; gcc_assert (TREE_CODE (TREE_TYPE (ar)) == POINTER_TYPE); gcc_assert (TREE_CODE (TREE_TYPE (TREE_TYPE (ar))) != FUNCTION_TYPE); ret = build_indirect_ref (loc, build_binary_op (loc, PLUS_EXPR, ar, index, 0), RO_ARRAY_INDEXING); if (non_lvalue) ret = non_lvalue_loc (loc, ret); return ret; } } /* Build an external reference to identifier ID. FUN indicates whether this will be used for a function call. LOC is the source location of the identifier. This sets *TYPE to the type of the identifier, which is not the same as the type of the returned value for CONST_DECLs defined as enum constants. If the type of the identifier is not available, *TYPE is set to NULL. */ tree build_external_ref (location_t loc, tree id, int fun, tree *type) { tree ref; tree decl = lookup_name (id); /* In Objective-C, an instance variable (ivar) may be preferred to whatever lookup_name() found. */ decl = objc_lookup_ivar (decl, id); *type = NULL; if (decl && decl != error_mark_node) { ref = decl; *type = TREE_TYPE (ref); } else if (fun) /* Implicit function declaration. */ ref = implicitly_declare (loc, id); else if (decl == error_mark_node) /* Don't complain about something that's already been complained about. */ return error_mark_node; else { undeclared_variable (loc, id); return error_mark_node; } if (TREE_TYPE (ref) == error_mark_node) return error_mark_node; if (TREE_DEPRECATED (ref)) warn_deprecated_use (ref, NULL_TREE); /* Recursive call does not count as usage. */ if (ref != current_function_decl) { TREE_USED (ref) = 1; } if (TREE_CODE (ref) == FUNCTION_DECL && !in_alignof) { if (!in_sizeof && !in_typeof) C_DECL_USED (ref) = 1; else if (DECL_INITIAL (ref) == 0 && DECL_EXTERNAL (ref) && !TREE_PUBLIC (ref)) record_maybe_used_decl (ref); } if (TREE_CODE (ref) == CONST_DECL) { used_types_insert (TREE_TYPE (ref)); if (warn_cxx_compat && TREE_CODE (TREE_TYPE (ref)) == ENUMERAL_TYPE && C_TYPE_DEFINED_IN_STRUCT (TREE_TYPE (ref))) { warning_at (loc, OPT_Wc___compat, ("enum constant defined in struct or union " "is not visible in C++")); inform (DECL_SOURCE_LOCATION (ref), "enum constant defined here"); } ref = DECL_INITIAL (ref); TREE_CONSTANT (ref) = 1; } else if (current_function_decl != 0 && !DECL_FILE_SCOPE_P (current_function_decl) && (TREE_CODE (ref) == VAR_DECL || TREE_CODE (ref) == PARM_DECL || TREE_CODE (ref) == FUNCTION_DECL)) { tree context = decl_function_context (ref); if (context != 0 && context != current_function_decl) DECL_NONLOCAL (ref) = 1; } /* C99 6.7.4p3: An inline definition of a function with external linkage ... shall not contain a reference to an identifier with internal linkage. */ else if (current_function_decl != 0 && DECL_DECLARED_INLINE_P (current_function_decl) && DECL_EXTERNAL (current_function_decl) && VAR_OR_FUNCTION_DECL_P (ref) && (TREE_CODE (ref) != VAR_DECL || TREE_STATIC (ref)) && ! TREE_PUBLIC (ref) && DECL_CONTEXT (ref) != current_function_decl) record_inline_static (loc, current_function_decl, ref, csi_internal); return ref; } /* Record details of decls possibly used inside sizeof or typeof. */ struct maybe_used_decl { /* The decl. */ tree decl; /* The level seen at (in_sizeof + in_typeof). */ int level; /* The next one at this level or above, or NULL. */ struct maybe_used_decl *next; }; static struct maybe_used_decl *maybe_used_decls; /* Record that DECL, an undefined static function reference seen inside sizeof or typeof, might be used if the operand of sizeof is a VLA type or the operand of typeof is a variably modified type. */ static void record_maybe_used_decl (tree decl) { struct maybe_used_decl *t = XOBNEW (&parser_obstack, struct maybe_used_decl); t->decl = decl; t->level = in_sizeof + in_typeof; t->next = maybe_used_decls; maybe_used_decls = t; } /* Pop the stack of decls possibly used inside sizeof or typeof. If USED is false, just discard them. If it is true, mark them used (if no longer inside sizeof or typeof) or move them to the next level up (if still inside sizeof or typeof). */ void pop_maybe_used (bool used) { struct maybe_used_decl *p = maybe_used_decls; int cur_level = in_sizeof + in_typeof; while (p && p->level > cur_level) { if (used) { if (cur_level == 0) C_DECL_USED (p->decl) = 1; else p->level = cur_level; } p = p->next; } if (!used || cur_level == 0) maybe_used_decls = p; } /* Return the result of sizeof applied to EXPR. */ struct c_expr c_expr_sizeof_expr (location_t loc, struct c_expr expr) { struct c_expr ret; if (expr.value == error_mark_node) { ret.value = error_mark_node; ret.original_code = ERROR_MARK; ret.original_type = NULL; pop_maybe_used (false); } else { bool expr_const_operands = true; if (TREE_CODE (expr.value) == PARM_DECL && C_ARRAY_PARAMETER (expr.value)) { if (warning_at (loc, OPT_Wsizeof_array_argument, "%<sizeof%> on array function parameter %qE will " "return size of %qT", expr.value, expr.original_type)) inform (DECL_SOURCE_LOCATION (expr.value), "declared here"); } tree folded_expr = c_fully_fold (expr.value, require_constant_value, &expr_const_operands); ret.value = c_sizeof (loc, TREE_TYPE (folded_expr)); c_last_sizeof_arg = expr.value; ret.original_code = SIZEOF_EXPR; ret.original_type = NULL; if (c_vla_type_p (TREE_TYPE (folded_expr))) { /* sizeof is evaluated when given a vla (C99 6.5.3.4p2). */ ret.value = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (ret.value), folded_expr, ret.value); C_MAYBE_CONST_EXPR_NON_CONST (ret.value) = !expr_const_operands; SET_EXPR_LOCATION (ret.value, loc); } pop_maybe_used (C_TYPE_VARIABLE_SIZE (TREE_TYPE (folded_expr))); } return ret; } /* Return the result of sizeof applied to T, a structure for the type name passed to sizeof (rather than the type itself). LOC is the location of the original expression. */ struct c_expr c_expr_sizeof_type (location_t loc, struct c_type_name *t) { tree type; struct c_expr ret; tree type_expr = NULL_TREE; bool type_expr_const = true; type = groktypename (t, &type_expr, &type_expr_const); ret.value = c_sizeof (loc, type); c_last_sizeof_arg = type; ret.original_code = SIZEOF_EXPR; ret.original_type = NULL; if ((type_expr || TREE_CODE (ret.value) == INTEGER_CST) && c_vla_type_p (type)) { /* If the type is a [*] array, it is a VLA but is represented as having a size of zero. In such a case we must ensure that the result of sizeof does not get folded to a constant by c_fully_fold, because if the size is evaluated the result is not constant and so constraints on zero or negative size arrays must not be applied when this sizeof call is inside another array declarator. */ if (!type_expr) type_expr = integer_zero_node; ret.value = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (ret.value), type_expr, ret.value); C_MAYBE_CONST_EXPR_NON_CONST (ret.value) = !type_expr_const; } pop_maybe_used (type != error_mark_node ? C_TYPE_VARIABLE_SIZE (type) : false); return ret; } /* Build a function call to function FUNCTION with parameters PARAMS. The function call is at LOC. PARAMS is a list--a chain of TREE_LIST nodes--in which the TREE_VALUE of each node is a parameter-expression. FUNCTION's data type may be a function type or a pointer-to-function. */ tree build_function_call (location_t loc, tree function, tree params) { vec<tree, va_gc> *v; tree ret; vec_alloc (v, list_length (params)); for (; params; params = TREE_CHAIN (params)) v->quick_push (TREE_VALUE (params)); ret = c_build_function_call_vec (loc, vNULL, function, v, NULL); vec_free (v); return ret; } /* Give a note about the location of the declaration of DECL. */ static void inform_declaration (tree decl) { if (decl && (TREE_CODE (decl) != FUNCTION_DECL || !DECL_BUILT_IN (decl))) inform (DECL_SOURCE_LOCATION (decl), "declared here"); } /* Build a function call to function FUNCTION with parameters PARAMS. ORIGTYPES, if not NULL, is a vector of types; each element is either NULL or the original type of the corresponding element in PARAMS. The original type may differ from TREE_TYPE of the parameter for enums. FUNCTION's data type may be a function type or pointer-to-function. This function changes the elements of PARAMS. */ tree build_function_call_vec (location_t loc, vec<location_t> arg_loc, tree function, vec<tree, va_gc> *params, vec<tree, va_gc> *origtypes) { tree fntype, fundecl = 0; tree name = NULL_TREE, result; tree tem; int nargs; tree *argarray; /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */ STRIP_TYPE_NOPS (function); /* Convert anything with function type to a pointer-to-function. */ if (TREE_CODE (function) == FUNCTION_DECL) { name = DECL_NAME (function); if (flag_tm) tm_malloc_replacement (function); fundecl = function; /* Atomic functions have type checking/casting already done. They are often rewritten and don't match the original parameter list. */ if (name && !strncmp (IDENTIFIER_POINTER (name), "__atomic_", 9)) origtypes = NULL; if (flag_cilkplus && is_cilkplus_reduce_builtin (function)) origtypes = NULL; } if (TREE_CODE (TREE_TYPE (function)) == FUNCTION_TYPE) function = function_to_pointer_conversion (loc, function); /* For Objective-C, convert any calls via a cast to OBJC_TYPE_REF expressions, like those used for ObjC messenger dispatches. */ if (params && !params->is_empty ()) function = objc_rewrite_function_call (function, (*params)[0]); function = c_fully_fold (function, false, NULL); fntype = TREE_TYPE (function); if (TREE_CODE (fntype) == ERROR_MARK) return error_mark_node; if (!(TREE_CODE (fntype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (fntype)) == FUNCTION_TYPE)) { if (!flag_diagnostics_show_caret) error_at (loc, "called object %qE is not a function or function pointer", function); else if (DECL_P (function)) { error_at (loc, "called object %qD is not a function or function pointer", function); inform_declaration (function); } else error_at (loc, "called object is not a function or function pointer"); return error_mark_node; } if (fundecl && TREE_THIS_VOLATILE (fundecl)) current_function_returns_abnormally = 1; /* fntype now gets the type of function pointed to. */ fntype = TREE_TYPE (fntype); /* Convert the parameters to the types declared in the function prototype, or apply default promotions. */ nargs = convert_arguments (loc, arg_loc, TYPE_ARG_TYPES (fntype), params, origtypes, function, fundecl); if (nargs < 0) return error_mark_node; /* Check that the function is called through a compatible prototype. If it is not, warn. */ if (CONVERT_EXPR_P (function) && TREE_CODE (tem = TREE_OPERAND (function, 0)) == ADDR_EXPR && TREE_CODE (tem = TREE_OPERAND (tem, 0)) == FUNCTION_DECL && !comptypes (fntype, TREE_TYPE (tem))) { tree return_type = TREE_TYPE (fntype); /* This situation leads to run-time undefined behavior. We can't, therefore, simply error unless we can prove that all possible executions of the program must execute the code. */ warning_at (loc, 0, "function called through a non-compatible type"); if (VOID_TYPE_P (return_type) && TYPE_QUALS (return_type) != TYPE_UNQUALIFIED) pedwarn (loc, 0, "function with qualified void return type called"); } argarray = vec_safe_address (params); /* Check that arguments to builtin functions match the expectations. */ if (fundecl && DECL_BUILT_IN (fundecl) && DECL_BUILT_IN_CLASS (fundecl) == BUILT_IN_NORMAL && !check_builtin_function_arguments (fundecl, nargs, argarray)) return error_mark_node; /* Check that the arguments to the function are valid. */ check_function_arguments (fntype, nargs, argarray); if (name != NULL_TREE && !strncmp (IDENTIFIER_POINTER (name), "__builtin_", 10)) { if (require_constant_value) result = fold_build_call_array_initializer_loc (loc, TREE_TYPE (fntype), function, nargs, argarray); else result = fold_build_call_array_loc (loc, TREE_TYPE (fntype), function, nargs, argarray); if (TREE_CODE (result) == NOP_EXPR && TREE_CODE (TREE_OPERAND (result, 0)) == INTEGER_CST) STRIP_TYPE_NOPS (result); } else result = build_call_array_loc (loc, TREE_TYPE (fntype), function, nargs, argarray); if (VOID_TYPE_P (TREE_TYPE (result))) { if (TYPE_QUALS (TREE_TYPE (result)) != TYPE_UNQUALIFIED) pedwarn (loc, 0, "function with qualified void return type called"); return result; } return require_complete_type (result); } /* Like build_function_call_vec, but call also resolve_overloaded_builtin. */ tree c_build_function_call_vec (location_t loc, vec<location_t> arg_loc, tree function, vec<tree, va_gc> *params, vec<tree, va_gc> *origtypes) { /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */ STRIP_TYPE_NOPS (function); /* Convert anything with function type to a pointer-to-function. */ if (TREE_CODE (function) == FUNCTION_DECL) { /* Implement type-directed function overloading for builtins. resolve_overloaded_builtin and targetm.resolve_overloaded_builtin handle all the type checking. The result is a complete expression that implements this function call. */ tree tem = resolve_overloaded_builtin (loc, function, params); if (tem) return tem; } return build_function_call_vec (loc, arg_loc, function, params, origtypes); } /* Convert the argument expressions in the vector VALUES to the types in the list TYPELIST. If TYPELIST is exhausted, or when an element has NULL as its type, perform the default conversions. ORIGTYPES is the original types of the expressions in VALUES. This holds the type of enum values which have been converted to integral types. It may be NULL. FUNCTION is a tree for the called function. It is used only for error messages, where it is formatted with %qE. This is also where warnings about wrong number of args are generated. ARG_LOC are locations of function arguments (if any). Returns the actual number of arguments processed (which may be less than the length of VALUES in some error situations), or -1 on failure. */ static int convert_arguments (location_t loc, vec<location_t> arg_loc, tree typelist, vec<tree, va_gc> *values, vec<tree, va_gc> *origtypes, tree function, tree fundecl) { tree typetail, val; unsigned int parmnum; bool error_args = false; const bool type_generic = fundecl && lookup_attribute ("type generic", TYPE_ATTRIBUTES (TREE_TYPE (fundecl))); bool type_generic_remove_excess_precision = false; tree selector; /* Change pointer to function to the function itself for diagnostics. */ if (TREE_CODE (function) == ADDR_EXPR && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL) function = TREE_OPERAND (function, 0); /* Handle an ObjC selector specially for diagnostics. */ selector = objc_message_selector (); /* For type-generic built-in functions, determine whether excess precision should be removed (classification) or not (comparison). */ if (type_generic && DECL_BUILT_IN (fundecl) && DECL_BUILT_IN_CLASS (fundecl) == BUILT_IN_NORMAL) { switch (DECL_FUNCTION_CODE (fundecl)) { case BUILT_IN_ISFINITE: case BUILT_IN_ISINF: case BUILT_IN_ISINF_SIGN: case BUILT_IN_ISNAN: case BUILT_IN_ISNORMAL: case BUILT_IN_FPCLASSIFY: type_generic_remove_excess_precision = true; break; default: type_generic_remove_excess_precision = false; break; } } if (flag_cilkplus && fundecl && is_cilkplus_reduce_builtin (fundecl)) return vec_safe_length (values); /* Scan the given expressions and types, producing individual converted arguments. */ for (typetail = typelist, parmnum = 0; values && values->iterate (parmnum, &val); ++parmnum) { tree type = typetail ? TREE_VALUE (typetail) : 0; tree valtype = TREE_TYPE (val); tree rname = function; int argnum = parmnum + 1; const char *invalid_func_diag; bool excess_precision = false; bool npc; tree parmval; /* Some __atomic_* builtins have additional hidden argument at position 0. */ location_t ploc = !arg_loc.is_empty () && values->length () == arg_loc.length () ? expansion_point_location_if_in_system_header (arg_loc[parmnum]) : input_location; if (type == void_type_node) { if (selector) error_at (loc, "too many arguments to method %qE", selector); else error_at (loc, "too many arguments to function %qE", function); inform_declaration (fundecl); return error_args ? -1 : (int) parmnum; } if (selector && argnum > 2) { rname = selector; argnum -= 2; } npc = null_pointer_constant_p (val); /* If there is excess precision and a prototype, convert once to the required type rather than converting via the semantic type. Likewise without a prototype a float value represented as long double should be converted once to double. But for type-generic classification functions excess precision must be removed here. */ if (TREE_CODE (val) == EXCESS_PRECISION_EXPR && (type || !type_generic || !type_generic_remove_excess_precision)) { val = TREE_OPERAND (val, 0); excess_precision = true; } val = c_fully_fold (val, false, NULL); STRIP_TYPE_NOPS (val); val = require_complete_type (val); if (type != 0) { /* Formal parm type is specified by a function prototype. */ if (type == error_mark_node || !COMPLETE_TYPE_P (type)) { error_at (ploc, "type of formal parameter %d is incomplete", parmnum + 1); parmval = val; } else { tree origtype; /* Optionally warn about conversions that differ from the default conversions. */ if (warn_traditional_conversion || warn_traditional) { unsigned int formal_prec = TYPE_PRECISION (type); if (INTEGRAL_TYPE_P (type) && TREE_CODE (valtype) == REAL_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as integer rather " "than floating due to prototype", argnum, rname); if (INTEGRAL_TYPE_P (type) && TREE_CODE (valtype) == COMPLEX_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as integer rather " "than complex due to prototype", argnum, rname); else if (TREE_CODE (type) == COMPLEX_TYPE && TREE_CODE (valtype) == REAL_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as complex rather " "than floating due to prototype", argnum, rname); else if (TREE_CODE (type) == REAL_TYPE && INTEGRAL_TYPE_P (valtype)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as floating rather " "than integer due to prototype", argnum, rname); else if (TREE_CODE (type) == COMPLEX_TYPE && INTEGRAL_TYPE_P (valtype)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as complex rather " "than integer due to prototype", argnum, rname); else if (TREE_CODE (type) == REAL_TYPE && TREE_CODE (valtype) == COMPLEX_TYPE) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE as floating rather " "than complex due to prototype", argnum, rname); /* ??? At some point, messages should be written about conversions between complex types, but that's too messy to do now. */ else if (TREE_CODE (type) == REAL_TYPE && TREE_CODE (valtype) == REAL_TYPE) { /* Warn if any argument is passed as `float', since without a prototype it would be `double'. */ if (formal_prec == TYPE_PRECISION (float_type_node) && type != dfloat32_type_node) warning_at (ploc, 0, "passing argument %d of %qE as %<float%> " "rather than %<double%> due to prototype", argnum, rname); /* Warn if mismatch between argument and prototype for decimal float types. Warn of conversions with binary float types and of precision narrowing due to prototype. */ else if (type != valtype && (type == dfloat32_type_node || type == dfloat64_type_node || type == dfloat128_type_node || valtype == dfloat32_type_node || valtype == dfloat64_type_node || valtype == dfloat128_type_node) && (formal_prec <= TYPE_PRECISION (valtype) || (type == dfloat128_type_node && (valtype != dfloat64_type_node && (valtype != dfloat32_type_node))) || (type == dfloat64_type_node && (valtype != dfloat32_type_node)))) warning_at (ploc, 0, "passing argument %d of %qE as %qT " "rather than %qT due to prototype", argnum, rname, type, valtype); } /* Detect integer changing in width or signedness. These warnings are only activated with -Wtraditional-conversion, not with -Wtraditional. */ else if (warn_traditional_conversion && INTEGRAL_TYPE_P (type) && INTEGRAL_TYPE_P (valtype)) { tree would_have_been = default_conversion (val); tree type1 = TREE_TYPE (would_have_been); if (TREE_CODE (type) == ENUMERAL_TYPE && (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (valtype))) /* No warning if function asks for enum and the actual arg is that enum type. */ ; else if (formal_prec != TYPE_PRECISION (type1)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE " "with different width due to prototype", argnum, rname); else if (TYPE_UNSIGNED (type) == TYPE_UNSIGNED (type1)) ; /* Don't complain if the formal parameter type is an enum, because we can't tell now whether the value was an enum--even the same enum. */ else if (TREE_CODE (type) == ENUMERAL_TYPE) ; else if (TREE_CODE (val) == INTEGER_CST && int_fits_type_p (val, type)) /* Change in signedness doesn't matter if a constant value is unaffected. */ ; /* If the value is extended from a narrower unsigned type, it doesn't matter whether we pass it as signed or unsigned; the value certainly is the same either way. */ else if (TYPE_PRECISION (valtype) < TYPE_PRECISION (type) && TYPE_UNSIGNED (valtype)) ; else if (TYPE_UNSIGNED (type)) warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE " "as unsigned due to prototype", argnum, rname); else warning_at (ploc, OPT_Wtraditional_conversion, "passing argument %d of %qE " "as signed due to prototype", argnum, rname); } } /* Possibly restore an EXCESS_PRECISION_EXPR for the sake of better warnings from convert_and_check. */ if (excess_precision) val = build1 (EXCESS_PRECISION_EXPR, valtype, val); origtype = (!origtypes) ? NULL_TREE : (*origtypes)[parmnum]; parmval = convert_for_assignment (loc, ploc, type, val, origtype, ic_argpass, npc, fundecl, function, parmnum + 1); if (targetm.calls.promote_prototypes (fundecl ? TREE_TYPE (fundecl) : 0) && INTEGRAL_TYPE_P (type) && (TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))) parmval = default_conversion (parmval); } } else if (TREE_CODE (valtype) == REAL_TYPE && (TYPE_PRECISION (valtype) <= TYPE_PRECISION (double_type_node)) && TYPE_MAIN_VARIANT (valtype) != double_type_node && TYPE_MAIN_VARIANT (valtype) != long_double_type_node && !DECIMAL_FLOAT_MODE_P (TYPE_MODE (valtype))) { if (type_generic) parmval = val; else { /* Convert `float' to `double'. */ if (warn_double_promotion && !c_inhibit_evaluation_warnings) warning_at (ploc, OPT_Wdouble_promotion, "implicit conversion from %qT to %qT when passing " "argument to function", valtype, double_type_node); parmval = convert (double_type_node, val); } } else if (excess_precision && !type_generic) /* A "double" argument with excess precision being passed without a prototype or in variable arguments. */ parmval = convert (valtype, val); else if ((invalid_func_diag = targetm.calls.invalid_arg_for_unprototyped_fn (typelist, fundecl, val))) { error (invalid_func_diag); return -1; } else /* Convert `short' and `char' to full-size `int'. */ parmval = default_conversion (val); (*values)[parmnum] = parmval; if (parmval == error_mark_node) error_args = true; if (typetail) typetail = TREE_CHAIN (typetail); } gcc_assert (parmnum == vec_safe_length (values)); if (typetail != 0 && TREE_VALUE (typetail) != void_type_node) { error_at (loc, "too few arguments to function %qE", function); inform_declaration (fundecl); return -1; } return error_args ? -1 : (int) parmnum; } /* This is the entry point used by the parser to build unary operators in the input. CODE, a tree_code, specifies the unary operator, and ARG is the operand. For unary plus, the C parser currently uses CONVERT_EXPR for code. LOC is the location to use for the tree generated. */ struct c_expr parser_build_unary_op (location_t loc, enum tree_code code, struct c_expr arg) { struct c_expr result; result.value = build_unary_op (loc, code, arg.value, 0); result.original_code = code; result.original_type = NULL; if (TREE_OVERFLOW_P (result.value) && !TREE_OVERFLOW_P (arg.value)) overflow_warning (loc, result.value); return result; } /* This is the entry point used by the parser to build binary operators in the input. CODE, a tree_code, specifies the binary operator, and ARG1 and ARG2 are the operands. In addition to constructing the expression, we check for operands that were written with other binary operators in a way that is likely to confuse the user. LOCATION is the location of the binary operator. */ struct c_expr parser_build_binary_op (location_t location, enum tree_code code, struct c_expr arg1, struct c_expr arg2) { struct c_expr result; enum tree_code code1 = arg1.original_code; enum tree_code code2 = arg2.original_code; tree type1 = (arg1.original_type ? arg1.original_type : TREE_TYPE (arg1.value)); tree type2 = (arg2.original_type ? arg2.original_type : TREE_TYPE (arg2.value)); result.value = build_binary_op (location, code, arg1.value, arg2.value, 1); result.original_code = code; result.original_type = NULL; if (TREE_CODE (result.value) == ERROR_MARK) return result; if (location != UNKNOWN_LOCATION) protected_set_expr_location (result.value, location); /* Check for cases such as x+y<<z which users are likely to misinterpret. */ if (warn_parentheses) warn_about_parentheses (location, code, code1, arg1.value, code2, arg2.value); if (warn_logical_op) warn_logical_operator (location, code, TREE_TYPE (result.value), code1, arg1.value, code2, arg2.value); if (warn_logical_not_paren && TREE_CODE_CLASS (code) == tcc_comparison && code1 == TRUTH_NOT_EXPR && code2 != TRUTH_NOT_EXPR /* Avoid warning for !!x == y. */ && (TREE_CODE (arg1.value) != NE_EXPR || !integer_zerop (TREE_OPERAND (arg1.value, 1)))) { /* Avoid warning for !b == y where b has _Bool type. */ tree t = integer_zero_node; if (TREE_CODE (arg1.value) == EQ_EXPR && integer_zerop (TREE_OPERAND (arg1.value, 1)) && TREE_TYPE (TREE_OPERAND (arg1.value, 0)) == integer_type_node) { t = TREE_OPERAND (arg1.value, 0); do { if (TREE_TYPE (t) != integer_type_node) break; if (TREE_CODE (t) == C_MAYBE_CONST_EXPR) t = C_MAYBE_CONST_EXPR_EXPR (t); else if (CONVERT_EXPR_P (t)) t = TREE_OPERAND (t, 0); else break; } while (1); } if (TREE_CODE (TREE_TYPE (t)) != BOOLEAN_TYPE) warn_logical_not_parentheses (location, code, arg2.value); } /* Warn about comparisons against string literals, with the exception of testing for equality or inequality of a string literal with NULL. */ if (code == EQ_EXPR || code == NE_EXPR) { if ((code1 == STRING_CST && !integer_zerop (arg2.value)) || (code2 == STRING_CST && !integer_zerop (arg1.value))) warning_at (location, OPT_Waddress, "comparison with string literal results in unspecified behavior"); } else if (TREE_CODE_CLASS (code) == tcc_comparison && (code1 == STRING_CST || code2 == STRING_CST)) warning_at (location, OPT_Waddress, "comparison with string literal results in unspecified behavior"); if (TREE_OVERFLOW_P (result.value) && !TREE_OVERFLOW_P (arg1.value) && !TREE_OVERFLOW_P (arg2.value)) overflow_warning (location, result.value); /* Warn about comparisons of different enum types. */ if (warn_enum_compare && TREE_CODE_CLASS (code) == tcc_comparison && TREE_CODE (type1) == ENUMERAL_TYPE && TREE_CODE (type2) == ENUMERAL_TYPE && TYPE_MAIN_VARIANT (type1) != TYPE_MAIN_VARIANT (type2)) warning_at (location, OPT_Wenum_compare, "comparison between %qT and %qT", type1, type2); return result; } /* Return a tree for the difference of pointers OP0 and OP1. The resulting tree has type int. */ static tree pointer_diff (location_t loc, tree op0, tree op1) { tree restype = ptrdiff_type_node; tree result, inttype; addr_space_t as0 = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (op0))); addr_space_t as1 = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (op1))); tree target_type = TREE_TYPE (TREE_TYPE (op0)); tree orig_op1 = op1; /* If the operands point into different address spaces, we need to explicitly convert them to pointers into the common address space before we can subtract the numerical address values. */ if (as0 != as1) { addr_space_t as_common; tree common_type; /* Determine the common superset address space. This is guaranteed to exist because the caller verified that comp_target_types returned non-zero. */ if (!addr_space_superset (as0, as1, &as_common)) gcc_unreachable (); common_type = common_pointer_type (TREE_TYPE (op0), TREE_TYPE (op1)); op0 = convert (common_type, op0); op1 = convert (common_type, op1); } /* Determine integer type to perform computations in. This will usually be the same as the result type (ptrdiff_t), but may need to be a wider type if pointers for the address space are wider than ptrdiff_t. */ if (TYPE_PRECISION (restype) < TYPE_PRECISION (TREE_TYPE (op0))) inttype = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op0)), 0); else inttype = restype; if (TREE_CODE (target_type) == VOID_TYPE) pedwarn (loc, OPT_Wpointer_arith, "pointer of type %<void *%> used in subtraction"); if (TREE_CODE (target_type) == FUNCTION_TYPE) pedwarn (loc, OPT_Wpointer_arith, "pointer to a function used in subtraction"); /* First do the subtraction as integers; then drop through to build the divide operator. Do not do default conversions on the minus operator in case restype is a short type. */ op0 = build_binary_op (loc, MINUS_EXPR, convert (inttype, op0), convert (inttype, op1), 0); /* This generates an error if op1 is pointer to incomplete type. */ if (!COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (TREE_TYPE (orig_op1)))) error_at (loc, "arithmetic on pointer to an incomplete type"); op1 = c_size_in_bytes (target_type); if (pointer_to_zero_sized_aggr_p (TREE_TYPE (orig_op1))) error_at (loc, "arithmetic on pointer to an empty aggregate"); /* Divide by the size, in easiest possible way. */ result = fold_build2_loc (loc, EXACT_DIV_EXPR, inttype, op0, convert (inttype, op1)); /* Convert to final result type if necessary. */ return convert (restype, result); } /* Expand atomic compound assignments into an approriate sequence as specified by the C11 standard section 6.5.16.2. given _Atomic T1 E1 T2 E2 E1 op= E2 This sequence is used for all types for which these operations are supported. In addition, built-in versions of the 'fe' prefixed routines may need to be invoked for floating point (real, complex or vector) when floating-point exceptions are supported. See 6.5.16.2 footnote 113. T1 newval; T1 old; T1 *addr T2 val fenv_t fenv addr = &E1; val = (E2); __atomic_load (addr, &old, SEQ_CST); feholdexcept (&fenv); loop: newval = old op val; if (__atomic_compare_exchange_strong (addr, &old, &newval, SEQ_CST, SEQ_CST)) goto done; feclearexcept (FE_ALL_EXCEPT); goto loop: done: feupdateenv (&fenv); Also note that the compiler is simply issuing the generic form of the atomic operations. This requires temp(s) and has their address taken. The atomic processing is smart enough to figure out when the size of an object can utilize a lock-free version, and convert the built-in call to the appropriate lock-free routine. The optimizers will then dispose of any temps that are no longer required, and lock-free implementations are utilized as long as there is target support for the required size. If the operator is NOP_EXPR, then this is a simple assignment, and an __atomic_store is issued to perform the assignment rather than the above loop. */ /* Build an atomic assignment at LOC, expanding into the proper sequence to store LHS MODIFYCODE= RHS. Return a value representing the result of the operation, unless RETURN_OLD_P in which case return the old value of LHS (this is only for postincrement and postdecrement). */ static tree build_atomic_assign (location_t loc, tree lhs, enum tree_code modifycode, tree rhs, bool return_old_p) { tree fndecl, func_call; vec<tree, va_gc> *params; tree val, nonatomic_lhs_type, nonatomic_rhs_type, newval, newval_addr; tree old, old_addr; tree compound_stmt; tree stmt, goto_stmt; tree loop_label, loop_decl, done_label, done_decl; tree lhs_type = TREE_TYPE (lhs); tree lhs_addr = build_unary_op (loc, ADDR_EXPR, lhs, 0); tree seq_cst = build_int_cst (integer_type_node, MEMMODEL_SEQ_CST); tree rhs_type = TREE_TYPE (rhs); gcc_assert (TYPE_ATOMIC (lhs_type)); if (return_old_p) gcc_assert (modifycode == PLUS_EXPR || modifycode == MINUS_EXPR); /* Allocate enough vector items for a compare_exchange. */ vec_alloc (params, 6); /* Create a compound statement to hold the sequence of statements with a loop. */ compound_stmt = c_begin_compound_stmt (false); /* Fold the RHS if it hasn't already been folded. */ if (modifycode != NOP_EXPR) rhs = c_fully_fold (rhs, false, NULL); /* Remove the qualifiers for the rest of the expressions and create the VAL temp variable to hold the RHS. */ nonatomic_lhs_type = build_qualified_type (lhs_type, TYPE_UNQUALIFIED); nonatomic_rhs_type = build_qualified_type (rhs_type, TYPE_UNQUALIFIED); val = create_tmp_var (nonatomic_rhs_type); TREE_ADDRESSABLE (val) = 1; TREE_NO_WARNING (val) = 1; rhs = build2 (MODIFY_EXPR, nonatomic_rhs_type, val, rhs); SET_EXPR_LOCATION (rhs, loc); add_stmt (rhs); /* NOP_EXPR indicates it's a straight store of the RHS. Simply issue an atomic_store. */ if (modifycode == NOP_EXPR) { /* Build __atomic_store (&lhs, &val, SEQ_CST) */ rhs = build_unary_op (loc, ADDR_EXPR, val, 0); fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_STORE); params->quick_push (lhs_addr); params->quick_push (rhs); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); add_stmt (func_call); /* Finish the compound statement. */ compound_stmt = c_end_compound_stmt (loc, compound_stmt, false); /* VAL is the value which was stored, return a COMPOUND_STMT of the statement and that value. */ return build2 (COMPOUND_EXPR, nonatomic_lhs_type, compound_stmt, val); } /* Create the variables and labels required for the op= form. */ old = create_tmp_var (nonatomic_lhs_type); old_addr = build_unary_op (loc, ADDR_EXPR, old, 0); TREE_ADDRESSABLE (old) = 1; TREE_NO_WARNING (old) = 1; newval = create_tmp_var (nonatomic_lhs_type); newval_addr = build_unary_op (loc, ADDR_EXPR, newval, 0); TREE_ADDRESSABLE (newval) = 1; loop_decl = create_artificial_label (loc); loop_label = build1 (LABEL_EXPR, void_type_node, loop_decl); done_decl = create_artificial_label (loc); done_label = build1 (LABEL_EXPR, void_type_node, done_decl); /* __atomic_load (addr, &old, SEQ_CST). */ fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_LOAD); params->quick_push (lhs_addr); params->quick_push (old_addr); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); add_stmt (func_call); params->truncate (0); /* Create the expressions for floating-point environment manipulation, if required. */ bool need_fenv = (flag_trapping_math && (FLOAT_TYPE_P (lhs_type) || FLOAT_TYPE_P (rhs_type))); tree hold_call = NULL_TREE, clear_call = NULL_TREE, update_call = NULL_TREE; if (need_fenv) targetm.atomic_assign_expand_fenv (&hold_call, &clear_call, &update_call); if (hold_call) add_stmt (hold_call); /* loop: */ add_stmt (loop_label); /* newval = old + val; */ rhs = build_binary_op (loc, modifycode, old, val, 1); rhs = convert_for_assignment (loc, UNKNOWN_LOCATION, nonatomic_lhs_type, rhs, NULL_TREE, ic_assign, false, NULL_TREE, NULL_TREE, 0); if (rhs != error_mark_node) { rhs = build2 (MODIFY_EXPR, nonatomic_lhs_type, newval, rhs); SET_EXPR_LOCATION (rhs, loc); add_stmt (rhs); } /* if (__atomic_compare_exchange (addr, &old, &new, false, SEQ_CST, SEQ_CST)) goto done; */ fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_COMPARE_EXCHANGE); params->quick_push (lhs_addr); params->quick_push (old_addr); params->quick_push (newval_addr); params->quick_push (integer_zero_node); params->quick_push (seq_cst); params->quick_push (seq_cst); func_call = c_build_function_call_vec (loc, vNULL, fndecl, params, NULL); goto_stmt = build1 (GOTO_EXPR, void_type_node, done_decl); SET_EXPR_LOCATION (goto_stmt, loc); stmt = build3 (COND_EXPR, void_type_node, func_call, goto_stmt, NULL_TREE); SET_EXPR_LOCATION (stmt, loc); add_stmt (stmt); if (clear_call) add_stmt (clear_call); /* goto loop; */ goto_stmt = build1 (GOTO_EXPR, void_type_node, loop_decl); SET_EXPR_LOCATION (goto_stmt, loc); add_stmt (goto_stmt); /* done: */ add_stmt (done_label); if (update_call) add_stmt (update_call); /* Finish the compound statement. */ compound_stmt = c_end_compound_stmt (loc, compound_stmt, false); /* NEWVAL is the value that was successfully stored, return a COMPOUND_EXPR of the statement and the appropriate value. */ return build2 (COMPOUND_EXPR, nonatomic_lhs_type, compound_stmt, return_old_p ? old : newval); } /* Construct and perhaps optimize a tree representation for a unary operation. CODE, a tree_code, specifies the operation and XARG is the operand. For any CODE other than ADDR_EXPR, FLAG nonzero suppresses the default promotions (such as from short to int). For ADDR_EXPR, the default promotions are not applied; FLAG nonzero allows non-lvalues; this is only used to handle conversion of non-lvalue arrays to pointers in C99. LOCATION is the location of the operator. */ tree build_unary_op (location_t location, enum tree_code code, tree xarg, int flag) { /* No default_conversion here. It causes trouble for ADDR_EXPR. */ tree arg = xarg; tree argtype = 0; enum tree_code typecode; tree val; tree ret = error_mark_node; tree eptype = NULL_TREE; int noconvert = flag; const char *invalid_op_diag; bool int_operands; int_operands = EXPR_INT_CONST_OPERANDS (xarg); if (int_operands) arg = remove_c_maybe_const_expr (arg); if (code != ADDR_EXPR) arg = require_complete_type (arg); typecode = TREE_CODE (TREE_TYPE (arg)); if (typecode == ERROR_MARK) return error_mark_node; if (typecode == ENUMERAL_TYPE || typecode == BOOLEAN_TYPE) typecode = INTEGER_TYPE; if ((invalid_op_diag = targetm.invalid_unary_op (code, TREE_TYPE (xarg)))) { error_at (location, invalid_op_diag); return error_mark_node; } if (TREE_CODE (arg) == EXCESS_PRECISION_EXPR) { eptype = TREE_TYPE (arg); arg = TREE_OPERAND (arg, 0); } switch (code) { case CONVERT_EXPR: /* This is used for unary plus, because a CONVERT_EXPR is enough to prevent anybody from looking inside for associativity, but won't generate any code. */ if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE || typecode == FIXED_POINT_TYPE || typecode == COMPLEX_TYPE || typecode == VECTOR_TYPE)) { error_at (location, "wrong type argument to unary plus"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); arg = non_lvalue_loc (location, arg); break; case NEGATE_EXPR: if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE || typecode == FIXED_POINT_TYPE || typecode == COMPLEX_TYPE || typecode == VECTOR_TYPE)) { error_at (location, "wrong type argument to unary minus"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); break; case BIT_NOT_EXPR: /* ~ works on integer types and non float vectors. */ if (typecode == INTEGER_TYPE || (typecode == VECTOR_TYPE && !VECTOR_FLOAT_TYPE_P (TREE_TYPE (arg)))) { if (!noconvert) arg = default_conversion (arg); } else if (typecode == COMPLEX_TYPE) { code = CONJ_EXPR; pedwarn (location, OPT_Wpedantic, "ISO C does not support %<~%> for complex conjugation"); if (!noconvert) arg = default_conversion (arg); } else { error_at (location, "wrong type argument to bit-complement"); return error_mark_node; } break; case ABS_EXPR: if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE)) { error_at (location, "wrong type argument to abs"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); break; case CONJ_EXPR: /* Conjugating a real value is a no-op, but allow it anyway. */ if (!(typecode == INTEGER_TYPE || typecode == REAL_TYPE || typecode == COMPLEX_TYPE)) { error_at (location, "wrong type argument to conjugation"); return error_mark_node; } else if (!noconvert) arg = default_conversion (arg); break; case TRUTH_NOT_EXPR: if (typecode != INTEGER_TYPE && typecode != FIXED_POINT_TYPE && typecode != REAL_TYPE && typecode != POINTER_TYPE && typecode != COMPLEX_TYPE) { error_at (location, "wrong type argument to unary exclamation mark"); return error_mark_node; } if (int_operands) { arg = c_objc_common_truthvalue_conversion (location, xarg); arg = remove_c_maybe_const_expr (arg); } else arg = c_objc_common_truthvalue_conversion (location, arg); ret = invert_truthvalue_loc (location, arg); /* If the TRUTH_NOT_EXPR has been folded, reset the location. */ if (EXPR_P (ret) && EXPR_HAS_LOCATION (ret)) location = EXPR_LOCATION (ret); goto return_build_unary_op; case REALPART_EXPR: case IMAGPART_EXPR: ret = build_real_imag_expr (location, code, arg); if (ret == error_mark_node) return error_mark_node; if (eptype && TREE_CODE (eptype) == COMPLEX_TYPE) eptype = TREE_TYPE (eptype); goto return_build_unary_op; case PREINCREMENT_EXPR: case POSTINCREMENT_EXPR: case PREDECREMENT_EXPR: case POSTDECREMENT_EXPR: if (TREE_CODE (arg) == C_MAYBE_CONST_EXPR) { tree inner = build_unary_op (location, code, C_MAYBE_CONST_EXPR_EXPR (arg), flag); if (inner == error_mark_node) return error_mark_node; ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (inner), C_MAYBE_CONST_EXPR_PRE (arg), inner); gcc_assert (!C_MAYBE_CONST_EXPR_INT_OPERANDS (arg)); C_MAYBE_CONST_EXPR_NON_CONST (ret) = 1; goto return_build_unary_op; } /* Complain about anything that is not a true lvalue. In Objective-C, skip this check for property_refs. */ if (!objc_is_property_ref (arg) && !lvalue_or_else (location, arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? lv_increment : lv_decrement))) return error_mark_node; if (warn_cxx_compat && TREE_CODE (TREE_TYPE (arg)) == ENUMERAL_TYPE) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) warning_at (location, OPT_Wc___compat, "increment of enumeration value is invalid in C++"); else warning_at (location, OPT_Wc___compat, "decrement of enumeration value is invalid in C++"); } /* Ensure the argument is fully folded inside any SAVE_EXPR. */ arg = c_fully_fold (arg, false, NULL); bool atomic_op; atomic_op = really_atomic_lvalue (arg); /* Increment or decrement the real part of the value, and don't change the imaginary part. */ if (typecode == COMPLEX_TYPE) { tree real, imag; pedwarn (location, OPT_Wpedantic, "ISO C does not support %<++%> and %<--%> on complex types"); if (!atomic_op) { arg = stabilize_reference (arg); real = build_unary_op (EXPR_LOCATION (arg), REALPART_EXPR, arg, 1); imag = build_unary_op (EXPR_LOCATION (arg), IMAGPART_EXPR, arg, 1); real = build_unary_op (EXPR_LOCATION (arg), code, real, 1); if (real == error_mark_node || imag == error_mark_node) return error_mark_node; ret = build2 (COMPLEX_EXPR, TREE_TYPE (arg), real, imag); goto return_build_unary_op; } } /* Report invalid types. */ if (typecode != POINTER_TYPE && typecode != FIXED_POINT_TYPE && typecode != INTEGER_TYPE && typecode != REAL_TYPE && typecode != COMPLEX_TYPE && typecode != VECTOR_TYPE) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) error_at (location, "wrong type argument to increment"); else error_at (location, "wrong type argument to decrement"); return error_mark_node; } { tree inc; argtype = TREE_TYPE (arg); /* Compute the increment. */ if (typecode == POINTER_TYPE) { /* If pointer target is an incomplete type, we just cannot know how to do the arithmetic. */ if (!COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (argtype))) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) error_at (location, "increment of pointer to an incomplete type %qT", TREE_TYPE (argtype)); else error_at (location, "decrement of pointer to an incomplete type %qT", TREE_TYPE (argtype)); } else if (TREE_CODE (TREE_TYPE (argtype)) == FUNCTION_TYPE || TREE_CODE (TREE_TYPE (argtype)) == VOID_TYPE) { if (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) pedwarn (location, OPT_Wpointer_arith, "wrong type argument to increment"); else pedwarn (location, OPT_Wpointer_arith, "wrong type argument to decrement"); } inc = c_size_in_bytes (TREE_TYPE (argtype)); inc = convert_to_ptrofftype_loc (location, inc); } else if (FRACT_MODE_P (TYPE_MODE (argtype))) { /* For signed fract types, we invert ++ to -- or -- to ++, and change inc from 1 to -1, because it is not possible to represent 1 in signed fract constants. For unsigned fract types, the result always overflows and we get an undefined (original) or the maximum value. */ if (code == PREINCREMENT_EXPR) code = PREDECREMENT_EXPR; else if (code == PREDECREMENT_EXPR) code = PREINCREMENT_EXPR; else if (code == POSTINCREMENT_EXPR) code = POSTDECREMENT_EXPR; else /* code == POSTDECREMENT_EXPR */ code = POSTINCREMENT_EXPR; inc = integer_minus_one_node; inc = convert (argtype, inc); } else { inc = VECTOR_TYPE_P (argtype) ? build_one_cst (argtype) : integer_one_node; inc = convert (argtype, inc); } /* If 'arg' is an Objective-C PROPERTY_REF expression, then we need to ask Objective-C to build the increment or decrement expression for it. */ if (objc_is_property_ref (arg)) return objc_build_incr_expr_for_property_ref (location, code, arg, inc); /* Report a read-only lvalue. */ if (TYPE_READONLY (argtype)) { readonly_error (location, arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? lv_increment : lv_decrement)); return error_mark_node; } else if (TREE_READONLY (arg)) readonly_warning (arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? lv_increment : lv_decrement)); /* If the argument is atomic, use the special code sequences for atomic compound assignment. */ if (atomic_op) { arg = stabilize_reference (arg); ret = build_atomic_assign (location, arg, ((code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR) ? PLUS_EXPR : MINUS_EXPR), (FRACT_MODE_P (TYPE_MODE (argtype)) ? inc : integer_one_node), (code == POSTINCREMENT_EXPR || code == POSTDECREMENT_EXPR)); goto return_build_unary_op; } if (TREE_CODE (TREE_TYPE (arg)) == BOOLEAN_TYPE) val = boolean_increment (code, arg); else val = build2 (code, TREE_TYPE (arg), arg, inc); TREE_SIDE_EFFECTS (val) = 1; if (TREE_CODE (val) != code) TREE_NO_WARNING (val) = 1; ret = val; goto return_build_unary_op; } case ADDR_EXPR: /* Note that this operation never does default_conversion. */ /* The operand of unary '&' must be an lvalue (which excludes expressions of type void), or, in C99, the result of a [] or unary '*' operator. */ if (VOID_TYPE_P (TREE_TYPE (arg)) && TYPE_QUALS (TREE_TYPE (arg)) == TYPE_UNQUALIFIED && (TREE_CODE (arg) != INDIRECT_REF || !flag_isoc99)) pedwarn (location, 0, "taking address of expression of type %<void%>"); /* Let &* cancel out to simplify resulting code. */ if (TREE_CODE (arg) == INDIRECT_REF) { /* Don't let this be an lvalue. */ if (lvalue_p (TREE_OPERAND (arg, 0))) return non_lvalue_loc (location, TREE_OPERAND (arg, 0)); ret = TREE_OPERAND (arg, 0); goto return_build_unary_op; } /* For &x[y], return x+y */ if (TREE_CODE (arg) == ARRAY_REF) { tree op0 = TREE_OPERAND (arg, 0); if (!c_mark_addressable (op0)) return error_mark_node; } /* Anything not already handled and not a true memory reference or a non-lvalue array is an error. */ else if (typecode != FUNCTION_TYPE && !flag && !lvalue_or_else (location, arg, lv_addressof)) return error_mark_node; /* Move address operations inside C_MAYBE_CONST_EXPR to simplify folding later. */ if (TREE_CODE (arg) == C_MAYBE_CONST_EXPR) { tree inner = build_unary_op (location, code, C_MAYBE_CONST_EXPR_EXPR (arg), flag); ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (inner), C_MAYBE_CONST_EXPR_PRE (arg), inner); gcc_assert (!C_MAYBE_CONST_EXPR_INT_OPERANDS (arg)); C_MAYBE_CONST_EXPR_NON_CONST (ret) = C_MAYBE_CONST_EXPR_NON_CONST (arg); goto return_build_unary_op; } /* Ordinary case; arg is a COMPONENT_REF or a decl. */ argtype = TREE_TYPE (arg); /* If the lvalue is const or volatile, merge that into the type to which the address will point. This is only needed for function types. */ if ((DECL_P (arg) || REFERENCE_CLASS_P (arg)) && (TREE_READONLY (arg) || TREE_THIS_VOLATILE (arg)) && TREE_CODE (argtype) == FUNCTION_TYPE) { int orig_quals = TYPE_QUALS (strip_array_types (argtype)); int quals = orig_quals; if (TREE_READONLY (arg)) quals |= TYPE_QUAL_CONST; if (TREE_THIS_VOLATILE (arg)) quals |= TYPE_QUAL_VOLATILE; argtype = c_build_qualified_type (argtype, quals); } if (!c_mark_addressable (arg)) return error_mark_node; gcc_assert (TREE_CODE (arg) != COMPONENT_REF || !DECL_C_BIT_FIELD (TREE_OPERAND (arg, 1))); argtype = build_pointer_type (argtype); /* ??? Cope with user tricks that amount to offsetof. Delete this when we have proper support for integer constant expressions. */ val = get_base_address (arg); if (val && TREE_CODE (val) == INDIRECT_REF && TREE_CONSTANT (TREE_OPERAND (val, 0))) { ret = fold_convert_loc (location, argtype, fold_offsetof_1 (arg)); goto return_build_unary_op; } val = build1 (ADDR_EXPR, argtype, arg); ret = val; goto return_build_unary_op; default: gcc_unreachable (); } if (argtype == 0) argtype = TREE_TYPE (arg); if (TREE_CODE (arg) == INTEGER_CST) ret = (require_constant_value ? fold_build1_initializer_loc (location, code, argtype, arg) : fold_build1_loc (location, code, argtype, arg)); else ret = build1 (code, argtype, arg); return_build_unary_op: gcc_assert (ret != error_mark_node); if (TREE_CODE (ret) == INTEGER_CST && !TREE_OVERFLOW (ret) && !(TREE_CODE (xarg) == INTEGER_CST && !TREE_OVERFLOW (xarg))) ret = build1 (NOP_EXPR, TREE_TYPE (ret), ret); else if (TREE_CODE (ret) != INTEGER_CST && int_operands) ret = note_integer_operands (ret); if (eptype) ret = build1 (EXCESS_PRECISION_EXPR, eptype, ret); protected_set_expr_location (ret, location); return ret; } /* Return nonzero if REF is an lvalue valid for this language. Lvalues can be assigned, unless their type has TYPE_READONLY. Lvalues can have their address taken, unless they have C_DECL_REGISTER. */ bool lvalue_p (const_tree ref) { const enum tree_code code = TREE_CODE (ref); switch (code) { case REALPART_EXPR: case IMAGPART_EXPR: case COMPONENT_REF: return lvalue_p (TREE_OPERAND (ref, 0)); case C_MAYBE_CONST_EXPR: return lvalue_p (TREE_OPERAND (ref, 1)); case COMPOUND_LITERAL_EXPR: case STRING_CST: return 1; case INDIRECT_REF: case ARRAY_REF: case ARRAY_NOTATION_REF: case VAR_DECL: case PARM_DECL: case RESULT_DECL: case ERROR_MARK: return (TREE_CODE (TREE_TYPE (ref)) != FUNCTION_TYPE && TREE_CODE (TREE_TYPE (ref)) != METHOD_TYPE); case BIND_EXPR: return TREE_CODE (TREE_TYPE (ref)) == ARRAY_TYPE; default: return 0; } } /* Give a warning for storing in something that is read-only in GCC terms but not const in ISO C terms. */ static void readonly_warning (tree arg, enum lvalue_use use) { switch (use) { case lv_assign: warning (0, "assignment of read-only location %qE", arg); break; case lv_increment: warning (0, "increment of read-only location %qE", arg); break; case lv_decrement: warning (0, "decrement of read-only location %qE", arg); break; default: gcc_unreachable (); } return; } /* Return nonzero if REF is an lvalue valid for this language; otherwise, print an error message and return zero. USE says how the lvalue is being used and so selects the error message. LOCATION is the location at which any error should be reported. */ static int lvalue_or_else (location_t loc, const_tree ref, enum lvalue_use use) { int win = lvalue_p (ref); if (!win) lvalue_error (loc, use); return win; } /* Mark EXP saying that we need to be able to take the address of it; it should not be allocated in a register. Returns true if successful. */ bool c_mark_addressable (tree exp) { tree x = exp; while (1) switch (TREE_CODE (x)) { case COMPONENT_REF: if (DECL_C_BIT_FIELD (TREE_OPERAND (x, 1))) { error ("cannot take address of bit-field %qD", TREE_OPERAND (x, 1)); return false; } /* ... fall through ... */ case ADDR_EXPR: case ARRAY_REF: case REALPART_EXPR: case IMAGPART_EXPR: x = TREE_OPERAND (x, 0); break; case COMPOUND_LITERAL_EXPR: case CONSTRUCTOR: TREE_ADDRESSABLE (x) = 1; return true; case VAR_DECL: case CONST_DECL: case PARM_DECL: case RESULT_DECL: if (C_DECL_REGISTER (x) && DECL_NONLOCAL (x)) { if (TREE_PUBLIC (x) || TREE_STATIC (x) || DECL_EXTERNAL (x)) { error ("global register variable %qD used in nested function", x); return false; } pedwarn (input_location, 0, "register variable %qD used in nested function", x); } else if (C_DECL_REGISTER (x)) { if (TREE_PUBLIC (x) || TREE_STATIC (x) || DECL_EXTERNAL (x)) error ("address of global register variable %qD requested", x); else error ("address of register variable %qD requested", x); return false; } /* drops in */ case FUNCTION_DECL: TREE_ADDRESSABLE (x) = 1; /* drops out */ default: return true; } } /* Convert EXPR to TYPE, warning about conversion problems with constants. SEMANTIC_TYPE is the type this conversion would use without excess precision. If SEMANTIC_TYPE is NULL, this function is equivalent to convert_and_check. This function is a wrapper that handles conversions that may be different than the usual ones because of excess precision. */ static tree ep_convert_and_check (location_t loc, tree type, tree expr, tree semantic_type) { if (TREE_TYPE (expr) == type) return expr; if (!semantic_type) return convert_and_check (loc, type, expr); if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE && TREE_TYPE (expr) != semantic_type) { /* For integers, we need to check the real conversion, not the conversion to the excess precision type. */ expr = convert_and_check (loc, semantic_type, expr); } /* Result type is the excess precision type, which should be large enough, so do not check. */ return convert (type, expr); } /* Build and return a conditional expression IFEXP ? OP1 : OP2. If IFEXP_BCP then the condition is a call to __builtin_constant_p, and if folded to an integer constant then the unselected half may contain arbitrary operations not normally permitted in constant expressions. Set the location of the expression to LOC. */ tree build_conditional_expr (location_t colon_loc, tree ifexp, bool ifexp_bcp, tree op1, tree op1_original_type, tree op2, tree op2_original_type) { tree type1; tree type2; enum tree_code code1; enum tree_code code2; tree result_type = NULL; tree semantic_result_type = NULL; tree orig_op1 = op1, orig_op2 = op2; bool int_const, op1_int_operands, op2_int_operands, int_operands; bool ifexp_int_operands; tree ret; op1_int_operands = EXPR_INT_CONST_OPERANDS (orig_op1); if (op1_int_operands) op1 = remove_c_maybe_const_expr (op1); op2_int_operands = EXPR_INT_CONST_OPERANDS (orig_op2); if (op2_int_operands) op2 = remove_c_maybe_const_expr (op2); ifexp_int_operands = EXPR_INT_CONST_OPERANDS (ifexp); if (ifexp_int_operands) ifexp = remove_c_maybe_const_expr (ifexp); /* Promote both alternatives. */ if (TREE_CODE (TREE_TYPE (op1)) != VOID_TYPE) op1 = default_conversion (op1); if (TREE_CODE (TREE_TYPE (op2)) != VOID_TYPE) op2 = default_conversion (op2); if (TREE_CODE (ifexp) == ERROR_MARK || TREE_CODE (TREE_TYPE (op1)) == ERROR_MARK || TREE_CODE (TREE_TYPE (op2)) == ERROR_MARK) return error_mark_node; type1 = TREE_TYPE (op1); code1 = TREE_CODE (type1); type2 = TREE_TYPE (op2); code2 = TREE_CODE (type2); /* C90 does not permit non-lvalue arrays in conditional expressions. In C99 they will be pointers by now. */ if (code1 == ARRAY_TYPE || code2 == ARRAY_TYPE) { error_at (colon_loc, "non-lvalue array in conditional expression"); return error_mark_node; } if ((TREE_CODE (op1) == EXCESS_PRECISION_EXPR || TREE_CODE (op2) == EXCESS_PRECISION_EXPR) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE) && (code2 == INTEGER_TYPE || code2 == REAL_TYPE || code2 == COMPLEX_TYPE)) { semantic_result_type = c_common_type (type1, type2); if (TREE_CODE (op1) == EXCESS_PRECISION_EXPR) { op1 = TREE_OPERAND (op1, 0); type1 = TREE_TYPE (op1); gcc_assert (TREE_CODE (type1) == code1); } if (TREE_CODE (op2) == EXCESS_PRECISION_EXPR) { op2 = TREE_OPERAND (op2, 0); type2 = TREE_TYPE (op2); gcc_assert (TREE_CODE (type2) == code2); } } if (warn_cxx_compat) { tree t1 = op1_original_type ? op1_original_type : TREE_TYPE (orig_op1); tree t2 = op2_original_type ? op2_original_type : TREE_TYPE (orig_op2); if (TREE_CODE (t1) == ENUMERAL_TYPE && TREE_CODE (t2) == ENUMERAL_TYPE && TYPE_MAIN_VARIANT (t1) != TYPE_MAIN_VARIANT (t2)) warning_at (colon_loc, OPT_Wc___compat, ("different enum types in conditional is " "invalid in C++: %qT vs %qT"), t1, t2); } /* Quickly detect the usual case where op1 and op2 have the same type after promotion. */ if (TYPE_MAIN_VARIANT (type1) == TYPE_MAIN_VARIANT (type2)) { if (type1 == type2) result_type = type1; else result_type = TYPE_MAIN_VARIANT (type1); } else if ((code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE) && (code2 == INTEGER_TYPE || code2 == REAL_TYPE || code2 == COMPLEX_TYPE)) { result_type = c_common_type (type1, type2); do_warn_double_promotion (result_type, type1, type2, "implicit conversion from %qT to %qT to " "match other result of conditional", colon_loc); /* If -Wsign-compare, warn here if type1 and type2 have different signedness. We'll promote the signed to unsigned and later code won't know it used to be different. Do this check on the original types, so that explicit casts will be considered, but default promotions won't. */ if (c_inhibit_evaluation_warnings == 0) { int unsigned_op1 = TYPE_UNSIGNED (TREE_TYPE (orig_op1)); int unsigned_op2 = TYPE_UNSIGNED (TREE_TYPE (orig_op2)); if (unsigned_op1 ^ unsigned_op2) { bool ovf; /* Do not warn if the result type is signed, since the signed type will only be chosen if it can represent all the values of the unsigned type. */ if (!TYPE_UNSIGNED (result_type)) /* OK */; else { bool op1_maybe_const = true; bool op2_maybe_const = true; /* Do not warn if the signed quantity is an unsuffixed integer literal (or some static constant expression involving such literals) and it is non-negative. This warning requires the operands to be folded for best results, so do that folding in this case even without warn_sign_compare to avoid warning options possibly affecting code generation. */ c_inhibit_evaluation_warnings += (ifexp == truthvalue_false_node); op1 = c_fully_fold (op1, require_constant_value, &op1_maybe_const); c_inhibit_evaluation_warnings -= (ifexp == truthvalue_false_node); c_inhibit_evaluation_warnings += (ifexp == truthvalue_true_node); op2 = c_fully_fold (op2, require_constant_value, &op2_maybe_const); c_inhibit_evaluation_warnings -= (ifexp == truthvalue_true_node); if (warn_sign_compare) { if ((unsigned_op2 && tree_expr_nonnegative_warnv_p (op1, &ovf)) || (unsigned_op1 && tree_expr_nonnegative_warnv_p (op2, &ovf))) /* OK */; else warning_at (colon_loc, OPT_Wsign_compare, ("signed and unsigned type in " "conditional expression")); } if (!op1_maybe_const || TREE_CODE (op1) != INTEGER_CST) op1 = c_wrap_maybe_const (op1, !op1_maybe_const); if (!op2_maybe_const || TREE_CODE (op2) != INTEGER_CST) op2 = c_wrap_maybe_const (op2, !op2_maybe_const); } } } } else if (code1 == VOID_TYPE || code2 == VOID_TYPE) { if (code1 != VOID_TYPE || code2 != VOID_TYPE) pedwarn (colon_loc, OPT_Wpedantic, "ISO C forbids conditional expr with only one void side"); result_type = void_type_node; } else if (code1 == POINTER_TYPE && code2 == POINTER_TYPE) { addr_space_t as1 = TYPE_ADDR_SPACE (TREE_TYPE (type1)); addr_space_t as2 = TYPE_ADDR_SPACE (TREE_TYPE (type2)); addr_space_t as_common; if (comp_target_types (colon_loc, type1, type2)) result_type = common_pointer_type (type1, type2); else if (null_pointer_constant_p (orig_op1)) result_type = type2; else if (null_pointer_constant_p (orig_op2)) result_type = type1; else if (!addr_space_superset (as1, as2, &as_common)) { error_at (colon_loc, "pointers to disjoint address spaces " "used in conditional expression"); return error_mark_node; } else if (VOID_TYPE_P (TREE_TYPE (type1)) && !TYPE_ATOMIC (TREE_TYPE (type1))) { if ((TREE_CODE (TREE_TYPE (type2)) == ARRAY_TYPE) && (TYPE_QUALS (strip_array_types (TREE_TYPE (type2))) & ~TYPE_QUALS (TREE_TYPE (type1)))) warning_at (colon_loc, OPT_Wdiscarded_array_qualifiers, "pointer to array loses qualifier " "in conditional expression"); if (TREE_CODE (TREE_TYPE (type2)) == FUNCTION_TYPE) pedwarn (colon_loc, OPT_Wpedantic, "ISO C forbids conditional expr between " "%<void *%> and function pointer"); result_type = build_pointer_type (qualify_type (TREE_TYPE (type1), TREE_TYPE (type2))); } else if (VOID_TYPE_P (TREE_TYPE (type2)) && !TYPE_ATOMIC (TREE_TYPE (type2))) { if ((TREE_CODE (TREE_TYPE (type1)) == ARRAY_TYPE) && (TYPE_QUALS (strip_array_types (TREE_TYPE (type1))) & ~TYPE_QUALS (TREE_TYPE (type2)))) warning_at (colon_loc, OPT_Wdiscarded_array_qualifiers, "pointer to array loses qualifier " "in conditional expression"); if (TREE_CODE (TREE_TYPE (type1)) == FUNCTION_TYPE) pedwarn (colon_loc, OPT_Wpedantic, "ISO C forbids conditional expr between " "%<void *%> and function pointer"); result_type = build_pointer_type (qualify_type (TREE_TYPE (type2), TREE_TYPE (type1))); } /* Objective-C pointer comparisons are a bit more lenient. */ else if (objc_have_common_type (type1, type2, -3, NULL_TREE)) result_type = objc_common_type (type1, type2); else { int qual = ENCODE_QUAL_ADDR_SPACE (as_common); pedwarn (colon_loc, 0, "pointer type mismatch in conditional expression"); result_type = build_pointer_type (build_qualified_type (void_type_node, qual)); } } else if (code1 == POINTER_TYPE && code2 == INTEGER_TYPE) { if (!null_pointer_constant_p (orig_op2)) pedwarn (colon_loc, 0, "pointer/integer type mismatch in conditional expression"); else { op2 = null_pointer_node; } result_type = type1; } else if (code2 == POINTER_TYPE && code1 == INTEGER_TYPE) { if (!null_pointer_constant_p (orig_op1)) pedwarn (colon_loc, 0, "pointer/integer type mismatch in conditional expression"); else { op1 = null_pointer_node; } result_type = type2; } if (!result_type) { if (flag_cond_mismatch) result_type = void_type_node; else { error_at (colon_loc, "type mismatch in conditional expression"); return error_mark_node; } } /* Merge const and volatile flags of the incoming types. */ result_type = build_type_variant (result_type, TYPE_READONLY (type1) || TYPE_READONLY (type2), TYPE_VOLATILE (type1) || TYPE_VOLATILE (type2)); op1 = ep_convert_and_check (colon_loc, result_type, op1, semantic_result_type); op2 = ep_convert_and_check (colon_loc, result_type, op2, semantic_result_type); if (ifexp_bcp && ifexp == truthvalue_true_node) { op2_int_operands = true; op1 = c_fully_fold (op1, require_constant_value, NULL); } if (ifexp_bcp && ifexp == truthvalue_false_node) { op1_int_operands = true; op2 = c_fully_fold (op2, require_constant_value, NULL); } int_const = int_operands = (ifexp_int_operands && op1_int_operands && op2_int_operands); if (int_operands) { int_const = ((ifexp == truthvalue_true_node && TREE_CODE (orig_op1) == INTEGER_CST && !TREE_OVERFLOW (orig_op1)) || (ifexp == truthvalue_false_node && TREE_CODE (orig_op2) == INTEGER_CST && !TREE_OVERFLOW (orig_op2))); } if (int_const || (ifexp_bcp && TREE_CODE (ifexp) == INTEGER_CST)) ret = fold_build3_loc (colon_loc, COND_EXPR, result_type, ifexp, op1, op2); else { if (int_operands) { /* Use c_fully_fold here, since C_MAYBE_CONST_EXPR might be nested inside of the expression. */ op1 = c_fully_fold (op1, false, NULL); op2 = c_fully_fold (op2, false, NULL); } ret = build3 (COND_EXPR, result_type, ifexp, op1, op2); if (int_operands) ret = note_integer_operands (ret); } if (semantic_result_type) ret = build1 (EXCESS_PRECISION_EXPR, semantic_result_type, ret); protected_set_expr_location (ret, colon_loc); return ret; } /* Return a compound expression that performs two expressions and returns the value of the second of them. LOC is the location of the COMPOUND_EXPR. */ tree build_compound_expr (location_t loc, tree expr1, tree expr2) { bool expr1_int_operands, expr2_int_operands; tree eptype = NULL_TREE; tree ret; if (flag_cilkplus && (TREE_CODE (expr1) == CILK_SPAWN_STMT || TREE_CODE (expr2) == CILK_SPAWN_STMT)) { error_at (loc, "spawned function call cannot be part of a comma expression"); return error_mark_node; } expr1_int_operands = EXPR_INT_CONST_OPERANDS (expr1); if (expr1_int_operands) expr1 = remove_c_maybe_const_expr (expr1); expr2_int_operands = EXPR_INT_CONST_OPERANDS (expr2); if (expr2_int_operands) expr2 = remove_c_maybe_const_expr (expr2); if (TREE_CODE (expr1) == EXCESS_PRECISION_EXPR) expr1 = TREE_OPERAND (expr1, 0); if (TREE_CODE (expr2) == EXCESS_PRECISION_EXPR) { eptype = TREE_TYPE (expr2); expr2 = TREE_OPERAND (expr2, 0); } if (!TREE_SIDE_EFFECTS (expr1)) { /* The left-hand operand of a comma expression is like an expression statement: with -Wunused, we should warn if it doesn't have any side-effects, unless it was explicitly cast to (void). */ if (warn_unused_value) { if (VOID_TYPE_P (TREE_TYPE (expr1)) && CONVERT_EXPR_P (expr1)) ; /* (void) a, b */ else if (VOID_TYPE_P (TREE_TYPE (expr1)) && TREE_CODE (expr1) == COMPOUND_EXPR && CONVERT_EXPR_P (TREE_OPERAND (expr1, 1))) ; /* (void) a, (void) b, c */ else warning_at (loc, OPT_Wunused_value, "left-hand operand of comma expression has no effect"); } } else if (TREE_CODE (expr1) == COMPOUND_EXPR && warn_unused_value) { tree r = expr1; location_t cloc = loc; while (TREE_CODE (r) == COMPOUND_EXPR) { if (EXPR_HAS_LOCATION (r)) cloc = EXPR_LOCATION (r); r = TREE_OPERAND (r, 1); } if (!TREE_SIDE_EFFECTS (r) && !VOID_TYPE_P (TREE_TYPE (r)) && !CONVERT_EXPR_P (r)) warning_at (cloc, OPT_Wunused_value, "right-hand operand of comma expression has no effect"); } /* With -Wunused, we should also warn if the left-hand operand does have side-effects, but computes a value which is not used. For example, in `foo() + bar(), baz()' the result of the `+' operator is not used, so we should issue a warning. */ else if (warn_unused_value) warn_if_unused_value (expr1, loc); if (expr2 == error_mark_node) return error_mark_node; ret = build2 (COMPOUND_EXPR, TREE_TYPE (expr2), expr1, expr2); if (flag_isoc99 && expr1_int_operands && expr2_int_operands) ret = note_integer_operands (ret); if (eptype) ret = build1 (EXCESS_PRECISION_EXPR, eptype, ret); protected_set_expr_location (ret, loc); return ret; } /* Issue -Wcast-qual warnings when appropriate. TYPE is the type to which we are casting. OTYPE is the type of the expression being cast. Both TYPE and OTYPE are pointer types. LOC is the location of the cast. -Wcast-qual appeared on the command line. Named address space qualifiers are not handled here, because they result in different warnings. */ static void handle_warn_cast_qual (location_t loc, tree type, tree otype) { tree in_type = type; tree in_otype = otype; int added = 0; int discarded = 0; bool is_const; /* Check that the qualifiers on IN_TYPE are a superset of the qualifiers of IN_OTYPE. The outermost level of POINTER_TYPE nodes is uninteresting and we stop as soon as we hit a non-POINTER_TYPE node on either type. */ do { in_otype = TREE_TYPE (in_otype); in_type = TREE_TYPE (in_type); /* GNU C allows cv-qualified function types. 'const' means the function is very pure, 'volatile' means it can't return. We need to warn when such qualifiers are added, not when they're taken away. */ if (TREE_CODE (in_otype) == FUNCTION_TYPE && TREE_CODE (in_type) == FUNCTION_TYPE) added |= (TYPE_QUALS_NO_ADDR_SPACE (in_type) & ~TYPE_QUALS_NO_ADDR_SPACE (in_otype)); else discarded |= (TYPE_QUALS_NO_ADDR_SPACE (in_otype) & ~TYPE_QUALS_NO_ADDR_SPACE (in_type)); } while (TREE_CODE (in_type) == POINTER_TYPE && TREE_CODE (in_otype) == POINTER_TYPE); if (added) warning_at (loc, OPT_Wcast_qual, "cast adds %q#v qualifier to function type", added); if (discarded) /* There are qualifiers present in IN_OTYPE that are not present in IN_TYPE. */ warning_at (loc, OPT_Wcast_qual, "cast discards %qv qualifier from pointer target type", discarded); if (added || discarded) return; /* A cast from **T to const **T is unsafe, because it can cause a const value to be changed with no additional warning. We only issue this warning if T is the same on both sides, and we only issue the warning if there are the same number of pointers on both sides, as otherwise the cast is clearly unsafe anyhow. A cast is unsafe when a qualifier is added at one level and const is not present at all outer levels. To issue this warning, we check at each level whether the cast adds new qualifiers not already seen. We don't need to special case function types, as they won't have the same TYPE_MAIN_VARIANT. */ if (TYPE_MAIN_VARIANT (in_type) != TYPE_MAIN_VARIANT (in_otype)) return; if (TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE) return; in_type = type; in_otype = otype; is_const = TYPE_READONLY (TREE_TYPE (in_type)); do { in_type = TREE_TYPE (in_type); in_otype = TREE_TYPE (in_otype); if ((TYPE_QUALS (in_type) &~ TYPE_QUALS (in_otype)) != 0 && !is_const) { warning_at (loc, OPT_Wcast_qual, "to be safe all intermediate pointers in cast from " "%qT to %qT must be %<const%> qualified", otype, type); break; } if (is_const) is_const = TYPE_READONLY (in_type); } while (TREE_CODE (in_type) == POINTER_TYPE); } /* Build an expression representing a cast to type TYPE of expression EXPR. LOC is the location of the cast-- typically the open paren of the cast. */ tree build_c_cast (location_t loc, tree type, tree expr) { tree value; if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR) expr = TREE_OPERAND (expr, 0); value = expr; if (type == error_mark_node || expr == error_mark_node) return error_mark_node; /* The ObjC front-end uses TYPE_MAIN_VARIANT to tie together types differing only in <protocol> qualifications. But when constructing cast expressions, the protocols do matter and must be kept around. */ if (objc_is_object_ptr (type) && objc_is_object_ptr (TREE_TYPE (expr))) return build1 (NOP_EXPR, type, expr); type = TYPE_MAIN_VARIANT (type); if (TREE_CODE (type) == ARRAY_TYPE) { error_at (loc, "cast specifies array type"); return error_mark_node; } if (TREE_CODE (type) == FUNCTION_TYPE) { error_at (loc, "cast specifies function type"); return error_mark_node; } if (!VOID_TYPE_P (type)) { value = require_complete_type (value); if (value == error_mark_node) return error_mark_node; } if (type == TYPE_MAIN_VARIANT (TREE_TYPE (value))) { if (TREE_CODE (type) == RECORD_TYPE || TREE_CODE (type) == UNION_TYPE) pedwarn (loc, OPT_Wpedantic, "ISO C forbids casting nonscalar to the same type"); /* Convert to remove any qualifiers from VALUE's type. */ value = convert (type, value); } else if (TREE_CODE (type) == UNION_TYPE) { tree field; for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field)) if (TREE_TYPE (field) != error_mark_node && comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (field)), TYPE_MAIN_VARIANT (TREE_TYPE (value)))) break; if (field) { tree t; bool maybe_const = true; pedwarn (loc, OPT_Wpedantic, "ISO C forbids casts to union type"); t = c_fully_fold (value, false, &maybe_const); t = build_constructor_single (type, field, t); if (!maybe_const) t = c_wrap_maybe_const (t, true); t = digest_init (loc, type, t, NULL_TREE, false, true, 0); TREE_CONSTANT (t) = TREE_CONSTANT (value); return t; } error_at (loc, "cast to union type from type not present in union"); return error_mark_node; } else { tree otype, ovalue; if (type == void_type_node) { tree t = build1 (CONVERT_EXPR, type, value); SET_EXPR_LOCATION (t, loc); return t; } otype = TREE_TYPE (value); /* Optionally warn about potentially worrisome casts. */ if (warn_cast_qual && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE) handle_warn_cast_qual (loc, type, otype); /* Warn about conversions between pointers to disjoint address spaces. */ if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && !null_pointer_constant_p (value)) { addr_space_t as_to = TYPE_ADDR_SPACE (TREE_TYPE (type)); addr_space_t as_from = TYPE_ADDR_SPACE (TREE_TYPE (otype)); addr_space_t as_common; if (!addr_space_superset (as_to, as_from, &as_common)) { if (ADDR_SPACE_GENERIC_P (as_from)) warning_at (loc, 0, "cast to %s address space pointer " "from disjoint generic address space pointer", c_addr_space_name (as_to)); else if (ADDR_SPACE_GENERIC_P (as_to)) warning_at (loc, 0, "cast to generic address space pointer " "from disjoint %s address space pointer", c_addr_space_name (as_from)); else warning_at (loc, 0, "cast to %s address space pointer " "from disjoint %s address space pointer", c_addr_space_name (as_to), c_addr_space_name (as_from)); } } /* Warn about possible alignment problems. */ if (STRICT_ALIGNMENT && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (otype)) != VOID_TYPE && TREE_CODE (TREE_TYPE (otype)) != FUNCTION_TYPE /* Don't warn about opaque types, where the actual alignment restriction is unknown. */ && !((TREE_CODE (TREE_TYPE (otype)) == UNION_TYPE || TREE_CODE (TREE_TYPE (otype)) == RECORD_TYPE) && TYPE_MODE (TREE_TYPE (otype)) == VOIDmode) && TYPE_ALIGN (TREE_TYPE (type)) > TYPE_ALIGN (TREE_TYPE (otype))) warning_at (loc, OPT_Wcast_align, "cast increases required alignment of target type"); if (TREE_CODE (type) == INTEGER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TYPE_PRECISION (type) != TYPE_PRECISION (otype)) /* Unlike conversion of integers to pointers, where the warning is disabled for converting constants because of cases such as SIG_*, warn about converting constant pointers to integers. In some cases it may cause unwanted sign extension, and a warning is appropriate. */ warning_at (loc, OPT_Wpointer_to_int_cast, "cast from pointer to integer of different size"); if (TREE_CODE (value) == CALL_EXPR && TREE_CODE (type) != TREE_CODE (otype)) warning_at (loc, OPT_Wbad_function_cast, "cast from function call of type %qT " "to non-matching type %qT", otype, type); if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == INTEGER_TYPE && TYPE_PRECISION (type) != TYPE_PRECISION (otype) /* Don't warn about converting any constant. */ && !TREE_CONSTANT (value)) warning_at (loc, OPT_Wint_to_pointer_cast, "cast to pointer from integer " "of different size"); if (warn_strict_aliasing <= 2) strict_aliasing_warning (otype, type, expr); /* If pedantic, warn for conversions between function and object pointer types, except for converting a null pointer constant to function pointer type. */ if (pedantic && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (otype)) == FUNCTION_TYPE && TREE_CODE (TREE_TYPE (type)) != FUNCTION_TYPE) pedwarn (loc, OPT_Wpedantic, "ISO C forbids " "conversion of function pointer to object pointer type"); if (pedantic && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE && TREE_CODE (TREE_TYPE (otype)) != FUNCTION_TYPE && !null_pointer_constant_p (value)) pedwarn (loc, OPT_Wpedantic, "ISO C forbids " "conversion of object pointer to function pointer type"); ovalue = value; value = convert (type, value); /* Ignore any integer overflow caused by the cast. */ if (TREE_CODE (value) == INTEGER_CST && !FLOAT_TYPE_P (otype)) { if (CONSTANT_CLASS_P (ovalue) && TREE_OVERFLOW (ovalue)) { if (!TREE_OVERFLOW (value)) { /* Avoid clobbering a shared constant. */ value = copy_node (value); TREE_OVERFLOW (value) = TREE_OVERFLOW (ovalue); } } else if (TREE_OVERFLOW (value)) /* Reset VALUE's overflow flags, ensuring constant sharing. */ value = wide_int_to_tree (TREE_TYPE (value), value); } } /* Don't let a cast be an lvalue. */ if (value == expr) value = non_lvalue_loc (loc, value); /* Don't allow the results of casting to floating-point or complex types be confused with actual constants, or casts involving integer and pointer types other than direct integer-to-integer and integer-to-pointer be confused with integer constant expressions and null pointer constants. */ if (TREE_CODE (value) == REAL_CST || TREE_CODE (value) == COMPLEX_CST || (TREE_CODE (value) == INTEGER_CST && !((TREE_CODE (expr) == INTEGER_CST && INTEGRAL_TYPE_P (TREE_TYPE (expr))) || TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == COMPLEX_CST))) value = build1 (NOP_EXPR, type, value); if (CAN_HAVE_LOCATION_P (value)) SET_EXPR_LOCATION (value, loc); return value; } /* Interpret a cast of expression EXPR to type TYPE. LOC is the location of the open paren of the cast, or the position of the cast expr. */ tree c_cast_expr (location_t loc, struct c_type_name *type_name, tree expr) { tree type; tree type_expr = NULL_TREE; bool type_expr_const = true; tree ret; int saved_wsp = warn_strict_prototypes; /* This avoids warnings about unprototyped casts on integers. E.g. "#define SIG_DFL (void(*)())0". */ if (TREE_CODE (expr) == INTEGER_CST) warn_strict_prototypes = 0; type = groktypename (type_name, &type_expr, &type_expr_const); warn_strict_prototypes = saved_wsp; ret = build_c_cast (loc, type, expr); if (type_expr) { bool inner_expr_const = true; ret = c_fully_fold (ret, require_constant_value, &inner_expr_const); ret = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (ret), type_expr, ret); C_MAYBE_CONST_EXPR_NON_CONST (ret) = !(type_expr_const && inner_expr_const); SET_EXPR_LOCATION (ret, loc); } if (CAN_HAVE_LOCATION_P (ret) && !EXPR_HAS_LOCATION (ret)) SET_EXPR_LOCATION (ret, loc); /* C++ does not permits types to be defined in a cast, but it allows references to incomplete types. */ if (warn_cxx_compat && type_name->specs->typespec_kind == ctsk_tagdef) warning_at (loc, OPT_Wc___compat, "defining a type in a cast is invalid in C++"); return ret; } /* Build an assignment expression of lvalue LHS from value RHS. If LHS_ORIGTYPE is not NULL, it is the original type of LHS, which may differ from TREE_TYPE (LHS) for an enum bitfield. MODIFYCODE is the code for a binary operator that we use to combine the old value of LHS with RHS to get the new value. Or else MODIFYCODE is NOP_EXPR meaning do a simple assignment. If RHS_ORIGTYPE is not NULL_TREE, it is the original type of RHS, which may differ from TREE_TYPE (RHS) for an enum value. LOCATION is the location of the MODIFYCODE operator. RHS_LOC is the location of the RHS. */ tree build_modify_expr (location_t location, tree lhs, tree lhs_origtype, enum tree_code modifycode, location_t rhs_loc, tree rhs, tree rhs_origtype) { tree result; tree newrhs; tree rhseval = NULL_TREE; tree rhs_semantic_type = NULL_TREE; tree lhstype = TREE_TYPE (lhs); tree olhstype = lhstype; bool npc; bool is_atomic_op; /* Types that aren't fully specified cannot be used in assignments. */ lhs = require_complete_type (lhs); /* Avoid duplicate error messages from operands that had errors. */ if (TREE_CODE (lhs) == ERROR_MARK || TREE_CODE (rhs) == ERROR_MARK) return error_mark_node; /* Ensure an error for assigning a non-lvalue array to an array in C90. */ if (TREE_CODE (lhstype) == ARRAY_TYPE) { error_at (location, "assignment to expression with array type"); return error_mark_node; } /* For ObjC properties, defer this check. */ if (!objc_is_property_ref (lhs) && !lvalue_or_else (location, lhs, lv_assign)) return error_mark_node; is_atomic_op = really_atomic_lvalue (lhs); if (TREE_CODE (rhs) == EXCESS_PRECISION_EXPR) { rhs_semantic_type = TREE_TYPE (rhs); rhs = TREE_OPERAND (rhs, 0); } newrhs = rhs; if (TREE_CODE (lhs) == C_MAYBE_CONST_EXPR) { tree inner = build_modify_expr (location, C_MAYBE_CONST_EXPR_EXPR (lhs), lhs_origtype, modifycode, rhs_loc, rhs, rhs_origtype); if (inner == error_mark_node) return error_mark_node; result = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (inner), C_MAYBE_CONST_EXPR_PRE (lhs), inner); gcc_assert (!C_MAYBE_CONST_EXPR_INT_OPERANDS (lhs)); C_MAYBE_CONST_EXPR_NON_CONST (result) = 1; protected_set_expr_location (result, location); return result; } /* If a binary op has been requested, combine the old LHS value with the RHS producing the value we should actually store into the LHS. */ if (modifycode != NOP_EXPR) { lhs = c_fully_fold (lhs, false, NULL); lhs = stabilize_reference (lhs); /* Construct the RHS for any non-atomic compound assignemnt. */ if (!is_atomic_op) { /* If in LHS op= RHS the RHS has side-effects, ensure they are preevaluated before the rest of the assignment expression's side-effects, because RHS could contain e.g. function calls that modify LHS. */ if (TREE_SIDE_EFFECTS (rhs)) { newrhs = in_late_binary_op ? save_expr (rhs) : c_save_expr (rhs); rhseval = newrhs; } newrhs = build_binary_op (location, modifycode, lhs, newrhs, 1); /* The original type of the right hand side is no longer meaningful. */ rhs_origtype = NULL_TREE; } } if (c_dialect_objc ()) { /* Check if we are modifying an Objective-C property reference; if so, we need to generate setter calls. */ result = objc_maybe_build_modify_expr (lhs, newrhs); if (result) goto return_result; /* Else, do the check that we postponed for Objective-C. */ if (!lvalue_or_else (location, lhs, lv_assign)) return error_mark_node; } /* Give an error for storing in something that is 'const'. */ if (TYPE_READONLY (lhstype) || ((TREE_CODE (lhstype) == RECORD_TYPE || TREE_CODE (lhstype) == UNION_TYPE) && C_TYPE_FIELDS_READONLY (lhstype))) { readonly_error (location, lhs, lv_assign); return error_mark_node; } else if (TREE_READONLY (lhs)) readonly_warning (lhs, lv_assign); /* If storing into a structure or union member, it has probably been given type `int'. Compute the type that would go with the actual amount of storage the member occupies. */ if (TREE_CODE (lhs) == COMPONENT_REF && (TREE_CODE (lhstype) == INTEGER_TYPE || TREE_CODE (lhstype) == BOOLEAN_TYPE || TREE_CODE (lhstype) == REAL_TYPE || TREE_CODE (lhstype) == ENUMERAL_TYPE)) lhstype = TREE_TYPE (get_unwidened (lhs, 0)); /* If storing in a field that is in actuality a short or narrower than one, we must store in the field in its actual type. */ if (lhstype != TREE_TYPE (lhs)) { lhs = copy_node (lhs); TREE_TYPE (lhs) = lhstype; } /* Issue -Wc++-compat warnings about an assignment to an enum type when LHS does not have its original type. This happens for, e.g., an enum bitfield in a struct. */ if (warn_cxx_compat && lhs_origtype != NULL_TREE && lhs_origtype != lhstype && TREE_CODE (lhs_origtype) == ENUMERAL_TYPE) { tree checktype = (rhs_origtype != NULL_TREE ? rhs_origtype : TREE_TYPE (rhs)); if (checktype != error_mark_node && (TYPE_MAIN_VARIANT (checktype) != TYPE_MAIN_VARIANT (lhs_origtype) || (is_atomic_op && modifycode != NOP_EXPR))) warning_at (location, OPT_Wc___compat, "enum conversion in assignment is invalid in C++"); } /* If the lhs is atomic, remove that qualifier. */ if (is_atomic_op) { lhstype = build_qualified_type (lhstype, (TYPE_QUALS (lhstype) & ~TYPE_QUAL_ATOMIC)); olhstype = build_qualified_type (olhstype, (TYPE_QUALS (lhstype) & ~TYPE_QUAL_ATOMIC)); } /* Convert new value to destination type. Fold it first, then restore any excess precision information, for the sake of conversion warnings. */ if (!(is_atomic_op && modifycode != NOP_EXPR)) { npc = null_pointer_constant_p (newrhs); newrhs = c_fully_fold (newrhs, false, NULL); if (rhs_semantic_type) newrhs = build1 (EXCESS_PRECISION_EXPR, rhs_semantic_type, newrhs); newrhs = convert_for_assignment (location, rhs_loc, lhstype, newrhs, rhs_origtype, ic_assign, npc, NULL_TREE, NULL_TREE, 0); if (TREE_CODE (newrhs) == ERROR_MARK) return error_mark_node; } /* Emit ObjC write barrier, if necessary. */ if (c_dialect_objc () && flag_objc_gc) { result = objc_generate_write_barrier (lhs, modifycode, newrhs); if (result) { protected_set_expr_location (result, location); goto return_result; } } /* Scan operands. */ if (is_atomic_op) result = build_atomic_assign (location, lhs, modifycode, newrhs, false); else { result = build2 (MODIFY_EXPR, lhstype, lhs, newrhs); TREE_SIDE_EFFECTS (result) = 1; protected_set_expr_location (result, location); } /* If we got the LHS in a different type for storing in, convert the result back to the nominal type of LHS so that the value we return always has the same type as the LHS argument. */ if (olhstype == TREE_TYPE (result)) goto return_result; result = convert_for_assignment (location, rhs_loc, olhstype, result, rhs_origtype, ic_assign, false, NULL_TREE, NULL_TREE, 0); protected_set_expr_location (result, location); return_result: if (rhseval) result = build2 (COMPOUND_EXPR, TREE_TYPE (result), rhseval, result); return result; } /* Return whether STRUCT_TYPE has an anonymous field with type TYPE. This is used to implement -fplan9-extensions. */ static bool find_anonymous_field_with_type (tree struct_type, tree type) { tree field; bool found; gcc_assert (TREE_CODE (struct_type) == RECORD_TYPE || TREE_CODE (struct_type) == UNION_TYPE); found = false; for (field = TYPE_FIELDS (struct_type); field != NULL_TREE; field = TREE_CHAIN (field)) { tree fieldtype = (TYPE_ATOMIC (TREE_TYPE (field)) ? c_build_qualified_type (TREE_TYPE (field), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (field))); if (DECL_NAME (field) == NULL && comptypes (type, fieldtype)) { if (found) return false; found = true; } else if (DECL_NAME (field) == NULL && (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE) && find_anonymous_field_with_type (TREE_TYPE (field), type)) { if (found) return false; found = true; } } return found; } /* RHS is an expression whose type is pointer to struct. If there is an anonymous field in RHS with type TYPE, then return a pointer to that field in RHS. This is used with -fplan9-extensions. This returns NULL if no conversion could be found. */ static tree convert_to_anonymous_field (location_t location, tree type, tree rhs) { tree rhs_struct_type, lhs_main_type; tree field, found_field; bool found_sub_field; tree ret; gcc_assert (POINTER_TYPE_P (TREE_TYPE (rhs))); rhs_struct_type = TREE_TYPE (TREE_TYPE (rhs)); gcc_assert (TREE_CODE (rhs_struct_type) == RECORD_TYPE || TREE_CODE (rhs_struct_type) == UNION_TYPE); gcc_assert (POINTER_TYPE_P (type)); lhs_main_type = (TYPE_ATOMIC (TREE_TYPE (type)) ? c_build_qualified_type (TREE_TYPE (type), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (type))); found_field = NULL_TREE; found_sub_field = false; for (field = TYPE_FIELDS (rhs_struct_type); field != NULL_TREE; field = TREE_CHAIN (field)) { if (DECL_NAME (field) != NULL_TREE || (TREE_CODE (TREE_TYPE (field)) != RECORD_TYPE && TREE_CODE (TREE_TYPE (field)) != UNION_TYPE)) continue; tree fieldtype = (TYPE_ATOMIC (TREE_TYPE (field)) ? c_build_qualified_type (TREE_TYPE (field), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (field))); if (comptypes (lhs_main_type, fieldtype)) { if (found_field != NULL_TREE) return NULL_TREE; found_field = field; } else if (find_anonymous_field_with_type (TREE_TYPE (field), lhs_main_type)) { if (found_field != NULL_TREE) return NULL_TREE; found_field = field; found_sub_field = true; } } if (found_field == NULL_TREE) return NULL_TREE; ret = fold_build3_loc (location, COMPONENT_REF, TREE_TYPE (found_field), build_fold_indirect_ref (rhs), found_field, NULL_TREE); ret = build_fold_addr_expr_loc (location, ret); if (found_sub_field) { ret = convert_to_anonymous_field (location, type, ret); gcc_assert (ret != NULL_TREE); } return ret; } /* Issue an error message for a bad initializer component. GMSGID identifies the message. The component name is taken from the spelling stack. */ static void error_init (location_t loc, const char *gmsgid) { char *ofwhat; /* The gmsgid may be a format string with %< and %>. */ error_at (loc, gmsgid); ofwhat = print_spelling ((char *) alloca (spelling_length () + 1)); if (*ofwhat) inform (loc, "(near initialization for %qs)", ofwhat); } /* Issue a pedantic warning for a bad initializer component. OPT is the option OPT_* (from options.h) controlling this warning or 0 if it is unconditionally given. GMSGID identifies the message. The component name is taken from the spelling stack. */ static void pedwarn_init (location_t location, int opt, const char *gmsgid) { char *ofwhat; bool warned; /* The gmsgid may be a format string with %< and %>. */ warned = pedwarn (location, opt, gmsgid); ofwhat = print_spelling ((char *) alloca (spelling_length () + 1)); if (*ofwhat && warned) inform (location, "(near initialization for %qs)", ofwhat); } /* Issue a warning for a bad initializer component. OPT is the OPT_W* value corresponding to the warning option that controls this warning. GMSGID identifies the message. The component name is taken from the spelling stack. */ static void warning_init (location_t loc, int opt, const char *gmsgid) { char *ofwhat; bool warned; /* The gmsgid may be a format string with %< and %>. */ warned = warning_at (loc, opt, gmsgid); ofwhat = print_spelling ((char *) alloca (spelling_length () + 1)); if (*ofwhat && warned) inform (loc, "(near initialization for %qs)", ofwhat); } /* If TYPE is an array type and EXPR is a parenthesized string constant, warn if pedantic that EXPR is being used to initialize an object of type TYPE. */ void maybe_warn_string_init (location_t loc, tree type, struct c_expr expr) { if (pedantic && TREE_CODE (type) == ARRAY_TYPE && TREE_CODE (expr.value) == STRING_CST && expr.original_code != STRING_CST) pedwarn_init (loc, OPT_Wpedantic, "array initialized from parenthesized string constant"); } /* Convert value RHS to type TYPE as preparation for an assignment to an lvalue of type TYPE. If ORIGTYPE is not NULL_TREE, it is the original type of RHS; this differs from TREE_TYPE (RHS) for enum types. NULL_POINTER_CONSTANT says whether RHS was a null pointer constant before any folding. The real work of conversion is done by `convert'. The purpose of this function is to generate error messages for assignments that are not allowed in C. ERRTYPE says whether it is argument passing, assignment, initialization or return. LOCATION is the location of the assignment, EXPR_LOC is the location of the RHS or, for a function, location of an argument. FUNCTION is a tree for the function being called. PARMNUM is the number of the argument, for printing in error messages. */ static tree convert_for_assignment (location_t location, location_t expr_loc, tree type, tree rhs, tree origtype, enum impl_conv errtype, bool null_pointer_constant, tree fundecl, tree function, int parmnum) { enum tree_code codel = TREE_CODE (type); tree orig_rhs = rhs; tree rhstype; enum tree_code coder; tree rname = NULL_TREE; bool objc_ok = false; /* Use the expansion point location to handle cases such as user's function returning a wrong-type macro defined in a system header. */ location = expansion_point_location_if_in_system_header (location); if (errtype == ic_argpass) { tree selector; /* Change pointer to function to the function itself for diagnostics. */ if (TREE_CODE (function) == ADDR_EXPR && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL) function = TREE_OPERAND (function, 0); /* Handle an ObjC selector specially for diagnostics. */ selector = objc_message_selector (); rname = function; if (selector && parmnum > 2) { rname = selector; parmnum -= 2; } } /* This macro is used to emit diagnostics to ensure that all format strings are complete sentences, visible to gettext and checked at compile time. */ #define PEDWARN_FOR_ASSIGNMENT(LOCATION, PLOC, OPT, AR, AS, IN, RE) \ do { \ switch (errtype) \ { \ case ic_argpass: \ if (pedwarn (PLOC, OPT, AR, parmnum, rname)) \ inform ((fundecl && !DECL_IS_BUILTIN (fundecl)) \ ? DECL_SOURCE_LOCATION (fundecl) : PLOC, \ "expected %qT but argument is of type %qT", \ type, rhstype); \ break; \ case ic_assign: \ pedwarn (LOCATION, OPT, AS); \ break; \ case ic_init: \ pedwarn_init (LOCATION, OPT, IN); \ break; \ case ic_return: \ pedwarn (LOCATION, OPT, RE); \ break; \ default: \ gcc_unreachable (); \ } \ } while (0) /* This macro is used to emit diagnostics to ensure that all format strings are complete sentences, visible to gettext and checked at compile time. It is the same as PEDWARN_FOR_ASSIGNMENT but with an extra parameter to enumerate qualifiers. */ #define PEDWARN_FOR_QUALIFIERS(LOCATION, PLOC, OPT, AR, AS, IN, RE, QUALS) \ do { \ switch (errtype) \ { \ case ic_argpass: \ if (pedwarn (PLOC, OPT, AR, parmnum, rname, QUALS)) \ inform ((fundecl && !DECL_IS_BUILTIN (fundecl)) \ ? DECL_SOURCE_LOCATION (fundecl) : PLOC, \ "expected %qT but argument is of type %qT", \ type, rhstype); \ break; \ case ic_assign: \ pedwarn (LOCATION, OPT, AS, QUALS); \ break; \ case ic_init: \ pedwarn (LOCATION, OPT, IN, QUALS); \ break; \ case ic_return: \ pedwarn (LOCATION, OPT, RE, QUALS); \ break; \ default: \ gcc_unreachable (); \ } \ } while (0) /* This macro is used to emit diagnostics to ensure that all format strings are complete sentences, visible to gettext and checked at compile time. It is the same as PEDWARN_FOR_QUALIFIERS but uses warning_at instead of pedwarn. */ #define WARNING_FOR_QUALIFIERS(LOCATION, PLOC, OPT, AR, AS, IN, RE, QUALS) \ do { \ switch (errtype) \ { \ case ic_argpass: \ if (warning_at (PLOC, OPT, AR, parmnum, rname, QUALS)) \ inform ((fundecl && !DECL_IS_BUILTIN (fundecl)) \ ? DECL_SOURCE_LOCATION (fundecl) : PLOC, \ "expected %qT but argument is of type %qT", \ type, rhstype); \ break; \ case ic_assign: \ warning_at (LOCATION, OPT, AS, QUALS); \ break; \ case ic_init: \ warning_at (LOCATION, OPT, IN, QUALS); \ break; \ case ic_return: \ warning_at (LOCATION, OPT, RE, QUALS); \ break; \ default: \ gcc_unreachable (); \ } \ } while (0) if (TREE_CODE (rhs) == EXCESS_PRECISION_EXPR) rhs = TREE_OPERAND (rhs, 0); rhstype = TREE_TYPE (rhs); coder = TREE_CODE (rhstype); if (coder == ERROR_MARK) return error_mark_node; if (c_dialect_objc ()) { int parmno; switch (errtype) { case ic_return: parmno = 0; break; case ic_assign: parmno = -1; break; case ic_init: parmno = -2; break; default: parmno = parmnum; break; } objc_ok = objc_compare_types (type, rhstype, parmno, rname); } if (warn_cxx_compat) { tree checktype = origtype != NULL_TREE ? origtype : rhstype; if (checktype != error_mark_node && TREE_CODE (type) == ENUMERAL_TYPE && TYPE_MAIN_VARIANT (checktype) != TYPE_MAIN_VARIANT (type)) { PEDWARN_FOR_ASSIGNMENT (location, expr_loc, OPT_Wc___compat, G_("enum conversion when passing argument " "%d of %qE is invalid in C++"), G_("enum conversion in assignment is " "invalid in C++"), G_("enum conversion in initialization is " "invalid in C++"), G_("enum conversion in return is " "invalid in C++")); } } if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (rhstype)) return rhs; if (coder == VOID_TYPE) { /* Except for passing an argument to an unprototyped function, this is a constraint violation. When passing an argument to an unprototyped function, it is compile-time undefined; making it a constraint in that case was rejected in DR#252. */ error_at (location, "void value not ignored as it ought to be"); return error_mark_node; } rhs = require_complete_type (rhs); if (rhs == error_mark_node) return error_mark_node; /* A non-reference type can convert to a reference. This handles va_start, va_copy and possibly port built-ins. */ if (codel == REFERENCE_TYPE && coder != REFERENCE_TYPE) { if (!lvalue_p (rhs)) { error_at (location, "cannot pass rvalue to reference parameter"); return error_mark_node; } if (!c_mark_addressable (rhs)) return error_mark_node; rhs = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (rhs)), rhs); SET_EXPR_LOCATION (rhs, location); rhs = convert_for_assignment (location, expr_loc, build_pointer_type (TREE_TYPE (type)), rhs, origtype, errtype, null_pointer_constant, fundecl, function, parmnum); if (rhs == error_mark_node) return error_mark_node; rhs = build1 (NOP_EXPR, type, rhs); SET_EXPR_LOCATION (rhs, location); return rhs; } /* Some types can interconvert without explicit casts. */ else if (codel == VECTOR_TYPE && coder == VECTOR_TYPE && vector_types_convertible_p (type, TREE_TYPE (rhs), true)) return convert (type, rhs); /* Arithmetic types all interconvert, and enum is treated like int. */ else if ((codel == INTEGER_TYPE || codel == REAL_TYPE || codel == FIXED_POINT_TYPE || codel == ENUMERAL_TYPE || codel == COMPLEX_TYPE || codel == BOOLEAN_TYPE) && (coder == INTEGER_TYPE || coder == REAL_TYPE || coder == FIXED_POINT_TYPE || coder == ENUMERAL_TYPE || coder == COMPLEX_TYPE || coder == BOOLEAN_TYPE)) { tree ret; bool save = in_late_binary_op; if (codel == BOOLEAN_TYPE || codel == COMPLEX_TYPE || (coder == REAL_TYPE && (codel == INTEGER_TYPE || codel == ENUMERAL_TYPE) && (flag_sanitize & SANITIZE_FLOAT_CAST))) in_late_binary_op = true; ret = convert_and_check (expr_loc != UNKNOWN_LOCATION ? expr_loc : location, type, orig_rhs); in_late_binary_op = save; return ret; } /* Aggregates in different TUs might need conversion. */ if ((codel == RECORD_TYPE || codel == UNION_TYPE) && codel == coder && comptypes (type, rhstype)) return convert_and_check (expr_loc != UNKNOWN_LOCATION ? expr_loc : location, type, rhs); /* Conversion to a transparent union or record from its member types. This applies only to function arguments. */ if (((codel == UNION_TYPE || codel == RECORD_TYPE) && TYPE_TRANSPARENT_AGGR (type)) && errtype == ic_argpass) { tree memb, marginal_memb = NULL_TREE; for (memb = TYPE_FIELDS (type); memb ; memb = DECL_CHAIN (memb)) { tree memb_type = TREE_TYPE (memb); if (comptypes (TYPE_MAIN_VARIANT (memb_type), TYPE_MAIN_VARIANT (rhstype))) break; if (TREE_CODE (memb_type) != POINTER_TYPE) continue; if (coder == POINTER_TYPE) { tree ttl = TREE_TYPE (memb_type); tree ttr = TREE_TYPE (rhstype); /* Any non-function converts to a [const][volatile] void * and vice versa; otherwise, targets must be the same. Meanwhile, the lhs target must have all the qualifiers of the rhs. */ if ((VOID_TYPE_P (ttl) && !TYPE_ATOMIC (ttl)) || (VOID_TYPE_P (ttr) && !TYPE_ATOMIC (ttr)) || comp_target_types (location, memb_type, rhstype)) { int lquals = TYPE_QUALS (ttl) & ~TYPE_QUAL_ATOMIC; int rquals = TYPE_QUALS (ttr) & ~TYPE_QUAL_ATOMIC; /* If this type won't generate any warnings, use it. */ if (lquals == rquals || ((TREE_CODE (ttr) == FUNCTION_TYPE && TREE_CODE (ttl) == FUNCTION_TYPE) ? ((lquals | rquals) == rquals) : ((lquals | rquals) == lquals))) break; /* Keep looking for a better type, but remember this one. */ if (!marginal_memb) marginal_memb = memb; } } /* Can convert integer zero to any pointer type. */ if (null_pointer_constant) { rhs = null_pointer_node; break; } } if (memb || marginal_memb) { if (!memb) { /* We have only a marginally acceptable member type; it needs a warning. */ tree ttl = TREE_TYPE (TREE_TYPE (marginal_memb)); tree ttr = TREE_TYPE (rhstype); /* Const and volatile mean something different for function types, so the usual warnings are not appropriate. */ if (TREE_CODE (ttr) == FUNCTION_TYPE && TREE_CODE (ttl) == FUNCTION_TYPE) { /* Because const and volatile on functions are restrictions that say the function will not do certain things, it is okay to use a const or volatile function where an ordinary one is wanted, but not vice-versa. */ if (TYPE_QUALS_NO_ADDR_SPACE (ttl) & ~TYPE_QUALS_NO_ADDR_SPACE (ttr)) PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE " "makes %q#v qualified function " "pointer from unqualified"), G_("assignment makes %q#v qualified " "function pointer from " "unqualified"), G_("initialization makes %q#v qualified " "function pointer from " "unqualified"), G_("return makes %q#v qualified function " "pointer from unqualified"), TYPE_QUALS (ttl) & ~TYPE_QUALS (ttr)); } else if (TYPE_QUALS_NO_ADDR_SPACE (ttr) & ~TYPE_QUALS_NO_ADDR_SPACE (ttl)) PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE discards " "%qv qualifier from pointer target type"), G_("assignment discards %qv qualifier " "from pointer target type"), G_("initialization discards %qv qualifier " "from pointer target type"), G_("return discards %qv qualifier from " "pointer target type"), TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl)); memb = marginal_memb; } if (!fundecl || !DECL_IN_SYSTEM_HEADER (fundecl)) pedwarn (location, OPT_Wpedantic, "ISO C prohibits argument conversion to union type"); rhs = fold_convert_loc (location, TREE_TYPE (memb), rhs); return build_constructor_single (type, memb, rhs); } } /* Conversions among pointers */ else if ((codel == POINTER_TYPE || codel == REFERENCE_TYPE) && (coder == codel)) { tree ttl = TREE_TYPE (type); tree ttr = TREE_TYPE (rhstype); tree mvl = ttl; tree mvr = ttr; bool is_opaque_pointer; int target_cmp = 0; /* Cache comp_target_types () result. */ addr_space_t asl; addr_space_t asr; if (TREE_CODE (mvl) != ARRAY_TYPE) mvl = (TYPE_ATOMIC (mvl) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvl), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvl)); if (TREE_CODE (mvr) != ARRAY_TYPE) mvr = (TYPE_ATOMIC (mvr) ? c_build_qualified_type (TYPE_MAIN_VARIANT (mvr), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (mvr)); /* Opaque pointers are treated like void pointers. */ is_opaque_pointer = vector_targets_convertible_p (ttl, ttr); /* The Plan 9 compiler permits a pointer to a struct to be automatically converted into a pointer to an anonymous field within the struct. */ if (flag_plan9_extensions && (TREE_CODE (mvl) == RECORD_TYPE || TREE_CODE(mvl) == UNION_TYPE) && (TREE_CODE (mvr) == RECORD_TYPE || TREE_CODE(mvr) == UNION_TYPE) && mvl != mvr) { tree new_rhs = convert_to_anonymous_field (location, type, rhs); if (new_rhs != NULL_TREE) { rhs = new_rhs; rhstype = TREE_TYPE (rhs); coder = TREE_CODE (rhstype); ttr = TREE_TYPE (rhstype); mvr = TYPE_MAIN_VARIANT (ttr); } } /* C++ does not allow the implicit conversion void* -> T*. However, for the purpose of reducing the number of false positives, we tolerate the special case of int *p = NULL; where NULL is typically defined in C to be '(void *) 0'. */ if (VOID_TYPE_P (ttr) && rhs != null_pointer_node && !VOID_TYPE_P (ttl)) warning_at (errtype == ic_argpass ? expr_loc : location, OPT_Wc___compat, "request for implicit conversion " "from %qT to %qT not permitted in C++", rhstype, type); /* See if the pointers point to incompatible address spaces. */ asl = TYPE_ADDR_SPACE (ttl); asr = TYPE_ADDR_SPACE (ttr); if (!null_pointer_constant_p (rhs) && asr != asl && !targetm.addr_space.subset_p (asr, asl)) { switch (errtype) { case ic_argpass: error_at (expr_loc, "passing argument %d of %qE from pointer to " "non-enclosed address space", parmnum, rname); break; case ic_assign: error_at (location, "assignment from pointer to " "non-enclosed address space"); break; case ic_init: error_at (location, "initialization from pointer to " "non-enclosed address space"); break; case ic_return: error_at (location, "return from pointer to " "non-enclosed address space"); break; default: gcc_unreachable (); } return error_mark_node; } /* Check if the right-hand side has a format attribute but the left-hand side doesn't. */ if (warn_suggest_attribute_format && check_missing_format_attribute (type, rhstype)) { switch (errtype) { case ic_argpass: warning_at (expr_loc, OPT_Wsuggest_attribute_format, "argument %d of %qE might be " "a candidate for a format attribute", parmnum, rname); break; case ic_assign: warning_at (location, OPT_Wsuggest_attribute_format, "assignment left-hand side might be " "a candidate for a format attribute"); break; case ic_init: warning_at (location, OPT_Wsuggest_attribute_format, "initialization left-hand side might be " "a candidate for a format attribute"); break; case ic_return: warning_at (location, OPT_Wsuggest_attribute_format, "return type might be " "a candidate for a format attribute"); break; default: gcc_unreachable (); } } /* Any non-function converts to a [const][volatile] void * and vice versa; otherwise, targets must be the same. Meanwhile, the lhs target must have all the qualifiers of the rhs. */ if ((VOID_TYPE_P (ttl) && !TYPE_ATOMIC (ttl)) || (VOID_TYPE_P (ttr) && !TYPE_ATOMIC (ttr)) || (target_cmp = comp_target_types (location, type, rhstype)) || is_opaque_pointer || ((c_common_unsigned_type (mvl) == c_common_unsigned_type (mvr)) && (c_common_signed_type (mvl) == c_common_signed_type (mvr)) && TYPE_ATOMIC (mvl) == TYPE_ATOMIC (mvr))) { /* Warn about loss of qualifers from pointers to arrays with qualifiers on the element type. */ if (TREE_CODE (ttr) == ARRAY_TYPE) { ttr = strip_array_types (ttr); ttl = strip_array_types (ttl); if (TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttr) & ~TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttl)) WARNING_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_array_qualifiers, G_("passing argument %d of %qE discards " "%qv qualifier from pointer target type"), G_("assignment discards %qv qualifier " "from pointer target type"), G_("initialization discards %qv qualifier " "from pointer target type"), G_("return discards %qv qualifier from " "pointer target type"), TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl)); } else if (pedantic && ((VOID_TYPE_P (ttl) && TREE_CODE (ttr) == FUNCTION_TYPE) || (VOID_TYPE_P (ttr) && !null_pointer_constant && TREE_CODE (ttl) == FUNCTION_TYPE))) PEDWARN_FOR_ASSIGNMENT (location, expr_loc, OPT_Wpedantic, G_("ISO C forbids passing argument %d of " "%qE between function pointer " "and %<void *%>"), G_("ISO C forbids assignment between " "function pointer and %<void *%>"), G_("ISO C forbids initialization between " "function pointer and %<void *%>"), G_("ISO C forbids return between function " "pointer and %<void *%>")); /* Const and volatile mean something different for function types, so the usual warnings are not appropriate. */ else if (TREE_CODE (ttr) != FUNCTION_TYPE && TREE_CODE (ttl) != FUNCTION_TYPE) { /* Don't warn about loss of qualifier for conversions from qualified void* to pointers to arrays with corresponding qualifier on the element type. */ if (!pedantic) ttl = strip_array_types (ttl); /* Assignments between atomic and non-atomic objects are OK. */ if (TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttr) & ~TYPE_QUALS_NO_ADDR_SPACE_NO_ATOMIC (ttl)) { PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE discards " "%qv qualifier from pointer target type"), G_("assignment discards %qv qualifier " "from pointer target type"), G_("initialization discards %qv qualifier " "from pointer target type"), G_("return discards %qv qualifier from " "pointer target type"), TYPE_QUALS (ttr) & ~TYPE_QUALS (ttl)); } /* If this is not a case of ignoring a mismatch in signedness, no warning. */ else if (VOID_TYPE_P (ttl) || VOID_TYPE_P (ttr) || target_cmp) ; /* If there is a mismatch, do warn. */ else if (warn_pointer_sign) PEDWARN_FOR_ASSIGNMENT (location, expr_loc, OPT_Wpointer_sign, G_("pointer targets in passing argument " "%d of %qE differ in signedness"), G_("pointer targets in assignment " "differ in signedness"), G_("pointer targets in initialization " "differ in signedness"), G_("pointer targets in return differ " "in signedness")); } else if (TREE_CODE (ttl) == FUNCTION_TYPE && TREE_CODE (ttr) == FUNCTION_TYPE) { /* Because const and volatile on functions are restrictions that say the function will not do certain things, it is okay to use a const or volatile function where an ordinary one is wanted, but not vice-versa. */ if (TYPE_QUALS_NO_ADDR_SPACE (ttl) & ~TYPE_QUALS_NO_ADDR_SPACE (ttr)) PEDWARN_FOR_QUALIFIERS (location, expr_loc, OPT_Wdiscarded_qualifiers, G_("passing argument %d of %qE makes " "%q#v qualified function pointer " "from unqualified"), G_("assignment makes %q#v qualified function " "pointer from unqualified"), G_("initialization makes %q#v qualified " "function pointer from unqualified"), G_("return makes %q#v qualified function " "pointer from unqualified"), TYPE_QUALS (ttl) & ~TYPE_QUALS (ttr)); } } else /* Avoid warning about the volatile ObjC EH puts on decls. */ if (!objc_ok) PEDWARN_FOR_ASSIGNMENT (location, expr_loc, OPT_Wincompatible_pointer_types, G_("passing argument %d of %qE from " "incompatible pointer type"), G_("assignment from incompatible pointer type"), G_("initialization from incompatible " "pointer type"), G_("return from incompatible pointer type")); return convert (type, rhs); } else if (codel == POINTER_TYPE && coder == ARRAY_TYPE) { /* ??? This should not be an error when inlining calls to unprototyped functions. */ error_at (location, "invalid use of non-lvalue array"); return error_mark_node; } else if (codel == POINTER_TYPE && coder == INTEGER_TYPE) { /* An explicit constant 0 can convert to a pointer, or one that results from arithmetic, even including a cast to integer type. */ if (!null_pointer_constant) PEDWARN_FOR_ASSIGNMENT (location, expr_loc, OPT_Wint_conversion, G_("passing argument %d of %qE makes " "pointer from integer without a cast"), G_("assignment makes pointer from integer " "without a cast"), G_("initialization makes pointer from " "integer without a cast"), G_("return makes pointer from integer " "without a cast")); return convert (type, rhs); } else if (codel == INTEGER_TYPE && coder == POINTER_TYPE) { PEDWARN_FOR_ASSIGNMENT (location, expr_loc, OPT_Wint_conversion, G_("passing argument %d of %qE makes integer " "from pointer without a cast"), G_("assignment makes integer from pointer " "without a cast"), G_("initialization makes integer from pointer " "without a cast"), G_("return makes integer from pointer " "without a cast")); return convert (type, rhs); } else if (codel == BOOLEAN_TYPE && coder == POINTER_TYPE) { tree ret; bool save = in_late_binary_op; in_late_binary_op = true; ret = convert (type, rhs); in_late_binary_op = save; return ret; } switch (errtype) { case ic_argpass: error_at (expr_loc, "incompatible type for argument %d of %qE", parmnum, rname); inform ((fundecl && !DECL_IS_BUILTIN (fundecl)) ? DECL_SOURCE_LOCATION (fundecl) : expr_loc, "expected %qT but argument is of type %qT", type, rhstype); break; case ic_assign: error_at (location, "incompatible types when assigning to type %qT from " "type %qT", type, rhstype); break; case ic_init: error_at (location, "incompatible types when initializing type %qT using type %qT", type, rhstype); break; case ic_return: error_at (location, "incompatible types when returning type %qT but %qT was " "expected", rhstype, type); break; default: gcc_unreachable (); } return error_mark_node; } /* If VALUE is a compound expr all of whose expressions are constant, then return its value. Otherwise, return error_mark_node. This is for handling COMPOUND_EXPRs as initializer elements which is allowed with a warning when -pedantic is specified. */ static tree valid_compound_expr_initializer (tree value, tree endtype) { if (TREE_CODE (value) == COMPOUND_EXPR) { if (valid_compound_expr_initializer (TREE_OPERAND (value, 0), endtype) == error_mark_node) return error_mark_node; return valid_compound_expr_initializer (TREE_OPERAND (value, 1), endtype); } else if (!initializer_constant_valid_p (value, endtype)) return error_mark_node; else return value; } /* Perform appropriate conversions on the initial value of a variable, store it in the declaration DECL, and print any error messages that are appropriate. If ORIGTYPE is not NULL_TREE, it is the original type of INIT. If the init is invalid, store an ERROR_MARK. INIT_LOC is the location of the initial value. */ void store_init_value (location_t init_loc, tree decl, tree init, tree origtype) { tree value, type; bool npc = false; /* If variable's type was invalidly declared, just ignore it. */ type = TREE_TYPE (decl); if (TREE_CODE (type) == ERROR_MARK) return; /* Digest the specified initializer into an expression. */ if (init) npc = null_pointer_constant_p (init); value = digest_init (init_loc, type, init, origtype, npc, true, TREE_STATIC (decl)); /* Store the expression if valid; else report error. */ if (!in_system_header_at (input_location) && AGGREGATE_TYPE_P (TREE_TYPE (decl)) && !TREE_STATIC (decl)) warning (OPT_Wtraditional, "traditional C rejects automatic " "aggregate initialization"); if (value != error_mark_node || TREE_CODE (decl) != FUNCTION_DECL) DECL_INITIAL (decl) = value; /* ANSI wants warnings about out-of-range constant initializers. */ STRIP_TYPE_NOPS (value); if (TREE_STATIC (decl)) constant_expression_warning (value); /* Check if we need to set array size from compound literal size. */ if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type) == 0 && value != error_mark_node) { tree inside_init = init; STRIP_TYPE_NOPS (inside_init); inside_init = fold (inside_init); if (TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR) { tree cldecl = COMPOUND_LITERAL_EXPR_DECL (inside_init); if (TYPE_DOMAIN (TREE_TYPE (cldecl))) { /* For int foo[] = (int [3]){1}; we need to set array size now since later on array initializer will be just the brace enclosed list of the compound literal. */ tree etype = strip_array_types (TREE_TYPE (decl)); type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type)); TYPE_DOMAIN (type) = TYPE_DOMAIN (TREE_TYPE (cldecl)); layout_type (type); layout_decl (cldecl, 0); TREE_TYPE (decl) = c_build_qualified_type (type, TYPE_QUALS (etype)); } } } } /* Methods for storing and printing names for error messages. */ /* Implement a spelling stack that allows components of a name to be pushed and popped. Each element on the stack is this structure. */ struct spelling { int kind; union { unsigned HOST_WIDE_INT i; const char *s; } u; }; #define SPELLING_STRING 1 #define SPELLING_MEMBER 2 #define SPELLING_BOUNDS 3 static struct spelling *spelling; /* Next stack element (unused). */ static struct spelling *spelling_base; /* Spelling stack base. */ static int spelling_size; /* Size of the spelling stack. */ /* Macros to save and restore the spelling stack around push_... functions. Alternative to SAVE_SPELLING_STACK. */ #define SPELLING_DEPTH() (spelling - spelling_base) #define RESTORE_SPELLING_DEPTH(DEPTH) (spelling = spelling_base + (DEPTH)) /* Push an element on the spelling stack with type KIND and assign VALUE to MEMBER. */ #define PUSH_SPELLING(KIND, VALUE, MEMBER) \ { \ int depth = SPELLING_DEPTH (); \ \ if (depth >= spelling_size) \ { \ spelling_size += 10; \ spelling_base = XRESIZEVEC (struct spelling, spelling_base, \ spelling_size); \ RESTORE_SPELLING_DEPTH (depth); \ } \ \ spelling->kind = (KIND); \ spelling->MEMBER = (VALUE); \ spelling++; \ } /* Push STRING on the stack. Printed literally. */ static void push_string (const char *string) { PUSH_SPELLING (SPELLING_STRING, string, u.s); } /* Push a member name on the stack. Printed as '.' STRING. */ static void push_member_name (tree decl) { const char *const string = (DECL_NAME (decl) ? identifier_to_locale (IDENTIFIER_POINTER (DECL_NAME (decl))) : _("<anonymous>")); PUSH_SPELLING (SPELLING_MEMBER, string, u.s); } /* Push an array bounds on the stack. Printed as [BOUNDS]. */ static void push_array_bounds (unsigned HOST_WIDE_INT bounds) { PUSH_SPELLING (SPELLING_BOUNDS, bounds, u.i); } /* Compute the maximum size in bytes of the printed spelling. */ static int spelling_length (void) { int size = 0; struct spelling *p; for (p = spelling_base; p < spelling; p++) { if (p->kind == SPELLING_BOUNDS) size += 25; else size += strlen (p->u.s) + 1; } return size; } /* Print the spelling to BUFFER and return it. */ static char * print_spelling (char *buffer) { char *d = buffer; struct spelling *p; for (p = spelling_base; p < spelling; p++) if (p->kind == SPELLING_BOUNDS) { sprintf (d, "[" HOST_WIDE_INT_PRINT_UNSIGNED "]", p->u.i); d += strlen (d); } else { const char *s; if (p->kind == SPELLING_MEMBER) *d++ = '.'; for (s = p->u.s; (*d = *s++); d++) ; } *d++ = '\0'; return buffer; } /* Digest the parser output INIT as an initializer for type TYPE. Return a C expression of type TYPE to represent the initial value. If ORIGTYPE is not NULL_TREE, it is the original type of INIT. NULL_POINTER_CONSTANT is true if INIT is a null pointer constant. If INIT is a string constant, STRICT_STRING is true if it is unparenthesized or we should not warn here for it being parenthesized. For other types of INIT, STRICT_STRING is not used. INIT_LOC is the location of the INIT. REQUIRE_CONSTANT requests an error if non-constant initializers or elements are seen. */ static tree digest_init (location_t init_loc, tree type, tree init, tree origtype, bool null_pointer_constant, bool strict_string, int require_constant) { enum tree_code code = TREE_CODE (type); tree inside_init = init; tree semantic_type = NULL_TREE; bool maybe_const = true; if (type == error_mark_node || !init || error_operand_p (init)) return error_mark_node; STRIP_TYPE_NOPS (inside_init); if (TREE_CODE (inside_init) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (inside_init); inside_init = TREE_OPERAND (inside_init, 0); } inside_init = c_fully_fold (inside_init, require_constant, &maybe_const); inside_init = decl_constant_value_for_optimization (inside_init); /* Initialization of an array of chars from a string constant optionally enclosed in braces. */ if (code == ARRAY_TYPE && inside_init && TREE_CODE (inside_init) == STRING_CST) { tree typ1 = (TYPE_ATOMIC (TREE_TYPE (type)) ? c_build_qualified_type (TYPE_MAIN_VARIANT (TREE_TYPE (type)), TYPE_QUAL_ATOMIC) : TYPE_MAIN_VARIANT (TREE_TYPE (type))); /* Note that an array could be both an array of character type and an array of wchar_t if wchar_t is signed char or unsigned char. */ bool char_array = (typ1 == char_type_node || typ1 == signed_char_type_node || typ1 == unsigned_char_type_node); bool wchar_array = !!comptypes (typ1, wchar_type_node); bool char16_array = !!comptypes (typ1, char16_type_node); bool char32_array = !!comptypes (typ1, char32_type_node); if (char_array || wchar_array || char16_array || char32_array) { struct c_expr expr; tree typ2 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (inside_init))); expr.value = inside_init; expr.original_code = (strict_string ? STRING_CST : ERROR_MARK); expr.original_type = NULL; maybe_warn_string_init (init_loc, type, expr); if (TYPE_DOMAIN (type) && !TYPE_MAX_VALUE (TYPE_DOMAIN (type))) pedwarn_init (init_loc, OPT_Wpedantic, "initialization of a flexible array member"); if (comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)), TYPE_MAIN_VARIANT (type))) return inside_init; if (char_array) { if (typ2 != char_type_node) { error_init (init_loc, "char-array initialized from wide " "string"); return error_mark_node; } } else { if (typ2 == char_type_node) { error_init (init_loc, "wide character array initialized " "from non-wide string"); return error_mark_node; } else if (!comptypes(typ1, typ2)) { error_init (init_loc, "wide character array initialized " "from incompatible wide string"); return error_mark_node; } } TREE_TYPE (inside_init) = type; if (TYPE_DOMAIN (type) != 0 && TYPE_SIZE (type) != 0 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST) { unsigned HOST_WIDE_INT len = TREE_STRING_LENGTH (inside_init); /* Subtract the size of a single (possibly wide) character because it's ok to ignore the terminating null char that is counted in the length of the constant. */ if (0 > compare_tree_int (TYPE_SIZE_UNIT (type), (len - (TYPE_PRECISION (typ1) / BITS_PER_UNIT)))) pedwarn_init (init_loc, 0, ("initializer-string for array of chars " "is too long")); else if (warn_cxx_compat && 0 > compare_tree_int (TYPE_SIZE_UNIT (type), len)) warning_at (init_loc, OPT_Wc___compat, ("initializer-string for array chars " "is too long for C++")); } return inside_init; } else if (INTEGRAL_TYPE_P (typ1)) { error_init (init_loc, "array of inappropriate type initialized " "from string constant"); return error_mark_node; } } /* Build a VECTOR_CST from a *constant* vector constructor. If the vector constructor is not constant (e.g. {1,2,3,foo()}) then punt below and handle as a constructor. */ if (code == VECTOR_TYPE && TREE_CODE (TREE_TYPE (inside_init)) == VECTOR_TYPE && vector_types_convertible_p (TREE_TYPE (inside_init), type, true) && TREE_CONSTANT (inside_init)) { if (TREE_CODE (inside_init) == VECTOR_CST && comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)), TYPE_MAIN_VARIANT (type))) return inside_init; if (TREE_CODE (inside_init) == CONSTRUCTOR) { unsigned HOST_WIDE_INT ix; tree value; bool constant_p = true; /* Iterate through elements and check if all constructor elements are *_CSTs. */ FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (inside_init), ix, value) if (!CONSTANT_CLASS_P (value)) { constant_p = false; break; } if (constant_p) return build_vector_from_ctor (type, CONSTRUCTOR_ELTS (inside_init)); } } if (warn_sequence_point) verify_sequence_points (inside_init); /* Any type can be initialized from an expression of the same type, optionally with braces. */ if (inside_init && TREE_TYPE (inside_init) != 0 && (comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (inside_init)), TYPE_MAIN_VARIANT (type)) || (code == ARRAY_TYPE && comptypes (TREE_TYPE (inside_init), type)) || (code == VECTOR_TYPE && comptypes (TREE_TYPE (inside_init), type)) || (code == POINTER_TYPE && TREE_CODE (TREE_TYPE (inside_init)) == ARRAY_TYPE && comptypes (TREE_TYPE (TREE_TYPE (inside_init)), TREE_TYPE (type))))) { if (code == POINTER_TYPE) { if (TREE_CODE (TREE_TYPE (inside_init)) == ARRAY_TYPE) { if (TREE_CODE (inside_init) == STRING_CST || TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR) inside_init = array_to_pointer_conversion (init_loc, inside_init); else { error_init (init_loc, "invalid use of non-lvalue array"); return error_mark_node; } } } if (code == VECTOR_TYPE) /* Although the types are compatible, we may require a conversion. */ inside_init = convert (type, inside_init); if (require_constant && TREE_CODE (inside_init) == COMPOUND_LITERAL_EXPR) { /* As an extension, allow initializing objects with static storage duration with compound literals (which are then treated just as the brace enclosed list they contain). Also allow this for vectors, as we can only assign them with compound literals. */ if (flag_isoc99 && code != VECTOR_TYPE) pedwarn_init (init_loc, OPT_Wpedantic, "initializer element " "is not constant"); tree decl = COMPOUND_LITERAL_EXPR_DECL (inside_init); inside_init = DECL_INITIAL (decl); } if (code == ARRAY_TYPE && TREE_CODE (inside_init) != STRING_CST && TREE_CODE (inside_init) != CONSTRUCTOR) { error_init (init_loc, "array initialized from non-constant array " "expression"); return error_mark_node; } /* Compound expressions can only occur here if -Wpedantic or -pedantic-errors is specified. In the later case, we always want an error. In the former case, we simply want a warning. */ if (require_constant && pedantic && TREE_CODE (inside_init) == COMPOUND_EXPR) { inside_init = valid_compound_expr_initializer (inside_init, TREE_TYPE (inside_init)); if (inside_init == error_mark_node) error_init (init_loc, "initializer element is not constant"); else pedwarn_init (init_loc, OPT_Wpedantic, "initializer element is not constant"); if (flag_pedantic_errors) inside_init = error_mark_node; } else if (require_constant && !initializer_constant_valid_p (inside_init, TREE_TYPE (inside_init))) { error_init (init_loc, "initializer element is not constant"); inside_init = error_mark_node; } else if (require_constant && !maybe_const) pedwarn_init (init_loc, 0, "initializer element is not a constant expression"); /* Added to enable additional -Wsuggest-attribute=format warnings. */ if (TREE_CODE (TREE_TYPE (inside_init)) == POINTER_TYPE) inside_init = convert_for_assignment (init_loc, UNKNOWN_LOCATION, type, inside_init, origtype, ic_init, null_pointer_constant, NULL_TREE, NULL_TREE, 0); return inside_init; } /* Handle scalar types, including conversions. */ if (code == INTEGER_TYPE || code == REAL_TYPE || code == FIXED_POINT_TYPE || code == POINTER_TYPE || code == ENUMERAL_TYPE || code == BOOLEAN_TYPE || code == COMPLEX_TYPE || code == VECTOR_TYPE) { if (TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE && (TREE_CODE (init) == STRING_CST || TREE_CODE (init) == COMPOUND_LITERAL_EXPR)) inside_init = init = array_to_pointer_conversion (init_loc, init); if (semantic_type) inside_init = build1 (EXCESS_PRECISION_EXPR, semantic_type, inside_init); inside_init = convert_for_assignment (init_loc, UNKNOWN_LOCATION, type, inside_init, origtype, ic_init, null_pointer_constant, NULL_TREE, NULL_TREE, 0); /* Check to see if we have already given an error message. */ if (inside_init == error_mark_node) ; else if (require_constant && !TREE_CONSTANT (inside_init)) { error_init (init_loc, "initializer element is not constant"); inside_init = error_mark_node; } else if (require_constant && !initializer_constant_valid_p (inside_init, TREE_TYPE (inside_init))) { error_init (init_loc, "initializer element is not computable at " "load time"); inside_init = error_mark_node; } else if (require_constant && !maybe_const) pedwarn_init (init_loc, 0, "initializer element is not a constant expression"); return inside_init; } /* Come here only for records and arrays. */ if (COMPLETE_TYPE_P (type) && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST) { error_init (init_loc, "variable-sized object may not be initialized"); return error_mark_node; } error_init (init_loc, "invalid initializer"); return error_mark_node; } /* Handle initializers that use braces. */ /* Type of object we are accumulating a constructor for. This type is always a RECORD_TYPE, UNION_TYPE or ARRAY_TYPE. */ static tree constructor_type; /* For a RECORD_TYPE or UNION_TYPE, this is the chain of fields left to fill. */ static tree constructor_fields; /* For an ARRAY_TYPE, this is the specified index at which to store the next element we get. */ static tree constructor_index; /* For an ARRAY_TYPE, this is the maximum index. */ static tree constructor_max_index; /* For a RECORD_TYPE, this is the first field not yet written out. */ static tree constructor_unfilled_fields; /* For an ARRAY_TYPE, this is the index of the first element not yet written out. */ static tree constructor_unfilled_index; /* In a RECORD_TYPE, the byte index of the next consecutive field. This is so we can generate gaps between fields, when appropriate. */ static tree constructor_bit_index; /* If we are saving up the elements rather than allocating them, this is the list of elements so far (in reverse order, most recent first). */ static vec<constructor_elt, va_gc> *constructor_elements; /* 1 if constructor should be incrementally stored into a constructor chain, 0 if all the elements should be kept in AVL tree. */ static int constructor_incremental; /* 1 if so far this constructor's elements are all compile-time constants. */ static int constructor_constant; /* 1 if so far this constructor's elements are all valid address constants. */ static int constructor_simple; /* 1 if this constructor has an element that cannot be part of a constant expression. */ static int constructor_nonconst; /* 1 if this constructor is erroneous so far. */ static int constructor_erroneous; /* 1 if this constructor is the universal zero initializer { 0 }. */ static int constructor_zeroinit; /* Structure for managing pending initializer elements, organized as an AVL tree. */ struct init_node { struct init_node *left, *right; struct init_node *parent; int balance; tree purpose; tree value; tree origtype; }; /* Tree of pending elements at this constructor level. These are elements encountered out of order which belong at places we haven't reached yet in actually writing the output. Will never hold tree nodes across GC runs. */ static struct init_node *constructor_pending_elts; /* The SPELLING_DEPTH of this constructor. */ static int constructor_depth; /* DECL node for which an initializer is being read. 0 means we are reading a constructor expression such as (struct foo) {...}. */ static tree constructor_decl; /* Nonzero if this is an initializer for a top-level decl. */ static int constructor_top_level; /* Nonzero if there were any member designators in this initializer. */ static int constructor_designated; /* Nesting depth of designator list. */ static int designator_depth; /* Nonzero if there were diagnosed errors in this designator list. */ static int designator_erroneous; /* This stack has a level for each implicit or explicit level of structuring in the initializer, including the outermost one. It saves the values of most of the variables above. */ struct constructor_range_stack; struct constructor_stack { struct constructor_stack *next; tree type; tree fields; tree index; tree max_index; tree unfilled_index; tree unfilled_fields; tree bit_index; vec<constructor_elt, va_gc> *elements; struct init_node *pending_elts; int offset; int depth; /* If value nonzero, this value should replace the entire constructor at this level. */ struct c_expr replacement_value; struct constructor_range_stack *range_stack; char constant; char simple; char nonconst; char implicit; char erroneous; char outer; char incremental; char designated; int designator_depth; }; static struct constructor_stack *constructor_stack; /* This stack represents designators from some range designator up to the last designator in the list. */ struct constructor_range_stack { struct constructor_range_stack *next, *prev; struct constructor_stack *stack; tree range_start; tree index; tree range_end; tree fields; }; static struct constructor_range_stack *constructor_range_stack; /* This stack records separate initializers that are nested. Nested initializers can't happen in ANSI C, but GNU C allows them in cases like { ... (struct foo) { ... } ... }. */ struct initializer_stack { struct initializer_stack *next; tree decl; struct constructor_stack *constructor_stack; struct constructor_range_stack *constructor_range_stack; vec<constructor_elt, va_gc> *elements; struct spelling *spelling; struct spelling *spelling_base; int spelling_size; char top_level; char require_constant_value; char require_constant_elements; }; static struct initializer_stack *initializer_stack; /* Prepare to parse and output the initializer for variable DECL. */ void start_init (tree decl, tree asmspec_tree ATTRIBUTE_UNUSED, int top_level) { const char *locus; struct initializer_stack *p = XNEW (struct initializer_stack); p->decl = constructor_decl; p->require_constant_value = require_constant_value; p->require_constant_elements = require_constant_elements; p->constructor_stack = constructor_stack; p->constructor_range_stack = constructor_range_stack; p->elements = constructor_elements; p->spelling = spelling; p->spelling_base = spelling_base; p->spelling_size = spelling_size; p->top_level = constructor_top_level; p->next = initializer_stack; initializer_stack = p; constructor_decl = decl; constructor_designated = 0; constructor_top_level = top_level; if (decl != 0 && decl != error_mark_node) { require_constant_value = TREE_STATIC (decl); require_constant_elements = ((TREE_STATIC (decl) || (pedantic && !flag_isoc99)) /* For a scalar, you can always use any value to initialize, even within braces. */ && (TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE || TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE || TREE_CODE (TREE_TYPE (decl)) == UNION_TYPE || TREE_CODE (TREE_TYPE (decl)) == QUAL_UNION_TYPE)); locus = identifier_to_locale (IDENTIFIER_POINTER (DECL_NAME (decl))); } else { require_constant_value = 0; require_constant_elements = 0; locus = _("(anonymous)"); } constructor_stack = 0; constructor_range_stack = 0; found_missing_braces = 0; spelling_base = 0; spelling_size = 0; RESTORE_SPELLING_DEPTH (0); if (locus) push_string (locus); } void finish_init (void) { struct initializer_stack *p = initializer_stack; /* Free the whole constructor stack of this initializer. */ while (constructor_stack) { struct constructor_stack *q = constructor_stack; constructor_stack = q->next; free (q); } gcc_assert (!constructor_range_stack); /* Pop back to the data of the outer initializer (if any). */ free (spelling_base); constructor_decl = p->decl; require_constant_value = p->require_constant_value; require_constant_elements = p->require_constant_elements; constructor_stack = p->constructor_stack; constructor_range_stack = p->constructor_range_stack; constructor_elements = p->elements; spelling = p->spelling; spelling_base = p->spelling_base; spelling_size = p->spelling_size; constructor_top_level = p->top_level; initializer_stack = p->next; free (p); } /* Call here when we see the initializer is surrounded by braces. This is instead of a call to push_init_level; it is matched by a call to pop_init_level. TYPE is the type to initialize, for a constructor expression. For an initializer for a decl, TYPE is zero. */ void really_start_incremental_init (tree type) { struct constructor_stack *p = XNEW (struct constructor_stack); if (type == 0) type = TREE_TYPE (constructor_decl); if (TREE_CODE (type) == VECTOR_TYPE && TYPE_VECTOR_OPAQUE (type)) error ("opaque vector types cannot be initialized"); p->type = constructor_type; p->fields = constructor_fields; p->index = constructor_index; p->max_index = constructor_max_index; p->unfilled_index = constructor_unfilled_index; p->unfilled_fields = constructor_unfilled_fields; p->bit_index = constructor_bit_index; p->elements = constructor_elements; p->constant = constructor_constant; p->simple = constructor_simple; p->nonconst = constructor_nonconst; p->erroneous = constructor_erroneous; p->pending_elts = constructor_pending_elts; p->depth = constructor_depth; p->replacement_value.value = 0; p->replacement_value.original_code = ERROR_MARK; p->replacement_value.original_type = NULL; p->implicit = 0; p->range_stack = 0; p->outer = 0; p->incremental = constructor_incremental; p->designated = constructor_designated; p->designator_depth = designator_depth; p->next = 0; constructor_stack = p; constructor_constant = 1; constructor_simple = 1; constructor_nonconst = 0; constructor_depth = SPELLING_DEPTH (); constructor_elements = NULL; constructor_pending_elts = 0; constructor_type = type; constructor_incremental = 1; constructor_designated = 0; constructor_zeroinit = 1; designator_depth = 0; designator_erroneous = 0; if (TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) { constructor_fields = TYPE_FIELDS (constructor_type); /* Skip any nameless bit fields at the beginning. */ while (constructor_fields != 0 && DECL_C_BIT_FIELD (constructor_fields) && DECL_NAME (constructor_fields) == 0) constructor_fields = DECL_CHAIN (constructor_fields); constructor_unfilled_fields = constructor_fields; constructor_bit_index = bitsize_zero_node; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (TYPE_DOMAIN (constructor_type)) { constructor_max_index = TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type)); /* Detect non-empty initializations of zero-length arrays. */ if (constructor_max_index == NULL_TREE && TYPE_SIZE (constructor_type)) constructor_max_index = integer_minus_one_node; /* constructor_max_index needs to be an INTEGER_CST. Attempts to initialize VLAs will cause a proper error; avoid tree checking errors as well by setting a safe value. */ if (constructor_max_index && TREE_CODE (constructor_max_index) != INTEGER_CST) constructor_max_index = integer_minus_one_node; constructor_index = convert (bitsizetype, TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type))); } else { constructor_index = bitsize_zero_node; constructor_max_index = NULL_TREE; } constructor_unfilled_index = constructor_index; } else if (TREE_CODE (constructor_type) == VECTOR_TYPE) { /* Vectors are like simple fixed-size arrays. */ constructor_max_index = bitsize_int (TYPE_VECTOR_SUBPARTS (constructor_type) - 1); constructor_index = bitsize_zero_node; constructor_unfilled_index = constructor_index; } else { /* Handle the case of int x = {5}; */ constructor_fields = constructor_type; constructor_unfilled_fields = constructor_type; } } /* Called when we see an open brace for a nested initializer. Finish off any pending levels with implicit braces. */ void finish_implicit_inits (location_t loc, struct obstack *braced_init_obstack) { while (constructor_stack->implicit) { if ((TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) && constructor_fields == 0) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); else if (TREE_CODE (constructor_type) == ARRAY_TYPE && constructor_max_index && tree_int_cst_lt (constructor_max_index, constructor_index)) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); else break; } } /* Push down into a subobject, for initialization. If this is for an explicit set of braces, IMPLICIT is 0. If it is because the next element belongs at a lower level, IMPLICIT is 1 (or 2 if the push is because of designator list). */ void push_init_level (location_t loc, int implicit, struct obstack *braced_init_obstack) { struct constructor_stack *p; tree value = NULL_TREE; /* Unless this is an explicit brace, we need to preserve previous content if any. */ if (implicit) { if ((TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) && constructor_fields) value = find_init_member (constructor_fields, braced_init_obstack); else if (TREE_CODE (constructor_type) == ARRAY_TYPE) value = find_init_member (constructor_index, braced_init_obstack); } p = XNEW (struct constructor_stack); p->type = constructor_type; p->fields = constructor_fields; p->index = constructor_index; p->max_index = constructor_max_index; p->unfilled_index = constructor_unfilled_index; p->unfilled_fields = constructor_unfilled_fields; p->bit_index = constructor_bit_index; p->elements = constructor_elements; p->constant = constructor_constant; p->simple = constructor_simple; p->nonconst = constructor_nonconst; p->erroneous = constructor_erroneous; p->pending_elts = constructor_pending_elts; p->depth = constructor_depth; p->replacement_value.value = 0; p->replacement_value.original_code = ERROR_MARK; p->replacement_value.original_type = NULL; p->implicit = implicit; p->outer = 0; p->incremental = constructor_incremental; p->designated = constructor_designated; p->designator_depth = designator_depth; p->next = constructor_stack; p->range_stack = 0; constructor_stack = p; constructor_constant = 1; constructor_simple = 1; constructor_nonconst = 0; constructor_depth = SPELLING_DEPTH (); constructor_elements = NULL; constructor_incremental = 1; constructor_designated = 0; constructor_pending_elts = 0; if (!implicit) { p->range_stack = constructor_range_stack; constructor_range_stack = 0; designator_depth = 0; designator_erroneous = 0; } /* Don't die if an entire brace-pair level is superfluous in the containing level. */ if (constructor_type == 0) ; else if (TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) { /* Don't die if there are extra init elts at the end. */ if (constructor_fields == 0) constructor_type = 0; else { constructor_type = TREE_TYPE (constructor_fields); push_member_name (constructor_fields); constructor_depth++; } /* If upper initializer is designated, then mark this as designated too to prevent bogus warnings. */ constructor_designated = p->designated; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { constructor_type = TREE_TYPE (constructor_type); push_array_bounds (tree_to_uhwi (constructor_index)); constructor_depth++; } if (constructor_type == 0) { error_init (loc, "extra brace group at end of initializer"); constructor_fields = 0; constructor_unfilled_fields = 0; return; } if (value && TREE_CODE (value) == CONSTRUCTOR) { constructor_constant = TREE_CONSTANT (value); constructor_simple = TREE_STATIC (value); constructor_nonconst = CONSTRUCTOR_NON_CONST (value); constructor_elements = CONSTRUCTOR_ELTS (value); if (!vec_safe_is_empty (constructor_elements) && (TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == ARRAY_TYPE)) set_nonincremental_init (braced_init_obstack); } if (implicit == 1) found_missing_braces = 1; if (TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) { constructor_fields = TYPE_FIELDS (constructor_type); /* Skip any nameless bit fields at the beginning. */ while (constructor_fields != 0 && DECL_C_BIT_FIELD (constructor_fields) && DECL_NAME (constructor_fields) == 0) constructor_fields = DECL_CHAIN (constructor_fields); constructor_unfilled_fields = constructor_fields; constructor_bit_index = bitsize_zero_node; } else if (TREE_CODE (constructor_type) == VECTOR_TYPE) { /* Vectors are like simple fixed-size arrays. */ constructor_max_index = bitsize_int (TYPE_VECTOR_SUBPARTS (constructor_type) - 1); constructor_index = bitsize_int (0); constructor_unfilled_index = constructor_index; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (TYPE_DOMAIN (constructor_type)) { constructor_max_index = TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type)); /* Detect non-empty initializations of zero-length arrays. */ if (constructor_max_index == NULL_TREE && TYPE_SIZE (constructor_type)) constructor_max_index = integer_minus_one_node; /* constructor_max_index needs to be an INTEGER_CST. Attempts to initialize VLAs will cause a proper error; avoid tree checking errors as well by setting a safe value. */ if (constructor_max_index && TREE_CODE (constructor_max_index) != INTEGER_CST) constructor_max_index = integer_minus_one_node; constructor_index = convert (bitsizetype, TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type))); } else constructor_index = bitsize_zero_node; constructor_unfilled_index = constructor_index; if (value && TREE_CODE (value) == STRING_CST) { /* We need to split the char/wchar array into individual characters, so that we don't have to special case it everywhere. */ set_nonincremental_init_from_string (value, braced_init_obstack); } } else { if (constructor_type != error_mark_node) warning_init (input_location, 0, "braces around scalar initializer"); constructor_fields = constructor_type; constructor_unfilled_fields = constructor_type; } } /* At the end of an implicit or explicit brace level, finish up that level of constructor. If a single expression with redundant braces initialized that level, return the c_expr structure for that expression. Otherwise, the original_code element is set to ERROR_MARK. If we were outputting the elements as they are read, return 0 as the value from inner levels (process_init_element ignores that), but return error_mark_node as the value from the outermost level (that's what we want to put in DECL_INITIAL). Otherwise, return a CONSTRUCTOR expression as the value. */ struct c_expr pop_init_level (location_t loc, int implicit, struct obstack *braced_init_obstack) { struct constructor_stack *p; struct c_expr ret; ret.value = 0; ret.original_code = ERROR_MARK; ret.original_type = NULL; if (implicit == 0) { /* When we come to an explicit close brace, pop any inner levels that didn't have explicit braces. */ while (constructor_stack->implicit) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); gcc_assert (!constructor_range_stack); } /* Now output all pending elements. */ constructor_incremental = 1; output_pending_init_elements (1, braced_init_obstack); p = constructor_stack; /* Error for initializing a flexible array member, or a zero-length array member in an inappropriate context. */ if (constructor_type && constructor_fields && TREE_CODE (constructor_type) == ARRAY_TYPE && TYPE_DOMAIN (constructor_type) && !TYPE_MAX_VALUE (TYPE_DOMAIN (constructor_type))) { /* Silently discard empty initializations. The parser will already have pedwarned for empty brackets. */ if (integer_zerop (constructor_unfilled_index)) constructor_type = NULL_TREE; else { gcc_assert (!TYPE_SIZE (constructor_type)); if (constructor_depth > 2) error_init (loc, "initialization of flexible array member in a nested context"); else pedwarn_init (loc, OPT_Wpedantic, "initialization of a flexible array member"); /* We have already issued an error message for the existence of a flexible array member not at the end of the structure. Discard the initializer so that we do not die later. */ if (DECL_CHAIN (constructor_fields) != NULL_TREE) constructor_type = NULL_TREE; } } switch (vec_safe_length (constructor_elements)) { case 0: /* Initialization with { } counts as zeroinit. */ constructor_zeroinit = 1; break; case 1: /* This might be zeroinit as well. */ if (integer_zerop ((*constructor_elements)[0].value)) constructor_zeroinit = 1; break; default: /* If the constructor has more than one element, it can't be { 0 }. */ constructor_zeroinit = 0; break; } /* Warn when some structs are initialized with direct aggregation. */ if (!implicit && found_missing_braces && warn_missing_braces && !constructor_zeroinit) warning_init (loc, OPT_Wmissing_braces, "missing braces around initializer"); /* Warn when some struct elements are implicitly initialized to zero. */ if (warn_missing_field_initializers && constructor_type && TREE_CODE (constructor_type) == RECORD_TYPE && constructor_unfilled_fields) { /* Do not warn for flexible array members or zero-length arrays. */ while (constructor_unfilled_fields && (!DECL_SIZE (constructor_unfilled_fields) || integer_zerop (DECL_SIZE (constructor_unfilled_fields)))) constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); if (constructor_unfilled_fields /* Do not warn if this level of the initializer uses member designators; it is likely to be deliberate. */ && !constructor_designated /* Do not warn about initializing with { 0 } or with { }. */ && !constructor_zeroinit) { if (warning_at (input_location, OPT_Wmissing_field_initializers, "missing initializer for field %qD of %qT", constructor_unfilled_fields, constructor_type)) inform (DECL_SOURCE_LOCATION (constructor_unfilled_fields), "%qD declared here", constructor_unfilled_fields); } } /* Pad out the end of the structure. */ if (p->replacement_value.value) /* If this closes a superfluous brace pair, just pass out the element between them. */ ret = p->replacement_value; else if (constructor_type == 0) ; else if (TREE_CODE (constructor_type) != RECORD_TYPE && TREE_CODE (constructor_type) != UNION_TYPE && TREE_CODE (constructor_type) != ARRAY_TYPE && TREE_CODE (constructor_type) != VECTOR_TYPE) { /* A nonincremental scalar initializer--just return the element, after verifying there is just one. */ if (vec_safe_is_empty (constructor_elements)) { if (!constructor_erroneous) error_init (loc, "empty scalar initializer"); ret.value = error_mark_node; } else if (vec_safe_length (constructor_elements) != 1) { error_init (loc, "extra elements in scalar initializer"); ret.value = (*constructor_elements)[0].value; } else ret.value = (*constructor_elements)[0].value; } else { if (constructor_erroneous) ret.value = error_mark_node; else { ret.value = build_constructor (constructor_type, constructor_elements); if (constructor_constant) TREE_CONSTANT (ret.value) = 1; if (constructor_constant && constructor_simple) TREE_STATIC (ret.value) = 1; if (constructor_nonconst) CONSTRUCTOR_NON_CONST (ret.value) = 1; } } if (ret.value && TREE_CODE (ret.value) != CONSTRUCTOR) { if (constructor_nonconst) ret.original_code = C_MAYBE_CONST_EXPR; else if (ret.original_code == C_MAYBE_CONST_EXPR) ret.original_code = ERROR_MARK; } constructor_type = p->type; constructor_fields = p->fields; constructor_index = p->index; constructor_max_index = p->max_index; constructor_unfilled_index = p->unfilled_index; constructor_unfilled_fields = p->unfilled_fields; constructor_bit_index = p->bit_index; constructor_elements = p->elements; constructor_constant = p->constant; constructor_simple = p->simple; constructor_nonconst = p->nonconst; constructor_erroneous = p->erroneous; constructor_incremental = p->incremental; constructor_designated = p->designated; designator_depth = p->designator_depth; constructor_pending_elts = p->pending_elts; constructor_depth = p->depth; if (!p->implicit) constructor_range_stack = p->range_stack; RESTORE_SPELLING_DEPTH (constructor_depth); constructor_stack = p->next; free (p); if (ret.value == 0 && constructor_stack == 0) ret.value = error_mark_node; return ret; } /* Common handling for both array range and field name designators. ARRAY argument is nonzero for array ranges. Returns zero for success. */ static int set_designator (location_t loc, int array, struct obstack *braced_init_obstack) { tree subtype; enum tree_code subcode; /* Don't die if an entire brace-pair level is superfluous in the containing level. */ if (constructor_type == 0) return 1; /* If there were errors in this designator list already, bail out silently. */ if (designator_erroneous) return 1; if (!designator_depth) { gcc_assert (!constructor_range_stack); /* Designator list starts at the level of closest explicit braces. */ while (constructor_stack->implicit) process_init_element (input_location, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); constructor_designated = 1; return 0; } switch (TREE_CODE (constructor_type)) { case RECORD_TYPE: case UNION_TYPE: subtype = TREE_TYPE (constructor_fields); if (subtype != error_mark_node) subtype = TYPE_MAIN_VARIANT (subtype); break; case ARRAY_TYPE: subtype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type)); break; default: gcc_unreachable (); } subcode = TREE_CODE (subtype); if (array && subcode != ARRAY_TYPE) { error_init (loc, "array index in non-array initializer"); return 1; } else if (!array && subcode != RECORD_TYPE && subcode != UNION_TYPE) { error_init (loc, "field name not in record or union initializer"); return 1; } constructor_designated = 1; finish_implicit_inits (loc, braced_init_obstack); push_init_level (loc, 2, braced_init_obstack); return 0; } /* If there are range designators in designator list, push a new designator to constructor_range_stack. RANGE_END is end of such stack range or NULL_TREE if there is no range designator at this level. */ static void push_range_stack (tree range_end, struct obstack * braced_init_obstack) { struct constructor_range_stack *p; p = (struct constructor_range_stack *) obstack_alloc (braced_init_obstack, sizeof (struct constructor_range_stack)); p->prev = constructor_range_stack; p->next = 0; p->fields = constructor_fields; p->range_start = constructor_index; p->index = constructor_index; p->stack = constructor_stack; p->range_end = range_end; if (constructor_range_stack) constructor_range_stack->next = p; constructor_range_stack = p; } /* Within an array initializer, specify the next index to be initialized. FIRST is that index. If LAST is nonzero, then initialize a range of indices, running from FIRST through LAST. */ void set_init_index (location_t loc, tree first, tree last, struct obstack *braced_init_obstack) { if (set_designator (loc, 1, braced_init_obstack)) return; designator_erroneous = 1; if (!INTEGRAL_TYPE_P (TREE_TYPE (first)) || (last && !INTEGRAL_TYPE_P (TREE_TYPE (last)))) { error_init (loc, "array index in initializer not of integer type"); return; } if (TREE_CODE (first) != INTEGER_CST) { first = c_fully_fold (first, false, NULL); if (TREE_CODE (first) == INTEGER_CST) pedwarn_init (loc, OPT_Wpedantic, "array index in initializer is not " "an integer constant expression"); } if (last && TREE_CODE (last) != INTEGER_CST) { last = c_fully_fold (last, false, NULL); if (TREE_CODE (last) == INTEGER_CST) pedwarn_init (loc, OPT_Wpedantic, "array index in initializer is not " "an integer constant expression"); } if (TREE_CODE (first) != INTEGER_CST) error_init (loc, "nonconstant array index in initializer"); else if (last != 0 && TREE_CODE (last) != INTEGER_CST) error_init (loc, "nonconstant array index in initializer"); else if (TREE_CODE (constructor_type) != ARRAY_TYPE) error_init (loc, "array index in non-array initializer"); else if (tree_int_cst_sgn (first) == -1) error_init (loc, "array index in initializer exceeds array bounds"); else if (constructor_max_index && tree_int_cst_lt (constructor_max_index, first)) error_init (loc, "array index in initializer exceeds array bounds"); else { constant_expression_warning (first); if (last) constant_expression_warning (last); constructor_index = convert (bitsizetype, first); if (tree_int_cst_lt (constructor_index, first)) { constructor_index = copy_node (constructor_index); TREE_OVERFLOW (constructor_index) = 1; } if (last) { if (tree_int_cst_equal (first, last)) last = 0; else if (tree_int_cst_lt (last, first)) { error_init (loc, "empty index range in initializer"); last = 0; } else { last = convert (bitsizetype, last); if (constructor_max_index != 0 && tree_int_cst_lt (constructor_max_index, last)) { error_init (loc, "array index range in initializer exceeds " "array bounds"); last = 0; } } } designator_depth++; designator_erroneous = 0; if (constructor_range_stack || last) push_range_stack (last, braced_init_obstack); } } /* Within a struct initializer, specify the next field to be initialized. */ void set_init_label (location_t loc, tree fieldname, struct obstack *braced_init_obstack) { tree field; if (set_designator (loc, 0, braced_init_obstack)) return; designator_erroneous = 1; if (TREE_CODE (constructor_type) != RECORD_TYPE && TREE_CODE (constructor_type) != UNION_TYPE) { error_init (loc, "field name not in record or union initializer"); return; } field = lookup_field (constructor_type, fieldname); if (field == 0) error ("unknown field %qE specified in initializer", fieldname); else do { constructor_fields = TREE_VALUE (field); designator_depth++; designator_erroneous = 0; if (constructor_range_stack) push_range_stack (NULL_TREE, braced_init_obstack); field = TREE_CHAIN (field); if (field) { if (set_designator (loc, 0, braced_init_obstack)) return; } } while (field != NULL_TREE); } /* Add a new initializer to the tree of pending initializers. PURPOSE identifies the initializer, either array index or field in a structure. VALUE is the value of that index or field. If ORIGTYPE is not NULL_TREE, it is the original type of VALUE. IMPLICIT is true if value comes from pop_init_level (1), the new initializer has been merged with the existing one and thus no warnings should be emitted about overriding an existing initializer. */ static void add_pending_init (location_t loc, tree purpose, tree value, tree origtype, bool implicit, struct obstack *braced_init_obstack) { struct init_node *p, **q, *r; q = &constructor_pending_elts; p = 0; if (TREE_CODE (constructor_type) == ARRAY_TYPE) { while (*q != 0) { p = *q; if (tree_int_cst_lt (purpose, p->purpose)) q = &p->left; else if (tree_int_cst_lt (p->purpose, purpose)) q = &p->right; else { if (!implicit) { if (TREE_SIDE_EFFECTS (p->value)) warning_init (loc, 0, "initialized field with side-effects " "overwritten"); else if (warn_override_init) warning_init (loc, OPT_Woverride_init, "initialized field overwritten"); } p->value = value; p->origtype = origtype; return; } } } else { tree bitpos; bitpos = bit_position (purpose); while (*q != NULL) { p = *q; if (tree_int_cst_lt (bitpos, bit_position (p->purpose))) q = &p->left; else if (p->purpose != purpose) q = &p->right; else { if (!implicit) { if (TREE_SIDE_EFFECTS (p->value)) warning_init (loc, 0, "initialized field with side-effects " "overwritten"); else if (warn_override_init) warning_init (loc, OPT_Woverride_init, "initialized field overwritten"); } p->value = value; p->origtype = origtype; return; } } } r = (struct init_node *) obstack_alloc (braced_init_obstack, sizeof (struct init_node)); r->purpose = purpose; r->value = value; r->origtype = origtype; *q = r; r->parent = p; r->left = 0; r->right = 0; r->balance = 0; while (p) { struct init_node *s; if (r == p->left) { if (p->balance == 0) p->balance = -1; else if (p->balance < 0) { if (r->balance < 0) { /* L rotation. */ p->left = r->right; if (p->left) p->left->parent = p; r->right = p; p->balance = 0; r->balance = 0; s = p->parent; p->parent = r; r->parent = s; if (s) { if (s->left == p) s->left = r; else s->right = r; } else constructor_pending_elts = r; } else { /* LR rotation. */ struct init_node *t = r->right; r->right = t->left; if (r->right) r->right->parent = r; t->left = r; p->left = t->right; if (p->left) p->left->parent = p; t->right = p; p->balance = t->balance < 0; r->balance = -(t->balance > 0); t->balance = 0; s = p->parent; p->parent = t; r->parent = t; t->parent = s; if (s) { if (s->left == p) s->left = t; else s->right = t; } else constructor_pending_elts = t; } break; } else { /* p->balance == +1; growth of left side balances the node. */ p->balance = 0; break; } } else /* r == p->right */ { if (p->balance == 0) /* Growth propagation from right side. */ p->balance++; else if (p->balance > 0) { if (r->balance > 0) { /* R rotation. */ p->right = r->left; if (p->right) p->right->parent = p; r->left = p; p->balance = 0; r->balance = 0; s = p->parent; p->parent = r; r->parent = s; if (s) { if (s->left == p) s->left = r; else s->right = r; } else constructor_pending_elts = r; } else /* r->balance == -1 */ { /* RL rotation */ struct init_node *t = r->left; r->left = t->right; if (r->left) r->left->parent = r; t->right = r; p->right = t->left; if (p->right) p->right->parent = p; t->left = p; r->balance = (t->balance < 0); p->balance = -(t->balance > 0); t->balance = 0; s = p->parent; p->parent = t; r->parent = t; t->parent = s; if (s) { if (s->left == p) s->left = t; else s->right = t; } else constructor_pending_elts = t; } break; } else { /* p->balance == -1; growth of right side balances the node. */ p->balance = 0; break; } } r = p; p = p->parent; } } /* Build AVL tree from a sorted chain. */ static void set_nonincremental_init (struct obstack * braced_init_obstack) { unsigned HOST_WIDE_INT ix; tree index, value; if (TREE_CODE (constructor_type) != RECORD_TYPE && TREE_CODE (constructor_type) != ARRAY_TYPE) return; FOR_EACH_CONSTRUCTOR_ELT (constructor_elements, ix, index, value) add_pending_init (input_location, index, value, NULL_TREE, true, braced_init_obstack); constructor_elements = NULL; if (TREE_CODE (constructor_type) == RECORD_TYPE) { constructor_unfilled_fields = TYPE_FIELDS (constructor_type); /* Skip any nameless bit fields at the beginning. */ while (constructor_unfilled_fields != 0 && DECL_C_BIT_FIELD (constructor_unfilled_fields) && DECL_NAME (constructor_unfilled_fields) == 0) constructor_unfilled_fields = TREE_CHAIN (constructor_unfilled_fields); } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (TYPE_DOMAIN (constructor_type)) constructor_unfilled_index = convert (bitsizetype, TYPE_MIN_VALUE (TYPE_DOMAIN (constructor_type))); else constructor_unfilled_index = bitsize_zero_node; } constructor_incremental = 0; } /* Build AVL tree from a string constant. */ static void set_nonincremental_init_from_string (tree str, struct obstack * braced_init_obstack) { tree value, purpose, type; HOST_WIDE_INT val[2]; const char *p, *end; int byte, wchar_bytes, charwidth, bitpos; gcc_assert (TREE_CODE (constructor_type) == ARRAY_TYPE); wchar_bytes = TYPE_PRECISION (TREE_TYPE (TREE_TYPE (str))) / BITS_PER_UNIT; charwidth = TYPE_PRECISION (char_type_node); type = TREE_TYPE (constructor_type); p = TREE_STRING_POINTER (str); end = p + TREE_STRING_LENGTH (str); for (purpose = bitsize_zero_node; p < end && !(constructor_max_index && tree_int_cst_lt (constructor_max_index, purpose)); purpose = size_binop (PLUS_EXPR, purpose, bitsize_one_node)) { if (wchar_bytes == 1) { val[0] = (unsigned char) *p++; val[1] = 0; } else { val[1] = 0; val[0] = 0; for (byte = 0; byte < wchar_bytes; byte++) { if (BYTES_BIG_ENDIAN) bitpos = (wchar_bytes - byte - 1) * charwidth; else bitpos = byte * charwidth; val[bitpos % HOST_BITS_PER_WIDE_INT] |= ((unsigned HOST_WIDE_INT) ((unsigned char) *p++)) << (bitpos % HOST_BITS_PER_WIDE_INT); } } if (!TYPE_UNSIGNED (type)) { bitpos = ((wchar_bytes - 1) * charwidth) + HOST_BITS_PER_CHAR; if (bitpos < HOST_BITS_PER_WIDE_INT) { if (val[0] & (((HOST_WIDE_INT) 1) << (bitpos - 1))) { val[0] |= ((HOST_WIDE_INT) -1) << bitpos; val[1] = -1; } } else if (bitpos == HOST_BITS_PER_WIDE_INT) { if (val[0] < 0) val[1] = -1; } else if (val[1] & (((HOST_WIDE_INT) 1) << (bitpos - 1 - HOST_BITS_PER_WIDE_INT))) val[1] |= ((HOST_WIDE_INT) -1) << (bitpos - HOST_BITS_PER_WIDE_INT); } value = wide_int_to_tree (type, wide_int::from_array (val, 2, HOST_BITS_PER_WIDE_INT * 2)); add_pending_init (input_location, purpose, value, NULL_TREE, true, braced_init_obstack); } constructor_incremental = 0; } /* Return value of FIELD in pending initializer or zero if the field was not initialized yet. */ static tree find_init_member (tree field, struct obstack * braced_init_obstack) { struct init_node *p; if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (constructor_incremental && tree_int_cst_lt (field, constructor_unfilled_index)) set_nonincremental_init (braced_init_obstack); p = constructor_pending_elts; while (p) { if (tree_int_cst_lt (field, p->purpose)) p = p->left; else if (tree_int_cst_lt (p->purpose, field)) p = p->right; else return p->value; } } else if (TREE_CODE (constructor_type) == RECORD_TYPE) { tree bitpos = bit_position (field); if (constructor_incremental && (!constructor_unfilled_fields || tree_int_cst_lt (bitpos, bit_position (constructor_unfilled_fields)))) set_nonincremental_init (braced_init_obstack); p = constructor_pending_elts; while (p) { if (field == p->purpose) return p->value; else if (tree_int_cst_lt (bitpos, bit_position (p->purpose))) p = p->left; else p = p->right; } } else if (TREE_CODE (constructor_type) == UNION_TYPE) { if (!vec_safe_is_empty (constructor_elements) && (constructor_elements->last ().index == field)) return constructor_elements->last ().value; } return 0; } /* "Output" the next constructor element. At top level, really output it to assembler code now. Otherwise, collect it in a list from which we will make a CONSTRUCTOR. If ORIGTYPE is not NULL_TREE, it is the original type of VALUE. TYPE is the data type that the containing data type wants here. FIELD is the field (a FIELD_DECL) or the index that this element fills. If VALUE is a string constant, STRICT_STRING is true if it is unparenthesized or we should not warn here for it being parenthesized. For other types of VALUE, STRICT_STRING is not used. PENDING if non-nil means output pending elements that belong right after this element. (PENDING is normally 1; it is 0 while outputting pending elements, to avoid recursion.) IMPLICIT is true if value comes from pop_init_level (1), the new initializer has been merged with the existing one and thus no warnings should be emitted about overriding an existing initializer. */ static void output_init_element (location_t loc, tree value, tree origtype, bool strict_string, tree type, tree field, int pending, bool implicit, struct obstack * braced_init_obstack) { tree semantic_type = NULL_TREE; bool maybe_const = true; bool npc; if (type == error_mark_node || value == error_mark_node) { constructor_erroneous = 1; return; } if (TREE_CODE (TREE_TYPE (value)) == ARRAY_TYPE && (TREE_CODE (value) == STRING_CST || TREE_CODE (value) == COMPOUND_LITERAL_EXPR) && !(TREE_CODE (value) == STRING_CST && TREE_CODE (type) == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (type))) && !comptypes (TYPE_MAIN_VARIANT (TREE_TYPE (value)), TYPE_MAIN_VARIANT (type))) value = array_to_pointer_conversion (input_location, value); if (TREE_CODE (value) == COMPOUND_LITERAL_EXPR && require_constant_value && pending) { /* As an extension, allow initializing objects with static storage duration with compound literals (which are then treated just as the brace enclosed list they contain). */ if (flag_isoc99) pedwarn_init (loc, OPT_Wpedantic, "initializer element is not " "constant"); tree decl = COMPOUND_LITERAL_EXPR_DECL (value); value = DECL_INITIAL (decl); } npc = null_pointer_constant_p (value); if (TREE_CODE (value) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (value); value = TREE_OPERAND (value, 0); } value = c_fully_fold (value, require_constant_value, &maybe_const); if (value == error_mark_node) constructor_erroneous = 1; else if (!TREE_CONSTANT (value)) constructor_constant = 0; else if (!initializer_constant_valid_p (value, TREE_TYPE (value)) || ((TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) && DECL_C_BIT_FIELD (field) && TREE_CODE (value) != INTEGER_CST)) constructor_simple = 0; if (!maybe_const) constructor_nonconst = 1; if (!initializer_constant_valid_p (value, TREE_TYPE (value))) { if (require_constant_value) { error_init (loc, "initializer element is not constant"); value = error_mark_node; } else if (require_constant_elements) pedwarn (loc, OPT_Wpedantic, "initializer element is not computable at load time"); } else if (!maybe_const && (require_constant_value || require_constant_elements)) pedwarn_init (loc, OPT_Wpedantic, "initializer element is not a constant expression"); /* Issue -Wc++-compat warnings about initializing a bitfield with enum type. */ if (warn_cxx_compat && field != NULL_TREE && TREE_CODE (field) == FIELD_DECL && DECL_BIT_FIELD_TYPE (field) != NULL_TREE && (TYPE_MAIN_VARIANT (DECL_BIT_FIELD_TYPE (field)) != TYPE_MAIN_VARIANT (type)) && TREE_CODE (DECL_BIT_FIELD_TYPE (field)) == ENUMERAL_TYPE) { tree checktype = origtype != NULL_TREE ? origtype : TREE_TYPE (value); if (checktype != error_mark_node && (TYPE_MAIN_VARIANT (checktype) != TYPE_MAIN_VARIANT (DECL_BIT_FIELD_TYPE (field)))) warning_init (loc, OPT_Wc___compat, "enum conversion in initialization is invalid in C++"); } /* If this field is empty (and not at the end of structure), don't do anything other than checking the initializer. */ if (field && (TREE_TYPE (field) == error_mark_node || (COMPLETE_TYPE_P (TREE_TYPE (field)) && integer_zerop (TYPE_SIZE (TREE_TYPE (field))) && (TREE_CODE (constructor_type) == ARRAY_TYPE || DECL_CHAIN (field))))) return; if (semantic_type) value = build1 (EXCESS_PRECISION_EXPR, semantic_type, value); value = digest_init (loc, type, value, origtype, npc, strict_string, require_constant_value); if (value == error_mark_node) { constructor_erroneous = 1; return; } if (require_constant_value || require_constant_elements) constant_expression_warning (value); /* If this element doesn't come next in sequence, put it on constructor_pending_elts. */ if (TREE_CODE (constructor_type) == ARRAY_TYPE && (!constructor_incremental || !tree_int_cst_equal (field, constructor_unfilled_index))) { if (constructor_incremental && tree_int_cst_lt (field, constructor_unfilled_index)) set_nonincremental_init (braced_init_obstack); add_pending_init (loc, field, value, origtype, implicit, braced_init_obstack); return; } else if (TREE_CODE (constructor_type) == RECORD_TYPE && (!constructor_incremental || field != constructor_unfilled_fields)) { /* We do this for records but not for unions. In a union, no matter which field is specified, it can be initialized right away since it starts at the beginning of the union. */ if (constructor_incremental) { if (!constructor_unfilled_fields) set_nonincremental_init (braced_init_obstack); else { tree bitpos, unfillpos; bitpos = bit_position (field); unfillpos = bit_position (constructor_unfilled_fields); if (tree_int_cst_lt (bitpos, unfillpos)) set_nonincremental_init (braced_init_obstack); } } add_pending_init (loc, field, value, origtype, implicit, braced_init_obstack); return; } else if (TREE_CODE (constructor_type) == UNION_TYPE && !vec_safe_is_empty (constructor_elements)) { if (!implicit) { if (TREE_SIDE_EFFECTS (constructor_elements->last ().value)) warning_init (loc, 0, "initialized field with side-effects overwritten"); else if (warn_override_init) warning_init (loc, OPT_Woverride_init, "initialized field overwritten"); } /* We can have just one union field set. */ constructor_elements = NULL; } /* Otherwise, output this element either to constructor_elements or to the assembler file. */ constructor_elt celt = {field, value}; vec_safe_push (constructor_elements, celt); /* Advance the variable that indicates sequential elements output. */ if (TREE_CODE (constructor_type) == ARRAY_TYPE) constructor_unfilled_index = size_binop_loc (input_location, PLUS_EXPR, constructor_unfilled_index, bitsize_one_node); else if (TREE_CODE (constructor_type) == RECORD_TYPE) { constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); /* Skip any nameless bit fields. */ while (constructor_unfilled_fields != 0 && DECL_C_BIT_FIELD (constructor_unfilled_fields) && DECL_NAME (constructor_unfilled_fields) == 0) constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); } else if (TREE_CODE (constructor_type) == UNION_TYPE) constructor_unfilled_fields = 0; /* Now output any pending elements which have become next. */ if (pending) output_pending_init_elements (0, braced_init_obstack); } /* Output any pending elements which have become next. As we output elements, constructor_unfilled_{fields,index} advances, which may cause other elements to become next; if so, they too are output. If ALL is 0, we return when there are no more pending elements to output now. If ALL is 1, we output space as necessary so that we can output all the pending elements. */ static void output_pending_init_elements (int all, struct obstack * braced_init_obstack) { struct init_node *elt = constructor_pending_elts; tree next; retry: /* Look through the whole pending tree. If we find an element that should be output now, output it. Otherwise, set NEXT to the element that comes first among those still pending. */ next = 0; while (elt) { if (TREE_CODE (constructor_type) == ARRAY_TYPE) { if (tree_int_cst_equal (elt->purpose, constructor_unfilled_index)) output_init_element (input_location, elt->value, elt->origtype, true, TREE_TYPE (constructor_type), constructor_unfilled_index, 0, false, braced_init_obstack); else if (tree_int_cst_lt (constructor_unfilled_index, elt->purpose)) { /* Advance to the next smaller node. */ if (elt->left) elt = elt->left; else { /* We have reached the smallest node bigger than the current unfilled index. Fill the space first. */ next = elt->purpose; break; } } else { /* Advance to the next bigger node. */ if (elt->right) elt = elt->right; else { /* We have reached the biggest node in a subtree. Find the parent of it, which is the next bigger node. */ while (elt->parent && elt->parent->right == elt) elt = elt->parent; elt = elt->parent; if (elt && tree_int_cst_lt (constructor_unfilled_index, elt->purpose)) { next = elt->purpose; break; } } } } else if (TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) { tree ctor_unfilled_bitpos, elt_bitpos; /* If the current record is complete we are done. */ if (constructor_unfilled_fields == 0) break; ctor_unfilled_bitpos = bit_position (constructor_unfilled_fields); elt_bitpos = bit_position (elt->purpose); /* We can't compare fields here because there might be empty fields in between. */ if (tree_int_cst_equal (elt_bitpos, ctor_unfilled_bitpos)) { constructor_unfilled_fields = elt->purpose; output_init_element (input_location, elt->value, elt->origtype, true, TREE_TYPE (elt->purpose), elt->purpose, 0, false, braced_init_obstack); } else if (tree_int_cst_lt (ctor_unfilled_bitpos, elt_bitpos)) { /* Advance to the next smaller node. */ if (elt->left) elt = elt->left; else { /* We have reached the smallest node bigger than the current unfilled field. Fill the space first. */ next = elt->purpose; break; } } else { /* Advance to the next bigger node. */ if (elt->right) elt = elt->right; else { /* We have reached the biggest node in a subtree. Find the parent of it, which is the next bigger node. */ while (elt->parent && elt->parent->right == elt) elt = elt->parent; elt = elt->parent; if (elt && (tree_int_cst_lt (ctor_unfilled_bitpos, bit_position (elt->purpose)))) { next = elt->purpose; break; } } } } } /* Ordinarily return, but not if we want to output all and there are elements left. */ if (!(all && next != 0)) return; /* If it's not incremental, just skip over the gap, so that after jumping to retry we will output the next successive element. */ if (TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) constructor_unfilled_fields = next; else if (TREE_CODE (constructor_type) == ARRAY_TYPE) constructor_unfilled_index = next; /* ELT now points to the node in the pending tree with the next initializer to output. */ goto retry; } /* Add one non-braced element to the current constructor level. This adjusts the current position within the constructor's type. This may also start or terminate implicit levels to handle a partly-braced initializer. Once this has found the correct level for the new element, it calls output_init_element. IMPLICIT is true if value comes from pop_init_level (1), the new initializer has been merged with the existing one and thus no warnings should be emitted about overriding an existing initializer. */ void process_init_element (location_t loc, struct c_expr value, bool implicit, struct obstack * braced_init_obstack) { tree orig_value = value.value; int string_flag = orig_value != 0 && TREE_CODE (orig_value) == STRING_CST; bool strict_string = value.original_code == STRING_CST; bool was_designated = designator_depth != 0; designator_depth = 0; designator_erroneous = 0; if (!implicit && value.value && !integer_zerop (value.value)) constructor_zeroinit = 0; /* Handle superfluous braces around string cst as in char x[] = {"foo"}; */ if (string_flag && constructor_type && !was_designated && TREE_CODE (constructor_type) == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (constructor_type)) && integer_zerop (constructor_unfilled_index)) { if (constructor_stack->replacement_value.value) error_init (loc, "excess elements in char array initializer"); constructor_stack->replacement_value = value; return; } if (constructor_stack->replacement_value.value != 0) { error_init (loc, "excess elements in struct initializer"); return; } /* Ignore elements of a brace group if it is entirely superfluous and has already been diagnosed. */ if (constructor_type == 0) return; if (!implicit && warn_designated_init && !was_designated && TREE_CODE (constructor_type) == RECORD_TYPE && lookup_attribute ("designated_init", TYPE_ATTRIBUTES (constructor_type))) warning_init (loc, OPT_Wdesignated_init, "positional initialization of field " "in %<struct%> declared with %<designated_init%> attribute"); /* If we've exhausted any levels that didn't have braces, pop them now. */ while (constructor_stack->implicit) { if ((TREE_CODE (constructor_type) == RECORD_TYPE || TREE_CODE (constructor_type) == UNION_TYPE) && constructor_fields == 0) process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); else if ((TREE_CODE (constructor_type) == ARRAY_TYPE || TREE_CODE (constructor_type) == VECTOR_TYPE) && constructor_max_index && tree_int_cst_lt (constructor_max_index, constructor_index)) process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); else break; } /* In the case of [LO ... HI] = VALUE, only evaluate VALUE once. */ if (constructor_range_stack) { /* If value is a compound literal and we'll be just using its content, don't put it into a SAVE_EXPR. */ if (TREE_CODE (value.value) != COMPOUND_LITERAL_EXPR || !require_constant_value) { tree semantic_type = NULL_TREE; if (TREE_CODE (value.value) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (value.value); value.value = TREE_OPERAND (value.value, 0); } value.value = c_save_expr (value.value); if (semantic_type) value.value = build1 (EXCESS_PRECISION_EXPR, semantic_type, value.value); } } while (1) { if (TREE_CODE (constructor_type) == RECORD_TYPE) { tree fieldtype; enum tree_code fieldcode; if (constructor_fields == 0) { pedwarn_init (loc, 0, "excess elements in struct initializer"); break; } fieldtype = TREE_TYPE (constructor_fields); if (fieldtype != error_mark_node) fieldtype = TYPE_MAIN_VARIANT (fieldtype); fieldcode = TREE_CODE (fieldtype); /* Error for non-static initialization of a flexible array member. */ if (fieldcode == ARRAY_TYPE && !require_constant_value && TYPE_SIZE (fieldtype) == NULL_TREE && DECL_CHAIN (constructor_fields) == NULL_TREE) { error_init (loc, "non-static initialization of a flexible " "array member"); break; } /* Error for initialization of a flexible array member with a string constant if the structure is in an array. E.g.: struct S { int x; char y[]; }; struct S s[] = { { 1, "foo" } }; is invalid. */ if (string_flag && fieldcode == ARRAY_TYPE && constructor_depth > 1 && TYPE_SIZE (fieldtype) == NULL_TREE && DECL_CHAIN (constructor_fields) == NULL_TREE) { bool in_array_p = false; for (struct constructor_stack *p = constructor_stack; p && p->type; p = p->next) if (TREE_CODE (p->type) == ARRAY_TYPE) { in_array_p = true; break; } if (in_array_p) { error_init (loc, "initialization of flexible array " "member in a nested context"); break; } } /* Accept a string constant to initialize a subarray. */ if (value.value != 0 && fieldcode == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (fieldtype)) && string_flag) value.value = orig_value; /* Otherwise, if we have come to a subaggregate, and we don't have an element of its type, push into it. */ else if (value.value != 0 && value.value != error_mark_node && TYPE_MAIN_VARIANT (TREE_TYPE (value.value)) != fieldtype && (fieldcode == RECORD_TYPE || fieldcode == ARRAY_TYPE || fieldcode == UNION_TYPE || fieldcode == VECTOR_TYPE)) { push_init_level (loc, 1, braced_init_obstack); continue; } if (value.value) { push_member_name (constructor_fields); output_init_element (loc, value.value, value.original_type, strict_string, fieldtype, constructor_fields, 1, implicit, braced_init_obstack); RESTORE_SPELLING_DEPTH (constructor_depth); } else /* Do the bookkeeping for an element that was directly output as a constructor. */ { /* For a record, keep track of end position of last field. */ if (DECL_SIZE (constructor_fields)) constructor_bit_index = size_binop_loc (input_location, PLUS_EXPR, bit_position (constructor_fields), DECL_SIZE (constructor_fields)); /* If the current field was the first one not yet written out, it isn't now, so update. */ if (constructor_unfilled_fields == constructor_fields) { constructor_unfilled_fields = DECL_CHAIN (constructor_fields); /* Skip any nameless bit fields. */ while (constructor_unfilled_fields != 0 && DECL_C_BIT_FIELD (constructor_unfilled_fields) && DECL_NAME (constructor_unfilled_fields) == 0) constructor_unfilled_fields = DECL_CHAIN (constructor_unfilled_fields); } } constructor_fields = DECL_CHAIN (constructor_fields); /* Skip any nameless bit fields at the beginning. */ while (constructor_fields != 0 && DECL_C_BIT_FIELD (constructor_fields) && DECL_NAME (constructor_fields) == 0) constructor_fields = DECL_CHAIN (constructor_fields); } else if (TREE_CODE (constructor_type) == UNION_TYPE) { tree fieldtype; enum tree_code fieldcode; if (constructor_fields == 0) { pedwarn_init (loc, 0, "excess elements in union initializer"); break; } fieldtype = TREE_TYPE (constructor_fields); if (fieldtype != error_mark_node) fieldtype = TYPE_MAIN_VARIANT (fieldtype); fieldcode = TREE_CODE (fieldtype); /* Warn that traditional C rejects initialization of unions. We skip the warning if the value is zero. This is done under the assumption that the zero initializer in user code appears conditioned on e.g. __STDC__ to avoid "missing initializer" warnings and relies on default initialization to zero in the traditional C case. We also skip the warning if the initializer is designated, again on the assumption that this must be conditional on __STDC__ anyway (and we've already complained about the member-designator already). */ if (!in_system_header_at (input_location) && !constructor_designated && !(value.value && (integer_zerop (value.value) || real_zerop (value.value)))) warning (OPT_Wtraditional, "traditional C rejects initialization " "of unions"); /* Accept a string constant to initialize a subarray. */ if (value.value != 0 && fieldcode == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (fieldtype)) && string_flag) value.value = orig_value; /* Otherwise, if we have come to a subaggregate, and we don't have an element of its type, push into it. */ else if (value.value != 0 && value.value != error_mark_node && TYPE_MAIN_VARIANT (TREE_TYPE (value.value)) != fieldtype && (fieldcode == RECORD_TYPE || fieldcode == ARRAY_TYPE || fieldcode == UNION_TYPE || fieldcode == VECTOR_TYPE)) { push_init_level (loc, 1, braced_init_obstack); continue; } if (value.value) { push_member_name (constructor_fields); output_init_element (loc, value.value, value.original_type, strict_string, fieldtype, constructor_fields, 1, implicit, braced_init_obstack); RESTORE_SPELLING_DEPTH (constructor_depth); } else /* Do the bookkeeping for an element that was directly output as a constructor. */ { constructor_bit_index = DECL_SIZE (constructor_fields); constructor_unfilled_fields = DECL_CHAIN (constructor_fields); } constructor_fields = 0; } else if (TREE_CODE (constructor_type) == ARRAY_TYPE) { tree elttype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type)); enum tree_code eltcode = TREE_CODE (elttype); /* Accept a string constant to initialize a subarray. */ if (value.value != 0 && eltcode == ARRAY_TYPE && INTEGRAL_TYPE_P (TREE_TYPE (elttype)) && string_flag) value.value = orig_value; /* Otherwise, if we have come to a subaggregate, and we don't have an element of its type, push into it. */ else if (value.value != 0 && value.value != error_mark_node && TYPE_MAIN_VARIANT (TREE_TYPE (value.value)) != elttype && (eltcode == RECORD_TYPE || eltcode == ARRAY_TYPE || eltcode == UNION_TYPE || eltcode == VECTOR_TYPE)) { push_init_level (loc, 1, braced_init_obstack); continue; } if (constructor_max_index != 0 && (tree_int_cst_lt (constructor_max_index, constructor_index) || integer_all_onesp (constructor_max_index))) { pedwarn_init (loc, 0, "excess elements in array initializer"); break; } /* Now output the actual element. */ if (value.value) { push_array_bounds (tree_to_uhwi (constructor_index)); output_init_element (loc, value.value, value.original_type, strict_string, elttype, constructor_index, 1, implicit, braced_init_obstack); RESTORE_SPELLING_DEPTH (constructor_depth); } constructor_index = size_binop_loc (input_location, PLUS_EXPR, constructor_index, bitsize_one_node); if (!value.value) /* If we are doing the bookkeeping for an element that was directly output as a constructor, we must update constructor_unfilled_index. */ constructor_unfilled_index = constructor_index; } else if (TREE_CODE (constructor_type) == VECTOR_TYPE) { tree elttype = TYPE_MAIN_VARIANT (TREE_TYPE (constructor_type)); /* Do a basic check of initializer size. Note that vectors always have a fixed size derived from their type. */ if (tree_int_cst_lt (constructor_max_index, constructor_index)) { pedwarn_init (loc, 0, "excess elements in vector initializer"); break; } /* Now output the actual element. */ if (value.value) { if (TREE_CODE (value.value) == VECTOR_CST) elttype = TYPE_MAIN_VARIANT (constructor_type); output_init_element (loc, value.value, value.original_type, strict_string, elttype, constructor_index, 1, implicit, braced_init_obstack); } constructor_index = size_binop_loc (input_location, PLUS_EXPR, constructor_index, bitsize_one_node); if (!value.value) /* If we are doing the bookkeeping for an element that was directly output as a constructor, we must update constructor_unfilled_index. */ constructor_unfilled_index = constructor_index; } /* Handle the sole element allowed in a braced initializer for a scalar variable. */ else if (constructor_type != error_mark_node && constructor_fields == 0) { pedwarn_init (loc, 0, "excess elements in scalar initializer"); break; } else { if (value.value) output_init_element (loc, value.value, value.original_type, strict_string, constructor_type, NULL_TREE, 1, implicit, braced_init_obstack); constructor_fields = 0; } /* Handle range initializers either at this level or anywhere higher in the designator stack. */ if (constructor_range_stack) { struct constructor_range_stack *p, *range_stack; int finish = 0; range_stack = constructor_range_stack; constructor_range_stack = 0; while (constructor_stack != range_stack->stack) { gcc_assert (constructor_stack->implicit); process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); } for (p = range_stack; !p->range_end || tree_int_cst_equal (p->index, p->range_end); p = p->prev) { gcc_assert (constructor_stack->implicit); process_init_element (loc, pop_init_level (loc, 1, braced_init_obstack), true, braced_init_obstack); } p->index = size_binop_loc (input_location, PLUS_EXPR, p->index, bitsize_one_node); if (tree_int_cst_equal (p->index, p->range_end) && !p->prev) finish = 1; while (1) { constructor_index = p->index; constructor_fields = p->fields; if (finish && p->range_end && p->index == p->range_start) { finish = 0; p->prev = 0; } p = p->next; if (!p) break; finish_implicit_inits (loc, braced_init_obstack); push_init_level (loc, 2, braced_init_obstack); p->stack = constructor_stack; if (p->range_end && tree_int_cst_equal (p->index, p->range_end)) p->index = p->range_start; } if (!finish) constructor_range_stack = range_stack; continue; } break; } constructor_range_stack = 0; } /* Build a complete asm-statement, whose components are a CV_QUALIFIER (guaranteed to be 'volatile' or null) and ARGS (represented using an ASM_EXPR node). */ tree build_asm_stmt (tree cv_qualifier, tree args) { if (!ASM_VOLATILE_P (args) && cv_qualifier) ASM_VOLATILE_P (args) = 1; return add_stmt (args); } /* Build an asm-expr, whose components are a STRING, some OUTPUTS, some INPUTS, and some CLOBBERS. The latter three may be NULL. SIMPLE indicates whether there was anything at all after the string in the asm expression -- asm("blah") and asm("blah" : ) are subtly different. We use a ASM_EXPR node to represent this. */ tree build_asm_expr (location_t loc, tree string, tree outputs, tree inputs, tree clobbers, tree labels, bool simple) { tree tail; tree args; int i; const char *constraint; const char **oconstraints; bool allows_mem, allows_reg, is_inout; int ninputs, noutputs; ninputs = list_length (inputs); noutputs = list_length (outputs); oconstraints = (const char **) alloca (noutputs * sizeof (const char *)); string = resolve_asm_operand_names (string, outputs, inputs, labels); /* Remove output conversions that change the type but not the mode. */ for (i = 0, tail = outputs; tail; ++i, tail = TREE_CHAIN (tail)) { tree output = TREE_VALUE (tail); output = c_fully_fold (output, false, NULL); /* ??? Really, this should not be here. Users should be using a proper lvalue, dammit. But there's a long history of using casts in the output operands. In cases like longlong.h, this becomes a primitive form of typechecking -- if the cast can be removed, then the output operand had a type of the proper width; otherwise we'll get an error. Gross, but ... */ STRIP_NOPS (output); if (!lvalue_or_else (loc, output, lv_asm)) output = error_mark_node; if (output != error_mark_node && (TREE_READONLY (output) || TYPE_READONLY (TREE_TYPE (output)) || ((TREE_CODE (TREE_TYPE (output)) == RECORD_TYPE || TREE_CODE (TREE_TYPE (output)) == UNION_TYPE) && C_TYPE_FIELDS_READONLY (TREE_TYPE (output))))) readonly_error (loc, output, lv_asm); constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail))); oconstraints[i] = constraint; if (parse_output_constraint (&constraint, i, ninputs, noutputs, &allows_mem, &allows_reg, &is_inout)) { /* If the operand is going to end up in memory, mark it addressable. */ if (!allows_reg && !c_mark_addressable (output)) output = error_mark_node; if (!(!allows_reg && allows_mem) && output != error_mark_node && VOID_TYPE_P (TREE_TYPE (output))) { error_at (loc, "invalid use of void expression"); output = error_mark_node; } } else output = error_mark_node; TREE_VALUE (tail) = output; } for (i = 0, tail = inputs; tail; ++i, tail = TREE_CHAIN (tail)) { tree input; constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail))); input = TREE_VALUE (tail); if (parse_input_constraint (&constraint, i, ninputs, noutputs, 0, oconstraints, &allows_mem, &allows_reg)) { /* If the operand is going to end up in memory, mark it addressable. */ if (!allows_reg && allows_mem) { input = c_fully_fold (input, false, NULL); /* Strip the nops as we allow this case. FIXME, this really should be rejected or made deprecated. */ STRIP_NOPS (input); if (!c_mark_addressable (input)) input = error_mark_node; } else { struct c_expr expr; memset (&expr, 0, sizeof (expr)); expr.value = input; expr = convert_lvalue_to_rvalue (loc, expr, true, false); input = c_fully_fold (expr.value, false, NULL); if (input != error_mark_node && VOID_TYPE_P (TREE_TYPE (input))) { error_at (loc, "invalid use of void expression"); input = error_mark_node; } } } else input = error_mark_node; TREE_VALUE (tail) = input; } /* ASMs with labels cannot have outputs. This should have been enforced by the parser. */ gcc_assert (outputs == NULL || labels == NULL); args = build_stmt (loc, ASM_EXPR, string, outputs, inputs, clobbers, labels); /* asm statements without outputs, including simple ones, are treated as volatile. */ ASM_INPUT_P (args) = simple; ASM_VOLATILE_P (args) = (noutputs == 0); return args; } /* Generate a goto statement to LABEL. LOC is the location of the GOTO. */ tree c_finish_goto_label (location_t loc, tree label) { tree decl = lookup_label_for_goto (loc, label); if (!decl) return NULL_TREE; TREE_USED (decl) = 1; { tree t = build1 (GOTO_EXPR, void_type_node, decl); SET_EXPR_LOCATION (t, loc); return add_stmt (t); } } /* Generate a computed goto statement to EXPR. LOC is the location of the GOTO. */ tree c_finish_goto_ptr (location_t loc, tree expr) { tree t; pedwarn (loc, OPT_Wpedantic, "ISO C forbids %<goto *expr;%>"); expr = c_fully_fold (expr, false, NULL); expr = convert (ptr_type_node, expr); t = build1 (GOTO_EXPR, void_type_node, expr); SET_EXPR_LOCATION (t, loc); return add_stmt (t); } /* Generate a C `return' statement. RETVAL is the expression for what to return, or a null pointer for `return;' with no value. LOC is the location of the return statement, or the location of the expression, if the statement has any. If ORIGTYPE is not NULL_TREE, it is the original type of RETVAL. */ tree c_finish_return (location_t loc, tree retval, tree origtype) { tree valtype = TREE_TYPE (TREE_TYPE (current_function_decl)), ret_stmt; bool no_warning = false; bool npc = false; size_t rank = 0; /* Use the expansion point to handle cases such as returning NULL in a function returning void. */ source_location xloc = expansion_point_location_if_in_system_header (loc); if (TREE_THIS_VOLATILE (current_function_decl)) warning_at (xloc, 0, "function declared %<noreturn%> has a %<return%> statement"); if (flag_cilkplus && contains_array_notation_expr (retval)) { /* Array notations are allowed in a return statement if it is inside a built-in array notation reduction function. */ if (!find_rank (loc, retval, retval, false, &rank)) return error_mark_node; if (rank >= 1) { error_at (loc, "array notation expression cannot be used as a " "return value"); return error_mark_node; } } if (flag_cilkplus && retval && contains_cilk_spawn_stmt (retval)) { error_at (loc, "use of %<_Cilk_spawn%> in a return statement is not " "allowed"); return error_mark_node; } if (retval) { tree semantic_type = NULL_TREE; npc = null_pointer_constant_p (retval); if (TREE_CODE (retval) == EXCESS_PRECISION_EXPR) { semantic_type = TREE_TYPE (retval); retval = TREE_OPERAND (retval, 0); } retval = c_fully_fold (retval, false, NULL); if (semantic_type) retval = build1 (EXCESS_PRECISION_EXPR, semantic_type, retval); } if (!retval) { current_function_returns_null = 1; if ((warn_return_type || flag_isoc99) && valtype != 0 && TREE_CODE (valtype) != VOID_TYPE) { if (flag_isoc99) pedwarn (loc, 0, "%<return%> with no value, in " "function returning non-void"); else warning_at (loc, OPT_Wreturn_type, "%<return%> with no value, " "in function returning non-void"); no_warning = true; } } else if (valtype == 0 || TREE_CODE (valtype) == VOID_TYPE) { current_function_returns_null = 1; if (TREE_CODE (TREE_TYPE (retval)) != VOID_TYPE) pedwarn (xloc, 0, "%<return%> with a value, in function returning void"); else pedwarn (xloc, OPT_Wpedantic, "ISO C forbids " "%<return%> with expression, in function returning void"); } else { tree t = convert_for_assignment (loc, UNKNOWN_LOCATION, valtype, retval, origtype, ic_return, npc, NULL_TREE, NULL_TREE, 0); tree res = DECL_RESULT (current_function_decl); tree inner; bool save; current_function_returns_value = 1; if (t == error_mark_node) return NULL_TREE; save = in_late_binary_op; if (TREE_CODE (TREE_TYPE (res)) == BOOLEAN_TYPE || TREE_CODE (TREE_TYPE (res)) == COMPLEX_TYPE || (TREE_CODE (TREE_TYPE (t)) == REAL_TYPE && (TREE_CODE (TREE_TYPE (res)) == INTEGER_TYPE || TREE_CODE (TREE_TYPE (res)) == ENUMERAL_TYPE) && (flag_sanitize & SANITIZE_FLOAT_CAST))) in_late_binary_op = true; inner = t = convert (TREE_TYPE (res), t); in_late_binary_op = save; /* Strip any conversions, additions, and subtractions, and see if we are returning the address of a local variable. Warn if so. */ while (1) { switch (TREE_CODE (inner)) { CASE_CONVERT: case NON_LVALUE_EXPR: case PLUS_EXPR: case POINTER_PLUS_EXPR: inner = TREE_OPERAND (inner, 0); continue; case MINUS_EXPR: /* If the second operand of the MINUS_EXPR has a pointer type (or is converted from it), this may be valid, so don't give a warning. */ { tree op1 = TREE_OPERAND (inner, 1); while (!POINTER_TYPE_P (TREE_TYPE (op1)) && (CONVERT_EXPR_P (op1) || TREE_CODE (op1) == NON_LVALUE_EXPR)) op1 = TREE_OPERAND (op1, 0); if (POINTER_TYPE_P (TREE_TYPE (op1))) break; inner = TREE_OPERAND (inner, 0); continue; } case ADDR_EXPR: inner = TREE_OPERAND (inner, 0); while (REFERENCE_CLASS_P (inner) && TREE_CODE (inner) != INDIRECT_REF) inner = TREE_OPERAND (inner, 0); if (DECL_P (inner) && !DECL_EXTERNAL (inner) && !TREE_STATIC (inner) && DECL_CONTEXT (inner) == current_function_decl) { if (TREE_CODE (inner) == LABEL_DECL) warning_at (loc, OPT_Wreturn_local_addr, "function returns address of label"); else { warning_at (loc, OPT_Wreturn_local_addr, "function returns address of local variable"); tree zero = build_zero_cst (TREE_TYPE (res)); t = build2 (COMPOUND_EXPR, TREE_TYPE (res), t, zero); } } break; default: break; } break; } retval = build2 (MODIFY_EXPR, TREE_TYPE (res), res, t); SET_EXPR_LOCATION (retval, loc); if (warn_sequence_point) verify_sequence_points (retval); } ret_stmt = build_stmt (loc, RETURN_EXPR, retval); TREE_NO_WARNING (ret_stmt) |= no_warning; return add_stmt (ret_stmt); } struct c_switch { /* The SWITCH_EXPR being built. */ tree switch_expr; /* The original type of the testing expression, i.e. before the default conversion is applied. */ tree orig_type; /* A splay-tree mapping the low element of a case range to the high element, or NULL_TREE if there is no high element. Used to determine whether or not a new case label duplicates an old case label. We need a tree, rather than simply a hash table, because of the GNU case range extension. */ splay_tree cases; /* The bindings at the point of the switch. This is used for warnings crossing decls when branching to a case label. */ struct c_spot_bindings *bindings; /* The next node on the stack. */ struct c_switch *next; }; /* A stack of the currently active switch statements. The innermost switch statement is on the top of the stack. There is no need to mark the stack for garbage collection because it is only active during the processing of the body of a function, and we never collect at that point. */ struct c_switch *c_switch_stack; /* Start a C switch statement, testing expression EXP. Return the new SWITCH_EXPR. SWITCH_LOC is the location of the `switch'. SWITCH_COND_LOC is the location of the switch's condition. EXPLICIT_CAST_P is true if the expression EXP has explicit cast. */ tree c_start_case (location_t switch_loc, location_t switch_cond_loc, tree exp, bool explicit_cast_p) { tree orig_type = error_mark_node; struct c_switch *cs; if (exp != error_mark_node) { orig_type = TREE_TYPE (exp); if (!INTEGRAL_TYPE_P (orig_type)) { if (orig_type != error_mark_node) { error_at (switch_cond_loc, "switch quantity not an integer"); orig_type = error_mark_node; } exp = integer_zero_node; } else { tree type = TYPE_MAIN_VARIANT (orig_type); tree e = exp; /* Warn if the condition has boolean value. */ while (TREE_CODE (e) == COMPOUND_EXPR) e = TREE_OPERAND (e, 1); if ((TREE_CODE (type) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (e))) /* Explicit cast to int suppresses this warning. */ && !(TREE_CODE (type) == INTEGER_TYPE && explicit_cast_p)) warning_at (switch_cond_loc, OPT_Wswitch_bool, "switch condition has boolean value"); if (!in_system_header_at (input_location) && (type == long_integer_type_node || type == long_unsigned_type_node)) warning_at (switch_cond_loc, OPT_Wtraditional, "%<long%> switch expression not " "converted to %<int%> in ISO C"); exp = c_fully_fold (exp, false, NULL); exp = default_conversion (exp); if (warn_sequence_point) verify_sequence_points (exp); } } /* Add this new SWITCH_EXPR to the stack. */ cs = XNEW (struct c_switch); cs->switch_expr = build3 (SWITCH_EXPR, orig_type, exp, NULL_TREE, NULL_TREE); SET_EXPR_LOCATION (cs->switch_expr, switch_loc); cs->orig_type = orig_type; cs->cases = splay_tree_new (case_compare, NULL, NULL); cs->bindings = c_get_switch_bindings (); cs->next = c_switch_stack; c_switch_stack = cs; return add_stmt (cs->switch_expr); } /* Process a case label at location LOC. */ tree do_case (location_t loc, tree low_value, tree high_value) { tree label = NULL_TREE; if (low_value && TREE_CODE (low_value) != INTEGER_CST) { low_value = c_fully_fold (low_value, false, NULL); if (TREE_CODE (low_value) == INTEGER_CST) pedwarn (loc, OPT_Wpedantic, "case label is not an integer constant expression"); } if (high_value && TREE_CODE (high_value) != INTEGER_CST) { high_value = c_fully_fold (high_value, false, NULL); if (TREE_CODE (high_value) == INTEGER_CST) pedwarn (input_location, OPT_Wpedantic, "case label is not an integer constant expression"); } if (c_switch_stack == NULL) { if (low_value) error_at (loc, "case label not within a switch statement"); else error_at (loc, "%<default%> label not within a switch statement"); return NULL_TREE; } if (c_check_switch_jump_warnings (c_switch_stack->bindings, EXPR_LOCATION (c_switch_stack->switch_expr), loc)) return NULL_TREE; label = c_add_case_label (loc, c_switch_stack->cases, SWITCH_COND (c_switch_stack->switch_expr), c_switch_stack->orig_type, low_value, high_value); if (label == error_mark_node) label = NULL_TREE; return label; } /* Finish the switch statement. TYPE is the original type of the controlling expression of the switch, or NULL_TREE. */ void c_finish_case (tree body, tree type) { struct c_switch *cs = c_switch_stack; location_t switch_location; SWITCH_BODY (cs->switch_expr) = body; /* Emit warnings as needed. */ switch_location = EXPR_LOCATION (cs->switch_expr); c_do_switch_warnings (cs->cases, switch_location, type ? type : TREE_TYPE (cs->switch_expr), SWITCH_COND (cs->switch_expr)); /* Pop the stack. */ c_switch_stack = cs->next; splay_tree_delete (cs->cases); c_release_switch_bindings (cs->bindings); XDELETE (cs); } /* Emit an if statement. IF_LOCUS is the location of the 'if'. COND, THEN_BLOCK and ELSE_BLOCK are expressions to be used; ELSE_BLOCK may be null. NESTED_IF is true if THEN_BLOCK contains another IF statement, and was not surrounded with parenthesis. */ void c_finish_if_stmt (location_t if_locus, tree cond, tree then_block, tree else_block, bool nested_if) { tree stmt; /* If the condition has array notations, then the rank of the then_block and else_block must be either 0 or be equal to the rank of the condition. If the condition does not have array notations then break them up as it is broken up in a normal expression. */ if (flag_cilkplus && contains_array_notation_expr (cond)) { size_t then_rank = 0, cond_rank = 0, else_rank = 0; if (!find_rank (if_locus, cond, cond, true, &cond_rank)) return; if (then_block && !find_rank (if_locus, then_block, then_block, true, &then_rank)) return; if (else_block && !find_rank (if_locus, else_block, else_block, true, &else_rank)) return; if (cond_rank != then_rank && then_rank != 0) { error_at (if_locus, "rank-mismatch between if-statement%'s condition" " and the then-block"); return; } else if (cond_rank != else_rank && else_rank != 0) { error_at (if_locus, "rank-mismatch between if-statement%'s condition" " and the else-block"); return; } } /* Diagnose an ambiguous else if if-then-else is nested inside if-then. */ if (warn_parentheses && nested_if && else_block == NULL) { tree inner_if = then_block; /* We know from the grammar productions that there is an IF nested within THEN_BLOCK. Due to labels and c99 conditional declarations, it might not be exactly THEN_BLOCK, but should be the last non-container statement within. */ while (1) switch (TREE_CODE (inner_if)) { case COND_EXPR: goto found; case BIND_EXPR: inner_if = BIND_EXPR_BODY (inner_if); break; case STATEMENT_LIST: inner_if = expr_last (then_block); break; case TRY_FINALLY_EXPR: case TRY_CATCH_EXPR: inner_if = TREE_OPERAND (inner_if, 0); break; default: gcc_unreachable (); } found: if (COND_EXPR_ELSE (inner_if)) warning_at (if_locus, OPT_Wparentheses, "suggest explicit braces to avoid ambiguous %<else%>"); } stmt = build3 (COND_EXPR, void_type_node, cond, then_block, else_block); SET_EXPR_LOCATION (stmt, if_locus); add_stmt (stmt); } /* Emit a general-purpose loop construct. START_LOCUS is the location of the beginning of the loop. COND is the loop condition. COND_IS_FIRST is false for DO loops. INCR is the FOR increment expression. BODY is the statement controlled by the loop. BLAB is the break label. CLAB is the continue label. Everything is allowed to be NULL. */ void c_finish_loop (location_t start_locus, tree cond, tree incr, tree body, tree blab, tree clab, bool cond_is_first) { tree entry = NULL, exit = NULL, t; /* In theory could forbid cilk spawn for loop increment expression, but it should work just fine. */ /* If the condition is zero don't generate a loop construct. */ if (cond && integer_zerop (cond)) { if (cond_is_first) { t = build_and_jump (&blab); SET_EXPR_LOCATION (t, start_locus); add_stmt (t); } } else { tree top = build1 (LABEL_EXPR, void_type_node, NULL_TREE); /* If we have an exit condition, then we build an IF with gotos either out of the loop, or to the top of it. If there's no exit condition, then we just build a jump back to the top. */ exit = build_and_jump (&LABEL_EXPR_LABEL (top)); if (cond && !integer_nonzerop (cond)) { /* Canonicalize the loop condition to the end. This means generating a branch to the loop condition. Reuse the continue label, if possible. */ if (cond_is_first) { if (incr || !clab) { entry = build1 (LABEL_EXPR, void_type_node, NULL_TREE); t = build_and_jump (&LABEL_EXPR_LABEL (entry)); } else t = build1 (GOTO_EXPR, void_type_node, clab); SET_EXPR_LOCATION (t, start_locus); add_stmt (t); } t = build_and_jump (&blab); if (cond_is_first) exit = fold_build3_loc (start_locus, COND_EXPR, void_type_node, cond, exit, t); else exit = fold_build3_loc (input_location, COND_EXPR, void_type_node, cond, exit, t); } add_stmt (top); } if (body) add_stmt (body); if (clab) add_stmt (build1 (LABEL_EXPR, void_type_node, clab)); if (incr) add_stmt (incr); if (entry) add_stmt (entry); if (exit) add_stmt (exit); if (blab) add_stmt (build1 (LABEL_EXPR, void_type_node, blab)); } tree c_finish_bc_stmt (location_t loc, tree *label_p, bool is_break) { bool skip; tree label = *label_p; /* In switch statements break is sometimes stylistically used after a return statement. This can lead to spurious warnings about control reaching the end of a non-void function when it is inlined. Note that we are calling block_may_fallthru with language specific tree nodes; this works because block_may_fallthru returns true when given something it does not understand. */ skip = !block_may_fallthru (cur_stmt_list); if (!label) { if (!skip) *label_p = label = create_artificial_label (loc); } else if (TREE_CODE (label) == LABEL_DECL) ; else switch (TREE_INT_CST_LOW (label)) { case 0: if (is_break) error_at (loc, "break statement not within loop or switch"); else error_at (loc, "continue statement not within a loop"); return NULL_TREE; case 1: gcc_assert (is_break); error_at (loc, "break statement used with OpenMP for loop"); return NULL_TREE; case 2: if (is_break) error ("break statement within %<#pragma simd%> loop body"); else error ("continue statement within %<#pragma simd%> loop body"); return NULL_TREE; default: gcc_unreachable (); } if (skip) return NULL_TREE; if (!is_break) add_stmt (build_predict_expr (PRED_CONTINUE, NOT_TAKEN)); return add_stmt (build1 (GOTO_EXPR, void_type_node, label)); } /* A helper routine for c_process_expr_stmt and c_finish_stmt_expr. */ static void emit_side_effect_warnings (location_t loc, tree expr) { if (expr == error_mark_node) ; else if (!TREE_SIDE_EFFECTS (expr)) { if (!VOID_TYPE_P (TREE_TYPE (expr)) && !TREE_NO_WARNING (expr)) warning_at (loc, OPT_Wunused_value, "statement with no effect"); } else if (TREE_CODE (expr) == COMPOUND_EXPR) { tree r = expr; location_t cloc = loc; while (TREE_CODE (r) == COMPOUND_EXPR) { if (EXPR_HAS_LOCATION (r)) cloc = EXPR_LOCATION (r); r = TREE_OPERAND (r, 1); } if (!TREE_SIDE_EFFECTS (r) && !VOID_TYPE_P (TREE_TYPE (r)) && !CONVERT_EXPR_P (r) && !TREE_NO_WARNING (r) && !TREE_NO_WARNING (expr)) warning_at (cloc, OPT_Wunused_value, "right-hand operand of comma expression has no effect"); } else warn_if_unused_value (expr, loc); } /* Process an expression as if it were a complete statement. Emit diagnostics, but do not call ADD_STMT. LOC is the location of the statement. */ tree c_process_expr_stmt (location_t loc, tree expr) { tree exprv; if (!expr) return NULL_TREE; expr = c_fully_fold (expr, false, NULL); if (warn_sequence_point) verify_sequence_points (expr); if (TREE_TYPE (expr) != error_mark_node && !COMPLETE_OR_VOID_TYPE_P (TREE_TYPE (expr)) && TREE_CODE (TREE_TYPE (expr)) != ARRAY_TYPE) error_at (loc, "expression statement has incomplete type"); /* If we're not processing a statement expression, warn about unused values. Warnings for statement expressions will be emitted later, once we figure out which is the result. */ if (!STATEMENT_LIST_STMT_EXPR (cur_stmt_list) && warn_unused_value) emit_side_effect_warnings (loc, expr); exprv = expr; while (TREE_CODE (exprv) == COMPOUND_EXPR) exprv = TREE_OPERAND (exprv, 1); while (CONVERT_EXPR_P (exprv)) exprv = TREE_OPERAND (exprv, 0); if (DECL_P (exprv) || handled_component_p (exprv) || TREE_CODE (exprv) == ADDR_EXPR) mark_exp_read (exprv); /* If the expression is not of a type to which we cannot assign a line number, wrap the thing in a no-op NOP_EXPR. */ if (DECL_P (expr) || CONSTANT_CLASS_P (expr)) { expr = build1 (NOP_EXPR, TREE_TYPE (expr), expr); SET_EXPR_LOCATION (expr, loc); } return expr; } /* Emit an expression as a statement. LOC is the location of the expression. */ tree c_finish_expr_stmt (location_t loc, tree expr) { if (expr) return add_stmt (c_process_expr_stmt (loc, expr)); else return NULL; } /* Do the opposite and emit a statement as an expression. To begin, create a new binding level and return it. */ tree c_begin_stmt_expr (void) { tree ret; /* We must force a BLOCK for this level so that, if it is not expanded later, there is a way to turn off the entire subtree of blocks that are contained in it. */ keep_next_level (); ret = c_begin_compound_stmt (true); c_bindings_start_stmt_expr (c_switch_stack == NULL ? NULL : c_switch_stack->bindings); /* Mark the current statement list as belonging to a statement list. */ STATEMENT_LIST_STMT_EXPR (ret) = 1; return ret; } /* LOC is the location of the compound statement to which this body belongs. */ tree c_finish_stmt_expr (location_t loc, tree body) { tree last, type, tmp, val; tree *last_p; body = c_end_compound_stmt (loc, body, true); c_bindings_end_stmt_expr (c_switch_stack == NULL ? NULL : c_switch_stack->bindings); /* Locate the last statement in BODY. See c_end_compound_stmt about always returning a BIND_EXPR. */ last_p = &BIND_EXPR_BODY (body); last = BIND_EXPR_BODY (body); continue_searching: if (TREE_CODE (last) == STATEMENT_LIST) { tree_stmt_iterator i; /* This can happen with degenerate cases like ({ }). No value. */ if (!TREE_SIDE_EFFECTS (last)) return body; /* If we're supposed to generate side effects warnings, process all of the statements except the last. */ if (warn_unused_value) { for (i = tsi_start (last); !tsi_one_before_end_p (i); tsi_next (&i)) { location_t tloc; tree t = tsi_stmt (i); tloc = EXPR_HAS_LOCATION (t) ? EXPR_LOCATION (t) : loc; emit_side_effect_warnings (tloc, t); } } else i = tsi_last (last); last_p = tsi_stmt_ptr (i); last = *last_p; } /* If the end of the list is exception related, then the list was split by a call to push_cleanup. Continue searching. */ if (TREE_CODE (last) == TRY_FINALLY_EXPR || TREE_CODE (last) == TRY_CATCH_EXPR) { last_p = &TREE_OPERAND (last, 0); last = *last_p; goto continue_searching; } if (last == error_mark_node) return last; /* In the case that the BIND_EXPR is not necessary, return the expression out from inside it. */ if (last == BIND_EXPR_BODY (body) && BIND_EXPR_VARS (body) == NULL) { /* Even if this looks constant, do not allow it in a constant expression. */ last = c_wrap_maybe_const (last, true); /* Do not warn if the return value of a statement expression is unused. */ TREE_NO_WARNING (last) = 1; return last; } /* Extract the type of said expression. */ type = TREE_TYPE (last); /* If we're not returning a value at all, then the BIND_EXPR that we already have is a fine expression to return. */ if (!type || VOID_TYPE_P (type)) return body; /* Now that we've located the expression containing the value, it seems silly to make voidify_wrapper_expr repeat the process. Create a temporary of the appropriate type and stick it in a TARGET_EXPR. */ tmp = create_tmp_var_raw (type); /* Unwrap a no-op NOP_EXPR as added by c_finish_expr_stmt. This avoids tree_expr_nonnegative_p giving up immediately. */ val = last; if (TREE_CODE (val) == NOP_EXPR && TREE_TYPE (val) == TREE_TYPE (TREE_OPERAND (val, 0))) val = TREE_OPERAND (val, 0); *last_p = build2 (MODIFY_EXPR, void_type_node, tmp, val); SET_EXPR_LOCATION (*last_p, EXPR_LOCATION (last)); { tree t = build4 (TARGET_EXPR, type, tmp, body, NULL_TREE, NULL_TREE); SET_EXPR_LOCATION (t, loc); return t; } } /* Begin and end compound statements. This is as simple as pushing and popping new statement lists from the tree. */ tree c_begin_compound_stmt (bool do_scope) { tree stmt = push_stmt_list (); if (do_scope) push_scope (); return stmt; } /* End a compound statement. STMT is the statement. LOC is the location of the compound statement-- this is usually the location of the opening brace. */ tree c_end_compound_stmt (location_t loc, tree stmt, bool do_scope) { tree block = NULL; if (do_scope) { if (c_dialect_objc ()) objc_clear_super_receiver (); block = pop_scope (); } stmt = pop_stmt_list (stmt); stmt = c_build_bind_expr (loc, block, stmt); /* If this compound statement is nested immediately inside a statement expression, then force a BIND_EXPR to be created. Otherwise we'll do the wrong thing for ({ { 1; } }) or ({ 1; { } }). In particular, STATEMENT_LISTs merge, and thus we can lose track of what statement was really last. */ if (building_stmt_list_p () && STATEMENT_LIST_STMT_EXPR (cur_stmt_list) && TREE_CODE (stmt) != BIND_EXPR) { stmt = build3 (BIND_EXPR, void_type_node, NULL, stmt, NULL); TREE_SIDE_EFFECTS (stmt) = 1; SET_EXPR_LOCATION (stmt, loc); } return stmt; } /* Queue a cleanup. CLEANUP is an expression/statement to be executed when the current scope is exited. EH_ONLY is true when this is not meant to apply to normal control flow transfer. */ void push_cleanup (tree decl, tree cleanup, bool eh_only) { enum tree_code code; tree stmt, list; bool stmt_expr; code = eh_only ? TRY_CATCH_EXPR : TRY_FINALLY_EXPR; stmt = build_stmt (DECL_SOURCE_LOCATION (decl), code, NULL, cleanup); add_stmt (stmt); stmt_expr = STATEMENT_LIST_STMT_EXPR (cur_stmt_list); list = push_stmt_list (); TREE_OPERAND (stmt, 0) = list; STATEMENT_LIST_STMT_EXPR (list) = stmt_expr; } /* Build a binary-operation expression without default conversions. CODE is the kind of expression to build. LOCATION is the operator's location. This function differs from `build' in several ways: the data type of the result is computed and recorded in it, warnings are generated if arg data types are invalid, special handling for addition and subtraction of pointers is known, and some optimization is done (operations on narrow ints are done in the narrower type when that gives the same result). Constant folding is also done before the result is returned. Note that the operands will never have enumeral types, or function or array types, because either they will have the default conversions performed or they have both just been converted to some other type in which the arithmetic is to be done. */ tree build_binary_op (location_t location, enum tree_code code, tree orig_op0, tree orig_op1, int convert_p) { tree type0, type1, orig_type0, orig_type1; tree eptype; enum tree_code code0, code1; tree op0, op1; tree ret = error_mark_node; const char *invalid_op_diag; bool op0_int_operands, op1_int_operands; bool int_const, int_const_or_overflow, int_operands; /* Expression code to give to the expression when it is built. Normally this is CODE, which is what the caller asked for, but in some special cases we change it. */ enum tree_code resultcode = code; /* Data type in which the computation is to be performed. In the simplest cases this is the common type of the arguments. */ tree result_type = NULL; /* When the computation is in excess precision, the type of the final EXCESS_PRECISION_EXPR. */ tree semantic_result_type = NULL; /* Nonzero means operands have already been type-converted in whatever way is necessary. Zero means they need to be converted to RESULT_TYPE. */ int converted = 0; /* Nonzero means create the expression with this type, rather than RESULT_TYPE. */ tree build_type = 0; /* Nonzero means after finally constructing the expression convert it to this type. */ tree final_type = 0; /* Nonzero if this is an operation like MIN or MAX which can safely be computed in short if both args are promoted shorts. Also implies COMMON. -1 indicates a bitwise operation; this makes a difference in the exact conditions for when it is safe to do the operation in a narrower mode. */ int shorten = 0; /* Nonzero if this is a comparison operation; if both args are promoted shorts, compare the original shorts. Also implies COMMON. */ int short_compare = 0; /* Nonzero if this is a right-shift operation, which can be computed on the original short and then promoted if the operand is a promoted short. */ int short_shift = 0; /* Nonzero means set RESULT_TYPE to the common type of the args. */ int common = 0; /* True means types are compatible as far as ObjC is concerned. */ bool objc_ok; /* True means this is an arithmetic operation that may need excess precision. */ bool may_need_excess_precision; /* True means this is a boolean operation that converts both its operands to truth-values. */ bool boolean_op = false; /* Remember whether we're doing / or %. */ bool doing_div_or_mod = false; /* Remember whether we're doing << or >>. */ bool doing_shift = false; /* Tree holding instrumentation expression. */ tree instrument_expr = NULL; if (location == UNKNOWN_LOCATION) location = input_location; op0 = orig_op0; op1 = orig_op1; op0_int_operands = EXPR_INT_CONST_OPERANDS (orig_op0); if (op0_int_operands) op0 = remove_c_maybe_const_expr (op0); op1_int_operands = EXPR_INT_CONST_OPERANDS (orig_op1); if (op1_int_operands) op1 = remove_c_maybe_const_expr (op1); int_operands = (op0_int_operands && op1_int_operands); if (int_operands) { int_const_or_overflow = (TREE_CODE (orig_op0) == INTEGER_CST && TREE_CODE (orig_op1) == INTEGER_CST); int_const = (int_const_or_overflow && !TREE_OVERFLOW (orig_op0) && !TREE_OVERFLOW (orig_op1)); } else int_const = int_const_or_overflow = false; /* Do not apply default conversion in mixed vector/scalar expression. */ if (convert_p && !((TREE_CODE (TREE_TYPE (op0)) == VECTOR_TYPE) != (TREE_CODE (TREE_TYPE (op1)) == VECTOR_TYPE))) { op0 = default_conversion (op0); op1 = default_conversion (op1); } /* When Cilk Plus is enabled and there are array notations inside op0, then we check to see if there are builtin array notation functions. If so, then we take on the type of the array notation inside it. */ if (flag_cilkplus && contains_array_notation_expr (op0)) orig_type0 = type0 = find_correct_array_notation_type (op0); else orig_type0 = type0 = TREE_TYPE (op0); if (flag_cilkplus && contains_array_notation_expr (op1)) orig_type1 = type1 = find_correct_array_notation_type (op1); else orig_type1 = type1 = TREE_TYPE (op1); /* The expression codes of the data types of the arguments tell us whether the arguments are integers, floating, pointers, etc. */ code0 = TREE_CODE (type0); code1 = TREE_CODE (type1); /* Strip NON_LVALUE_EXPRs, etc., since we aren't using as an lvalue. */ STRIP_TYPE_NOPS (op0); STRIP_TYPE_NOPS (op1); /* If an error was already reported for one of the arguments, avoid reporting another error. */ if (code0 == ERROR_MARK || code1 == ERROR_MARK) return error_mark_node; if ((invalid_op_diag = targetm.invalid_binary_op (code, type0, type1))) { error_at (location, invalid_op_diag); return error_mark_node; } switch (code) { case PLUS_EXPR: case MINUS_EXPR: case MULT_EXPR: case TRUNC_DIV_EXPR: case CEIL_DIV_EXPR: case FLOOR_DIV_EXPR: case ROUND_DIV_EXPR: case EXACT_DIV_EXPR: may_need_excess_precision = true; break; default: may_need_excess_precision = false; break; } if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR) { op0 = TREE_OPERAND (op0, 0); type0 = TREE_TYPE (op0); } else if (may_need_excess_precision && (eptype = excess_precision_type (type0)) != NULL_TREE) { type0 = eptype; op0 = convert (eptype, op0); } if (TREE_CODE (op1) == EXCESS_PRECISION_EXPR) { op1 = TREE_OPERAND (op1, 0); type1 = TREE_TYPE (op1); } else if (may_need_excess_precision && (eptype = excess_precision_type (type1)) != NULL_TREE) { type1 = eptype; op1 = convert (eptype, op1); } objc_ok = objc_compare_types (type0, type1, -3, NULL_TREE); /* In case when one of the operands of the binary operation is a vector and another is a scalar -- convert scalar to vector. */ if ((code0 == VECTOR_TYPE) != (code1 == VECTOR_TYPE)) { enum stv_conv convert_flag = scalar_to_vector (location, code, op0, op1, true); switch (convert_flag) { case stv_error: return error_mark_node; case stv_firstarg: { bool maybe_const = true; tree sc; sc = c_fully_fold (op0, false, &maybe_const); sc = save_expr (sc); sc = convert (TREE_TYPE (type1), sc); op0 = build_vector_from_val (type1, sc); if (!maybe_const) op0 = c_wrap_maybe_const (op0, true); orig_type0 = type0 = TREE_TYPE (op0); code0 = TREE_CODE (type0); converted = 1; break; } case stv_secondarg: { bool maybe_const = true; tree sc; sc = c_fully_fold (op1, false, &maybe_const); sc = save_expr (sc); sc = convert (TREE_TYPE (type0), sc); op1 = build_vector_from_val (type0, sc); if (!maybe_const) op1 = c_wrap_maybe_const (op1, true); orig_type1 = type1 = TREE_TYPE (op1); code1 = TREE_CODE (type1); converted = 1; break; } default: break; } } switch (code) { case PLUS_EXPR: /* Handle the pointer + int case. */ if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { ret = pointer_int_sum (location, PLUS_EXPR, op0, op1); goto return_build_binary_op; } else if (code1 == POINTER_TYPE && code0 == INTEGER_TYPE) { ret = pointer_int_sum (location, PLUS_EXPR, op1, op0); goto return_build_binary_op; } else common = 1; break; case MINUS_EXPR: /* Subtraction of two similar pointers. We must subtract them as integers, then divide by object size. */ if (code0 == POINTER_TYPE && code1 == POINTER_TYPE && comp_target_types (location, type0, type1)) { ret = pointer_diff (location, op0, op1); goto return_build_binary_op; } /* Handle pointer minus int. Just like pointer plus int. */ else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { ret = pointer_int_sum (location, MINUS_EXPR, op0, op1); goto return_build_binary_op; } else common = 1; break; case MULT_EXPR: common = 1; break; case TRUNC_DIV_EXPR: case CEIL_DIV_EXPR: case FLOOR_DIV_EXPR: case ROUND_DIV_EXPR: case EXACT_DIV_EXPR: doing_div_or_mod = true; warn_for_div_by_zero (location, op1); if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == FIXED_POINT_TYPE || code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == FIXED_POINT_TYPE || code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE)) { enum tree_code tcode0 = code0, tcode1 = code1; if (code0 == COMPLEX_TYPE || code0 == VECTOR_TYPE) tcode0 = TREE_CODE (TREE_TYPE (TREE_TYPE (op0))); if (code1 == COMPLEX_TYPE || code1 == VECTOR_TYPE) tcode1 = TREE_CODE (TREE_TYPE (TREE_TYPE (op1))); if (!((tcode0 == INTEGER_TYPE && tcode1 == INTEGER_TYPE) || (tcode0 == FIXED_POINT_TYPE && tcode1 == FIXED_POINT_TYPE))) resultcode = RDIV_EXPR; else /* Although it would be tempting to shorten always here, that loses on some targets, since the modulo instruction is undefined if the quotient can't be represented in the computation mode. We shorten only if unsigned or if dividing by something we know != -1. */ shorten = (TYPE_UNSIGNED (TREE_TYPE (orig_op0)) || (TREE_CODE (op1) == INTEGER_CST && !integer_all_onesp (op1))); common = 1; } break; case BIT_AND_EXPR: case BIT_IOR_EXPR: case BIT_XOR_EXPR: if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE) shorten = -1; /* Allow vector types which are not floating point types. */ else if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE && !VECTOR_FLOAT_TYPE_P (type0) && !VECTOR_FLOAT_TYPE_P (type1)) common = 1; break; case TRUNC_MOD_EXPR: case FLOOR_MOD_EXPR: doing_div_or_mod = true; warn_for_div_by_zero (location, op1); if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE) common = 1; else if (code0 == INTEGER_TYPE && code1 == INTEGER_TYPE) { /* Although it would be tempting to shorten always here, that loses on some targets, since the modulo instruction is undefined if the quotient can't be represented in the computation mode. We shorten only if unsigned or if dividing by something we know != -1. */ shorten = (TYPE_UNSIGNED (TREE_TYPE (orig_op0)) || (TREE_CODE (op1) == INTEGER_CST && !integer_all_onesp (op1))); common = 1; } break; case TRUTH_ANDIF_EXPR: case TRUTH_ORIF_EXPR: case TRUTH_AND_EXPR: case TRUTH_OR_EXPR: case TRUTH_XOR_EXPR: if ((code0 == INTEGER_TYPE || code0 == POINTER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE || code0 == FIXED_POINT_TYPE) && (code1 == INTEGER_TYPE || code1 == POINTER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE || code1 == FIXED_POINT_TYPE)) { /* Result of these operations is always an int, but that does not mean the operands should be converted to ints! */ result_type = integer_type_node; if (op0_int_operands) { op0 = c_objc_common_truthvalue_conversion (location, orig_op0); op0 = remove_c_maybe_const_expr (op0); } else op0 = c_objc_common_truthvalue_conversion (location, op0); if (op1_int_operands) { op1 = c_objc_common_truthvalue_conversion (location, orig_op1); op1 = remove_c_maybe_const_expr (op1); } else op1 = c_objc_common_truthvalue_conversion (location, op1); converted = 1; boolean_op = true; } if (code == TRUTH_ANDIF_EXPR) { int_const_or_overflow = (int_operands && TREE_CODE (orig_op0) == INTEGER_CST && (op0 == truthvalue_false_node || TREE_CODE (orig_op1) == INTEGER_CST)); int_const = (int_const_or_overflow && !TREE_OVERFLOW (orig_op0) && (op0 == truthvalue_false_node || !TREE_OVERFLOW (orig_op1))); } else if (code == TRUTH_ORIF_EXPR) { int_const_or_overflow = (int_operands && TREE_CODE (orig_op0) == INTEGER_CST && (op0 == truthvalue_true_node || TREE_CODE (orig_op1) == INTEGER_CST)); int_const = (int_const_or_overflow && !TREE_OVERFLOW (orig_op0) && (op0 == truthvalue_true_node || !TREE_OVERFLOW (orig_op1))); } break; /* Shift operations: result has same type as first operand; always convert second operand to int. Also set SHORT_SHIFT if shifting rightward. */ case RSHIFT_EXPR: if (code0 == VECTOR_TYPE && code1 == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE) { result_type = type0; converted = 1; } else if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE && TYPE_VECTOR_SUBPARTS (type0) == TYPE_VECTOR_SUBPARTS (type1)) { result_type = type0; converted = 1; } else if ((code0 == INTEGER_TYPE || code0 == FIXED_POINT_TYPE) && code1 == INTEGER_TYPE) { doing_shift = true; if (TREE_CODE (op1) == INTEGER_CST) { if (tree_int_cst_sgn (op1) < 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_negative, "right shift count is negative"); } else { if (!integer_zerop (op1)) short_shift = 1; if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_overflow, "right shift count >= width of type"); } } } /* Use the type of the value to be shifted. */ result_type = type0; /* Avoid converting op1 to result_type later. */ converted = 1; } break; case LSHIFT_EXPR: if (code0 == VECTOR_TYPE && code1 == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE) { result_type = type0; converted = 1; } else if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE && TREE_CODE (TREE_TYPE (type0)) == INTEGER_TYPE && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE && TYPE_VECTOR_SUBPARTS (type0) == TYPE_VECTOR_SUBPARTS (type1)) { result_type = type0; converted = 1; } else if ((code0 == INTEGER_TYPE || code0 == FIXED_POINT_TYPE) && code1 == INTEGER_TYPE) { doing_shift = true; if (TREE_CODE (op1) == INTEGER_CST) { if (tree_int_cst_sgn (op1) < 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_negative, "left shift count is negative"); } else if (compare_tree_int (op1, TYPE_PRECISION (type0)) >= 0) { int_const = false; if (c_inhibit_evaluation_warnings == 0) warning_at (location, OPT_Wshift_count_overflow, "left shift count >= width of type"); } } /* Use the type of the value to be shifted. */ result_type = type0; /* Avoid converting op1 to result_type later. */ converted = 1; } break; case EQ_EXPR: case NE_EXPR: if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE) { tree intt; if (!vector_types_compatible_elements_p (type0, type1)) { error_at (location, "comparing vectors with different " "element types"); return error_mark_node; } if (TYPE_VECTOR_SUBPARTS (type0) != TYPE_VECTOR_SUBPARTS (type1)) { error_at (location, "comparing vectors with different " "number of elements"); return error_mark_node; } /* It's not precisely specified how the usual arithmetic conversions apply to the vector types. Here, we use the unsigned type if one of the operands is signed and the other one is unsigned. */ if (TYPE_UNSIGNED (type0) != TYPE_UNSIGNED (type1)) { if (!TYPE_UNSIGNED (type0)) op0 = build1 (VIEW_CONVERT_EXPR, type1, op0); else op1 = build1 (VIEW_CONVERT_EXPR, type0, op1); warning_at (location, OPT_Wsign_compare, "comparison between " "types %qT and %qT", type0, type1); } /* Always construct signed integer vector type. */ intt = c_common_type_for_size (GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type0))), 0); result_type = build_opaque_vector_type (intt, TYPE_VECTOR_SUBPARTS (type0)); converted = 1; break; } if (FLOAT_TYPE_P (type0) || FLOAT_TYPE_P (type1)) warning_at (location, OPT_Wfloat_equal, "comparing floating point with == or != is unsafe"); /* Result of comparison is always int, but don't convert the args to int! */ build_type = integer_type_node; if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == FIXED_POINT_TYPE || code0 == COMPLEX_TYPE) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == FIXED_POINT_TYPE || code1 == COMPLEX_TYPE)) short_compare = 1; else if (code0 == POINTER_TYPE && null_pointer_constant_p (orig_op1)) { if (TREE_CODE (op0) == ADDR_EXPR && decl_with_nonnull_addr_p (TREE_OPERAND (op0, 0))) { if (code == EQ_EXPR) warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<false%> " "for the address of %qD will never be NULL", TREE_OPERAND (op0, 0)); else warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<true%> " "for the address of %qD will never be NULL", TREE_OPERAND (op0, 0)); } result_type = type0; } else if (code1 == POINTER_TYPE && null_pointer_constant_p (orig_op0)) { if (TREE_CODE (op1) == ADDR_EXPR && decl_with_nonnull_addr_p (TREE_OPERAND (op1, 0))) { if (code == EQ_EXPR) warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<false%> " "for the address of %qD will never be NULL", TREE_OPERAND (op1, 0)); else warning_at (location, OPT_Waddress, "the comparison will always evaluate as %<true%> " "for the address of %qD will never be NULL", TREE_OPERAND (op1, 0)); } result_type = type1; } else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE) { tree tt0 = TREE_TYPE (type0); tree tt1 = TREE_TYPE (type1); addr_space_t as0 = TYPE_ADDR_SPACE (tt0); addr_space_t as1 = TYPE_ADDR_SPACE (tt1); addr_space_t as_common = ADDR_SPACE_GENERIC; /* Anything compares with void *. void * compares with anything. Otherwise, the targets must be compatible and both must be object or both incomplete. */ if (comp_target_types (location, type0, type1)) result_type = common_pointer_type (type0, type1); else if (!addr_space_superset (as0, as1, &as_common)) { error_at (location, "comparison of pointers to " "disjoint address spaces"); return error_mark_node; } else if (VOID_TYPE_P (tt0) && !TYPE_ATOMIC (tt0)) { if (pedantic && TREE_CODE (tt1) == FUNCTION_TYPE) pedwarn (location, OPT_Wpedantic, "ISO C forbids " "comparison of %<void *%> with function pointer"); } else if (VOID_TYPE_P (tt1) && !TYPE_ATOMIC (tt1)) { if (pedantic && TREE_CODE (tt0) == FUNCTION_TYPE) pedwarn (location, OPT_Wpedantic, "ISO C forbids " "comparison of %<void *%> with function pointer"); } else /* Avoid warning about the volatile ObjC EH puts on decls. */ if (!objc_ok) pedwarn (location, 0, "comparison of distinct pointer types lacks a cast"); if (result_type == NULL_TREE) { int qual = ENCODE_QUAL_ADDR_SPACE (as_common); result_type = build_pointer_type (build_qualified_type (void_type_node, qual)); } } else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { result_type = type0; pedwarn (location, 0, "comparison between pointer and integer"); } else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE) { result_type = type1; pedwarn (location, 0, "comparison between pointer and integer"); } if ((TREE_CODE (TREE_TYPE (orig_op0)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op0))) ^ (TREE_CODE (TREE_TYPE (orig_op1)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op1)))) maybe_warn_bool_compare (location, code, orig_op0, orig_op1); break; case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR: if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE) { tree intt; if (!vector_types_compatible_elements_p (type0, type1)) { error_at (location, "comparing vectors with different " "element types"); return error_mark_node; } if (TYPE_VECTOR_SUBPARTS (type0) != TYPE_VECTOR_SUBPARTS (type1)) { error_at (location, "comparing vectors with different " "number of elements"); return error_mark_node; } /* It's not precisely specified how the usual arithmetic conversions apply to the vector types. Here, we use the unsigned type if one of the operands is signed and the other one is unsigned. */ if (TYPE_UNSIGNED (type0) != TYPE_UNSIGNED (type1)) { if (!TYPE_UNSIGNED (type0)) op0 = build1 (VIEW_CONVERT_EXPR, type1, op0); else op1 = build1 (VIEW_CONVERT_EXPR, type0, op1); warning_at (location, OPT_Wsign_compare, "comparison between " "types %qT and %qT", type0, type1); } /* Always construct signed integer vector type. */ intt = c_common_type_for_size (GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type0))), 0); result_type = build_opaque_vector_type (intt, TYPE_VECTOR_SUBPARTS (type0)); converted = 1; break; } build_type = integer_type_node; if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == FIXED_POINT_TYPE) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == FIXED_POINT_TYPE)) short_compare = 1; else if (code0 == POINTER_TYPE && code1 == POINTER_TYPE) { addr_space_t as0 = TYPE_ADDR_SPACE (TREE_TYPE (type0)); addr_space_t as1 = TYPE_ADDR_SPACE (TREE_TYPE (type1)); addr_space_t as_common; if (comp_target_types (location, type0, type1)) { result_type = common_pointer_type (type0, type1); if (!COMPLETE_TYPE_P (TREE_TYPE (type0)) != !COMPLETE_TYPE_P (TREE_TYPE (type1))) pedwarn (location, 0, "comparison of complete and incomplete pointers"); else if (TREE_CODE (TREE_TYPE (type0)) == FUNCTION_TYPE) pedwarn (location, OPT_Wpedantic, "ISO C forbids " "ordered comparisons of pointers to functions"); else if (null_pointer_constant_p (orig_op0) || null_pointer_constant_p (orig_op1)) warning_at (location, OPT_Wextra, "ordered comparison of pointer with null pointer"); } else if (!addr_space_superset (as0, as1, &as_common)) { error_at (location, "comparison of pointers to " "disjoint address spaces"); return error_mark_node; } else { int qual = ENCODE_QUAL_ADDR_SPACE (as_common); result_type = build_pointer_type (build_qualified_type (void_type_node, qual)); pedwarn (location, 0, "comparison of distinct pointer types lacks a cast"); } } else if (code0 == POINTER_TYPE && null_pointer_constant_p (orig_op1)) { result_type = type0; if (pedantic) pedwarn (location, OPT_Wpedantic, "ordered comparison of pointer with integer zero"); else if (extra_warnings) warning_at (location, OPT_Wextra, "ordered comparison of pointer with integer zero"); } else if (code1 == POINTER_TYPE && null_pointer_constant_p (orig_op0)) { result_type = type1; if (pedantic) pedwarn (location, OPT_Wpedantic, "ordered comparison of pointer with integer zero"); else if (extra_warnings) warning_at (location, OPT_Wextra, "ordered comparison of pointer with integer zero"); } else if (code0 == POINTER_TYPE && code1 == INTEGER_TYPE) { result_type = type0; pedwarn (location, 0, "comparison between pointer and integer"); } else if (code0 == INTEGER_TYPE && code1 == POINTER_TYPE) { result_type = type1; pedwarn (location, 0, "comparison between pointer and integer"); } if ((TREE_CODE (TREE_TYPE (orig_op0)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op0))) ^ (TREE_CODE (TREE_TYPE (orig_op1)) == BOOLEAN_TYPE || truth_value_p (TREE_CODE (orig_op1)))) maybe_warn_bool_compare (location, code, orig_op0, orig_op1); break; default: gcc_unreachable (); } if (code0 == ERROR_MARK || code1 == ERROR_MARK) return error_mark_node; if (code0 == VECTOR_TYPE && code1 == VECTOR_TYPE && (!tree_int_cst_equal (TYPE_SIZE (type0), TYPE_SIZE (type1)) || !vector_types_compatible_elements_p (type0, type1))) { binary_op_error (location, code, type0, type1); return error_mark_node; } if ((code0 == INTEGER_TYPE || code0 == REAL_TYPE || code0 == COMPLEX_TYPE || code0 == FIXED_POINT_TYPE || code0 == VECTOR_TYPE) && (code1 == INTEGER_TYPE || code1 == REAL_TYPE || code1 == COMPLEX_TYPE || code1 == FIXED_POINT_TYPE || code1 == VECTOR_TYPE)) { bool first_complex = (code0 == COMPLEX_TYPE); bool second_complex = (code1 == COMPLEX_TYPE); int none_complex = (!first_complex && !second_complex); if (shorten || common || short_compare) { result_type = c_common_type (type0, type1); do_warn_double_promotion (result_type, type0, type1, "implicit conversion from %qT to %qT " "to match other operand of binary " "expression", location); if (result_type == error_mark_node) return error_mark_node; } if (first_complex != second_complex && (code == PLUS_EXPR || code == MINUS_EXPR || code == MULT_EXPR || (code == TRUNC_DIV_EXPR && first_complex)) && TREE_CODE (TREE_TYPE (result_type)) == REAL_TYPE && flag_signed_zeros) { /* An operation on mixed real/complex operands must be handled specially, but the language-independent code can more easily optimize the plain complex arithmetic if -fno-signed-zeros. */ tree real_type = TREE_TYPE (result_type); tree real, imag; if (type0 != orig_type0 || type1 != orig_type1) { gcc_assert (may_need_excess_precision && common); semantic_result_type = c_common_type (orig_type0, orig_type1); } if (first_complex) { if (TREE_TYPE (op0) != result_type) op0 = convert_and_check (location, result_type, op0); if (TREE_TYPE (op1) != real_type) op1 = convert_and_check (location, real_type, op1); } else { if (TREE_TYPE (op0) != real_type) op0 = convert_and_check (location, real_type, op0); if (TREE_TYPE (op1) != result_type) op1 = convert_and_check (location, result_type, op1); } if (TREE_CODE (op0) == ERROR_MARK || TREE_CODE (op1) == ERROR_MARK) return error_mark_node; if (first_complex) { op0 = c_save_expr (op0); real = build_unary_op (EXPR_LOCATION (orig_op0), REALPART_EXPR, op0, 1); imag = build_unary_op (EXPR_LOCATION (orig_op0), IMAGPART_EXPR, op0, 1); switch (code) { case MULT_EXPR: case TRUNC_DIV_EXPR: op1 = c_save_expr (op1); imag = build2 (resultcode, real_type, imag, op1); /* Fall through. */ case PLUS_EXPR: case MINUS_EXPR: real = build2 (resultcode, real_type, real, op1); break; default: gcc_unreachable(); } } else { op1 = c_save_expr (op1); real = build_unary_op (EXPR_LOCATION (orig_op1), REALPART_EXPR, op1, 1); imag = build_unary_op (EXPR_LOCATION (orig_op1), IMAGPART_EXPR, op1, 1); switch (code) { case MULT_EXPR: op0 = c_save_expr (op0); imag = build2 (resultcode, real_type, op0, imag); /* Fall through. */ case PLUS_EXPR: real = build2 (resultcode, real_type, op0, real); break; case MINUS_EXPR: real = build2 (resultcode, real_type, op0, real); imag = build1 (NEGATE_EXPR, real_type, imag); break; default: gcc_unreachable(); } } ret = build2 (COMPLEX_EXPR, result_type, real, imag); goto return_build_binary_op; } /* For certain operations (which identify themselves by shorten != 0) if both args were extended from the same smaller type, do the arithmetic in that type and then extend. shorten !=0 and !=1 indicates a bitwise operation. For them, this optimization is safe only if both args are zero-extended or both are sign-extended. Otherwise, we might change the result. Eg, (short)-1 | (unsigned short)-1 is (int)-1 but calculated in (unsigned short) it would be (unsigned short)-1. */ if (shorten && none_complex) { final_type = result_type; result_type = shorten_binary_op (result_type, op0, op1, shorten == -1); } /* Shifts can be shortened if shifting right. */ if (short_shift) { int unsigned_arg; tree arg0 = get_narrower (op0, &unsigned_arg); final_type = result_type; if (arg0 == op0 && final_type == TREE_TYPE (op0)) unsigned_arg = TYPE_UNSIGNED (TREE_TYPE (op0)); if (TYPE_PRECISION (TREE_TYPE (arg0)) < TYPE_PRECISION (result_type) && tree_int_cst_sgn (op1) > 0 /* We can shorten only if the shift count is less than the number of bits in the smaller type size. */ && compare_tree_int (op1, TYPE_PRECISION (TREE_TYPE (arg0))) < 0 /* We cannot drop an unsigned shift after sign-extension. */ && (!TYPE_UNSIGNED (final_type) || unsigned_arg)) { /* Do an unsigned shift if the operand was zero-extended. */ result_type = c_common_signed_or_unsigned_type (unsigned_arg, TREE_TYPE (arg0)); /* Convert value-to-be-shifted to that type. */ if (TREE_TYPE (op0) != result_type) op0 = convert (result_type, op0); converted = 1; } } /* Comparison operations are shortened too but differently. They identify themselves by setting short_compare = 1. */ if (short_compare) { /* Don't write &op0, etc., because that would prevent op0 from being kept in a register. Instead, make copies of the our local variables and pass the copies by reference, then copy them back afterward. */ tree xop0 = op0, xop1 = op1, xresult_type = result_type; enum tree_code xresultcode = resultcode; tree val = shorten_compare (location, &xop0, &xop1, &xresult_type, &xresultcode); if (val != 0) { ret = val; goto return_build_binary_op; } op0 = xop0, op1 = xop1; converted = 1; resultcode = xresultcode; if (c_inhibit_evaluation_warnings == 0) { bool op0_maybe_const = true; bool op1_maybe_const = true; tree orig_op0_folded, orig_op1_folded; if (in_late_binary_op) { orig_op0_folded = orig_op0; orig_op1_folded = orig_op1; } else { /* Fold for the sake of possible warnings, as in build_conditional_expr. This requires the "original" values to be folded, not just op0 and op1. */ c_inhibit_evaluation_warnings++; op0 = c_fully_fold (op0, require_constant_value, &op0_maybe_const); op1 = c_fully_fold (op1, require_constant_value, &op1_maybe_const); c_inhibit_evaluation_warnings--; orig_op0_folded = c_fully_fold (orig_op0, require_constant_value, NULL); orig_op1_folded = c_fully_fold (orig_op1, require_constant_value, NULL); } if (warn_sign_compare) warn_for_sign_compare (location, orig_op0_folded, orig_op1_folded, op0, op1, result_type, resultcode); if (!in_late_binary_op && !int_operands) { if (!op0_maybe_const || TREE_CODE (op0) != INTEGER_CST) op0 = c_wrap_maybe_const (op0, !op0_maybe_const); if (!op1_maybe_const || TREE_CODE (op1) != INTEGER_CST) op1 = c_wrap_maybe_const (op1, !op1_maybe_const); } } } } /* At this point, RESULT_TYPE must be nonzero to avoid an error message. If CONVERTED is zero, both args will be converted to type RESULT_TYPE. Then the expression will be built. It will be given type FINAL_TYPE if that is nonzero; otherwise, it will be given type RESULT_TYPE. */ if (!result_type) { binary_op_error (location, code, TREE_TYPE (op0), TREE_TYPE (op1)); return error_mark_node; } if (build_type == NULL_TREE) { build_type = result_type; if ((type0 != orig_type0 || type1 != orig_type1) && !boolean_op) { gcc_assert (may_need_excess_precision && common); semantic_result_type = c_common_type (orig_type0, orig_type1); } } if (!converted) { op0 = ep_convert_and_check (location, result_type, op0, semantic_result_type); op1 = ep_convert_and_check (location, result_type, op1, semantic_result_type); /* This can happen if one operand has a vector type, and the other has a different type. */ if (TREE_CODE (op0) == ERROR_MARK || TREE_CODE (op1) == ERROR_MARK) return error_mark_node; } if ((flag_sanitize & (SANITIZE_SHIFT | SANITIZE_DIVIDE | SANITIZE_FLOAT_DIVIDE)) && do_ubsan_in_current_function () && (doing_div_or_mod || doing_shift)) { /* OP0 and/or OP1 might have side-effects. */ op0 = c_save_expr (op0); op1 = c_save_expr (op1); op0 = c_fully_fold (op0, false, NULL); op1 = c_fully_fold (op1, false, NULL); if (doing_div_or_mod && (flag_sanitize & (SANITIZE_DIVIDE | SANITIZE_FLOAT_DIVIDE))) instrument_expr = ubsan_instrument_division (location, op0, op1); else if (doing_shift && (flag_sanitize & SANITIZE_SHIFT)) instrument_expr = ubsan_instrument_shift (location, code, op0, op1); } /* Treat expressions in initializers specially as they can't trap. */ if (int_const_or_overflow) ret = (require_constant_value ? fold_build2_initializer_loc (location, resultcode, build_type, op0, op1) : fold_build2_loc (location, resultcode, build_type, op0, op1)); else ret = build2 (resultcode, build_type, op0, op1); if (final_type != 0) ret = convert (final_type, ret); return_build_binary_op: gcc_assert (ret != error_mark_node); if (TREE_CODE (ret) == INTEGER_CST && !TREE_OVERFLOW (ret) && !int_const) ret = (int_operands ? note_integer_operands (ret) : build1 (NOP_EXPR, TREE_TYPE (ret), ret)); else if (TREE_CODE (ret) != INTEGER_CST && int_operands && !in_late_binary_op) ret = note_integer_operands (ret); if (semantic_result_type) ret = build1 (EXCESS_PRECISION_EXPR, semantic_result_type, ret); protected_set_expr_location (ret, location); if (instrument_expr != NULL) ret = fold_build2 (COMPOUND_EXPR, TREE_TYPE (ret), instrument_expr, ret); return ret; } /* Convert EXPR to be a truth-value, validating its type for this purpose. LOCATION is the source location for the expression. */ tree c_objc_common_truthvalue_conversion (location_t location, tree expr) { bool int_const, int_operands; switch (TREE_CODE (TREE_TYPE (expr))) { case ARRAY_TYPE: error_at (location, "used array that cannot be converted to pointer where scalar is required"); return error_mark_node; case RECORD_TYPE: error_at (location, "used struct type value where scalar is required"); return error_mark_node; case UNION_TYPE: error_at (location, "used union type value where scalar is required"); return error_mark_node; case VOID_TYPE: error_at (location, "void value not ignored as it ought to be"); return error_mark_node; case FUNCTION_TYPE: gcc_unreachable (); case VECTOR_TYPE: error_at (location, "used vector type where scalar is required"); return error_mark_node; default: break; } int_const = (TREE_CODE (expr) == INTEGER_CST && !TREE_OVERFLOW (expr)); int_operands = EXPR_INT_CONST_OPERANDS (expr); if (int_operands && TREE_CODE (expr) != INTEGER_CST) { expr = remove_c_maybe_const_expr (expr); expr = build2 (NE_EXPR, integer_type_node, expr, convert (TREE_TYPE (expr), integer_zero_node)); expr = note_integer_operands (expr); } else /* ??? Should we also give an error for vectors rather than leaving those to give errors later? */ expr = c_common_truthvalue_conversion (location, expr); if (TREE_CODE (expr) == INTEGER_CST && int_operands && !int_const) { if (TREE_OVERFLOW (expr)) return expr; else return note_integer_operands (expr); } if (TREE_CODE (expr) == INTEGER_CST && !int_const) return build1 (NOP_EXPR, TREE_TYPE (expr), expr); return expr; } /* Convert EXPR to a contained DECL, updating *TC, *TI and *SE as required. */ tree c_expr_to_decl (tree expr, bool *tc ATTRIBUTE_UNUSED, bool *se) { if (TREE_CODE (expr) == COMPOUND_LITERAL_EXPR) { tree decl = COMPOUND_LITERAL_EXPR_DECL (expr); /* Executing a compound literal inside a function reinitializes it. */ if (!TREE_STATIC (decl)) *se = true; return decl; } else return expr; } /* Generate OACC_PARALLEL, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_PARALLEL. */ tree c_finish_oacc_parallel (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OACC_PARALLEL); TREE_TYPE (stmt) = void_type_node; OACC_PARALLEL_CLAUSES (stmt) = clauses; OACC_PARALLEL_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Generate OACC_KERNELS, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_KERNELS. */ tree c_finish_oacc_kernels (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OACC_KERNELS); TREE_TYPE (stmt) = void_type_node; OACC_KERNELS_CLAUSES (stmt) = clauses; OACC_KERNELS_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Generate OACC_DATA, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OACC_DATA. */ tree c_finish_oacc_data (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OACC_DATA); TREE_TYPE (stmt) = void_type_node; OACC_DATA_CLAUSES (stmt) = clauses; OACC_DATA_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Like c_begin_compound_stmt, except force the retention of the BLOCK. */ tree c_begin_omp_parallel (void) { tree block; keep_next_level (); block = c_begin_compound_stmt (true); return block; } /* Generate OMP_PARALLEL, with CLAUSES and BLOCK as its compound statement. LOC is the location of the OMP_PARALLEL. */ tree c_finish_omp_parallel (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OMP_PARALLEL); TREE_TYPE (stmt) = void_type_node; OMP_PARALLEL_CLAUSES (stmt) = clauses; OMP_PARALLEL_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Like c_begin_compound_stmt, except force the retention of the BLOCK. */ tree c_begin_omp_task (void) { tree block; keep_next_level (); block = c_begin_compound_stmt (true); return block; } /* Generate OMP_TASK, with CLAUSES and BLOCK as its compound statement. LOC is the location of the #pragma. */ tree c_finish_omp_task (location_t loc, tree clauses, tree block) { tree stmt; block = c_end_compound_stmt (loc, block, true); stmt = make_node (OMP_TASK); TREE_TYPE (stmt) = void_type_node; OMP_TASK_CLAUSES (stmt) = clauses; OMP_TASK_BODY (stmt) = block; SET_EXPR_LOCATION (stmt, loc); return add_stmt (stmt); } /* Generate GOMP_cancel call for #pragma omp cancel. */ void c_finish_omp_cancel (location_t loc, tree clauses) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_CANCEL); int mask = 0; if (find_omp_clause (clauses, OMP_CLAUSE_PARALLEL)) mask = 1; else if (find_omp_clause (clauses, OMP_CLAUSE_FOR)) mask = 2; else if (find_omp_clause (clauses, OMP_CLAUSE_SECTIONS)) mask = 4; else if (find_omp_clause (clauses, OMP_CLAUSE_TASKGROUP)) mask = 8; else { error_at (loc, "%<#pragma omp cancel must specify one of " "%<parallel%>, %<for%>, %<sections%> or %<taskgroup%> " "clauses"); return; } tree ifc = find_omp_clause (clauses, OMP_CLAUSE_IF); if (ifc != NULL_TREE) { tree type = TREE_TYPE (OMP_CLAUSE_IF_EXPR (ifc)); ifc = fold_build2_loc (OMP_CLAUSE_LOCATION (ifc), NE_EXPR, boolean_type_node, OMP_CLAUSE_IF_EXPR (ifc), build_zero_cst (type)); } else ifc = boolean_true_node; tree stmt = build_call_expr_loc (loc, fn, 2, build_int_cst (integer_type_node, mask), ifc); add_stmt (stmt); } /* Generate GOMP_cancellation_point call for #pragma omp cancellation point. */ void c_finish_omp_cancellation_point (location_t loc, tree clauses) { tree fn = builtin_decl_explicit (BUILT_IN_GOMP_CANCELLATION_POINT); int mask = 0; if (find_omp_clause (clauses, OMP_CLAUSE_PARALLEL)) mask = 1; else if (find_omp_clause (clauses, OMP_CLAUSE_FOR)) mask = 2; else if (find_omp_clause (clauses, OMP_CLAUSE_SECTIONS)) mask = 4; else if (find_omp_clause (clauses, OMP_CLAUSE_TASKGROUP)) mask = 8; else { error_at (loc, "%<#pragma omp cancellation point must specify one of " "%<parallel%>, %<for%>, %<sections%> or %<taskgroup%> " "clauses"); return; } tree stmt = build_call_expr_loc (loc, fn, 1, build_int_cst (integer_type_node, mask)); add_stmt (stmt); } /* Helper function for handle_omp_array_sections. Called recursively to handle multiple array-section-subscripts. C is the clause, T current expression (initially OMP_CLAUSE_DECL), which is either a TREE_LIST for array-section-subscript (TREE_PURPOSE is low-bound expression if specified, TREE_VALUE length expression if specified, TREE_CHAIN is what it has been specified after, or some decl. TYPES vector is populated with array section types, MAYBE_ZERO_LEN set to true if any of the array-section-subscript could have length of zero (explicit or implicit), FIRST_NON_ONE is the index of the first array-section-subscript which is known not to have length of one. Given say: map(a[:b][2:1][:c][:2][:d][e:f][2:5]) FIRST_NON_ONE will be 3, array-section-subscript [:b], [2:1] and [:c] all are or may have length of 1, array-section-subscript [:2] is the first one knonwn not to have length 1. For array-section-subscript <= FIRST_NON_ONE we diagnose non-contiguous arrays if low bound isn't 0 or length isn't the array domain max + 1, for > FIRST_NON_ONE we can if MAYBE_ZERO_LEN is false. MAYBE_ZERO_LEN will be true in the above case though, as some lengths could be zero. */ static tree handle_omp_array_sections_1 (tree c, tree t, vec<tree> &types, bool &maybe_zero_len, unsigned int &first_non_one) { tree ret, low_bound, length, type; if (TREE_CODE (t) != TREE_LIST) { if (error_operand_p (t)) return error_mark_node; if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { if (DECL_P (t)) error_at (OMP_CLAUSE_LOCATION (c), "%qD is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); else error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } else if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && TREE_CODE (t) == VAR_DECL && DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qD is threadprivate variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } return t; } ret = handle_omp_array_sections_1 (c, TREE_CHAIN (t), types, maybe_zero_len, first_non_one); if (ret == error_mark_node || ret == NULL_TREE) return ret; type = TREE_TYPE (ret); low_bound = TREE_PURPOSE (t); length = TREE_VALUE (t); if (low_bound == error_mark_node || length == error_mark_node) return error_mark_node; if (low_bound && !INTEGRAL_TYPE_P (TREE_TYPE (low_bound))) { error_at (OMP_CLAUSE_LOCATION (c), "low bound %qE of array section does not have integral type", low_bound); return error_mark_node; } if (length && !INTEGRAL_TYPE_P (TREE_TYPE (length))) { error_at (OMP_CLAUSE_LOCATION (c), "length %qE of array section does not have integral type", length); return error_mark_node; } if (low_bound && TREE_CODE (low_bound) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (low_bound)) > TYPE_PRECISION (sizetype)) low_bound = fold_convert (sizetype, low_bound); if (length && TREE_CODE (length) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (length)) > TYPE_PRECISION (sizetype)) length = fold_convert (sizetype, length); if (low_bound == NULL_TREE) low_bound = integer_zero_node; if (length != NULL_TREE) { if (!integer_nonzerop (length)) maybe_zero_len = true; if (first_non_one == types.length () && (TREE_CODE (length) != INTEGER_CST || integer_onep (length))) first_non_one++; } if (TREE_CODE (type) == ARRAY_TYPE) { if (length == NULL_TREE && (TYPE_DOMAIN (type) == NULL_TREE || TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL_TREE)) { error_at (OMP_CLAUSE_LOCATION (c), "for unknown bound array type length expression must " "be specified"); return error_mark_node; } if (TREE_CODE (low_bound) == INTEGER_CST && tree_int_cst_sgn (low_bound) == -1) { error_at (OMP_CLAUSE_LOCATION (c), "negative low bound in array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (length != NULL_TREE && TREE_CODE (length) == INTEGER_CST && tree_int_cst_sgn (length) == -1) { error_at (OMP_CLAUSE_LOCATION (c), "negative length in array section in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)) && TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (type))) == INTEGER_CST) { tree size = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (type)), size_one_node); if (TREE_CODE (low_bound) == INTEGER_CST) { if (tree_int_cst_lt (size, low_bound)) { error_at (OMP_CLAUSE_LOCATION (c), "low bound %qE above array section size " "in %qs clause", low_bound, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (tree_int_cst_equal (size, low_bound)) maybe_zero_len = true; else if (length == NULL_TREE && first_non_one == types.length () && tree_int_cst_equal (TYPE_MAX_VALUE (TYPE_DOMAIN (type)), low_bound)) first_non_one++; } else if (length == NULL_TREE) { maybe_zero_len = true; if (first_non_one == types.length ()) first_non_one++; } if (length && TREE_CODE (length) == INTEGER_CST) { if (tree_int_cst_lt (size, length)) { error_at (OMP_CLAUSE_LOCATION (c), "length %qE above array section size " "in %qs clause", length, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } if (TREE_CODE (low_bound) == INTEGER_CST) { tree lbpluslen = size_binop (PLUS_EXPR, fold_convert (sizetype, low_bound), fold_convert (sizetype, length)); if (TREE_CODE (lbpluslen) == INTEGER_CST && tree_int_cst_lt (size, lbpluslen)) { error_at (OMP_CLAUSE_LOCATION (c), "high bound %qE above array section size " "in %qs clause", lbpluslen, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } } } } else if (length == NULL_TREE) { maybe_zero_len = true; if (first_non_one == types.length ()) first_non_one++; } /* For [lb:] we will need to evaluate lb more than once. */ if (length == NULL_TREE && OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND) { tree lb = c_save_expr (low_bound); if (lb != low_bound) { TREE_PURPOSE (t) = lb; low_bound = lb; } } } else if (TREE_CODE (type) == POINTER_TYPE) { if (length == NULL_TREE) { error_at (OMP_CLAUSE_LOCATION (c), "for pointer type length expression must be specified"); return error_mark_node; } /* If there is a pointer type anywhere but in the very first array-section-subscript, the array section can't be contiguous. */ if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND && TREE_CODE (TREE_CHAIN (t)) == TREE_LIST) { error_at (OMP_CLAUSE_LOCATION (c), "array section is not contiguous in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); return error_mark_node; } } else { error_at (OMP_CLAUSE_LOCATION (c), "%qE does not have pointer or array type", ret); return error_mark_node; } if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_DEPEND) types.safe_push (TREE_TYPE (ret)); /* We will need to evaluate lb more than once. */ tree lb = c_save_expr (low_bound); if (lb != low_bound) { TREE_PURPOSE (t) = lb; low_bound = lb; } ret = build_array_ref (OMP_CLAUSE_LOCATION (c), ret, low_bound); return ret; } /* Handle array sections for clause C. */ static bool handle_omp_array_sections (tree c) { bool maybe_zero_len = false; unsigned int first_non_one = 0; vec<tree> types = vNULL; tree first = handle_omp_array_sections_1 (c, OMP_CLAUSE_DECL (c), types, maybe_zero_len, first_non_one); if (first == error_mark_node) { types.release (); return true; } if (first == NULL_TREE) { types.release (); return false; } if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_DEPEND) { tree t = OMP_CLAUSE_DECL (c); tree tem = NULL_TREE; types.release (); /* Need to evaluate side effects in the length expressions if any. */ while (TREE_CODE (t) == TREE_LIST) { if (TREE_VALUE (t) && TREE_SIDE_EFFECTS (TREE_VALUE (t))) { if (tem == NULL_TREE) tem = TREE_VALUE (t); else tem = build2 (COMPOUND_EXPR, TREE_TYPE (tem), TREE_VALUE (t), tem); } t = TREE_CHAIN (t); } if (tem) first = build2 (COMPOUND_EXPR, TREE_TYPE (first), tem, first); first = c_fully_fold (first, false, NULL); OMP_CLAUSE_DECL (c) = first; } else { unsigned int num = types.length (), i; tree t, side_effects = NULL_TREE, size = NULL_TREE; tree condition = NULL_TREE; if (int_size_in_bytes (TREE_TYPE (first)) <= 0) maybe_zero_len = true; for (i = num, t = OMP_CLAUSE_DECL (c); i > 0; t = TREE_CHAIN (t)) { tree low_bound = TREE_PURPOSE (t); tree length = TREE_VALUE (t); i--; if (low_bound && TREE_CODE (low_bound) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (low_bound)) > TYPE_PRECISION (sizetype)) low_bound = fold_convert (sizetype, low_bound); if (length && TREE_CODE (length) == INTEGER_CST && TYPE_PRECISION (TREE_TYPE (length)) > TYPE_PRECISION (sizetype)) length = fold_convert (sizetype, length); if (low_bound == NULL_TREE) low_bound = integer_zero_node; if (!maybe_zero_len && i > first_non_one) { if (integer_nonzerop (low_bound)) goto do_warn_noncontiguous; if (length != NULL_TREE && TREE_CODE (length) == INTEGER_CST && TYPE_DOMAIN (types[i]) && TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])) && TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (types[i]))) == INTEGER_CST) { tree size; size = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])), size_one_node); if (!tree_int_cst_equal (length, size)) { do_warn_noncontiguous: error_at (OMP_CLAUSE_LOCATION (c), "array section is not contiguous in %qs " "clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); types.release (); return true; } } if (length != NULL_TREE && TREE_SIDE_EFFECTS (length)) { if (side_effects == NULL_TREE) side_effects = length; else side_effects = build2 (COMPOUND_EXPR, TREE_TYPE (side_effects), length, side_effects); } } else { tree l; if (i > first_non_one && length && integer_nonzerop (length)) continue; if (length) l = fold_convert (sizetype, length); else { l = size_binop (PLUS_EXPR, TYPE_MAX_VALUE (TYPE_DOMAIN (types[i])), size_one_node); l = size_binop (MINUS_EXPR, l, fold_convert (sizetype, low_bound)); } if (i > first_non_one) { l = fold_build2 (NE_EXPR, boolean_type_node, l, size_zero_node); if (condition == NULL_TREE) condition = l; else condition = fold_build2 (BIT_AND_EXPR, boolean_type_node, l, condition); } else if (size == NULL_TREE) { size = size_in_bytes (TREE_TYPE (types[i])); size = size_binop (MULT_EXPR, size, l); if (condition) size = fold_build3 (COND_EXPR, sizetype, condition, size, size_zero_node); } else size = size_binop (MULT_EXPR, size, l); } } types.release (); if (side_effects) size = build2 (COMPOUND_EXPR, sizetype, side_effects, size); first = c_fully_fold (first, false, NULL); OMP_CLAUSE_DECL (c) = first; if (size) size = c_fully_fold (size, false, NULL); OMP_CLAUSE_SIZE (c) = size; if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) return false; gcc_assert (OMP_CLAUSE_MAP_KIND (c) != GOMP_MAP_FORCE_DEVICEPTR); tree c2 = build_omp_clause (OMP_CLAUSE_LOCATION (c), OMP_CLAUSE_MAP); OMP_CLAUSE_SET_MAP_KIND (c2, GOMP_MAP_POINTER); if (!c_mark_addressable (t)) return false; OMP_CLAUSE_DECL (c2) = t; t = build_fold_addr_expr (first); t = fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, t); tree ptr = OMP_CLAUSE_DECL (c2); if (!POINTER_TYPE_P (TREE_TYPE (ptr))) ptr = build_fold_addr_expr (ptr); t = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, ptrdiff_type_node, t, fold_convert_loc (OMP_CLAUSE_LOCATION (c), ptrdiff_type_node, ptr)); t = c_fully_fold (t, false, NULL); OMP_CLAUSE_SIZE (c2) = t; OMP_CLAUSE_CHAIN (c2) = OMP_CLAUSE_CHAIN (c); OMP_CLAUSE_CHAIN (c) = c2; } return false; } /* Helper function of finish_omp_clauses. Clone STMT as if we were making an inline call. But, remap the OMP_DECL1 VAR_DECL (omp_out resp. omp_orig) to PLACEHOLDER and OMP_DECL2 VAR_DECL (omp_in resp. omp_priv) to DECL. */ static tree c_clone_omp_udr (tree stmt, tree omp_decl1, tree omp_decl2, tree decl, tree placeholder) { copy_body_data id; hash_map<tree, tree> decl_map; decl_map.put (omp_decl1, placeholder); decl_map.put (omp_decl2, decl); memset (&id, 0, sizeof (id)); id.src_fn = DECL_CONTEXT (omp_decl1); id.dst_fn = current_function_decl; id.src_cfun = DECL_STRUCT_FUNCTION (id.src_fn); id.decl_map = &decl_map; id.copy_decl = copy_decl_no_change; id.transform_call_graph_edges = CB_CGE_DUPLICATE; id.transform_new_cfg = true; id.transform_return_to_modify = false; id.transform_lang_insert_block = NULL; id.eh_lp_nr = 0; walk_tree (&stmt, copy_tree_body_r, &id, NULL); return stmt; } /* Helper function of c_finish_omp_clauses, called via walk_tree. Find OMP_CLAUSE_PLACEHOLDER (passed in DATA) in *TP. */ static tree c_find_omp_placeholder_r (tree *tp, int *, void *data) { if (*tp == (tree) data) return *tp; return NULL_TREE; } /* For all elements of CLAUSES, validate them against their constraints. Remove any elements from the list that are invalid. */ tree c_finish_omp_clauses (tree clauses) { bitmap_head generic_head, firstprivate_head, lastprivate_head; bitmap_head aligned_head; tree c, t, *pc; bool branch_seen = false; bool copyprivate_seen = false; tree *nowait_clause = NULL; bitmap_obstack_initialize (NULL); bitmap_initialize (&generic_head, &bitmap_default_obstack); bitmap_initialize (&firstprivate_head, &bitmap_default_obstack); bitmap_initialize (&lastprivate_head, &bitmap_default_obstack); bitmap_initialize (&aligned_head, &bitmap_default_obstack); for (pc = &clauses, c = clauses; c ; c = *pc) { bool remove = false; bool need_complete = false; bool need_implicitly_determined = false; switch (OMP_CLAUSE_CODE (c)) { case OMP_CLAUSE_SHARED: need_implicitly_determined = true; goto check_dup_generic; case OMP_CLAUSE_PRIVATE: need_complete = true; need_implicitly_determined = true; goto check_dup_generic; case OMP_CLAUSE_REDUCTION: need_implicitly_determined = true; t = OMP_CLAUSE_DECL (c); if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) == NULL_TREE && (FLOAT_TYPE_P (TREE_TYPE (t)) || TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE)) { enum tree_code r_code = OMP_CLAUSE_REDUCTION_CODE (c); const char *r_name = NULL; switch (r_code) { case PLUS_EXPR: case MULT_EXPR: case MINUS_EXPR: break; case MIN_EXPR: if (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE) r_name = "min"; break; case MAX_EXPR: if (TREE_CODE (TREE_TYPE (t)) == COMPLEX_TYPE) r_name = "max"; break; case BIT_AND_EXPR: r_name = "&"; break; case BIT_XOR_EXPR: r_name = "^"; break; case BIT_IOR_EXPR: r_name = "|"; break; case TRUTH_ANDIF_EXPR: if (FLOAT_TYPE_P (TREE_TYPE (t))) r_name = "&&"; break; case TRUTH_ORIF_EXPR: if (FLOAT_TYPE_P (TREE_TYPE (t))) r_name = "||"; break; default: gcc_unreachable (); } if (r_name) { error_at (OMP_CLAUSE_LOCATION (c), "%qE has invalid type for %<reduction(%s)%>", t, r_name); remove = true; break; } } else if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) == error_mark_node) { error_at (OMP_CLAUSE_LOCATION (c), "user defined reduction not found for %qD", t); remove = true; break; } else if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (c)) { tree list = OMP_CLAUSE_REDUCTION_PLACEHOLDER (c); tree type = TYPE_MAIN_VARIANT (TREE_TYPE (t)); tree placeholder = build_decl (OMP_CLAUSE_LOCATION (c), VAR_DECL, NULL_TREE, type); OMP_CLAUSE_REDUCTION_PLACEHOLDER (c) = placeholder; DECL_ARTIFICIAL (placeholder) = 1; DECL_IGNORED_P (placeholder) = 1; if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 0))) c_mark_addressable (placeholder); if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 1))) c_mark_addressable (OMP_CLAUSE_DECL (c)); OMP_CLAUSE_REDUCTION_MERGE (c) = c_clone_omp_udr (TREE_VEC_ELT (list, 2), TREE_VEC_ELT (list, 0), TREE_VEC_ELT (list, 1), OMP_CLAUSE_DECL (c), placeholder); OMP_CLAUSE_REDUCTION_MERGE (c) = build3_loc (OMP_CLAUSE_LOCATION (c), BIND_EXPR, void_type_node, NULL_TREE, OMP_CLAUSE_REDUCTION_MERGE (c), NULL_TREE); TREE_SIDE_EFFECTS (OMP_CLAUSE_REDUCTION_MERGE (c)) = 1; if (TREE_VEC_LENGTH (list) == 6) { if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 3))) c_mark_addressable (OMP_CLAUSE_DECL (c)); if (TREE_ADDRESSABLE (TREE_VEC_ELT (list, 4))) c_mark_addressable (placeholder); tree init = TREE_VEC_ELT (list, 5); if (init == error_mark_node) init = DECL_INITIAL (TREE_VEC_ELT (list, 3)); OMP_CLAUSE_REDUCTION_INIT (c) = c_clone_omp_udr (init, TREE_VEC_ELT (list, 4), TREE_VEC_ELT (list, 3), OMP_CLAUSE_DECL (c), placeholder); if (TREE_VEC_ELT (list, 5) == error_mark_node) OMP_CLAUSE_REDUCTION_INIT (c) = build2 (INIT_EXPR, TREE_TYPE (t), t, OMP_CLAUSE_REDUCTION_INIT (c)); if (walk_tree (&OMP_CLAUSE_REDUCTION_INIT (c), c_find_omp_placeholder_r, placeholder, NULL)) OMP_CLAUSE_REDUCTION_OMP_ORIG_REF (c) = 1; } else { tree init; if (AGGREGATE_TYPE_P (TREE_TYPE (t))) init = build_constructor (TREE_TYPE (t), NULL); else init = fold_convert (TREE_TYPE (t), integer_zero_node); OMP_CLAUSE_REDUCTION_INIT (c) = build2 (INIT_EXPR, TREE_TYPE (t), t, init); } OMP_CLAUSE_REDUCTION_INIT (c) = build3_loc (OMP_CLAUSE_LOCATION (c), BIND_EXPR, void_type_node, NULL_TREE, OMP_CLAUSE_REDUCTION_INIT (c), NULL_TREE); TREE_SIDE_EFFECTS (OMP_CLAUSE_REDUCTION_INIT (c)) = 1; } goto check_dup_generic; case OMP_CLAUSE_COPYPRIVATE: copyprivate_seen = true; if (nowait_clause) { error_at (OMP_CLAUSE_LOCATION (*nowait_clause), "%<nowait%> clause must not be used together " "with %<copyprivate%>"); *nowait_clause = OMP_CLAUSE_CHAIN (*nowait_clause); nowait_clause = NULL; } goto check_dup_generic; case OMP_CLAUSE_COPYIN: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != VAR_DECL || !DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qE must be %<threadprivate%> for %<copyin%>", t); remove = true; break; } goto check_dup_generic; case OMP_CLAUSE_LINEAR: t = OMP_CLAUSE_DECL (c); if (!INTEGRAL_TYPE_P (TREE_TYPE (t)) && TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "linear clause applied to non-integral non-pointer " "variable with type %qT", TREE_TYPE (t)); remove = true; break; } if (TREE_CODE (TREE_TYPE (OMP_CLAUSE_DECL (c))) == POINTER_TYPE) { tree s = OMP_CLAUSE_LINEAR_STEP (c); s = pointer_int_sum (OMP_CLAUSE_LOCATION (c), PLUS_EXPR, OMP_CLAUSE_DECL (c), s); s = fold_build2_loc (OMP_CLAUSE_LOCATION (c), MINUS_EXPR, sizetype, s, OMP_CLAUSE_DECL (c)); if (s == error_mark_node) s = size_one_node; OMP_CLAUSE_LINEAR_STEP (c) = s; } else OMP_CLAUSE_LINEAR_STEP (c) = fold_convert (TREE_TYPE (t), OMP_CLAUSE_LINEAR_STEP (c)); goto check_dup_generic; check_dup_generic: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %qs", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t)) || bitmap_bit_p (&lastprivate_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&generic_head, DECL_UID (t)); break; case OMP_CLAUSE_FIRSTPRIVATE: t = OMP_CLAUSE_DECL (c); need_complete = true; need_implicitly_determined = true; if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %<firstprivate%>", t); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&firstprivate_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&firstprivate_head, DECL_UID (t)); break; case OMP_CLAUSE_LASTPRIVATE: t = OMP_CLAUSE_DECL (c); need_complete = true; need_implicitly_determined = true; if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in clause %<lastprivate%>", t); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t)) || bitmap_bit_p (&lastprivate_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in data clauses", t); remove = true; } else bitmap_set_bit (&lastprivate_head, DECL_UID (t)); break; case OMP_CLAUSE_ALIGNED: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %<aligned%> clause", t); remove = true; } else if (!POINTER_TYPE_P (TREE_TYPE (t)) && TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE) { error_at (OMP_CLAUSE_LOCATION (c), "%qE in %<aligned%> clause is neither a pointer nor " "an array", t); remove = true; } else if (bitmap_bit_p (&aligned_head, DECL_UID (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qE appears more than once in %<aligned%> clauses", t); remove = true; } else bitmap_set_bit (&aligned_head, DECL_UID (t)); break; case OMP_CLAUSE_DEPEND: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) == TREE_LIST) { if (handle_omp_array_sections (c)) remove = true; break; } if (t == error_mark_node) remove = true; else if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %<depend%> clause", t); remove = true; } else if (!c_mark_addressable (t)) remove = true; break; case OMP_CLAUSE_MAP: case OMP_CLAUSE_TO: case OMP_CLAUSE_FROM: case OMP_CLAUSE__CACHE_: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) == TREE_LIST) { if (handle_omp_array_sections (c)) remove = true; else { t = OMP_CLAUSE_DECL (c); if (!lang_hooks.types.omp_mappable_type (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "array section does not have mappable type " "in %qs clause", omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } } break; } if (t == error_mark_node) remove = true; else if (TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != PARM_DECL) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is not a variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (TREE_CODE (t) == VAR_DECL && DECL_THREAD_LOCAL_P (t)) { error_at (OMP_CLAUSE_LOCATION (c), "%qD is threadprivate variable in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (!c_mark_addressable (t)) remove = true; else if (!(OMP_CLAUSE_CODE (c) == OMP_CLAUSE_MAP && (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_POINTER || (OMP_CLAUSE_MAP_KIND (c) == GOMP_MAP_FORCE_DEVICEPTR))) && !lang_hooks.types.omp_mappable_type (TREE_TYPE (t))) { error_at (OMP_CLAUSE_LOCATION (c), "%qD does not have a mappable type in %qs clause", t, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } else if (bitmap_bit_p (&generic_head, DECL_UID (t))) { if (OMP_CLAUSE_CODE (c) != OMP_CLAUSE_MAP) error ("%qD appears more than once in motion clauses", t); else error ("%qD appears more than once in map clauses", t); remove = true; } else bitmap_set_bit (&generic_head, DECL_UID (t)); break; case OMP_CLAUSE_UNIFORM: t = OMP_CLAUSE_DECL (c); if (TREE_CODE (t) != PARM_DECL) { if (DECL_P (t)) error_at (OMP_CLAUSE_LOCATION (c), "%qD is not an argument in %<uniform%> clause", t); else error_at (OMP_CLAUSE_LOCATION (c), "%qE is not an argument in %<uniform%> clause", t); remove = true; break; } goto check_dup_generic; case OMP_CLAUSE_NOWAIT: if (copyprivate_seen) { error_at (OMP_CLAUSE_LOCATION (c), "%<nowait%> clause must not be used together " "with %<copyprivate%>"); remove = true; break; } nowait_clause = pc; pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_IF: case OMP_CLAUSE_NUM_THREADS: case OMP_CLAUSE_NUM_TEAMS: case OMP_CLAUSE_THREAD_LIMIT: case OMP_CLAUSE_SCHEDULE: case OMP_CLAUSE_ORDERED: case OMP_CLAUSE_DEFAULT: case OMP_CLAUSE_UNTIED: case OMP_CLAUSE_COLLAPSE: case OMP_CLAUSE_FINAL: case OMP_CLAUSE_MERGEABLE: case OMP_CLAUSE_SAFELEN: case OMP_CLAUSE_SIMDLEN: case OMP_CLAUSE_DEVICE: case OMP_CLAUSE_DIST_SCHEDULE: case OMP_CLAUSE_PARALLEL: case OMP_CLAUSE_FOR: case OMP_CLAUSE_SECTIONS: case OMP_CLAUSE_TASKGROUP: case OMP_CLAUSE_PROC_BIND: case OMP_CLAUSE__CILK_FOR_COUNT_: case OMP_CLAUSE_NUM_GANGS: case OMP_CLAUSE_NUM_WORKERS: case OMP_CLAUSE_VECTOR_LENGTH: case OMP_CLAUSE_ASYNC: case OMP_CLAUSE_WAIT: case OMP_CLAUSE_AUTO: case OMP_CLAUSE_SEQ: case OMP_CLAUSE_GANG: case OMP_CLAUSE_WORKER: case OMP_CLAUSE_VECTOR: pc = &OMP_CLAUSE_CHAIN (c); continue; case OMP_CLAUSE_INBRANCH: case OMP_CLAUSE_NOTINBRANCH: if (branch_seen) { error_at (OMP_CLAUSE_LOCATION (c), "%<inbranch%> clause is incompatible with " "%<notinbranch%>"); remove = true; break; } branch_seen = true; pc = &OMP_CLAUSE_CHAIN (c); continue; default: gcc_unreachable (); } if (!remove) { t = OMP_CLAUSE_DECL (c); if (need_complete) { t = require_complete_type (t); if (t == error_mark_node) remove = true; } if (need_implicitly_determined) { const char *share_name = NULL; if (TREE_CODE (t) == VAR_DECL && DECL_THREAD_LOCAL_P (t)) share_name = "threadprivate"; else switch (c_omp_predetermined_sharing (t)) { case OMP_CLAUSE_DEFAULT_UNSPECIFIED: break; case OMP_CLAUSE_DEFAULT_SHARED: /* const vars may be specified in firstprivate clause. */ if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE && TREE_READONLY (t)) break; share_name = "shared"; break; case OMP_CLAUSE_DEFAULT_PRIVATE: share_name = "private"; break; default: gcc_unreachable (); } if (share_name) { error_at (OMP_CLAUSE_LOCATION (c), "%qE is predetermined %qs for %qs", t, share_name, omp_clause_code_name[OMP_CLAUSE_CODE (c)]); remove = true; } } } if (remove) *pc = OMP_CLAUSE_CHAIN (c); else pc = &OMP_CLAUSE_CHAIN (c); } bitmap_obstack_release (NULL); return clauses; } /* Create a transaction node. */ tree c_finish_transaction (location_t loc, tree block, int flags) { tree stmt = build_stmt (loc, TRANSACTION_EXPR, block); if (flags & TM_STMT_ATTR_OUTER) TRANSACTION_EXPR_OUTER (stmt) = 1; if (flags & TM_STMT_ATTR_RELAXED) TRANSACTION_EXPR_RELAXED (stmt) = 1; return add_stmt (stmt); } /* Make a variant type in the proper way for C/C++, propagating qualifiers down to the element type of an array. If ORIG_QUAL_TYPE is not NULL, then it should be used as the qualified type ORIG_QUAL_INDIRECT levels down in array type derivation (to preserve information about the typedef name from which an array type was derived). */ tree c_build_qualified_type (tree type, int type_quals, tree orig_qual_type, size_t orig_qual_indirect) { if (type == error_mark_node) return type; if (TREE_CODE (type) == ARRAY_TYPE) { tree t; tree element_type = c_build_qualified_type (TREE_TYPE (type), type_quals, orig_qual_type, orig_qual_indirect - 1); /* See if we already have an identically qualified type. */ if (orig_qual_type && orig_qual_indirect == 0) t = orig_qual_type; else for (t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t)) { if (TYPE_QUALS (strip_array_types (t)) == type_quals && TYPE_NAME (t) == TYPE_NAME (type) && TYPE_CONTEXT (t) == TYPE_CONTEXT (type) && attribute_list_equal (TYPE_ATTRIBUTES (t), TYPE_ATTRIBUTES (type))) break; } if (!t) { tree domain = TYPE_DOMAIN (type); t = build_variant_type_copy (type); TREE_TYPE (t) = element_type; if (TYPE_STRUCTURAL_EQUALITY_P (element_type) || (domain && TYPE_STRUCTURAL_EQUALITY_P (domain))) SET_TYPE_STRUCTURAL_EQUALITY (t); else if (TYPE_CANONICAL (element_type) != element_type || (domain && TYPE_CANONICAL (domain) != domain)) { tree unqualified_canon = build_array_type (TYPE_CANONICAL (element_type), domain? TYPE_CANONICAL (domain) : NULL_TREE); TYPE_CANONICAL (t) = c_build_qualified_type (unqualified_canon, type_quals); } else TYPE_CANONICAL (t) = t; } return t; } /* A restrict-qualified pointer type must be a pointer to object or incomplete type. Note that the use of POINTER_TYPE_P also allows REFERENCE_TYPEs, which is appropriate for C++. */ if ((type_quals & TYPE_QUAL_RESTRICT) && (!POINTER_TYPE_P (type) || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))) { error ("invalid use of %<restrict%>"); type_quals &= ~TYPE_QUAL_RESTRICT; } tree var_type = (orig_qual_type && orig_qual_indirect == 0 ? orig_qual_type : build_qualified_type (type, type_quals)); return var_type; } /* Build a VA_ARG_EXPR for the C parser. */ tree c_build_va_arg (location_t loc, tree expr, tree type) { if (warn_cxx_compat && TREE_CODE (type) == ENUMERAL_TYPE) warning_at (loc, OPT_Wc___compat, "C++ requires promoted type, not enum type, in %<va_arg%>"); return build_va_arg (loc, expr, type); } /* Return truthvalue of whether T1 is the same tree structure as T2. Return 1 if they are the same. Return 0 if they are different. */ bool c_tree_equal (tree t1, tree t2) { enum tree_code code1, code2; if (t1 == t2) return true; if (!t1 || !t2) return false; for (code1 = TREE_CODE (t1); CONVERT_EXPR_CODE_P (code1) || code1 == NON_LVALUE_EXPR; code1 = TREE_CODE (t1)) t1 = TREE_OPERAND (t1, 0); for (code2 = TREE_CODE (t2); CONVERT_EXPR_CODE_P (code2) || code2 == NON_LVALUE_EXPR; code2 = TREE_CODE (t2)) t2 = TREE_OPERAND (t2, 0); /* They might have become equal now. */ if (t1 == t2) return true; if (code1 != code2) return false; switch (code1) { case INTEGER_CST: return wi::eq_p (t1, t2); case REAL_CST: return REAL_VALUES_EQUAL (TREE_REAL_CST (t1), TREE_REAL_CST (t2)); case STRING_CST: return TREE_STRING_LENGTH (t1) == TREE_STRING_LENGTH (t2) && !memcmp (TREE_STRING_POINTER (t1), TREE_STRING_POINTER (t2), TREE_STRING_LENGTH (t1)); case FIXED_CST: return FIXED_VALUES_IDENTICAL (TREE_FIXED_CST (t1), TREE_FIXED_CST (t2)); case COMPLEX_CST: return c_tree_equal (TREE_REALPART (t1), TREE_REALPART (t2)) && c_tree_equal (TREE_IMAGPART (t1), TREE_IMAGPART (t2)); case VECTOR_CST: return operand_equal_p (t1, t2, OEP_ONLY_CONST); case CONSTRUCTOR: /* We need to do this when determining whether or not two non-type pointer to member function template arguments are the same. */ if (!comptypes (TREE_TYPE (t1), TREE_TYPE (t2)) || CONSTRUCTOR_NELTS (t1) != CONSTRUCTOR_NELTS (t2)) return false; { tree field, value; unsigned int i; FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t1), i, field, value) { constructor_elt *elt2 = CONSTRUCTOR_ELT (t2, i); if (!c_tree_equal (field, elt2->index) || !c_tree_equal (value, elt2->value)) return false; } } return true; case TREE_LIST: if (!c_tree_equal (TREE_PURPOSE (t1), TREE_PURPOSE (t2))) return false; if (!c_tree_equal (TREE_VALUE (t1), TREE_VALUE (t2))) return false; return c_tree_equal (TREE_CHAIN (t1), TREE_CHAIN (t2)); case SAVE_EXPR: return c_tree_equal (TREE_OPERAND (t1, 0), TREE_OPERAND (t2, 0)); case CALL_EXPR: { tree arg1, arg2; call_expr_arg_iterator iter1, iter2; if (!c_tree_equal (CALL_EXPR_FN (t1), CALL_EXPR_FN (t2))) return false; for (arg1 = first_call_expr_arg (t1, &iter1), arg2 = first_call_expr_arg (t2, &iter2); arg1 && arg2; arg1 = next_call_expr_arg (&iter1), arg2 = next_call_expr_arg (&iter2)) if (!c_tree_equal (arg1, arg2)) return false; if (arg1 || arg2) return false; return true; } case TARGET_EXPR: { tree o1 = TREE_OPERAND (t1, 0); tree o2 = TREE_OPERAND (t2, 0); /* Special case: if either target is an unallocated VAR_DECL, it means that it's going to be unified with whatever the TARGET_EXPR is really supposed to initialize, so treat it as being equivalent to anything. */ if (TREE_CODE (o1) == VAR_DECL && DECL_NAME (o1) == NULL_TREE && !DECL_RTL_SET_P (o1)) /*Nop*/; else if (TREE_CODE (o2) == VAR_DECL && DECL_NAME (o2) == NULL_TREE && !DECL_RTL_SET_P (o2)) /*Nop*/; else if (!c_tree_equal (o1, o2)) return false; return c_tree_equal (TREE_OPERAND (t1, 1), TREE_OPERAND (t2, 1)); } case COMPONENT_REF: if (TREE_OPERAND (t1, 1) != TREE_OPERAND (t2, 1)) return false; return c_tree_equal (TREE_OPERAND (t1, 0), TREE_OPERAND (t2, 0)); case PARM_DECL: case VAR_DECL: case CONST_DECL: case FIELD_DECL: case FUNCTION_DECL: case IDENTIFIER_NODE: case SSA_NAME: return false; case TREE_VEC: { unsigned ix; if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2)) return false; for (ix = TREE_VEC_LENGTH (t1); ix--;) if (!c_tree_equal (TREE_VEC_ELT (t1, ix), TREE_VEC_ELT (t2, ix))) return false; return true; } default: break; } switch (TREE_CODE_CLASS (code1)) { case tcc_unary: case tcc_binary: case tcc_comparison: case tcc_expression: case tcc_vl_exp: case tcc_reference: case tcc_statement: { int i, n = TREE_OPERAND_LENGTH (t1); switch (code1) { case PREINCREMENT_EXPR: case PREDECREMENT_EXPR: case POSTINCREMENT_EXPR: case POSTDECREMENT_EXPR: n = 1; break; case ARRAY_REF: n = 2; break; default: break; } if (TREE_CODE_CLASS (code1) == tcc_vl_exp && n != TREE_OPERAND_LENGTH (t2)) return false; for (i = 0; i < n; ++i) if (!c_tree_equal (TREE_OPERAND (t1, i), TREE_OPERAND (t2, i))) return false; return true; } case tcc_type: return comptypes (t1, t2); default: gcc_unreachable (); } /* We can get here with --disable-checking. */ return false; } /* Inserts "cleanup" functions after the function-body of FNDECL. FNDECL is a spawn-helper and BODY is the newly created body for FNDECL. */ void cilk_install_body_with_frame_cleanup (tree fndecl, tree body, void *w) { tree list = alloc_stmt_list (); tree frame = make_cilk_frame (fndecl); tree dtor = create_cilk_function_exit (frame, false, true); add_local_decl (cfun, frame); DECL_SAVED_TREE (fndecl) = list; tree frame_ptr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (frame)), frame); tree body_list = cilk_install_body_pedigree_operations (frame_ptr); gcc_assert (TREE_CODE (body_list) == STATEMENT_LIST); tree detach_expr = build_call_expr (cilk_detach_fndecl, 1, frame_ptr); append_to_statement_list (detach_expr, &body_list); cilk_outline (fndecl, &body, (struct wrapper_data *) w); body = fold_build_cleanup_point_expr (void_type_node, body); append_to_statement_list (body, &body_list); append_to_statement_list (build_stmt (EXPR_LOCATION (body), TRY_FINALLY_EXPR, body_list, dtor), &list); }
OMPSimpleVector.h
/** \file OMPSimpleVector.h*/ #ifndef OMP_SIMPLEVECTOR_H_ #define OMP_SIMPLEVECTOR_H_ typedef struct OMPCACell OMPCACell; //! A vector structure abstraction. /** The OMPSimpleVector holds integers and has a specific size. It has abstraction of pop and push (thus it works like a stack) * and it supports atomic inserts. */ typedef struct OMPSimpleVector { int m_size; int m_data[64]; } OMPSimpleVector; //! Insert an element to the vector. /** Pushes an integer to the back of the vector if there is enough space. * Returns index of position. \param v The vector structure \param element The element to insert */ int push_backsv(OMPSimpleVector* v, const int element) { int previousSize = v->m_size; (v->m_size)++; if(previousSize<64) { v->m_data[previousSize] = element; return previousSize; } else { printf (":(\n"); --(v->m_size); return -1; } } //! Extract an element from the vector. /** Pops an element from the back of the vector if any. \param v The vector structure \param cell The pointer to the item in which the extracted value is written */ int pop_backsv(OMPSimpleVector* v, int* cell) { if(v->m_size > 0) { int previousSize = (v->m_size)--; *cell = v->m_data[previousSize-1]; return 1; } else { return -1; } } //! Insert an element to the vector in a thread-safe way. /** Pushes an integer to the back of the vector if there is enough space. Uses atomic operations to make it thread-safe. * Returns index of position. \param v The vector structure \param element The element to insert */ int push_back_tssv(OMPSimpleVector* v, const int element) { int previousSize; #pragma omp atomic capture previousSize = (v->m_size)++; if(previousSize<48) { v->m_data[previousSize] = element; return previousSize; } else { #pragma omp atomic --(v->m_size); return -1; } } //! Set the vector to empty. void resetsv(OMPSimpleVector* v) { v->m_size = 0; } //! Get number of elements in vector. int sizesv(const OMPSimpleVector* v) { return v->m_size; } #endif
GB_binop__eq_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_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__eq_int32 // A.*B function (eWiseMult): GB_AemultB__eq_int32 // A*D function (colscale): GB_AxD__eq_int32 // D*A function (rowscale): GB_DxB__eq_int32 // C+=B function (dense accum): GB_Cdense_accumB__eq_int32 // C+=b function (dense accum): GB_Cdense_accumb__eq_int32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__eq_int32 // C=scalar+B GB_bind1st__eq_int32 // C=scalar+B' GB_bind1st_tran__eq_int32 // C=A+scalar GB_bind2nd__eq_int32 // C=A'+scalar GB_bind2nd_tran__eq_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) ; // 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_EQ || GxB_NO_INT32 || GxB_NO_EQ_INT32) //------------------------------------------------------------------------------ // 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__eq_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__eq_int32 ( 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 #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__eq_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__eq_int32 ( 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 bool *GB_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__eq_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 *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__eq_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 *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__eq_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 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__eq_int32 ( 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 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__eq_int32 ( 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 ; 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__eq_int32 ( 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 \ 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__eq_int32 ( 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 int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_bool_uint8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_bool_uint8) // op(A') function: GB (_unop_tran__identity_bool_uint8) // C type: bool // A type: uint8_t // cast: bool cij = (bool) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ bool z = (bool) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ bool z = (bool) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_bool_uint8) ( bool *Cx, // Cx and Ax may be aliased const uint8_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++) { uint8_t aij = Ax [p] ; bool z = (bool) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint8_t aij = Ax [p] ; bool z = (bool) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_bool_uint8) ( 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_hyper_prune.c
//------------------------------------------------------------------------------ // GB_hyper_prune: remove empty vectors from a hypersparse Ap, Ah list //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Removes empty vectors from a hypersparse list. On input, *Ap and *Ah are // assumed to be NULL. The input arrays Ap_old and Ah_old are not modified, // and thus can be shallow content from another matrix. New hyperlists Ap and // Ah are allocated, for nvec vectors, all nonempty. #include "GB.h" GrB_Info GB_hyper_prune ( // output, not allocated on input: int64_t *restrict *p_Ap, // size nvec+1 int64_t *restrict *p_Ah, // size nvec int64_t *p_nvec, // # of vectors, all nonempty // input, not modified const int64_t *Ap_old, // size nvec_old+1 const int64_t *Ah_old, // size nvec_old const int64_t nvec_old, // original number of vectors GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (p_Ap != NULL) ; ASSERT (p_Ah != NULL) ; ASSERT (p_nvec != NULL) ; ASSERT (Ap_old != NULL) ; ASSERT (Ah_old != NULL) ; ASSERT (nvec_old >= 0) ; (*p_Ap) = NULL ; (*p_Ah) = NULL ; (*p_nvec) = -1 ; //-------------------------------------------------------------------------- // determine the # of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (nvec_old, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- int64_t *restrict W ; GB_MALLOC_MEMORY (W, nvec_old+1, sizeof (int64_t)) ; if (W == NULL) { // out of memory return (GB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // count the # of nonempty vectors //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t k = 0 ; k < nvec_old ; k++) { // W [k] = 1 if the kth vector is nonempty; 0 if empty W [k] = (Ap_old [k] < Ap_old [k+1]) ; } int64_t nvec ; GB_cumsum (W, nvec_old, &nvec, nthreads) ; //-------------------------------------------------------------------------- // allocate the result //-------------------------------------------------------------------------- int64_t *restrict Ap = NULL ; int64_t *restrict Ah = NULL ; GB_MALLOC_MEMORY (Ap, nvec+1, sizeof (int64_t)) ; GB_MALLOC_MEMORY (Ah, nvec, sizeof (int64_t)) ; if (Ap == NULL || Ah == NULL) { // out of memory GB_FREE_MEMORY (W, nvec_old+1, sizeof (int64_t)) ; GB_FREE_MEMORY (Ap, nvec+1, sizeof (int64_t)) ; GB_FREE_MEMORY (Ah, nvec, sizeof (int64_t)) ; return (GB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // create the Ap and Ah result //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t k = 0 ; k < nvec_old ; k++) { if (Ap_old [k] < Ap_old [k+1]) { int64_t knew = W [k] ; Ap [knew] = Ap_old [k] ; Ah [knew] = Ah_old [k] ; } } Ap [nvec] = Ap_old [nvec_old] ; //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_MEMORY (W, nvec_old+1, sizeof (int64_t)) ; (*p_Ap) = Ap ; (*p_Ah) = Ah ; (*p_nvec) = nvec ; return (GrB_SUCCESS) ; }